Merge remote-tracking branch 'upstream/master' into feat/mocha-tests

This commit is contained in:
Par Winzell 2018-12-19 09:31:08 -08:00
commit f94b3650f2
67 changed files with 5426 additions and 5249 deletions

View File

@ -35,7 +35,7 @@ BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: false
ColumnLimit: 80
ColumnLimit: 100
CommentPragmas: '^ IWYU pragma:'
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4

View File

@ -35,8 +35,7 @@ int main(int argc, char* argv[]) {
CLI::App app{
fmt::sprintf(
"FBX2glTF %s: Generate a glTF 2.0 representation of an FBX model.",
FBX2GLTF_VERSION),
"FBX2glTF %s: Generate a glTF 2.0 representation of an FBX model.", FBX2GLTF_VERSION),
"FBX2glTF"};
app.add_flag(
@ -45,32 +44,22 @@ int main(int argc, char* argv[]) {
"Include blend shape tangents, if reported present by the FBX SDK.");
app.add_flag_function("-V,--version", [&](size_t count) {
fmt::printf(
"FBX2glTF version %s\nCopyright (c) 2016-2018 Oculus VR, LLC.\n",
FBX2GLTF_VERSION);
fmt::printf("FBX2glTF version %s\nCopyright (c) 2016-2018 Oculus VR, LLC.\n", FBX2GLTF_VERSION);
exit(0);
});
std::string inputPath;
app.add_option("FBX Model", inputPath, "The FBX model to convert.")
->check(CLI::ExistingFile);
app.add_option("-i,--input", inputPath, "The FBX model to convert.")
->check(CLI::ExistingFile);
app.add_option("FBX Model", inputPath, "The FBX model to convert.")->check(CLI::ExistingFile);
app.add_option("-i,--input", inputPath, "The FBX model to convert.")->check(CLI::ExistingFile);
std::string outputPath;
app.add_option(
"-o,--output",
outputPath,
"Where to generate the output, without suffix.");
app.add_option("-o,--output", outputPath, "Where to generate the output, without suffix.");
app.add_flag(
"-e,--embed",
gltfOptions.embedResources,
"Inline buffers as data:// URIs within generated non-binary glTF.");
app.add_flag(
"-b,--binary",
gltfOptions.outputBinary,
"Output a single binary format .glb file.");
app.add_flag("-b,--binary", gltfOptions.outputBinary, "Output a single binary format .glb file.");
app.add_option(
"--long-indices",
@ -119,8 +108,7 @@ int main(int argc, char* argv[]) {
"--flip-u",
[&](size_t count) {
if (count > 0) {
texturesTransforms.emplace_back(
[](Vec2f uv) { return Vec2f(1.0f - uv[0], uv[1]); });
texturesTransforms.emplace_back([](Vec2f uv) { return Vec2f(1.0f - uv[0], uv[1]); });
if (verboseOutput) {
fmt::printf("Flipping texture coordinates in the 'U' dimension.\n");
}
@ -128,23 +116,20 @@ int main(int argc, char* argv[]) {
},
"Flip all U texture coordinates.");
app.add_flag("--no-flip-u", "Don't flip U texture coordinates.")
->excludes("--flip-u");
app.add_flag("--no-flip-u", "Don't flip U texture coordinates.")->excludes("--flip-u");
app.add_flag_function(
"--no-flip-v",
[&](size_t count) {
if (count > 0) {
texturesTransforms.emplace_back(
[](Vec2f uv) { return Vec2f(uv[0], 1.0f - uv[1]); });
texturesTransforms.emplace_back([](Vec2f uv) { return Vec2f(uv[0], 1.0f - uv[1]); });
if (verboseOutput) {
fmt::printf("NOT flipping texture coordinates in the 'V' dimension.\n");
}
}
},
"Flip all V texture coordinates.");
app.add_flag("--flip-v", "Don't flip U texture coordinates.")
->excludes("--no-flip-v");
app.add_flag("--flip-v", "Don't flip U texture coordinates.")->excludes("--no-flip-v");
app.add_flag(
"--pbr-metallic-rougnness",
@ -181,8 +166,8 @@ int main(int argc, char* argv[]) {
app.add_option(
"-k,--keep-attribute",
[&](std::vector<std::string> attributes) -> bool {
gltfOptions.keepAttribs = RAW_VERTEX_ATTRIBUTE_JOINT_INDICES |
RAW_VERTEX_ATTRIBUTE_JOINT_WEIGHTS;
gltfOptions.keepAttribs =
RAW_VERTEX_ATTRIBUTE_JOINT_INDICES | RAW_VERTEX_ATTRIBUTE_JOINT_WEIGHTS;
for (std::string attribute : attributes) {
if (attribute == "position") {
gltfOptions.keepAttribs |= RAW_VERTEX_ATTRIBUTE_POSITION;
@ -212,9 +197,7 @@ int main(int argc, char* argv[]) {
->type_name("(position|normal|tangent|binormial|color|uv0|uv1|auto)");
app.add_flag(
"-d,--draco",
gltfOptions.draco.enabled,
"Apply Draco mesh compression to geometries.")
"-d,--draco", gltfOptions.draco.enabled, "Apply Draco mesh compression to geometries.")
->group("Draco");
app.add_option(
@ -301,16 +284,12 @@ int main(int argc, char* argv[]) {
} else {
// in gltf mode, we create a folder and write into that
outputFolder = fmt::format(
"{}_out{}",
outputPath.c_str(),
(const char)StringUtils::GetPathSeparator());
modelPath =
outputFolder + StringUtils::GetFileNameString(outputPath) + ".gltf";
outputFolder =
fmt::format("{}_out{}", outputPath.c_str(), (const char)StringUtils::GetPathSeparator());
modelPath = outputFolder + StringUtils::GetFileNameString(outputPath) + ".gltf";
}
if (!FileUtils::CreatePath(modelPath.c_str())) {
fmt::fprintf(
stderr, "ERROR: Failed to create folder: %s'\n", outputFolder.c_str());
fmt::fprintf(stderr, "ERROR: Failed to create folder: %s'\n", outputFolder.c_str());
return 1;
}
@ -334,14 +313,9 @@ int main(int argc, char* argv[]) {
std::ofstream outStream; // note: auto-flushes in destructor
const auto streamStart = outStream.tellp();
outStream.open(
modelPath,
std::ios::trunc | std::ios::ate | std::ios::out | std::ios::binary);
outStream.open(modelPath, std::ios::trunc | std::ios::ate | std::ios::out | std::ios::binary);
if (outStream.fail()) {
fmt::fprintf(
stderr,
"ERROR:: Couldn't open file for writing: %s\n",
modelPath.c_str());
fmt::fprintf(stderr, "ERROR:: Couldn't open file for writing: %s\n", modelPath.c_str());
return 1;
}
data_render_model = Raw2Gltf(outStream, outputFolder, raw, gltfOptions);
@ -371,8 +345,7 @@ int main(int argc, char* argv[]) {
const std::string binaryPath = outputFolder + extBufferFilename;
FILE* fp = fopen(binaryPath.c_str(), "wb");
if (fp == nullptr) {
fmt::fprintf(
stderr, "ERROR:: Couldn't open file '%s' for writing.\n", binaryPath);
fmt::fprintf(stderr, "ERROR:: Couldn't open file '%s' for writing.\n", binaryPath);
return 1;
}
@ -381,16 +354,12 @@ int main(int argc, char* argv[]) {
unsigned long binarySize = data_render_model->binary->size();
if (fwrite(binaryData, binarySize, 1, fp) != 1) {
fmt::fprintf(
stderr,
"ERROR: Failed to write %lu bytes to file '%s'.\n",
binarySize,
binaryPath);
stderr, "ERROR: Failed to write %lu bytes to file '%s'.\n", binarySize, binaryPath);
fclose(fp);
return 1;
}
fclose(fp);
fmt::printf(
"Wrote %lu bytes of binary data to %s.\n", binarySize, binaryPath);
fmt::printf("Wrote %lu bytes of binary data to %s.\n", binarySize, binaryPath);
}
delete data_render_model;

View File

@ -10,22 +10,22 @@
#include "Fbx2Raw.hpp"
#include <algorithm>
#include <vector>
#include <unordered_map>
#include <cassert>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <fstream>
#include <map>
#include <set>
#include <string>
#include <fstream>
#include <cstdint>
#include <cstdio>
#include <cassert>
#include <cmath>
#include <unordered_map>
#include <vector>
#include "FBX2glTF.h"
#include "raw/RawModel.hpp"
#include "utils/File_Utils.hpp"
#include "utils/String_Utils.hpp"
#include "raw/RawModel.hpp"
#include "FbxBlendShapesAccess.hpp"
#include "FbxLayerElementAccess.hpp"
@ -34,18 +34,20 @@
float scaleFactor;
static bool TriangleTexturePolarity(const Vec2f &uv0, const Vec2f &uv1, const Vec2f &uv2)
{
static bool TriangleTexturePolarity(const Vec2f& uv0, const Vec2f& uv1, const Vec2f& uv2) {
const Vec2f d0 = uv1 - uv0;
const Vec2f d1 = uv2 - uv0;
return (d0[0] * d1[1] - d0[1] * d1[0] < 0.0f);
}
static RawMaterialType
GetMaterialType(const RawModel &raw, const int textures[RAW_TEXTURE_USAGE_MAX], const bool vertexTransparency, const bool skinned)
{
// DIFFUSE and ALBEDO are different enough to represent distinctly, but they both help determine transparency.
static RawMaterialType GetMaterialType(
const RawModel& raw,
const int textures[RAW_TEXTURE_USAGE_MAX],
const bool vertexTransparency,
const bool skinned) {
// DIFFUSE and ALBEDO are different enough to represent distinctly, but they both help determine
// transparency.
int diffuseTexture = textures[RAW_TEXTURE_USAGE_DIFFUSE];
if (diffuseTexture < 0) {
diffuseTexture = textures[RAW_TEXTURE_USAGE_ALBEDO];
@ -62,13 +64,15 @@ GetMaterialType(const RawModel &raw, const int textures[RAW_TEXTURE_USAGE_MAX],
return skinned ? RAW_MATERIAL_TYPE_SKINNED_TRANSPARENT : RAW_MATERIAL_TYPE_TRANSPARENT;
}
// Default to simply opaque.
return skinned ? RAW_MATERIAL_TYPE_SKINNED_OPAQUE : RAW_MATERIAL_TYPE_OPAQUE;
}
static void ReadMesh(RawModel &raw, FbxScene *pScene, FbxNode *pNode, const std::map<const FbxTexture *, FbxString> &textureLocations)
{
static void ReadMesh(
RawModel& raw,
FbxScene* pScene,
FbxNode* pNode,
const std::map<const FbxTexture*, FbxString>& textureLocations) {
FbxGeometryConverter meshConverter(pScene->GetFbxManager());
meshConverter.Triangulate(pNode->GetNodeAttribute(), true);
FbxMesh* pMesh = pNode->GetMesh();
@ -92,20 +96,29 @@ static void ReadMesh(RawModel &raw, FbxScene *pScene, FbxNode *pNode, const std:
const int rawSurfaceIndex = raw.AddSurface(meshName, surfaceId);
const FbxVector4* controlPoints = pMesh->GetControlPoints();
const FbxLayerElementAccess<FbxVector4> normalLayer(pMesh->GetElementNormal(), pMesh->GetElementNormalCount());
const FbxLayerElementAccess<FbxVector4> binormalLayer(pMesh->GetElementBinormal(), pMesh->GetElementBinormalCount());
const FbxLayerElementAccess<FbxVector4> tangentLayer(pMesh->GetElementTangent(), pMesh->GetElementTangentCount());
const FbxLayerElementAccess<FbxColor> colorLayer(pMesh->GetElementVertexColor(), pMesh->GetElementVertexColorCount());
const FbxLayerElementAccess<FbxVector2> uvLayer0(pMesh->GetElementUV(0), pMesh->GetElementUVCount());
const FbxLayerElementAccess<FbxVector2> uvLayer1(pMesh->GetElementUV(1), pMesh->GetElementUVCount());
const FbxLayerElementAccess<FbxVector4> normalLayer(
pMesh->GetElementNormal(), pMesh->GetElementNormalCount());
const FbxLayerElementAccess<FbxVector4> binormalLayer(
pMesh->GetElementBinormal(), pMesh->GetElementBinormalCount());
const FbxLayerElementAccess<FbxVector4> tangentLayer(
pMesh->GetElementTangent(), pMesh->GetElementTangentCount());
const FbxLayerElementAccess<FbxColor> colorLayer(
pMesh->GetElementVertexColor(), pMesh->GetElementVertexColorCount());
const FbxLayerElementAccess<FbxVector2> uvLayer0(
pMesh->GetElementUV(0), pMesh->GetElementUVCount());
const FbxLayerElementAccess<FbxVector2> uvLayer1(
pMesh->GetElementUV(1), pMesh->GetElementUVCount());
const FbxSkinningAccess skinning(pMesh, pScene, pNode);
const FbxMaterialsAccess materials(pMesh, textureLocations);
const FbxBlendShapesAccess blendShapes(pMesh);
if (verboseOutput) {
fmt::printf(
"mesh %d: %s (skinned: %s)\n", rawSurfaceIndex, meshName,
skinning.IsSkinned() ? raw.GetNode(raw.GetNodeById(skinning.GetRootNode())).name.c_str() : "NO");
"mesh %d: %s (skinned: %s)\n",
rawSurfaceIndex,
meshName,
skinning.IsSkinned() ? raw.GetNode(raw.GetNodeById(skinning.GetRootNode())).name.c_str()
: "NO");
}
// The FbxNode geometric transformation describes how a FbxNodeAttribute is offset from
@ -120,17 +133,30 @@ static void ReadMesh(RawModel &raw, FbxScene *pScene, FbxNode *pNode, const std:
const FbxAMatrix meshTransform(meshTranslation, meshRotation, meshScaling);
const FbxMatrix transform = meshTransform;
// Remove translation & scaling from transforms that will bi applied to normals, tangents & binormals
// Remove translation & scaling from transforms that will bi applied to normals, tangents &
// binormals
const FbxMatrix normalTransform(FbxVector4(), meshRotation, meshScaling);
const FbxMatrix inverseTransposeTransform = normalTransform.Inverse().Transpose();
raw.AddVertexAttribute(RAW_VERTEX_ATTRIBUTE_POSITION);
if (normalLayer.LayerPresent()) { raw.AddVertexAttribute(RAW_VERTEX_ATTRIBUTE_NORMAL); }
if (tangentLayer.LayerPresent()) { raw.AddVertexAttribute(RAW_VERTEX_ATTRIBUTE_TANGENT); }
if (binormalLayer.LayerPresent()) { raw.AddVertexAttribute(RAW_VERTEX_ATTRIBUTE_BINORMAL); }
if (colorLayer.LayerPresent()) { raw.AddVertexAttribute(RAW_VERTEX_ATTRIBUTE_COLOR); }
if (uvLayer0.LayerPresent()) { raw.AddVertexAttribute(RAW_VERTEX_ATTRIBUTE_UV0); }
if (uvLayer1.LayerPresent()) { raw.AddVertexAttribute(RAW_VERTEX_ATTRIBUTE_UV1); }
if (normalLayer.LayerPresent()) {
raw.AddVertexAttribute(RAW_VERTEX_ATTRIBUTE_NORMAL);
}
if (tangentLayer.LayerPresent()) {
raw.AddVertexAttribute(RAW_VERTEX_ATTRIBUTE_TANGENT);
}
if (binormalLayer.LayerPresent()) {
raw.AddVertexAttribute(RAW_VERTEX_ATTRIBUTE_BINORMAL);
}
if (colorLayer.LayerPresent()) {
raw.AddVertexAttribute(RAW_VERTEX_ATTRIBUTE_COLOR);
}
if (uvLayer0.LayerPresent()) {
raw.AddVertexAttribute(RAW_VERTEX_ATTRIBUTE_UV0);
}
if (uvLayer1.LayerPresent()) {
raw.AddVertexAttribute(RAW_VERTEX_ATTRIBUTE_UV1);
}
if (skinning.IsSkinned()) {
raw.AddVertexAttribute(RAW_VERTEX_ATTRIBUTE_JOINT_WEIGHTS);
raw.AddVertexAttribute(RAW_VERTEX_ATTRIBUTE_JOINT_INDICES);
@ -141,13 +167,15 @@ static void ReadMesh(RawModel &raw, FbxScene *pScene, FbxNode *pNode, const std:
Mat4f scaleMatrix = Mat4f::FromScaleVector(Vec3f(scaleFactor, scaleFactor, scaleFactor));
Mat4f invScaleMatrix = scaleMatrix.Inverse();
rawSurface.skeletonRootId = (skinning.IsSkinned()) ? skinning.GetRootNode() : pNode->GetUniqueID();
rawSurface.skeletonRootId =
(skinning.IsSkinned()) ? skinning.GetRootNode() : pNode->GetUniqueID();
for (int jointIndex = 0; jointIndex < skinning.GetNodeCount(); jointIndex++) {
const long jointId = skinning.GetJointId(jointIndex);
raw.GetNode(raw.GetNodeById(jointId)).isJoint = true;
rawSurface.jointIds.emplace_back(jointId);
rawSurface.inverseBindMatrices.push_back(invScaleMatrix * toMat4f(skinning.GetInverseBindMatrix(jointIndex)) * scaleMatrix);
rawSurface.inverseBindMatrices.push_back(
invScaleMatrix * toMat4f(skinning.GetInverseBindMatrix(jointIndex)) * scaleMatrix);
rawSurface.jointGeometryMins.emplace_back(FLT_MAX, FLT_MAX, FLT_MAX);
rawSurface.jointGeometryMaxs.emplace_back(-FLT_MAX, -FLT_MAX, -FLT_MAX);
}
@ -156,16 +184,16 @@ static void ReadMesh(RawModel &raw, FbxScene *pScene, FbxNode *pNode, const std:
std::vector<const FbxBlendShapesAccess::TargetShape*> targetShapes;
for (size_t channelIx = 0; channelIx < blendShapes.GetChannelCount(); channelIx++) {
for (size_t targetIx = 0; targetIx < blendShapes.GetTargetShapeCount(channelIx); targetIx++) {
const FbxBlendShapesAccess::TargetShape &shape = blendShapes.GetTargetShape(channelIx, targetIx);
const FbxBlendShapesAccess::TargetShape& shape =
blendShapes.GetTargetShape(channelIx, targetIx);
targetShapes.push_back(&shape);
auto& blendChannel = blendShapes.GetBlendChannel(channelIx);
rawSurface.blendChannels.push_back(RawBlendChannel {
static_cast<float>(blendChannel.deformPercent),
rawSurface.blendChannels.push_back(
RawBlendChannel{static_cast<float>(blendChannel.deformPercent),
shape.normals.LayerPresent(),
shape.tangents.LayerPresent(),
blendChannel.name
});
blendChannel.name});
}
}
@ -183,8 +211,13 @@ static void ReadMesh(RawModel &raw, FbxScene *pScene, FbxNode *pNode, const std:
if (fbxMaterial == nullptr) {
materialName = "DefaultMaterial";
rawMatProps.reset(new RawTraditionalMatProps(RAW_SHADING_MODEL_LAMBERT,
Vec3f(0, 0, 0), Vec4f(.5, .5, .5, 1), Vec3f(0, 0, 0), Vec3f(0, 0, 0), 0.5));
rawMatProps.reset(new RawTraditionalMatProps(
RAW_SHADING_MODEL_LAMBERT,
Vec3f(0, 0, 0),
Vec4f(.5, .5, .5, 1),
Vec3f(0, 0, 0),
Vec3f(0, 0, 0),
0.5));
} else {
materialName = fbxMaterial->name;
@ -193,13 +226,15 @@ static void ReadMesh(RawModel &raw, FbxScene *pScene, FbxNode *pNode, const std:
if (tex != nullptr) {
// dig out the inferred filename from the textureLocations map
FbxString inferredPath = textureLocations.find(tex)->second;
textures[usage] = raw.AddTexture(tex->GetName(), tex->GetFileName(), inferredPath.Buffer(), usage);
textures[usage] =
raw.AddTexture(tex->GetName(), tex->GetFileName(), inferredPath.Buffer(), usage);
}
};
std::shared_ptr<RawMatProps> matInfo;
if (fbxMaterial->shadingModel == FbxRoughMetMaterialInfo::FBX_SHADER_METROUGH) {
FbxRoughMetMaterialInfo *fbxMatInfo = static_cast<FbxRoughMetMaterialInfo *>(fbxMaterial.get());
FbxRoughMetMaterialInfo* fbxMatInfo =
static_cast<FbxRoughMetMaterialInfo*>(fbxMaterial.get());
maybeAddTexture(fbxMatInfo->texColor, RAW_TEXTURE_USAGE_ALBEDO);
maybeAddTexture(fbxMatInfo->texNormal, RAW_TEXTURE_USAGE_NORMAL);
@ -208,11 +243,15 @@ static void ReadMesh(RawModel &raw, FbxScene *pScene, FbxNode *pNode, const std:
maybeAddTexture(fbxMatInfo->texMetallic, RAW_TEXTURE_USAGE_METALLIC);
maybeAddTexture(fbxMatInfo->texAmbientOcclusion, RAW_TEXTURE_USAGE_OCCLUSION);
rawMatProps.reset(new RawMetRoughMatProps(
RAW_SHADING_MODEL_PBR_MET_ROUGH, toVec4f(fbxMatInfo->colBase), toVec3f(fbxMatInfo->colEmissive),
fbxMatInfo->emissiveIntensity, fbxMatInfo->metallic, fbxMatInfo->roughness));
RAW_SHADING_MODEL_PBR_MET_ROUGH,
toVec4f(fbxMatInfo->colBase),
toVec3f(fbxMatInfo->colEmissive),
fbxMatInfo->emissiveIntensity,
fbxMatInfo->metallic,
fbxMatInfo->roughness));
} else {
FbxTraditionalMaterialInfo *fbxMatInfo = static_cast<FbxTraditionalMaterialInfo *>(fbxMaterial.get());
FbxTraditionalMaterialInfo* fbxMatInfo =
static_cast<FbxTraditionalMaterialInfo*>(fbxMaterial.get());
RawShadingModel shadingModel;
if (fbxMaterial->shadingModel == "Lambert") {
shadingModel = RAW_SHADING_MODEL_LAMBERT;
@ -231,9 +270,13 @@ static void ReadMesh(RawModel &raw, FbxScene *pScene, FbxNode *pNode, const std:
maybeAddTexture(fbxMatInfo->texShininess, RAW_TEXTURE_USAGE_SHININESS);
maybeAddTexture(fbxMatInfo->texAmbient, RAW_TEXTURE_USAGE_AMBIENT);
maybeAddTexture(fbxMatInfo->texSpecular, RAW_TEXTURE_USAGE_SPECULAR);
rawMatProps.reset(new RawTraditionalMatProps(shadingModel,
toVec3f(fbxMatInfo->colAmbient), toVec4f(fbxMatInfo->colDiffuse), toVec3f(fbxMatInfo->colEmissive),
toVec3f(fbxMatInfo->colSpecular), fbxMatInfo->shininess));
rawMatProps.reset(new RawTraditionalMatProps(
shadingModel,
toVec3f(fbxMatInfo->colAmbient),
toVec4f(fbxMatInfo->colDiffuse),
toVec3f(fbxMatInfo->colEmissive),
toVec3f(fbxMatInfo->colSpecular),
fbxMatInfo->shininess));
}
}
@ -245,15 +288,32 @@ static void ReadMesh(RawModel &raw, FbxScene *pScene, FbxNode *pNode, const std:
// Note that the default values here must be the same as the RawVertex default values!
const FbxVector4 fbxPosition = transform.MultNormalize(controlPoints[controlPointIndex]);
const FbxVector4 fbxNormal = normalLayer.GetElement(
polygonIndex, polygonVertexIndex, controlPointIndex, FbxVector4(0.0f, 0.0f, 0.0f, 0.0f), inverseTransposeTransform, true);
polygonIndex,
polygonVertexIndex,
controlPointIndex,
FbxVector4(0.0f, 0.0f, 0.0f, 0.0f),
inverseTransposeTransform,
true);
const FbxVector4 fbxTangent = tangentLayer.GetElement(
polygonIndex, polygonVertexIndex, controlPointIndex, FbxVector4(0.0f, 0.0f, 0.0f, 0.0f), inverseTransposeTransform, true);
polygonIndex,
polygonVertexIndex,
controlPointIndex,
FbxVector4(0.0f, 0.0f, 0.0f, 0.0f),
inverseTransposeTransform,
true);
const FbxVector4 fbxBinormal = binormalLayer.GetElement(
polygonIndex, polygonVertexIndex, controlPointIndex, FbxVector4(0.0f, 0.0f, 0.0f, 0.0f), inverseTransposeTransform, true);
const FbxColor fbxColor = colorLayer
.GetElement(polygonIndex, polygonVertexIndex, controlPointIndex, FbxColor(0.0f, 0.0f, 0.0f, 0.0f));
const FbxVector2 fbxUV0 = uvLayer0.GetElement(polygonIndex, polygonVertexIndex, controlPointIndex, FbxVector2(0.0f, 0.0f));
const FbxVector2 fbxUV1 = uvLayer1.GetElement(polygonIndex, polygonVertexIndex, controlPointIndex, FbxVector2(0.0f, 0.0f));
polygonIndex,
polygonVertexIndex,
controlPointIndex,
FbxVector4(0.0f, 0.0f, 0.0f, 0.0f),
inverseTransposeTransform,
true);
const FbxColor fbxColor = colorLayer.GetElement(
polygonIndex, polygonVertexIndex, controlPointIndex, FbxColor(0.0f, 0.0f, 0.0f, 0.0f));
const FbxVector2 fbxUV0 = uvLayer0.GetElement(
polygonIndex, polygonVertexIndex, controlPointIndex, FbxVector2(0.0f, 0.0f));
const FbxVector2 fbxUV1 = uvLayer1.GetElement(
polygonIndex, polygonVertexIndex, controlPointIndex, FbxVector2(0.0f, 0.0f));
RawVertex& vertex = rawVertices[vertexIndex];
vertex.position[0] = (float)fbxPosition[0] * scaleFactor;
@ -281,7 +341,8 @@ static void ReadMesh(RawModel &raw, FbxScene *pScene, FbxNode *pNode, const std:
vertex.jointWeights = skinning.GetVertexWeights(controlPointIndex);
vertex.polarityUv0 = false;
// flag this triangle as transparent if any of its corner vertices substantially deviates from fully opaque
// flag this triangle as transparent if any of its corner vertices substantially deviates from
// fully opaque
vertexTransparency |= colorLayer.LayerPresent() && (fabs(fbxColor.mAlpha - 1.0) > 1e-3);
rawSurface.bounds.AddPoint(vertex.position);
@ -291,16 +352,27 @@ static void ReadMesh(RawModel &raw, FbxScene *pScene, FbxNode *pNode, const std:
for (const auto* targetShape : targetShapes) {
RawBlendVertex blendVertex;
// the morph target data must be transformed just as with the vertex positions above
const FbxVector4 &shapePosition = transform.MultNormalize(targetShape->positions[controlPointIndex]);
const FbxVector4& shapePosition =
transform.MultNormalize(targetShape->positions[controlPointIndex]);
blendVertex.position = toVec3f(shapePosition - fbxPosition) * scaleFactor;
if (targetShape->normals.LayerPresent()) {
const FbxVector4& normal = targetShape->normals.GetElement(
polygonIndex, polygonVertexIndex, controlPointIndex, FbxVector4(0.0f, 0.0f, 0.0f, 0.0f), inverseTransposeTransform, true);
polygonIndex,
polygonVertexIndex,
controlPointIndex,
FbxVector4(0.0f, 0.0f, 0.0f, 0.0f),
inverseTransposeTransform,
true);
blendVertex.normal = toVec3f(normal - fbxNormal);
}
if (targetShape->tangents.LayerPresent()) {
const FbxVector4& tangent = targetShape->tangents.GetElement(
polygonIndex, polygonVertexIndex, controlPointIndex, FbxVector4(0.0f, 0.0f, 0.0f, 0.0f), inverseTransposeTransform, true);
polygonIndex,
polygonVertexIndex,
controlPointIndex,
FbxVector4(0.0f, 0.0f, 0.0f, 0.0f),
inverseTransposeTransform,
true);
blendVertex.tangent = toVec4f(tangent - fbxTangent);
}
vertex.blends.push_back(blendVertex);
@ -310,18 +382,14 @@ static void ReadMesh(RawModel &raw, FbxScene *pScene, FbxNode *pNode, const std:
}
if (skinning.IsSkinned()) {
const int jointIndices[FbxSkinningAccess::MAX_WEIGHTS] = {
vertex.jointIndices[0],
const int jointIndices[FbxSkinningAccess::MAX_WEIGHTS] = {vertex.jointIndices[0],
vertex.jointIndices[1],
vertex.jointIndices[2],
vertex.jointIndices[3]
};
const float jointWeights[FbxSkinningAccess::MAX_WEIGHTS] = {
vertex.jointWeights[0],
vertex.jointIndices[3]};
const float jointWeights[FbxSkinningAccess::MAX_WEIGHTS] = {vertex.jointWeights[0],
vertex.jointWeights[1],
vertex.jointWeights[2],
vertex.jointWeights[3]
};
vertex.jointWeights[3]};
const FbxMatrix skinningMatrix =
skinning.GetJointSkinningTransform(jointIndices[0]) * jointWeights[0] +
skinning.GetJointSkinningTransform(jointIndices[1]) * jointWeights[1] +
@ -332,7 +400,8 @@ static void ReadMesh(RawModel &raw, FbxScene *pScene, FbxNode *pNode, const std:
for (int i = 0; i < FbxSkinningAccess::MAX_WEIGHTS; i++) {
if (jointWeights[i] > 0.0f) {
const FbxVector4 localPosition =
skinning.GetJointInverseGlobalTransforms(jointIndices[i]).MultNormalize(globalPosition);
skinning.GetJointInverseGlobalTransforms(jointIndices[i])
.MultNormalize(globalPosition);
Vec3f& mins = rawSurface.jointGeometryMins[jointIndices[i]];
mins[0] = std::min(mins[0], (float)localPosition[0]);
@ -349,8 +418,10 @@ static void ReadMesh(RawModel &raw, FbxScene *pScene, FbxNode *pNode, const std:
}
if (textures[RAW_TEXTURE_USAGE_NORMAL] != -1) {
// Distinguish vertices that are used by triangles with a different texture polarity to avoid degenerate tangent space smoothing.
const bool polarity = TriangleTexturePolarity(rawVertices[0].uv0, rawVertices[1].uv0, rawVertices[2].uv0);
// Distinguish vertices that are used by triangles with a different texture polarity to avoid
// degenerate tangent space smoothing.
const bool polarity =
TriangleTexturePolarity(rawVertices[0].uv0, rawVertices[1].uv0, rawVertices[2].uv0);
rawVertices[0].polarityUv0 = polarity;
rawVertices[1].polarityUv0 = polarity;
rawVertices[2].polarityUv0 = polarity;
@ -361,22 +432,27 @@ static void ReadMesh(RawModel &raw, FbxScene *pScene, FbxNode *pNode, const std:
rawVertexIndices[vertexIndex] = raw.AddVertex(rawVertices[vertexIndex]);
}
const RawMaterialType materialType = GetMaterialType(raw, textures, vertexTransparency, skinning.IsSkinned());
const int rawMaterialIndex = raw.AddMaterial(materialName, materialType, textures, rawMatProps, userProperties);
const RawMaterialType materialType =
GetMaterialType(raw, textures, vertexTransparency, skinning.IsSkinned());
const int rawMaterialIndex =
raw.AddMaterial(materialName, materialType, textures, rawMatProps, userProperties);
raw.AddTriangle(rawVertexIndices[0], rawVertexIndices[1], rawVertexIndices[2], rawMaterialIndex, rawSurfaceIndex);
raw.AddTriangle(
rawVertexIndices[0],
rawVertexIndices[1],
rawVertexIndices[2],
rawMaterialIndex,
rawSurfaceIndex);
}
}
// ar : aspectY / aspectX
double HFOV2VFOV(double h, double ar)
{
double HFOV2VFOV(double h, double ar) {
return 2.0 * std::atan((ar)*std::tan((h * FBXSDK_PI_DIV_180) * 0.5)) * FBXSDK_180_DIV_PI;
};
// ar : aspectX / aspectY
double VFOV2HFOV(double v, double ar)
{
double VFOV2HFOV(double v, double ar) {
return 2.0 * std::atan((ar)*std::tan((v * FBXSDK_PI_DIV_180) * 0.5)) * FBXSDK_180_DIV_PI;
}
@ -388,18 +464,20 @@ static void ReadLight(RawModel &raw, FbxScene *pScene, FbxNode *pNode) {
Vec3f color = toVec3f(pLight->Color.Get());
switch (pLight->LightType.Get()) {
case FbxLight::eDirectional: {
lightIx = raw.AddLight(pLight->GetName(), RAW_LIGHT_TYPE_DIRECTIONAL,
color, intensity, 0, 0);
lightIx = raw.AddLight(pLight->GetName(), RAW_LIGHT_TYPE_DIRECTIONAL, color, intensity, 0, 0);
break;
}
case FbxLight::ePoint: {
lightIx = raw.AddLight(pLight->GetName(), RAW_LIGHT_TYPE_POINT, color,
intensity, 0, 0);
lightIx = raw.AddLight(pLight->GetName(), RAW_LIGHT_TYPE_POINT, color, intensity, 0, 0);
break;
}
case FbxLight::eSpot: {
lightIx = raw.AddLight(pLight->GetName(), RAW_LIGHT_TYPE_SPOT, color,
intensity, (float)pLight->InnerAngle.Get(),
lightIx = raw.AddLight(
pLight->GetName(),
RAW_LIGHT_TYPE_SPOT,
color,
intensity,
(float)pLight->InnerAngle.Get(),
(float)pLight->OuterAngle.Get());
break;
}
@ -415,8 +493,7 @@ static void ReadLight(RawModel &raw, FbxScene *pScene, FbxNode *pNode) {
}
// Largely adopted from fbx example
static void ReadCamera(RawModel &raw, FbxScene *pScene, FbxNode *pNode)
{
static void ReadCamera(RawModel& raw, FbxScene* pScene, FbxNode* pNode) {
const FbxCamera* pCamera = pNode->GetCamera();
double filmHeight = pCamera->GetApertureHeight();
@ -428,8 +505,7 @@ static void ReadCamera(RawModel &raw, FbxScene *pScene, FbxNode *pNode)
double fovx = 0.0f;
double fovy = 0.0f;
switch(pCamera->GetApertureMode())
{
switch (pCamera->GetApertureMode()) {
case FbxCamera::EApertureMode::eHorizAndVert: {
fovx = pCamera->FieldOfViewX;
fovy = pCamera->FieldOfViewY;
@ -458,14 +534,21 @@ static void ReadCamera(RawModel &raw, FbxScene *pScene, FbxNode *pNode)
if (pCamera->ProjectionType.Get() == FbxCamera::EProjectionType::ePerspective) {
raw.AddCameraPerspective(
"", pNode->GetUniqueID(), (float) pCamera->FilmAspectRatio,
(float) fovx, (float) fovy,
(float) pCamera->NearPlane, (float) pCamera->FarPlane);
"",
pNode->GetUniqueID(),
(float)pCamera->FilmAspectRatio,
(float)fovx,
(float)fovy,
(float)pCamera->NearPlane,
(float)pCamera->FarPlane);
} else {
raw.AddCameraOrthographic(
"", pNode->GetUniqueID(),
(float) pCamera->OrthoZoom, (float) pCamera->OrthoZoom,
(float) pCamera->FarPlane, (float) pCamera->NearPlane);
"",
pNode->GetUniqueID(),
(float)pCamera->OrthoZoom,
(float)pCamera->OrthoZoom,
(float)pCamera->FarPlane,
(float)pCamera->NearPlane);
}
// Cameras in FBX coordinate space face +X when rotation is (0,0,0)
@ -477,8 +560,7 @@ static void ReadCamera(RawModel &raw, FbxScene *pScene, FbxNode *pNode)
rawNode.rotation = rawNode.rotation * r;
}
static void ReadNodeProperty(RawModel &raw, FbxNode *pNode, FbxProperty &prop)
{
static void ReadNodeProperty(RawModel& raw, FbxNode* pNode, FbxProperty& prop) {
int nodeId = raw.GetNodeById(pNode->GetUniqueID());
if (nodeId >= 0) {
RawNode& node = raw.GetNode(nodeId);
@ -487,16 +569,17 @@ static void ReadNodeProperty(RawModel &raw, FbxNode *pNode, FbxProperty &prop)
}
static void ReadNodeAttributes(
RawModel &raw, FbxScene *pScene, FbxNode *pNode, const std::map<const FbxTexture *, FbxString> &textureLocations)
{
RawModel& raw,
FbxScene* pScene,
FbxNode* pNode,
const std::map<const FbxTexture*, FbxString>& textureLocations) {
if (!pNode->GetVisibility()) {
return;
}
// Only support non-animated user defined properties for now
FbxProperty objectProperty = pNode->GetFirstProperty();
while (objectProperty.IsValid())
{
while (objectProperty.IsValid()) {
if (objectProperty.GetFlag(FbxPropertyFlags::eUserDefined)) {
ReadNodeProperty(raw, pNode, objectProperty);
}
@ -552,25 +635,26 @@ static void ReadNodeAttributes(
* Compute the local scale vector to use for a given node. This is an imperfect hack to cope with
* the FBX node transform's eInheritRrs inheritance type, in which ancestral scale is ignored
*/
static FbxVector4 computeLocalScale(FbxNode *pNode, FbxTime pTime = FBXSDK_TIME_INFINITE)
{
static FbxVector4 computeLocalScale(FbxNode* pNode, FbxTime pTime = FBXSDK_TIME_INFINITE) {
const FbxVector4 lScale = pNode->EvaluateLocalTransform(pTime).GetS();
if (pNode->GetParent() == nullptr ||
pNode->GetTransform().GetInheritType() != FbxTransform::eInheritRrs) {
return lScale;
}
// This is a very partial fix that is only correct for models that use identity scale in their rig's joints.
// We could write better support that compares local scale to parent's global scale and apply the ratio to
// our local translation. We'll always want to return scale 1, though -- that's the only way to encode the
// missing 'S' (parent scale) in the transform chain.
// This is a very partial fix that is only correct for models that use identity scale in their
// rig's joints. We could write better support that compares local scale to parent's global scale
// and apply the ratio to our local translation. We'll always want to return scale 1, though --
// that's the only way to encode the missing 'S' (parent scale) in the transform chain.
return FbxVector4(1, 1, 1, 1);
}
static void ReadNodeHierarchy(
RawModel &raw, FbxScene *pScene, FbxNode *pNode,
const long parentId, const std::string &path)
{
RawModel& raw,
FbxScene* pScene,
FbxNode* pNode,
const long parentId,
const std::string& path) {
const FbxUInt64 nodeId = pNode->GetUniqueID();
const char* nodeName = pNode->GetName();
const int nodeIndex = raw.AddNode(nodeId, nodeName, parentId);
@ -588,7 +672,9 @@ static void ReadNodeHierarchy(
static int warnRrsCount = 0;
if (lInheritType == FbxTransform::eInheritRrSs && parentId) {
if (++warnRrSsCount == 1) {
fmt::printf("Warning: node %s uses unsupported transform inheritance type 'eInheritRrSs'.\n", newPath);
fmt::printf(
"Warning: node %s uses unsupported transform inheritance type 'eInheritRrSs'.\n",
newPath);
fmt::printf(" (Further warnings of this type squelched.)\n");
}
@ -616,7 +702,8 @@ static void ReadNodeHierarchy(
if (parentId) {
RawNode& parentNode = raw.GetNode(raw.GetNodeById(parentId));
// Add unique child name to the parent node.
if (std::find(parentNode.childIds.begin(), parentNode.childIds.end(), nodeId) == parentNode.childIds.end()) {
if (std::find(parentNode.childIds.begin(), parentNode.childIds.end(), nodeId) ==
parentNode.childIds.end()) {
parentNode.childIds.push_back(nodeId);
}
} else {
@ -629,8 +716,7 @@ static void ReadNodeHierarchy(
}
}
static void ReadAnimations(RawModel &raw, FbxScene *pScene)
{
static void ReadAnimations(RawModel& raw, FbxScene* pScene) {
FbxTime::EMode eMode = FbxTime::eFrames24;
const double epsilon = 1e-5f;
@ -692,17 +778,17 @@ static void ReadAnimations(RawModel &raw, FbxScene *pScene)
const FbxQuaternion localRotation = localTransform.GetQ();
const FbxVector4 localScale = computeLocalScale(pNode, pTime);
hasTranslation |= (
fabs(localTranslation[0] - baseTranslation[0]) > epsilon ||
hasTranslation |=
(fabs(localTranslation[0] - baseTranslation[0]) > epsilon ||
fabs(localTranslation[1] - baseTranslation[1]) > epsilon ||
fabs(localTranslation[2] - baseTranslation[2]) > epsilon);
hasRotation |= (
fabs(localRotation[0] - baseRotation[0]) > epsilon ||
hasRotation |=
(fabs(localRotation[0] - baseRotation[0]) > epsilon ||
fabs(localRotation[1] - baseRotation[1]) > epsilon ||
fabs(localRotation[2] - baseRotation[2]) > epsilon ||
fabs(localRotation[3] - baseRotation[3]) > epsilon);
hasScale |= (
fabs(localScale[0] - baseScaling[0]) > epsilon ||
hasScale |=
(fabs(localScale[0] - baseScaling[0]) > epsilon ||
fabs(localScale[1] - baseScaling[1]) > epsilon ||
fabs(localScale[2] - baseScaling[2]) > epsilon);
@ -714,7 +800,8 @@ static void ReadAnimations(RawModel &raw, FbxScene *pScene)
std::vector<FbxAnimCurve*> shapeAnimCurves;
FbxNodeAttribute* nodeAttr = pNode->GetNodeAttribute();
if (nodeAttr != nullptr && nodeAttr->GetAttributeType() == FbxNodeAttribute::EType::eMesh) {
// it's inelegant to recreate this same access class multiple times, but it's also dirt cheap...
// it's inelegant to recreate this same access class multiple times, but it's also dirt
// cheap...
FbxBlendShapesAccess blendShapes(static_cast<FbxMesh*>(nodeAttr));
for (FbxLongLong frameIndex = firstFrameIndex; frameIndex <= lastFrameIndex; frameIndex++) {
@ -728,8 +815,8 @@ static void ReadAnimations(RawModel &raw, FbxScene *pScene)
int targetCount = static_cast<int>(blendShapes.GetTargetShapeCount(channelIx));
// the target shape 'fullWeight' values are a strictly ascending list of floats (between
// 0 and 100), forming a sequence of intervals -- this convenience function figures out if
// 'p' lays between some certain target fullWeights, and if so where (from 0 to 1).
// 0 and 100), forming a sequence of intervals -- this convenience function figures out
// if 'p' lays between some certain target fullWeights, and if so where (from 0 to 1).
auto findInInterval = [&](const double p, const int n) {
if (n >= targetCount) {
// p is certainly completely left of this interval
@ -772,8 +859,8 @@ static void ReadAnimations(RawModel &raw, FbxScene *pScene)
}
}
// this is here because we have to fill in a weight for every channelIx/targetIx permutation,
// regardless of whether or not they participate in this animation.
// this is here because we have to fill in a weight for every channelIx/targetIx
// permutation, regardless of whether or not they participate in this animation.
channel.weights.push_back(0.0f);
}
}
@ -803,7 +890,11 @@ static void ReadAnimations(RawModel &raw, FbxScene *pScene)
}
if (verboseOutput) {
fmt::printf("\ranimation %d: %s (%d%%)", animIx, (const char *) animStackName, nodeIndex * 100 / nodeCount);
fmt::printf(
"\ranimation %d: %s (%d%%)",
animIx,
(const char*)animStackName,
nodeIndex * 100 / nodeCount);
}
}
@ -811,19 +902,25 @@ static void ReadAnimations(RawModel &raw, FbxScene *pScene)
if (verboseOutput) {
fmt::printf(
"\ranimation %d: %s (%d channels, %3.1f MB)\n", animIx, (const char *) animStackName,
(int) animation.channels.size(), (float) totalSizeInBytes * 1e-6f);
"\ranimation %d: %s (%d channels, %3.1f MB)\n",
animIx,
(const char*)animStackName,
(int)animation.channels.size(),
(float)totalSizeInBytes * 1e-6f);
}
}
}
static std::string GetInferredFileName(const std::string &fbxFileName, const std::string &directory, const std::vector<std::string> &directoryFileList)
{
static std::string GetInferredFileName(
const std::string& fbxFileName,
const std::string& directory,
const std::vector<std::string>& directoryFileList) {
if (FileUtils::FileExists(fbxFileName)) {
return fbxFileName;
}
// Get the file name with file extension.
const std::string fileName = StringUtils::GetFileNameString(StringUtils::GetCleanPathString(fbxFileName));
const std::string fileName =
StringUtils::GetFileNameString(StringUtils::GetCleanPathString(fbxFileName));
// Try to find a match with extension.
for (const auto& file : directoryFileList) {
@ -856,10 +953,11 @@ static std::string GetInferredFileName(const std::string &fbxFileName, const std
path on the author's computer such as "C:\MyProject\TextureName.psd", and matches
it to a list of existing texture files in the same directory as the FBX file.
*/
static void
FindFbxTextures(
FbxScene *pScene, const char *fbxFileName, const char *extensions, std::map<const FbxTexture *, FbxString> &textureLocations)
{
static void FindFbxTextures(
FbxScene* pScene,
const char* fbxFileName,
const char* extensions,
std::map<const FbxTexture*, FbxString>& textureLocations) {
// Get the folder the FBX file is in.
const std::string folder = StringUtils::GetFolderString(fbxFileName);
@ -869,7 +967,8 @@ FindFbxTextures(
// Search either in the folder with embedded textures or in the same folder as the FBX file.
const std::string searchFolder = FileUtils::FolderExists(fbmFolderName) ? fbmFolderName : folder;
// Get a list with all the texture files from either the folder with embedded textures or the same folder as the FBX file.
// Get a list with all the texture files from either the folder with embedded textures or the same
// folder as the FBX file.
std::vector<std::string> fileList = FileUtils::ListFolderFiles(searchFolder.c_str(), extensions);
// Try to match the FBX texture names with the actual files on disk.
@ -878,18 +977,21 @@ FindFbxTextures(
if (pFileTexture == nullptr) {
continue;
}
const std::string inferredName = GetInferredFileName(pFileTexture->GetFileName(), searchFolder, fileList);
const std::string inferredName =
GetInferredFileName(pFileTexture->GetFileName(), searchFolder, fileList);
if (inferredName.empty()) {
fmt::printf("Warning: could not find a local image file for texture: %s.\n"
"Original filename: %s\n", pFileTexture->GetName(), pFileTexture->GetFileName());
fmt::printf(
"Warning: could not find a local image file for texture: %s.\n"
"Original filename: %s\n",
pFileTexture->GetName(),
pFileTexture->GetFileName());
}
// always extend the mapping, even for files we didn't find
textureLocations.emplace(pFileTexture, inferredName.c_str());
}
}
bool LoadFBXFile(RawModel &raw, const char *fbxFileName, const char *textureExtensions)
{
bool LoadFBXFile(RawModel& raw, const char* fbxFileName, const char* textureExtensions) {
FbxManager* pManager = FbxManager::Create();
FbxIOSettings* pIoSettings = FbxIOSettings::Create(pManager, IOSROOT);
pManager->SetIOSettings(pIoSettings);
@ -944,37 +1046,68 @@ bool LoadFBXFile(RawModel &raw, const char *fbxFileName, const char *textureExte
}
// convenience method for describing a property in JSON
json TranscribeProperty(FbxProperty &prop)
{
json TranscribeProperty(FbxProperty& prop) {
using fbxsdk::EFbxType;
std::string ename;
// Convert property type
switch (prop.GetPropertyDataType().GetType()) {
case eFbxBool: ename = "eFbxBool"; break;
case eFbxChar: ename = "eFbxChar"; break;
case eFbxUChar: ename = "eFbxUChar"; break;
case eFbxShort: ename = "eFbxShort"; break;
case eFbxUShort: ename = "eFbxUShort"; break;
case eFbxInt: ename = "eFbxInt"; break;
case eFbxUInt: ename = "eFbxUint"; break;
case eFbxLongLong: ename = "eFbxLongLong"; break;
case eFbxULongLong: ename = "eFbxULongLong"; break;
case eFbxFloat: ename = "eFbxFloat"; break;
case eFbxHalfFloat: ename = "eFbxHalfFloat"; break;
case eFbxDouble: ename = "eFbxDouble"; break;
case eFbxDouble2: ename = "eFbxDouble2"; break;
case eFbxDouble3: ename = "eFbxDouble3"; break;
case eFbxDouble4: ename = "eFbxDouble4"; break;
case eFbxString: ename = "eFbxString"; break;
case eFbxBool:
ename = "eFbxBool";
break;
case eFbxChar:
ename = "eFbxChar";
break;
case eFbxUChar:
ename = "eFbxUChar";
break;
case eFbxShort:
ename = "eFbxShort";
break;
case eFbxUShort:
ename = "eFbxUShort";
break;
case eFbxInt:
ename = "eFbxInt";
break;
case eFbxUInt:
ename = "eFbxUint";
break;
case eFbxLongLong:
ename = "eFbxLongLong";
break;
case eFbxULongLong:
ename = "eFbxULongLong";
break;
case eFbxFloat:
ename = "eFbxFloat";
break;
case eFbxHalfFloat:
ename = "eFbxHalfFloat";
break;
case eFbxDouble:
ename = "eFbxDouble";
break;
case eFbxDouble2:
ename = "eFbxDouble2";
break;
case eFbxDouble3:
ename = "eFbxDouble3";
break;
case eFbxDouble4:
ename = "eFbxDouble4";
break;
case eFbxString:
ename = "eFbxString";
break;
// Use this as fallback because it does not give very descriptive names
default: ename = prop.GetPropertyDataType().GetName(); break;
default:
ename = prop.GetPropertyDataType().GetName();
break;
}
json p = {
{"type", ename}
};
json p = {{"type", ename}};
// Convert property value
switch (prop.GetPropertyDataType().GetType()) {
@ -1024,8 +1157,5 @@ json TranscribeProperty(FbxProperty &prop)
}
}
return {
{prop.GetNameAsCStr(), p}
};
return {{prop.GetNameAsCStr(), p}};
}

View File

@ -9,37 +9,44 @@
#include "FbxBlendShapesAccess.hpp"
FbxBlendShapesAccess::TargetShape::TargetShape(const FbxShape *shape, FbxDouble fullWeight) :
shape(shape),
FbxBlendShapesAccess::TargetShape::TargetShape(const FbxShape* shape, FbxDouble fullWeight)
: shape(shape),
fullWeight(fullWeight),
count(shape->GetControlPointsCount()),
positions(shape->GetControlPoints()),
normals(FbxLayerElementAccess<FbxVector4>(shape->GetElementNormal(), shape->GetElementNormalCount())),
tangents(FbxLayerElementAccess<FbxVector4>(shape->GetElementTangent(), shape->GetElementTangentCount()))
{}
normals(FbxLayerElementAccess<FbxVector4>(
shape->GetElementNormal(),
shape->GetElementNormalCount())),
tangents(FbxLayerElementAccess<FbxVector4>(
shape->GetElementTangent(),
shape->GetElementTangentCount())) {}
FbxAnimCurve *FbxBlendShapesAccess::BlendChannel::ExtractAnimation(unsigned int animIx) const
{
FbxAnimCurve* FbxBlendShapesAccess::BlendChannel::ExtractAnimation(unsigned int animIx) const {
FbxAnimStack* stack = mesh->GetScene()->GetSrcObject<FbxAnimStack>(animIx);
FbxAnimLayer* layer = stack->GetMember<FbxAnimLayer>(0);
return mesh->GetShapeChannel(blendShapeIx, channelIx, layer, true);
}
FbxBlendShapesAccess::BlendChannel::BlendChannel(
FbxMesh *mesh, const unsigned int blendShapeIx, const unsigned int channelIx, const FbxDouble deformPercent,
const std::vector<FbxBlendShapesAccess::TargetShape> &targetShapes, std::string name) : mesh(mesh),
FbxMesh* mesh,
const unsigned int blendShapeIx,
const unsigned int channelIx,
const FbxDouble deformPercent,
const std::vector<FbxBlendShapesAccess::TargetShape>& targetShapes,
std::string name)
: mesh(mesh),
blendShapeIx(blendShapeIx),
channelIx(channelIx),
deformPercent(deformPercent),
targetShapes(targetShapes),
name(name)
{}
name(name) {}
std::vector<FbxBlendShapesAccess::BlendChannel> FbxBlendShapesAccess::extractChannels(FbxMesh *mesh) const
{
std::vector<FbxBlendShapesAccess::BlendChannel> FbxBlendShapesAccess::extractChannels(
FbxMesh* mesh) const {
std::vector<BlendChannel> channels;
for (int shapeIx = 0; shapeIx < mesh->GetDeformerCount(FbxDeformer::eBlendShape); shapeIx++) {
auto *fbxBlendShape = static_cast<FbxBlendShape *>(mesh->GetDeformer(shapeIx, FbxDeformer::eBlendShape));
auto* fbxBlendShape =
static_cast<FbxBlendShape*>(mesh->GetDeformer(shapeIx, FbxDeformer::eBlendShape));
for (int channelIx = 0; channelIx < fbxBlendShape->GetBlendShapeChannelCount(); ++channelIx) {
FbxBlendShapeChannel* fbxChannel = fbxBlendShape->GetBlendShapeChannel(channelIx);
@ -57,7 +64,8 @@ std::vector<FbxBlendShapesAccess::BlendChannel> FbxBlendShapesAccess::extractCha
FbxShape* fbxShape = fbxChannel->GetTargetShape(targetIx);
targetShapes.emplace_back(fbxShape, fullWeights[targetIx]);
}
channels.emplace_back(mesh, shapeIx, channelIx, fbxChannel->DeformPercent * 0.01, targetShapes, name);
channels.emplace_back(
mesh, shapeIx, channelIx, fbxChannel->DeformPercent * 0.01, targetShapes, name);
}
}
}

View File

@ -9,41 +9,41 @@
#pragma once
#include <algorithm>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include "FBX2glTF.h"
#include "FbxLayerElementAccess.hpp"
/**
* At the FBX level, each Mesh can have a set of FbxBlendShape deformers; organisational units that contain no data
* of their own. The actual deformation is determined by one or more FbxBlendShapeChannels, whose influences are all
* additively applied to the mesh. In a simpler world, each such channel would extend each base vertex with alternate
* position, and optionally normal and tangent.
* At the FBX level, each Mesh can have a set of FbxBlendShape deformers; organisational units that
* contain no data of their own. The actual deformation is determined by one or more
* FbxBlendShapeChannels, whose influences are all additively applied to the mesh. In a simpler
* world, each such channel would extend each base vertex with alternate position, and optionally
* normal and tangent.
*
* It's not quite so simple, though. We also have progressive morphing, where one logical morph actually consists of
* several concrete ones, each applied in sequence. For us, this means each channel contains a sequence of FbxShapes
* (aka target shape); these are the actual data-holding entities that provide the alternate vertex attributes. As such
* a channel is given more weight, it moves from one target shape to another.
* It's not quite so simple, though. We also have progressive morphing, where one logical morph
* actually consists of several concrete ones, each applied in sequence. For us, this means each
* channel contains a sequence of FbxShapes (aka target shape); these are the actual data-holding
* entities that provide the alternate vertex attributes. As such a channel is given more weight, it
* moves from one target shape to another.
*
* The total number of alternate sets of attributes, then, is the total number of target shapes across all the channels
* of all the blend shapes of the mesh.
* The total number of alternate sets of attributes, then, is the total number of target shapes
* across all the channels of all the blend shapes of the mesh.
*
* Each animation in the scene stack can yield one or zero FbxAnimCurves per channel (not target shape). We evaluate
* these curves to get the weight of the channel: this weight is further introspected on to figure out which target
* shapes we're currently interpolation between.
* Each animation in the scene stack can yield one or zero FbxAnimCurves per channel (not target
* shape). We evaluate these curves to get the weight of the channel: this weight is further
* introspected on to figure out which target shapes we're currently interpolation between.
*/
class FbxBlendShapesAccess
{
class FbxBlendShapesAccess {
public:
/**
* A target shape is on a 1:1 basis with the eventual glTF morph target, and is the object which contains the
* actual morphed vertex data.
* A target shape is on a 1:1 basis with the eventual glTF morph target, and is the object which
* contains the actual morphed vertex data.
*/
struct TargetShape
{
struct TargetShape {
explicit TargetShape(const FbxShape* shape, FbxDouble fullWeight);
const FbxShape* shape;
@ -57,16 +57,14 @@ public:
/**
* A channel collects a sequence (often of length 1) of target shapes.
*/
struct BlendChannel
{
struct BlendChannel {
BlendChannel(
FbxMesh* mesh,
const unsigned int blendShapeIx,
const unsigned int channelIx,
const FbxDouble deformPercent,
const std::vector<TargetShape>& targetShapes,
const std::string name
);
const std::string name);
FbxAnimCurve* ExtractAnimation(unsigned int animIx) const;
@ -80,16 +78,18 @@ public:
const FbxDouble deformPercent;
};
explicit FbxBlendShapesAccess(FbxMesh *mesh) :
channels(extractChannels(mesh))
{ }
explicit FbxBlendShapesAccess(FbxMesh* mesh) : channels(extractChannels(mesh)) {}
size_t GetChannelCount() const { return channels.size(); }
size_t GetChannelCount() const {
return channels.size();
}
const BlendChannel& GetBlendChannel(size_t channelIx) const {
return channels.at(channelIx);
}
size_t GetTargetShapeCount(size_t channelIx) const { return channels[channelIx].targetShapes.size(); }
size_t GetTargetShapeCount(size_t channelIx) const {
return channels[channelIx].targetShapes.size();
}
const TargetShape& GetTargetShape(size_t channelIx, size_t targetShapeIx) const {
return channels.at(channelIx).targetShapes[targetShapeIx];
}

View File

@ -10,21 +10,26 @@
#include "FBX2glTF.h"
template <typename _type_>
class FbxLayerElementAccess
{
class FbxLayerElementAccess {
public:
FbxLayerElementAccess(const FbxLayerElementTemplate<_type_>* layer, int count);
bool LayerPresent() const
{
bool LayerPresent() const {
return (mappingMode != FbxLayerElement::eNone);
}
_type_ GetElement(const int polygonIndex, const int polygonVertexIndex, const int controlPointIndex, const _type_ defaultValue) const;
_type_ GetElement(
const int polygonIndex, const int polygonVertexIndex, const int controlPointIndex, const _type_ defaultValue,
const FbxMatrix &transform, const bool normalize) const;
const int polygonIndex,
const int polygonVertexIndex,
const int controlPointIndex,
const _type_ defaultValue) const;
_type_ GetElement(
const int polygonIndex,
const int polygonVertexIndex,
const int controlPointIndex,
const _type_ defaultValue,
const FbxMatrix& transform,
const bool normalize) const;
private:
FbxLayerElement::EMappingMode mappingMode;
@ -33,11 +38,10 @@ private:
};
template <typename _type_>
FbxLayerElementAccess<_type_>::FbxLayerElementAccess(const FbxLayerElementTemplate<_type_> *layer, int count) :
mappingMode(FbxLayerElement::eNone),
elements(nullptr),
indices(nullptr)
{
FbxLayerElementAccess<_type_>::FbxLayerElementAccess(
const FbxLayerElementTemplate<_type_>* layer,
int count)
: mappingMode(FbxLayerElement::eNone), elements(nullptr), indices(nullptr) {
if (count <= 0 || layer == nullptr) {
return;
}
@ -47,19 +51,23 @@ FbxLayerElementAccess<_type_>::FbxLayerElementAccess(const FbxLayerElementTempla
newMappingMode == FbxLayerElement::eByPolygon) {
mappingMode = newMappingMode;
elements = &layer->GetDirectArray();
indices = (
layer->GetReferenceMode() == FbxLayerElement::eIndexToDirect ||
layer->GetReferenceMode() == FbxLayerElement::eIndex) ? &layer->GetIndexArray() : nullptr;
indices = (layer->GetReferenceMode() == FbxLayerElement::eIndexToDirect ||
layer->GetReferenceMode() == FbxLayerElement::eIndex)
? &layer->GetIndexArray()
: nullptr;
}
}
template <typename _type_>
_type_ FbxLayerElementAccess<_type_>::GetElement(
const int polygonIndex, const int polygonVertexIndex, const int controlPointIndex, const _type_ defaultValue) const
{
const int polygonIndex,
const int polygonVertexIndex,
const int controlPointIndex,
const _type_ defaultValue) const {
if (mappingMode != FbxLayerElement::eNone) {
int index = (mappingMode == FbxLayerElement::eByControlPoint) ? controlPointIndex :
((mappingMode == FbxLayerElement::eByPolygonVertex) ? polygonVertexIndex : polygonIndex);
int index = (mappingMode == FbxLayerElement::eByControlPoint)
? controlPointIndex
: ((mappingMode == FbxLayerElement::eByPolygonVertex) ? polygonVertexIndex : polygonIndex);
index = (indices != nullptr) ? (*indices)[index] : index;
_type_ element = elements->GetAt(index);
return element;
@ -69,11 +77,15 @@ _type_ FbxLayerElementAccess<_type_>::GetElement(
template <typename _type_>
_type_ FbxLayerElementAccess<_type_>::GetElement(
const int polygonIndex, const int polygonVertexIndex, const int controlPointIndex, const _type_ defaultValue,
const FbxMatrix &transform, const bool normalize) const
{
const int polygonIndex,
const int polygonVertexIndex,
const int controlPointIndex,
const _type_ defaultValue,
const FbxMatrix& transform,
const bool normalize) const {
if (mappingMode != FbxLayerElement::eNone) {
_type_ element = transform.MultNormalize(GetElement(polygonIndex, polygonVertexIndex, controlPointIndex, defaultValue));
_type_ element = transform.MultNormalize(
GetElement(polygonIndex, polygonVertexIndex, controlPointIndex, defaultValue));
if (normalize) {
element.Normalize();
}

View File

@ -14,8 +14,7 @@
class FbxMaterialInfo {
public:
FbxMaterialInfo(const FbxString& name, const FbxString& shadingModel)
: name(name),
shadingModel(shadingModel) {}
: name(name), shadingModel(shadingModel) {}
const FbxString name;
const FbxString shadingModel;

View File

@ -10,21 +10,23 @@
#include "FbxMaterialsAccess.hpp"
#include "Fbx2Raw.hpp"
FbxMaterialsAccess::FbxMaterialsAccess(const FbxMesh *pMesh, const std::map<const FbxTexture *, FbxString> &textureLocations) :
mappingMode(FbxGeometryElement::eNone),
mesh(nullptr),
indices(nullptr)
{
FbxMaterialsAccess::FbxMaterialsAccess(
const FbxMesh* pMesh,
const std::map<const FbxTexture*, FbxString>& textureLocations)
: mappingMode(FbxGeometryElement::eNone), mesh(nullptr), indices(nullptr) {
if (pMesh->GetElementMaterialCount() <= 0) {
return;
}
const FbxGeometryElement::EMappingMode materialMappingMode = pMesh->GetElementMaterial()->GetMappingMode();
if (materialMappingMode != FbxGeometryElement::eByPolygon && materialMappingMode != FbxGeometryElement::eAllSame) {
const FbxGeometryElement::EMappingMode materialMappingMode =
pMesh->GetElementMaterial()->GetMappingMode();
if (materialMappingMode != FbxGeometryElement::eByPolygon &&
materialMappingMode != FbxGeometryElement::eAllSame) {
return;
}
const FbxGeometryElement::EReferenceMode materialReferenceMode = pMesh->GetElementMaterial()->GetReferenceMode();
const FbxGeometryElement::EReferenceMode materialReferenceMode =
pMesh->GetElementMaterial()->GetReferenceMode();
if (materialReferenceMode != FbxGeometryElement::eIndexToDirect) {
return;
}
@ -39,16 +41,15 @@ FbxMaterialsAccess::FbxMaterialsAccess(const FbxMesh *pMesh, const std::map<cons
continue;
}
FbxSurfaceMaterial* surfaceMaterial = mesh->GetNode()->GetSrcObject<FbxSurfaceMaterial>(materialNum);
FbxSurfaceMaterial* surfaceMaterial =
mesh->GetNode()->GetSrcObject<FbxSurfaceMaterial>(materialNum);
if (materialNum >= summaries.size()) {
summaries.resize(materialNum + 1);
}
auto summary = summaries[materialNum];
if (summary == nullptr) {
summary = summaries[materialNum] = GetMaterialInfo(
surfaceMaterial,
textureLocations);
summary = summaries[materialNum] = GetMaterialInfo(surfaceMaterial, textureLocations);
}
if (materialNum >= userProperties.size()) {
@ -56,8 +57,7 @@ FbxMaterialsAccess::FbxMaterialsAccess(const FbxMesh *pMesh, const std::map<cons
}
if (userProperties[materialNum].empty()) {
FbxProperty objectProperty = surfaceMaterial->GetFirstProperty();
while (objectProperty.IsValid())
{
while (objectProperty.IsValid()) {
if (objectProperty.GetFlag(FbxPropertyFlags::eUserDefined)) {
userProperties[materialNum].push_back(TranscribeProperty(objectProperty).dump());
}
@ -67,10 +67,11 @@ FbxMaterialsAccess::FbxMaterialsAccess(const FbxMesh *pMesh, const std::map<cons
}
}
const std::shared_ptr<FbxMaterialInfo> FbxMaterialsAccess::GetMaterial(const int polygonIndex) const
{
const std::shared_ptr<FbxMaterialInfo> FbxMaterialsAccess::GetMaterial(
const int polygonIndex) const {
if (mappingMode != FbxGeometryElement::eNone) {
const int materialNum = indices->GetAt((mappingMode == FbxGeometryElement::eByPolygon) ? polygonIndex : 0);
const int materialNum =
indices->GetAt((mappingMode == FbxGeometryElement::eByPolygon) ? polygonIndex : 0);
if (materialNum < 0) {
return nullptr;
}
@ -79,10 +80,10 @@ const std::shared_ptr<FbxMaterialInfo> FbxMaterialsAccess::GetMaterial(const int
return nullptr;
}
const std::vector<std::string> FbxMaterialsAccess::GetUserProperties(const int polygonIndex) const
{
const std::vector<std::string> FbxMaterialsAccess::GetUserProperties(const int polygonIndex) const {
if (mappingMode != FbxGeometryElement::eNone) {
const int materialNum = indices->GetAt((mappingMode == FbxGeometryElement::eByPolygon) ? polygonIndex : 0);
const int materialNum =
indices->GetAt((mappingMode == FbxGeometryElement::eByPolygon) ? polygonIndex : 0);
if (materialNum < 0) {
return std::vector<std::string>();
}
@ -91,9 +92,9 @@ const std::vector<std::string> FbxMaterialsAccess::GetUserProperties(const int p
return std::vector<std::string>();
}
std::unique_ptr<FbxMaterialInfo>
FbxMaterialsAccess::GetMaterialInfo(FbxSurfaceMaterial *material, const std::map<const FbxTexture *, FbxString> &textureLocations)
{
std::unique_ptr<FbxMaterialInfo> FbxMaterialsAccess::GetMaterialInfo(
FbxSurfaceMaterial* material,
const std::map<const FbxTexture*, FbxString>& textureLocations) {
std::unique_ptr<FbxMaterialInfo> res;
res = FbxRoughMetMaterialInfo::From(material, textureLocations);
if (!res) {
@ -101,4 +102,3 @@ FbxMaterialsAccess::GetMaterialInfo(FbxSurfaceMaterial *material, const std::map
}
return res;
}

View File

@ -11,21 +11,22 @@
#include "Fbx2Raw.hpp"
#include "FbxMaterialInfo.hpp"
#include "FbxTraditionalMaterialInfo.hpp"
#include "FbxRoughMetMaterialInfo.hpp"
#include "FbxTraditionalMaterialInfo.hpp"
class FbxMaterialsAccess
{
class FbxMaterialsAccess {
public:
FbxMaterialsAccess(const FbxMesh *pMesh, const std::map<const FbxTexture *, FbxString> &textureLocations);
FbxMaterialsAccess(
const FbxMesh* pMesh,
const std::map<const FbxTexture*, FbxString>& textureLocations);
const std::shared_ptr<FbxMaterialInfo> GetMaterial(const int polygonIndex) const;
const std::vector<std::string> GetUserProperties(const int polygonIndex) const;
std::unique_ptr<FbxMaterialInfo>
GetMaterialInfo(FbxSurfaceMaterial *material, const std::map<const FbxTexture *, FbxString> &textureLocations);
std::unique_ptr<FbxMaterialInfo> GetMaterialInfo(
FbxSurfaceMaterial* material,
const std::map<const FbxTexture*, FbxString>& textureLocations);
private:
FbxGeometryElement::EMappingMode mappingMode;

View File

@ -9,18 +9,21 @@
#include "FbxRoughMetMaterialInfo.hpp"
std::unique_ptr<FbxRoughMetMaterialInfo>
FbxRoughMetMaterialInfo::From(FbxSurfaceMaterial *fbxMaterial, const std::map<const FbxTexture *, FbxString> &textureLocations)
{
std::unique_ptr<FbxRoughMetMaterialInfo> res(new FbxRoughMetMaterialInfo(fbxMaterial->GetName(), FBX_SHADER_METROUGH));
std::unique_ptr<FbxRoughMetMaterialInfo> FbxRoughMetMaterialInfo::From(
FbxSurfaceMaterial* fbxMaterial,
const std::map<const FbxTexture*, FbxString>& textureLocations) {
std::unique_ptr<FbxRoughMetMaterialInfo> res(
new FbxRoughMetMaterialInfo(fbxMaterial->GetName(), FBX_SHADER_METROUGH));
const FbxProperty mayaProp = fbxMaterial->FindProperty("Maya");
if (mayaProp.GetPropertyDataType() != FbxCompoundDT) {
return nullptr;
}
if (!fbxMaterial->ShadingModel.Get().IsEmpty()) {
::fmt::printf("Warning: Material %s has surprising shading model: %s\n",
fbxMaterial->GetName(), fbxMaterial->ShadingModel.Get());
::fmt::printf(
"Warning: Material %s has surprising shading model: %s\n",
fbxMaterial->GetName(),
fbxMaterial->ShadingModel.Get());
}
auto getTex = [&](std::string propName) {
@ -36,8 +39,10 @@ FbxRoughMetMaterialInfo::From(FbxSurfaceMaterial *fbxMaterial, const std::map<co
}
}
} else if (verboseOutput && useProp.IsValid()) {
fmt::printf("Note: Property '%s' of material '%s' exists, but is flagged as 'do not use'.\n",
propName, fbxMaterial->GetName());
fmt::printf(
"Note: Property '%s' of material '%s' exists, but is flagged as 'do not use'.\n",
propName,
fbxMaterial->GetName());
}
return ptr;
};

View File

@ -7,13 +7,13 @@
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include <algorithm>
#include <fstream>
#include <string>
#include <set>
#include <map>
#include <set>
#include <string>
#include <unordered_map>
#include <vector>
#include <algorithm>
#include "FbxMaterialInfo.hpp"
@ -25,8 +25,7 @@ struct FbxRoughMetMaterialInfo : FbxMaterialInfo {
const std::map<const FbxTexture*, FbxString>& textureLocations);
FbxRoughMetMaterialInfo(const FbxString& name, const FbxString& shadingModel)
: FbxMaterialInfo(name, shadingModel)
{}
: FbxMaterialInfo(name, shadingModel) {}
const FbxFileTexture* texColor{};
FbxVector4 colBase{};

View File

@ -10,10 +10,10 @@
#include "FbxSkinningAccess.hpp"
FbxSkinningAccess::FbxSkinningAccess(const FbxMesh* pMesh, FbxScene* pScene, FbxNode* pNode)
: rootIndex(-1)
{
: rootIndex(-1) {
for (int deformerIndex = 0; deformerIndex < pMesh->GetDeformerCount(); deformerIndex++) {
FbxSkin *skin = reinterpret_cast< FbxSkin * >( pMesh->GetDeformer(deformerIndex, FbxDeformer::eSkin));
FbxSkin* skin =
reinterpret_cast<FbxSkin*>(pMesh->GetDeformer(deformerIndex, FbxDeformer::eSkin));
if (skin != nullptr) {
const int clusterCount = skin->GetClusterCount();
if (clusterCount == 0) {
@ -47,7 +47,8 @@ FbxSkinningAccess::FbxSkinningAccess(const FbxMesh *pMesh, FbxScene *pScene, Fbx
jointIds.push_back(cluster->GetLink()->GetUniqueID());
const FbxAMatrix globalNodeTransform = cluster->GetLink()->EvaluateGlobalTransform();
jointSkinningTransforms.push_back(FbxMatrix(globalNodeTransform * globalBindposeInverseMatrix));
jointSkinningTransforms.push_back(
FbxMatrix(globalNodeTransform * globalBindposeInverseMatrix));
jointInverseGlobalTransforms.push_back(FbxMatrix(globalNodeTransform.Inverse()));
for (int i = 0; i < indexCount; i++) {
@ -60,14 +61,18 @@ FbxSkinningAccess::FbxSkinningAccess(const FbxMesh *pMesh, FbxScene *pScene, Fbx
vertexJointIndices[clusterIndices[i]][MAX_WEIGHTS - 1] = clusterIndex;
vertexJointWeights[clusterIndices[i]][MAX_WEIGHTS - 1] = (float)clusterWeights[i];
for (int j = MAX_WEIGHTS - 1; j > 0; j--) {
if (vertexJointWeights[clusterIndices[i]][j - 1] >= vertexJointWeights[clusterIndices[i]][j]) {
if (vertexJointWeights[clusterIndices[i]][j - 1] >=
vertexJointWeights[clusterIndices[i]][j]) {
break;
}
std::swap(vertexJointIndices[clusterIndices[i]][j - 1], vertexJointIndices[clusterIndices[i]][j]);
std::swap(vertexJointWeights[clusterIndices[i]][j - 1], vertexJointWeights[clusterIndices[i]][j]);
std::swap(
vertexJointIndices[clusterIndices[i]][j - 1],
vertexJointIndices[clusterIndices[i]][j]);
std::swap(
vertexJointWeights[clusterIndices[i]][j - 1],
vertexJointWeights[clusterIndices[i]][j]);
}
}
}
for (int i = 0; i < controlPointCount; i++) {
vertexJointWeights[i] = vertexJointWeights[i].Normalized();

View File

@ -9,75 +9,63 @@
#pragma once
#include <algorithm>
#include <fstream>
#include <string>
#include <set>
#include <map>
#include <set>
#include <string>
#include <unordered_map>
#include <vector>
#include <algorithm>
#include "FBX2glTF.h"
class FbxSkinningAccess
{
class FbxSkinningAccess {
public:
static const int MAX_WEIGHTS = 4;
FbxSkinningAccess(const FbxMesh* pMesh, FbxScene* pScene, FbxNode* pNode);
bool IsSkinned() const
{
bool IsSkinned() const {
return (vertexJointWeights.size() > 0);
}
int GetNodeCount() const
{
int GetNodeCount() const {
return (int)jointNodes.size();
}
FbxNode *GetJointNode(const int jointIndex) const
{
FbxNode* GetJointNode(const int jointIndex) const {
return jointNodes[jointIndex];
}
const long GetJointId(const int jointIndex) const
{
const long GetJointId(const int jointIndex) const {
return jointIds[jointIndex];
}
const FbxMatrix &GetJointSkinningTransform(const int jointIndex) const
{
const FbxMatrix& GetJointSkinningTransform(const int jointIndex) const {
return jointSkinningTransforms[jointIndex];
}
const FbxMatrix &GetJointInverseGlobalTransforms(const int jointIndex) const
{
const FbxMatrix& GetJointInverseGlobalTransforms(const int jointIndex) const {
return jointInverseGlobalTransforms[jointIndex];
}
const long GetRootNode() const
{
const long GetRootNode() const {
assert(rootIndex != -1);
return jointIds[rootIndex];
}
const FbxAMatrix &GetInverseBindMatrix(const int jointIndex) const
{
const FbxAMatrix& GetInverseBindMatrix(const int jointIndex) const {
return inverseBindMatrices[jointIndex];
}
const Vec4i GetVertexIndices(const int controlPointIndex) const
{
return (!vertexJointIndices.empty()) ?
vertexJointIndices[controlPointIndex] : Vec4i(0, 0, 0, 0);
const Vec4i GetVertexIndices(const int controlPointIndex) const {
return (!vertexJointIndices.empty()) ? vertexJointIndices[controlPointIndex]
: Vec4i(0, 0, 0, 0);
}
const Vec4f GetVertexWeights(const int controlPointIndex) const
{
return (!vertexJointWeights.empty()) ?
vertexJointWeights[controlPointIndex] : Vec4f(0, 0, 0, 0);
const Vec4f GetVertexWeights(const int controlPointIndex) const {
return (!vertexJointWeights.empty()) ? vertexJointWeights[controlPointIndex]
: Vec4f(0, 0, 0, 0);
}
private:

View File

@ -9,9 +9,9 @@
#include "FbxTraditionalMaterialInfo.hpp"
std::unique_ptr<FbxTraditionalMaterialInfo>
FbxTraditionalMaterialInfo::From(FbxSurfaceMaterial *fbxMaterial, const std::map<const FbxTexture *, FbxString> &textureLocations)
{
std::unique_ptr<FbxTraditionalMaterialInfo> FbxTraditionalMaterialInfo::From(
FbxSurfaceMaterial* fbxMaterial,
const std::map<const FbxTexture*, FbxString>& textureLocations) {
auto getSurfaceScalar = [&](const char* propName) -> std::tuple<FbxDouble, FbxFileTexture*> {
const FbxProperty prop = fbxMaterial->FindProperty(propName);
@ -40,7 +40,9 @@ FbxTraditionalMaterialInfo::From(FbxSurfaceMaterial *fbxMaterial, const std::map
return std::make_tuple(val, tex);
};
auto getSurfaceValues = [&](const char *colName, const char *facName) -> std::tuple<FbxVector4, FbxFileTexture *, FbxFileTexture *> {
auto getSurfaceValues =
[&](const char* colName,
const char* facName) -> std::tuple<FbxVector4, FbxFileTexture*, FbxFileTexture*> {
const FbxProperty colProp = fbxMaterial->FindProperty(colName);
const FbxProperty facProp = fbxMaterial->FindProperty(facName);
@ -63,25 +65,29 @@ FbxTraditionalMaterialInfo::From(FbxSurfaceMaterial *fbxMaterial, const std::map
}
auto val = FbxVector4(
colorVal[0] * factorVal,
colorVal[1] * factorVal,
colorVal[2] * factorVal,
factorVal);
colorVal[0] * factorVal, colorVal[1] * factorVal, colorVal[2] * factorVal, factorVal);
return std::make_tuple(val, colTex, facTex);
};
std::string name = fbxMaterial->GetName();
std::unique_ptr<FbxTraditionalMaterialInfo> res(new FbxTraditionalMaterialInfo(name.c_str(), fbxMaterial->ShadingModel.Get()));
std::unique_ptr<FbxTraditionalMaterialInfo> res(
new FbxTraditionalMaterialInfo(name.c_str(), fbxMaterial->ShadingModel.Get()));
// four properties are on the same structure and follow the same rules
auto handleBasicProperty = [&](const char *colName, const char *facName) -> std::tuple<FbxVector4, FbxFileTexture *>{
auto handleBasicProperty = [&](const char* colName,
const char* facName) -> std::tuple<FbxVector4, FbxFileTexture*> {
FbxFileTexture *colTex, *facTex;
FbxVector4 vec;
std::tie(vec, colTex, facTex) = getSurfaceValues(colName, facName);
if (colTex) {
if (facTex) {
fmt::printf("Warning: Mat [%s]: Can't handle both %s and %s textures; discarding %s.\n", name, colName, facName, facName);
fmt::printf(
"Warning: Mat [%s]: Can't handle both %s and %s textures; discarding %s.\n",
name,
colName,
facName,
facName);
}
return std::make_tuple(vec, colTex);
}
@ -109,15 +115,22 @@ FbxTraditionalMaterialInfo::From(FbxSurfaceMaterial *fbxMaterial, const std::map
FbxVector4 transparency;
// extract any existing textures only so we can warn that we're throwing them away
FbxFileTexture *colTex, *facTex;
std::tie(transparency, colTex, facTex) =
getSurfaceValues(FbxSurfaceMaterial::sTransparentColor, FbxSurfaceMaterial::sTransparencyFactor);
std::tie(transparency, colTex, facTex) = getSurfaceValues(
FbxSurfaceMaterial::sTransparentColor, FbxSurfaceMaterial::sTransparencyFactor);
if (colTex) {
fmt::printf("Warning: Mat [%s]: Can't handle texture for %s; discarding.\n", name, FbxSurfaceMaterial::sTransparentColor);
fmt::printf(
"Warning: Mat [%s]: Can't handle texture for %s; discarding.\n",
name,
FbxSurfaceMaterial::sTransparentColor);
}
if (facTex) {
fmt::printf("Warning: Mat [%s]: Can't handle texture for %s; discarding.\n", name, FbxSurfaceMaterial::sTransparencyFactor);
fmt::printf(
"Warning: Mat [%s]: Can't handle texture for %s; discarding.\n",
name,
FbxSurfaceMaterial::sTransparencyFactor);
}
// FBX color is RGB, so we calculate the A channel as the average of the FBX transparency color vector
// FBX color is RGB, so we calculate the A channel as the average of the FBX transparency color
// vector
res->colDiffuse[3] = 1.0 - (transparency[0] + transparency[1] + transparency[2]) / 3.0;
return res;

View File

@ -7,13 +7,13 @@
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include <algorithm>
#include <fstream>
#include <string>
#include <set>
#include <map>
#include <set>
#include <string>
#include <unordered_map>
#include <vector>
#include <algorithm>
#include "FbxMaterialInfo.hpp"
@ -23,8 +23,7 @@ struct FbxTraditionalMaterialInfo : FbxMaterialInfo {
static constexpr const char* FBX_SHADER_PHONG = "Phong";
FbxTraditionalMaterialInfo(const FbxString& name, const FbxString& shadingModel)
: FbxMaterialInfo(name, shadingModel)
{}
: FbxMaterialInfo(name, shadingModel) {}
FbxFileTexture* texAmbient{};
FbxVector4 colAmbient{};

View File

@ -18,8 +18,10 @@ std::unique_ptr<FbxRoughMetMaterialInfo> Fbx3dsMaxPhysicalMaterialResolver::reso
FbxString shadingModel = fbxMaterial->ShadingModel.Get();
if (!shadingModel.IsEmpty() && shadingModel != "unknown") {
::fmt::printf("Warning: Material %s has surprising shading model: %s\n",
fbxMaterial->GetName(), shadingModel);
::fmt::printf(
"Warning: Material %s has surprising shading model: %s\n",
fbxMaterial->GetName(),
shadingModel);
}
auto getTex = [&](std::string propName) -> const FbxFileTexture* {
@ -35,8 +37,10 @@ std::unique_ptr<FbxRoughMetMaterialInfo> Fbx3dsMaxPhysicalMaterialResolver::reso
}
}
} else if (verboseOutput && useProp.IsValid()) {
fmt::printf("Note: property '%s' of 3dsMax Physical material '%s' exists, but is flagged as 'off'.\n",
propName, fbxMaterial->GetName());
fmt::printf(
"Note: property '%s' of 3dsMax Physical material '%s' exists, but is flagged as 'off'.\n",
propName,
fbxMaterial->GetName());
}
return ptr;
};
@ -98,15 +102,12 @@ std::unique_ptr<FbxRoughMetMaterialInfo> Fbx3dsMaxPhysicalMaterialResolver::reso
const auto* bumpMap = getTex("bump");
const auto* displacementMap = getTex("displacement");
std::unique_ptr<FbxRoughMetMaterialInfo> res(
new FbxRoughMetMaterialInfo(
std::unique_ptr<FbxRoughMetMaterialInfo> res(new FbxRoughMetMaterialInfo(
fbxMaterial->GetName(),
FbxRoughMetMaterialInfo::FBX_SHADER_METROUGH,
baseCol,
metalness,
roughness
)
);
roughness));
res->texBaseColor = baseTex;
res->baseWeight = baseWeight;
res->texBaseWeight = baseWeightMap;

View File

@ -11,21 +11,23 @@
#include "RoughnessMetallicMaterials.hpp"
#include "TraditionalMaterials.hpp"
FbxMaterialsAccess::FbxMaterialsAccess(const FbxMesh *pMesh, const std::map<const FbxTexture *, FbxString> &textureLocations) :
mappingMode(FbxGeometryElement::eNone),
mesh(nullptr),
indices(nullptr)
{
FbxMaterialsAccess::FbxMaterialsAccess(
const FbxMesh* pMesh,
const std::map<const FbxTexture*, FbxString>& textureLocations)
: mappingMode(FbxGeometryElement::eNone), mesh(nullptr), indices(nullptr) {
if (pMesh->GetElementMaterialCount() <= 0) {
return;
}
const FbxGeometryElement::EMappingMode materialMappingMode = pMesh->GetElementMaterial()->GetMappingMode();
if (materialMappingMode != FbxGeometryElement::eByPolygon && materialMappingMode != FbxGeometryElement::eAllSame) {
const FbxGeometryElement::EMappingMode materialMappingMode =
pMesh->GetElementMaterial()->GetMappingMode();
if (materialMappingMode != FbxGeometryElement::eByPolygon &&
materialMappingMode != FbxGeometryElement::eAllSame) {
return;
}
const FbxGeometryElement::EReferenceMode materialReferenceMode = pMesh->GetElementMaterial()->GetReferenceMode();
const FbxGeometryElement::EReferenceMode materialReferenceMode =
pMesh->GetElementMaterial()->GetReferenceMode();
if (materialReferenceMode != FbxGeometryElement::eIndexToDirect) {
return;
}
@ -45,16 +47,16 @@ FbxMaterialsAccess::FbxMaterialsAccess(const FbxMesh *pMesh, const std::map<cons
auto summary = summaries[materialNum];
if (summary == nullptr) {
summary = summaries[materialNum] = GetMaterialInfo(
mesh->GetNode()->GetSrcObject<FbxSurfaceMaterial>(materialNum),
textureLocations);
mesh->GetNode()->GetSrcObject<FbxSurfaceMaterial>(materialNum), textureLocations);
}
}
}
const std::shared_ptr<FbxMaterialInfo> FbxMaterialsAccess::GetMaterial(const int polygonIndex) const
{
const std::shared_ptr<FbxMaterialInfo> FbxMaterialsAccess::GetMaterial(
const int polygonIndex) const {
if (mappingMode != FbxGeometryElement::eNone) {
const int materialNum = indices->GetAt((mappingMode == FbxGeometryElement::eByPolygon) ? polygonIndex : 0);
const int materialNum =
indices->GetAt((mappingMode == FbxGeometryElement::eByPolygon) ? polygonIndex : 0);
if (materialNum < 0) {
return nullptr;
}
@ -63,10 +65,11 @@ const std::shared_ptr<FbxMaterialInfo> FbxMaterialsAccess::GetMaterial(const int
return nullptr;
}
std::unique_ptr<FbxMaterialInfo>
FbxMaterialsAccess::GetMaterialInfo(FbxSurfaceMaterial *material, const std::map<const FbxTexture *, FbxString> &textureLocations)
{
std::unique_ptr<FbxMaterialInfo> res = FbxStingrayPBSMaterialResolver(material, textureLocations).resolve();
std::unique_ptr<FbxMaterialInfo> FbxMaterialsAccess::GetMaterialInfo(
FbxSurfaceMaterial* material,
const std::map<const FbxTexture*, FbxString>& textureLocations) {
std::unique_ptr<FbxMaterialInfo> res =
FbxStingrayPBSMaterialResolver(material, textureLocations).resolve();
if (res == nullptr) {
res = Fbx3dsMaxPhysicalMaterialResolver(material, textureLocations).resolve();
if (res == nullptr) {
@ -75,4 +78,3 @@ FbxMaterialsAccess::GetMaterialInfo(FbxSurfaceMaterial *material, const std::map
}
return res;
}

View File

@ -17,24 +17,19 @@
class FbxMaterialInfo {
public:
FbxMaterialInfo(const FbxString& name, const FbxString& shadingModel)
: name(name)
, shadingModel(shadingModel)
{}
: name(name), shadingModel(shadingModel) {}
const FbxString name;
const FbxString shadingModel;
};
template <class T>
class FbxMaterialResolver
{
class FbxMaterialResolver {
public:
FbxMaterialResolver(
FbxSurfaceMaterial* fbxMaterial,
const std::map<const FbxTexture*, FbxString>& textureLocations)
: fbxMaterial(fbxMaterial)
, textureLocations(textureLocations)
{}
: fbxMaterial(fbxMaterial), textureLocations(textureLocations) {}
virtual std::unique_ptr<T> resolve() const = 0;
protected:
@ -42,15 +37,17 @@ protected:
const std::map<const FbxTexture*, FbxString> textureLocations;
};
class FbxMaterialsAccess
{
class FbxMaterialsAccess {
public:
FbxMaterialsAccess(const FbxMesh *pMesh, const std::map<const FbxTexture *, FbxString> &textureLocations);
FbxMaterialsAccess(
const FbxMesh* pMesh,
const std::map<const FbxTexture*, FbxString>& textureLocations);
const std::shared_ptr<FbxMaterialInfo> GetMaterial(const int polygonIndex) const;
std::unique_ptr<FbxMaterialInfo>
GetMaterialInfo(FbxSurfaceMaterial *material, const std::map<const FbxTexture *, FbxString> &textureLocations);
std::unique_ptr<FbxMaterialInfo> GetMaterialInfo(
FbxSurfaceMaterial* material,
const std::map<const FbxTexture*, FbxString>& textureLocations);
private:
FbxGeometryElement::EMappingMode mappingMode;

View File

@ -25,13 +25,11 @@ struct FbxRoughMetMaterialInfo : FbxMaterialInfo {
const FbxString& shadingModel,
FbxDouble4 baseColor,
FbxDouble metallic,
FbxDouble roughness
)
: FbxMaterialInfo(name, shadingModel)
, baseColor(baseColor)
, metallic(metallic)
, roughness(roughness)
{}
FbxDouble roughness)
: FbxMaterialInfo(name, shadingModel),
baseColor(baseColor),
metallic(metallic),
roughness(roughness) {}
const FbxVector4 baseColor;
const FbxDouble metallic;
@ -56,8 +54,7 @@ public:
FbxStingrayPBSMaterialResolver(
FbxSurfaceMaterial* fbxMaterial,
const std::map<const FbxTexture*, FbxString>& textureLocations)
: FbxMaterialResolver(fbxMaterial, textureLocations)
{}
: FbxMaterialResolver(fbxMaterial, textureLocations) {}
virtual std::unique_ptr<FbxRoughMetMaterialInfo> resolve() const;
};
@ -67,8 +64,7 @@ public:
Fbx3dsMaxPhysicalMaterialResolver(
FbxSurfaceMaterial* fbxMaterial,
const std::map<const FbxTexture*, FbxString>& textureLocations)
: FbxMaterialResolver(fbxMaterial, textureLocations)
{}
: FbxMaterialResolver(fbxMaterial, textureLocations) {}
virtual std::unique_ptr<FbxRoughMetMaterialInfo> resolve() const;

View File

@ -15,8 +15,10 @@ std::unique_ptr<FbxRoughMetMaterialInfo> FbxStingrayPBSMaterialResolver::resolve
return nullptr;
}
if (!fbxMaterial->ShadingModel.Get().IsEmpty()) {
::fmt::printf("Warning: Material %s has surprising shading model: %s\n",
fbxMaterial->GetName(), fbxMaterial->ShadingModel.Get());
::fmt::printf(
"Warning: Material %s has surprising shading model: %s\n",
fbxMaterial->GetName(),
fbxMaterial->ShadingModel.Get());
}
auto getTex = [&](std::string propName) {
@ -32,8 +34,10 @@ std::unique_ptr<FbxRoughMetMaterialInfo> FbxStingrayPBSMaterialResolver::resolve
}
}
} else if (verboseOutput && useProp.IsValid()) {
fmt::printf("Note: Property '%s' of Stingray PBS material '%s' exists, but is flagged as 'do not use'.\n",
propName, fbxMaterial->GetName());
fmt::printf(
"Note: Property '%s' of Stingray PBS material '%s' exists, but is flagged as 'do not use'.\n",
propName,
fbxMaterial->GetName());
}
return ptr;
};
@ -49,15 +53,12 @@ std::unique_ptr<FbxRoughMetMaterialInfo> FbxStingrayPBSMaterialResolver::resolve
};
FbxDouble3 baseColor = getVec("base_color");
std::unique_ptr<FbxRoughMetMaterialInfo> res(
new FbxRoughMetMaterialInfo(
std::unique_ptr<FbxRoughMetMaterialInfo> res(new FbxRoughMetMaterialInfo(
fbxMaterial->GetName(),
FbxRoughMetMaterialInfo::FBX_SHADER_METROUGH,
FbxDouble4(baseColor[0], baseColor[1], baseColor[2], 1),
getVal("metallic"),
getVal("roughness")
)
);
getVal("roughness")));
res->texNormal = getTex("normal");
res->texBaseColor = getTex("color");
res->texAmbientOcclusion = getTex("ao");

View File

@ -9,8 +9,7 @@
#include "TraditionalMaterials.hpp"
std::unique_ptr<FbxTraditionalMaterialInfo> FbxTraditionalMaterialResolver::resolve() const
{
std::unique_ptr<FbxTraditionalMaterialInfo> FbxTraditionalMaterialResolver::resolve() const {
auto getSurfaceScalar = [&](const char* propName) -> std::tuple<FbxDouble, FbxFileTexture*> {
const FbxProperty prop = fbxMaterial->FindProperty(propName);
@ -39,7 +38,9 @@ std::unique_ptr<FbxTraditionalMaterialInfo> FbxTraditionalMaterialResolver::reso
return std::make_tuple(val, tex);
};
auto getSurfaceValues = [&](const char *colName, const char *facName) -> std::tuple<FbxVector4, FbxFileTexture *, FbxFileTexture *> {
auto getSurfaceValues =
[&](const char* colName,
const char* facName) -> std::tuple<FbxVector4, FbxFileTexture*, FbxFileTexture*> {
const FbxProperty colProp = fbxMaterial->FindProperty(colName);
const FbxProperty facProp = fbxMaterial->FindProperty(facName);
@ -62,25 +63,29 @@ std::unique_ptr<FbxTraditionalMaterialInfo> FbxTraditionalMaterialResolver::reso
}
auto val = FbxVector4(
colorVal[0] * factorVal,
colorVal[1] * factorVal,
colorVal[2] * factorVal,
factorVal);
colorVal[0] * factorVal, colorVal[1] * factorVal, colorVal[2] * factorVal, factorVal);
return std::make_tuple(val, colTex, facTex);
};
std::string name = fbxMaterial->GetName();
std::unique_ptr<FbxTraditionalMaterialInfo> res(new FbxTraditionalMaterialInfo(name.c_str(), fbxMaterial->ShadingModel.Get()));
std::unique_ptr<FbxTraditionalMaterialInfo> res(
new FbxTraditionalMaterialInfo(name.c_str(), fbxMaterial->ShadingModel.Get()));
// four properties are on the same structure and follow the same rules
auto handleBasicProperty = [&](const char *colName, const char *facName) -> std::tuple<FbxVector4, FbxFileTexture *>{
auto handleBasicProperty = [&](const char* colName,
const char* facName) -> std::tuple<FbxVector4, FbxFileTexture*> {
FbxFileTexture *colTex, *facTex;
FbxVector4 vec;
std::tie(vec, colTex, facTex) = getSurfaceValues(colName, facName);
if (colTex) {
if (facTex) {
fmt::printf("Warning: Mat [%s]: Can't handle both %s and %s textures; discarding %s.\n", name, colName, facName, facName);
fmt::printf(
"Warning: Mat [%s]: Can't handle both %s and %s textures; discarding %s.\n",
name,
colName,
facName,
facName);
}
return std::make_tuple(vec, colTex);
}
@ -108,15 +113,22 @@ std::unique_ptr<FbxTraditionalMaterialInfo> FbxTraditionalMaterialResolver::reso
FbxVector4 transparency;
// extract any existing textures only so we can warn that we're throwing them away
FbxFileTexture *colTex, *facTex;
std::tie(transparency, colTex, facTex) =
getSurfaceValues(FbxSurfaceMaterial::sTransparentColor, FbxSurfaceMaterial::sTransparencyFactor);
std::tie(transparency, colTex, facTex) = getSurfaceValues(
FbxSurfaceMaterial::sTransparentColor, FbxSurfaceMaterial::sTransparencyFactor);
if (colTex) {
fmt::printf("Warning: Mat [%s]: Can't handle texture for %s; discarding.\n", name, FbxSurfaceMaterial::sTransparentColor);
fmt::printf(
"Warning: Mat [%s]: Can't handle texture for %s; discarding.\n",
name,
FbxSurfaceMaterial::sTransparentColor);
}
if (facTex) {
fmt::printf("Warning: Mat [%s]: Can't handle texture for %s; discarding.\n", name, FbxSurfaceMaterial::sTransparencyFactor);
fmt::printf(
"Warning: Mat [%s]: Can't handle texture for %s; discarding.\n",
name,
FbxSurfaceMaterial::sTransparencyFactor);
}
// FBX color is RGB, so we calculate the A channel as the average of the FBX transparency color vector
// FBX color is RGB, so we calculate the A channel as the average of the FBX transparency color
// vector
res->colDiffuse[3] = 1.0 - (transparency[0] + transparency[1] + transparency[2]) / 3.0;
return res;

View File

@ -15,8 +15,7 @@ struct FbxTraditionalMaterialInfo : FbxMaterialInfo {
static constexpr const char* FBX_SHADER_PHONG = "Phong";
FbxTraditionalMaterialInfo(const FbxString& name, const FbxString& shadingModel)
: FbxMaterialInfo(name, shadingModel)
{}
: FbxMaterialInfo(name, shadingModel) {}
FbxFileTexture* texAmbient{};
FbxVector4 colAmbient{};
@ -36,8 +35,7 @@ public:
FbxTraditionalMaterialResolver(
FbxSurfaceMaterial* fbxMaterial,
const std::map<const FbxTexture*, FbxString>& textureLocations)
: FbxMaterialResolver(fbxMaterial, textureLocations)
{}
: FbxMaterialResolver(fbxMaterial, textureLocations) {}
virtual std::unique_ptr<FbxTraditionalMaterialInfo> resolve() const;
};

View File

@ -9,8 +9,9 @@
#include "GltfModel.hpp"
std::shared_ptr<BufferViewData> GltfModel::GetAlignedBufferView(BufferData &buffer, const BufferViewData::GL_ArrayType target)
{
std::shared_ptr<BufferViewData> GltfModel::GetAlignedBufferView(
BufferData& buffer,
const BufferViewData::GL_ArrayType target) {
unsigned long bufferSize = this->binary->size();
if ((bufferSize % 4) > 0) {
bufferSize += (4 - (bufferSize % 4));
@ -20,8 +21,8 @@ std::shared_ptr<BufferViewData> GltfModel::GetAlignedBufferView(BufferData &buff
}
// add a bufferview on the fly and copy data into it
std::shared_ptr<BufferViewData> GltfModel::AddRawBufferView(BufferData &buffer, const char *source, uint32_t bytes)
{
std::shared_ptr<BufferViewData>
GltfModel::AddRawBufferView(BufferData& buffer, const char* source, uint32_t bytes) {
auto bufferView = GetAlignedBufferView(buffer, BufferViewData::GL_ARRAY_NONE);
bufferView->byteLength = bytes;
@ -34,8 +35,9 @@ std::shared_ptr<BufferViewData> GltfModel::AddRawBufferView(BufferData &buffer,
return bufferView;
}
std::shared_ptr<BufferViewData> GltfModel::AddBufferViewForFile(BufferData &buffer, const std::string &filename)
{
std::shared_ptr<BufferViewData> GltfModel::AddBufferViewForFile(
BufferData& buffer,
const std::string& filename) {
// see if we've already created a BufferViewData for this precise file
auto iter = filenameToBufferView.find(filename);
if (iter != filenameToBufferView.end()) {
@ -62,8 +64,7 @@ std::shared_ptr<BufferViewData> GltfModel::AddBufferViewForFile(BufferData &buff
return result;
}
void GltfModel::serializeHolders(json &glTFJson)
{
void GltfModel::serializeHolders(json& glTFJson) {
serializeHolder(glTFJson, "buffers", buffers);
serializeHolder(glTFJson, "bufferViews", bufferViews);
serializeHolder(glTFJson, "scenes", scenes);

View File

@ -30,21 +30,20 @@
#include "gltf/properties/TextureData.hpp"
/**
* glTF 2.0 is based on the idea that data structs within a file are referenced by index; an accessor will
* point to the n:th buffer view, and so on. The Holder class takes a freshly instantiated class, and then
* creates, stored, and returns a shared_ptr<T> for it.
* glTF 2.0 is based on the idea that data structs within a file are referenced by index; an
* accessor will point to the n:th buffer view, and so on. The Holder class takes a freshly
* instantiated class, and then creates, stored, and returns a shared_ptr<T> for it.
*
* The idea is that every glTF resource in the file will live as long as the Holder does, and the Holders
* are all kept in the GLTFData struct. Clients may certainly cnhoose to perpetuate the full shared_ptr<T>
* reference counting type, but generally speaking we pass around simple T& and T* types because the GLTFData
* struct will, by design, outlive all other activity that takes place during in a single conversion run.
* The idea is that every glTF resource in the file will live as long as the Holder does, and the
* Holders are all kept in the GLTFData struct. Clients may certainly cnhoose to perpetuate the full
* shared_ptr<T> reference counting type, but generally speaking we pass around simple T& and T*
* types because the GLTFData struct will, by design, outlive all other activity that takes place
* during in a single conversion run.
*/
template <typename T>
class Holder
{
class Holder {
public:
std::shared_ptr<T> hold(T *ptr)
{
std::shared_ptr<T> hold(T* ptr) {
ptr->ix = ptrs.size();
ptrs.emplace_back(ptr);
return ptrs.back();
@ -52,26 +51,31 @@ public:
std::vector<std::shared_ptr<T>> ptrs;
};
class GltfModel
{
class GltfModel {
public:
explicit GltfModel(const GltfOptions& options)
: binary(new std::vector<uint8_t>)
, isGlb(options.outputBinary)
, defaultSampler(nullptr)
, defaultBuffer(buffers.hold(buildDefaultBuffer(options)))
{
: binary(new std::vector<uint8_t>),
isGlb(options.outputBinary),
defaultSampler(nullptr),
defaultBuffer(buffers.hold(buildDefaultBuffer(options))) {
defaultSampler = samplers.hold(buildDefaultSampler());
}
std::shared_ptr<BufferViewData> GetAlignedBufferView(BufferData &buffer, const BufferViewData::GL_ArrayType target);
std::shared_ptr<BufferViewData> AddRawBufferView(BufferData &buffer, const char *source, uint32_t bytes);
std::shared_ptr<BufferViewData> AddBufferViewForFile(BufferData &buffer, const std::string &filename);
std::shared_ptr<BufferViewData> GetAlignedBufferView(
BufferData& buffer,
const BufferViewData::GL_ArrayType target);
std::shared_ptr<BufferViewData>
AddRawBufferView(BufferData& buffer, const char* source, uint32_t bytes);
std::shared_ptr<BufferViewData> AddBufferViewForFile(
BufferData& buffer,
const std::string& filename);
template <class T>
std::shared_ptr<AccessorData> AddAccessorWithView(
BufferViewData &bufferView, const GLType &type, const std::vector<T> &source, std::string name)
{
BufferViewData& bufferView,
const GLType& type,
const std::vector<T>& source,
std::string name) {
auto accessor = accessors.hold(new AccessorData(bufferView, type, name));
accessor->appendAsBinaryArray(source, *binary);
bufferView.byteLength = accessor->byteLength();
@ -79,26 +83,28 @@ public:
}
template <class T>
std::shared_ptr<AccessorData> AddAccessorAndView(
BufferData &buffer, const GLType &type, const std::vector<T> &source)
{
std::shared_ptr<AccessorData>
AddAccessorAndView(BufferData& buffer, const GLType& type, const std::vector<T>& source) {
auto bufferView = GetAlignedBufferView(buffer, BufferViewData::GL_ARRAY_NONE);
return AddAccessorWithView(*bufferView, type, source, std::string(""));
}
template <class T>
std::shared_ptr<AccessorData> AddAccessorAndView(
BufferData &buffer, const GLType &type, const std::vector<T> &source, std::string name)
{
BufferData& buffer,
const GLType& type,
const std::vector<T>& source,
std::string name) {
auto bufferView = GetAlignedBufferView(buffer, BufferViewData::GL_ARRAY_NONE);
return AddAccessorWithView(*bufferView, type, source, name);
}
template <class T>
std::shared_ptr<AccessorData> AddAttributeToPrimitive(
BufferData &buffer, const RawModel &surfaceModel, PrimitiveData &primitive,
const AttributeDefinition<T> &attrDef)
{
BufferData& buffer,
const RawModel& surfaceModel,
PrimitiveData& primitive,
const AttributeDefinition<T>& attrDef) {
// copy attribute data into vector
std::vector<T> attribArr;
surfaceModel.GetAttributeArray<T>(attribArr, attrDef.rawAttributeIx);
@ -118,8 +124,7 @@ public:
};
template <class T>
void serializeHolder(json &glTFJson, std::string key, const Holder<T> holder)
{
void serializeHolder(json& glTFJson, std::string key, const Holder<T> holder) {
if (!holder.ptrs.empty()) {
std::vector<json> bits;
for (const auto& ptr : holder.ptrs) {
@ -161,8 +166,7 @@ private:
return new SamplerData();
}
BufferData* buildDefaultBuffer(const GltfOptions& options) {
return options.outputBinary ?
new BufferData(binary) :
new BufferData(extBufferFilename, binary, options.embedResources);
return options.outputBinary ? new BufferData(binary)
: new BufferData(extBufferFilename, binary, options.embedResources);
}
};

View File

@ -9,17 +9,17 @@
#include "Raw2Gltf.hpp"
#include <cstdint>
#include <cassert>
#include <iostream>
#include <cstdint>
#include <fstream>
#include <iostream>
#include <stb_image.h>
#include <stb_image_write.h>
#include "utils/String_Utils.hpp"
#include "utils/Image_Utils.hpp"
#include <utils/File_Utils.hpp>
#include "utils/Image_Utils.hpp"
#include "utils/String_Utils.hpp"
#include "raw/RawModel.hpp"
@ -38,8 +38,8 @@
#include "gltf/properties/SkinData.hpp"
#include "gltf/properties/TextureData.hpp"
#include "TextureBuilder.hpp"
#include "GltfModel.hpp"
#include "TextureBuilder.hpp"
typedef uint32_t TriangleIndex;
@ -51,8 +51,7 @@ typedef uint32_t TriangleIndex;
* classes are guaranteed to stick around for the duration of the process.
*/
template <typename T>
T &require(std::map<std::string, std::shared_ptr<T>> map, const std::string &key)
{
T& require(std::map<std::string, std::shared_ptr<T>> map, const std::string& key) {
auto iter = map.find(key);
assert(iter != map.end());
T& result = *iter->second;
@ -60,16 +59,14 @@ T &require(std::map<std::string, std::shared_ptr<T>> map, const std::string &key
}
template <typename T>
T &require(std::map<long, std::shared_ptr<T>> map, long key)
{
T& require(std::map<long, std::shared_ptr<T>> map, long key) {
auto iter = map.find(key);
assert(iter != map.end());
T& result = *iter->second;
return result;
}
static const std::vector<TriangleIndex> getIndexArray(const RawModel &raw)
{
static const std::vector<TriangleIndex> getIndexArray(const RawModel& raw) {
std::vector<TriangleIndex> result;
for (int i = 0; i < raw.GetTriangleCount(); i++) {
@ -89,14 +86,14 @@ ModelData *Raw2Gltf(
std::ofstream& gltfOutStream,
const std::string& outputFolder,
const RawModel& raw,
const GltfOptions &options
)
{
const GltfOptions& options) {
if (verboseOutput) {
fmt::printf("Building render model...\n");
for (int i = 0; i < raw.GetMaterialCount(); i++) {
fmt::printf(
"Material %d: %s [shading: %s]\n", i, raw.GetMaterial(i).name.c_str(),
"Material %d: %s [shading: %s]\n",
i,
raw.GetMaterial(i).name.c_str(),
Describe(raw.GetMaterial(i).info->shadingModel));
}
if (raw.GetVertexCount() > 2 * raw.GetTriangleCount()) {
@ -130,7 +127,8 @@ ModelData *Raw2Gltf(
std::map<std::string, std::shared_ptr<TextureData>> textureByIndicesKey;
std::map<long, std::shared_ptr<MeshData>> meshBySurfaceId;
// for now, we only have one buffer; data->binary points to the same vector as that BufferData does.
// for now, we only have one buffer; data->binary points to the same vector as that BufferData
// does.
BufferData& buffer = *gltf->defaultBuffer;
{
//
@ -165,7 +163,8 @@ ModelData *Raw2Gltf(
const RawAnimation& animation = raw.GetAnimation(i);
if (animation.channels.size() == 0) {
fmt::printf("Warning: animation '%s' has zero channels. Skipping.\n", animation.name.c_str());
fmt::printf(
"Warning: animation '%s' has zero channels. Skipping.\n", animation.name.c_str());
continue;
}
@ -175,7 +174,10 @@ ModelData *Raw2Gltf(
AnimationData& aDat = *gltf->animations.hold(new AnimationData(animation.name, *accessor));
if (verboseOutput) {
fmt::printf("Animation '%s' has %lu channels:\n", animation.name.c_str(), animation.channels.size());
fmt::printf(
"Animation '%s' has %lu channels:\n",
animation.name.c_str(),
animation.channels.size());
}
for (size_t channelIx = 0; channelIx < animation.channels.size(); channelIx++) {
@ -185,22 +187,34 @@ ModelData *Raw2Gltf(
if (verboseOutput) {
fmt::printf(
" Channel %lu (%s) has translations/rotations/scales/weights: [%lu, %lu, %lu, %lu]\n",
channelIx, node.name.c_str(), channel.translations.size(), channel.rotations.size(),
channel.scales.size(), channel.weights.size());
channelIx,
node.name.c_str(),
channel.translations.size(),
channel.rotations.size(),
channel.scales.size(),
channel.weights.size());
}
NodeData& nDat = require(nodesById, node.id);
if (!channel.translations.empty()) {
aDat.AddNodeChannel(nDat, *gltf->AddAccessorAndView(buffer, GLT_VEC3F, channel.translations), "translation");
aDat.AddNodeChannel(
nDat,
*gltf->AddAccessorAndView(buffer, GLT_VEC3F, channel.translations),
"translation");
}
if (!channel.rotations.empty()) {
aDat.AddNodeChannel(nDat, *gltf->AddAccessorAndView(buffer, GLT_QUATF, channel.rotations), "rotation");
aDat.AddNodeChannel(
nDat, *gltf->AddAccessorAndView(buffer, GLT_QUATF, channel.rotations), "rotation");
}
if (!channel.scales.empty()) {
aDat.AddNodeChannel(nDat, *gltf->AddAccessorAndView(buffer, GLT_VEC3F, channel.scales), "scale");
aDat.AddNodeChannel(
nDat, *gltf->AddAccessorAndView(buffer, GLT_VEC3F, channel.scales), "scale");
}
if (!channel.weights.empty()) {
aDat.AddNodeChannel(nDat, *gltf->AddAccessorAndView(buffer, {CT_FLOAT, 1, "SCALAR"}, channel.weights), "weights");
aDat.AddNodeChannel(
nDat,
*gltf->AddAccessorAndView(buffer, {CT_FLOAT, 1, "SCALAR"}, channel.weights),
"weights");
}
}
}
@ -220,8 +234,7 @@ ModelData *Raw2Gltf(
for (int materialIndex = 0; materialIndex < raw.GetMaterialCount(); materialIndex++) {
const RawMaterial& material = raw.GetMaterial(materialIndex);
const bool isTransparent =
material.type == RAW_MATERIAL_TYPE_TRANSPARENT ||
const bool isTransparent = material.type == RAW_MATERIAL_TYPE_TRANSPARENT ||
material.type == RAW_MATERIAL_TYPE_SKINNED_TRANSPARENT;
Vec3f emissiveFactor;
@ -229,7 +242,9 @@ ModelData *Raw2Gltf(
// acquire the texture of a specific RawTextureUsage as *TextData, or nullptr if none exists
auto simpleTex = [&](RawTextureUsage usage) -> std::shared_ptr<TextureData> {
return (material.textures[usage] >= 0) ? textureBuilder.simple(material.textures[usage], "simple") : nullptr;
return (material.textures[usage] >= 0)
? textureBuilder.simple(material.textures[usage], "simple")
: nullptr;
};
TextureData* normalTexture = simpleTex(RAW_TEXTURE_USAGE_NORMAL).get();
@ -251,7 +266,8 @@ ModelData *Raw2Gltf(
* Other values translate directly.
*/
RawMetRoughMatProps* props = (RawMetRoughMatProps*)material.info.get();
// merge metallic into the blue channel and roughness into the green, of a new combinatory texture
// merge metallic into the blue channel and roughness into the green, of a new combinatory
// texture
aoMetRoughTex = textureBuilder.combine(
{
material.textures[RAW_TEXTURE_USAGE_OCCLUSION],
@ -270,7 +286,8 @@ ModelData *Raw2Gltf(
roughness = props->roughness;
emissiveFactor = props->emissiveFactor;
emissiveIntensity = props->emissiveIntensity;
// add the occlusion texture only if actual occlusion pixels exist in the aoNetRough texture.
// add the occlusion texture only if actual occlusion pixels exist in the aoNetRough
// texture.
if (material.textures[RAW_TEXTURE_USAGE_OCCLUSION] >= 0) {
occlusionTexture = aoMetRoughTex.get();
}
@ -284,8 +301,7 @@ ModelData *Raw2Gltf(
diffuseFactor = props->diffuseFactor;
if (material.info->shadingModel == RAW_SHADING_MODEL_BLINN ||
material.info->shadingModel == RAW_SHADING_MODEL_PHONG)
{
material.info->shadingModel == RAW_SHADING_MODEL_PHONG) {
// blinn/phong hardcoded to 0.4 metallic
metallic = 0.4f;
@ -295,15 +311,17 @@ ModelData *Raw2Gltf(
// shininess 6 -> roughness 0.5
// shininess 16 -> roughness ~0.33
// as shininess ==> oo, roughness ==> 0
auto getRoughness = [&](float shininess) {
return sqrtf(2.0f / (2.0f + shininess));
};
auto getRoughness = [&](float shininess) { return sqrtf(2.0f / (2.0f + shininess)); };
aoMetRoughTex = textureBuilder.combine(
{ material.textures[RAW_TEXTURE_USAGE_SHININESS], },
{
material.textures[RAW_TEXTURE_USAGE_SHININESS],
},
"ao_met_rough",
[&](const std::vector<const TextureBuilder::pixel *> pixels) -> TextureBuilder::pixel {
// do not multiply with props->shininess; that doesn't work like the other factors.
[&](const std::vector<const TextureBuilder::pixel*> pixels)
-> TextureBuilder::pixel {
// do not multiply with props->shininess; that doesn't work like the other
// factors.
float shininess = props->shininess * (*pixels[0])[0];
return {{0, getRoughness(shininess), metallic, 1}};
},
@ -327,7 +345,8 @@ ModelData *Raw2Gltf(
emissiveFactor = props->emissiveFactor;
emissiveIntensity = 1.0f;
}
pbrMetRough.reset(new PBRMetallicRoughness(baseColorTex.get(), aoMetRoughTex.get(), diffuseFactor, metallic, roughness));
pbrMetRough.reset(new PBRMetallicRoughness(
baseColorTex.get(), aoMetRoughTex.get(), diffuseFactor, metallic, roughness));
}
std::shared_ptr<KHRCmnUnlitMaterial> khrCmnUnlitMat;
@ -350,7 +369,8 @@ ModelData *Raw2Gltf(
baseColorTex = simpleTex(RAW_TEXTURE_USAGE_DIFFUSE);
}
pbrMetRough.reset(new PBRMetallicRoughness(baseColorTex.get(), nullptr, diffuseFactor, 0.0f, 1.0f));
pbrMetRough.reset(
new PBRMetallicRoughness(baseColorTex.get(), nullptr, diffuseFactor, 0.0f, 1.0f));
khrCmnUnlitMat.reset(new KHRCmnUnlitMaterial());
}
@ -358,11 +378,16 @@ ModelData *Raw2Gltf(
occlusionTexture = simpleTex(RAW_TEXTURE_USAGE_OCCLUSION).get();
}
std::shared_ptr<MaterialData> mData = gltf->materials.hold(
new MaterialData(
material.name, isTransparent, material.info->shadingModel,
normalTexture, occlusionTexture, emissiveTexture,
emissiveFactor * emissiveIntensity, khrCmnUnlitMat, pbrMetRough));
std::shared_ptr<MaterialData> mData = gltf->materials.hold(new MaterialData(
material.name,
isTransparent,
material.info->shadingModel,
normalTexture,
occlusionTexture,
emissiveTexture,
emissiveFactor * emissiveIntensity,
khrCmnUnlitMat,
pbrMetRough));
materialsByName[materialHash(material)] = mData;
if (options.enableUserProperties) {
@ -375,7 +400,8 @@ ModelData *Raw2Gltf(
const RawSurface& rawSurface = surfaceModel.GetSurface(0);
const long surfaceId = rawSurface.id;
const RawMaterial &rawMaterial = surfaceModel.GetMaterial(surfaceModel.GetTriangle(0).materialIndex);
const RawMaterial& rawMaterial =
surfaceModel.GetMaterial(surfaceModel.GetTriangle(0).materialIndex);
const MaterialData& mData = require(materialsByName, materialHash(rawMaterial));
MeshData* mesh = nullptr;
@ -393,10 +419,9 @@ ModelData *Raw2Gltf(
mesh = meshPtr.get();
}
bool useLongIndices =
(options.useLongIndices == UseLongIndicesOptions::ALWAYS)
|| (options.useLongIndices == UseLongIndicesOptions::AUTO
&& surfaceModel.GetVertexCount() > 65535);
bool useLongIndices = (options.useLongIndices == UseLongIndicesOptions::ALWAYS) ||
(options.useLongIndices == UseLongIndicesOptions::AUTO &&
surfaceModel.GetVertexCount() > 65535);
std::shared_ptr<PrimitiveData> primitive;
if (options.draco.enabled) {
@ -414,13 +439,16 @@ ModelData *Raw2Gltf(
dracoMesh->SetFace(draco::FaceIndex(ii), face);
}
AccessorData &indexes = *gltf->accessors.hold(new AccessorData(useLongIndices ? GLT_UINT : GLT_USHORT));
AccessorData& indexes =
*gltf->accessors.hold(new AccessorData(useLongIndices ? GLT_UINT : GLT_USHORT));
indexes.count = 3 * triangleCount;
primitive.reset(new PrimitiveData(indexes, mData, dracoMesh));
} else {
const AccessorData& indexes = *gltf->AddAccessorWithView(
*gltf->GetAlignedBufferView(buffer, BufferViewData::GL_ELEMENT_ARRAY_BUFFER),
useLongIndices ? GLT_UINT : GLT_USHORT, getIndexArray(surfaceModel), std::string(""));
useLongIndices ? GLT_UINT : GLT_USHORT,
getIndexArray(surfaceModel),
std::string(""));
primitive.reset(new PrimitiveData(indexes, mData));
};
@ -429,17 +457,25 @@ ModelData *Raw2Gltf(
//
{
if ((surfaceModel.GetVertexAttributes() & RAW_VERTEX_ATTRIBUTE_POSITION) != 0) {
const AttributeDefinition<Vec3f> ATTR_POSITION("POSITION", &RawVertex::position,
GLT_VEC3F, draco::GeometryAttribute::POSITION, draco::DT_FLOAT32);
auto accessor = gltf->AddAttributeToPrimitive<Vec3f>(
buffer, surfaceModel, *primitive, ATTR_POSITION);
const AttributeDefinition<Vec3f> ATTR_POSITION(
"POSITION",
&RawVertex::position,
GLT_VEC3F,
draco::GeometryAttribute::POSITION,
draco::DT_FLOAT32);
auto accessor =
gltf->AddAttributeToPrimitive<Vec3f>(buffer, surfaceModel, *primitive, ATTR_POSITION);
accessor->min = toStdVec(rawSurface.bounds.min);
accessor->max = toStdVec(rawSurface.bounds.max);
}
if ((surfaceModel.GetVertexAttributes() & RAW_VERTEX_ATTRIBUTE_NORMAL) != 0) {
const AttributeDefinition<Vec3f> ATTR_NORMAL("NORMAL", &RawVertex::normal,
GLT_VEC3F, draco::GeometryAttribute::NORMAL, draco::DT_FLOAT32);
const AttributeDefinition<Vec3f> ATTR_NORMAL(
"NORMAL",
&RawVertex::normal,
GLT_VEC3F,
draco::GeometryAttribute::NORMAL,
draco::DT_FLOAT32);
gltf->AddAttributeToPrimitive<Vec3f>(buffer, surfaceModel, *primitive, ATTR_NORMAL);
}
if ((surfaceModel.GetVertexAttributes() & RAW_VERTEX_ATTRIBUTE_TANGENT) != 0) {
@ -447,28 +483,48 @@ ModelData *Raw2Gltf(
gltf->AddAttributeToPrimitive<Vec4f>(buffer, surfaceModel, *primitive, ATTR_TANGENT);
}
if ((surfaceModel.GetVertexAttributes() & RAW_VERTEX_ATTRIBUTE_COLOR) != 0) {
const AttributeDefinition<Vec4f> ATTR_COLOR("COLOR_0", &RawVertex::color, GLT_VEC4F,
draco::GeometryAttribute::COLOR, draco::DT_FLOAT32);
const AttributeDefinition<Vec4f> ATTR_COLOR(
"COLOR_0",
&RawVertex::color,
GLT_VEC4F,
draco::GeometryAttribute::COLOR,
draco::DT_FLOAT32);
gltf->AddAttributeToPrimitive<Vec4f>(buffer, surfaceModel, *primitive, ATTR_COLOR);
}
if ((surfaceModel.GetVertexAttributes() & RAW_VERTEX_ATTRIBUTE_UV0) != 0) {
const AttributeDefinition<Vec2f> ATTR_TEXCOORD_0("TEXCOORD_0", &RawVertex::uv0,
GLT_VEC2F, draco::GeometryAttribute::TEX_COORD, draco::DT_FLOAT32);
const AttributeDefinition<Vec2f> ATTR_TEXCOORD_0(
"TEXCOORD_0",
&RawVertex::uv0,
GLT_VEC2F,
draco::GeometryAttribute::TEX_COORD,
draco::DT_FLOAT32);
gltf->AddAttributeToPrimitive<Vec2f>(buffer, surfaceModel, *primitive, ATTR_TEXCOORD_0);
}
if ((surfaceModel.GetVertexAttributes() & RAW_VERTEX_ATTRIBUTE_UV1) != 0) {
const AttributeDefinition<Vec2f> ATTR_TEXCOORD_1("TEXCOORD_1", &RawVertex::uv1,
GLT_VEC2F, draco::GeometryAttribute::TEX_COORD, draco::DT_FLOAT32);
const AttributeDefinition<Vec2f> ATTR_TEXCOORD_1(
"TEXCOORD_1",
&RawVertex::uv1,
GLT_VEC2F,
draco::GeometryAttribute::TEX_COORD,
draco::DT_FLOAT32);
gltf->AddAttributeToPrimitive<Vec2f>(buffer, surfaceModel, *primitive, ATTR_TEXCOORD_1);
}
if ((surfaceModel.GetVertexAttributes() & RAW_VERTEX_ATTRIBUTE_JOINT_INDICES) != 0) {
const AttributeDefinition<Vec4i> ATTR_JOINTS("JOINTS_0", &RawVertex::jointIndices,
GLT_VEC4I, draco::GeometryAttribute::GENERIC, draco::DT_UINT16);
const AttributeDefinition<Vec4i> ATTR_JOINTS(
"JOINTS_0",
&RawVertex::jointIndices,
GLT_VEC4I,
draco::GeometryAttribute::GENERIC,
draco::DT_UINT16);
gltf->AddAttributeToPrimitive<Vec4i>(buffer, surfaceModel, *primitive, ATTR_JOINTS);
}
if ((surfaceModel.GetVertexAttributes() & RAW_VERTEX_ATTRIBUTE_JOINT_WEIGHTS) != 0) {
const AttributeDefinition<Vec4f> ATTR_WEIGHTS("WEIGHTS_0", &RawVertex::jointWeights,
GLT_VEC4F, draco::GeometryAttribute::GENERIC, draco::DT_FLOAT32);
const AttributeDefinition<Vec4f> ATTR_WEIGHTS(
"WEIGHTS_0",
&RawVertex::jointWeights,
GLT_VEC4F,
draco::GeometryAttribute::GENERIC,
draco::DT_FLOAT32);
gltf->AddAttributeToPrimitive<Vec4f>(buffer, surfaceModel, *primitive, ATTR_WEIGHTS);
}
@ -494,7 +550,9 @@ ModelData *Raw2Gltf(
}
std::shared_ptr<AccessorData> pAcc = gltf->AddAccessorWithView(
*gltf->GetAlignedBufferView(buffer, BufferViewData::GL_ARRAY_BUFFER),
GLT_VEC3F, positions, channel.name);
GLT_VEC3F,
positions,
channel.name);
pAcc->min = toStdVec(shapeBounds.min);
pAcc->max = toStdVec(shapeBounds.max);
@ -502,14 +560,18 @@ ModelData *Raw2Gltf(
if (!normals.empty()) {
nAcc = gltf->AddAccessorWithView(
*gltf->GetAlignedBufferView(buffer, BufferViewData::GL_ARRAY_BUFFER),
GLT_VEC3F, normals, channel.name);
GLT_VEC3F,
normals,
channel.name);
}
std::shared_ptr<AccessorData> tAcc;
if (!tangents.empty()) {
nAcc = gltf->AddAccessorWithView(
*gltf->GetAlignedBufferView(buffer, BufferViewData::GL_ARRAY_BUFFER),
GLT_VEC4F, tangents, channel.name);
GLT_VEC4F,
tangents,
channel.name);
}
primitive->AddTarget(pAcc.get(), nAcc.get(), tAcc.get());
@ -524,19 +586,24 @@ ModelData *Raw2Gltf(
encoder.SetSpeedOptions(dracoSpeed, dracoSpeed);
}
if (options.draco.quantBitsPosition != -1) {
encoder.SetAttributeQuantization(draco::GeometryAttribute::POSITION, options.draco.quantBitsPosition);
encoder.SetAttributeQuantization(
draco::GeometryAttribute::POSITION, options.draco.quantBitsPosition);
}
if (options.draco.quantBitsTexCoord != -1) {
encoder.SetAttributeQuantization(draco::GeometryAttribute::TEX_COORD, options.draco.quantBitsTexCoord);
encoder.SetAttributeQuantization(
draco::GeometryAttribute::TEX_COORD, options.draco.quantBitsTexCoord);
}
if (options.draco.quantBitsNormal != -1) {
encoder.SetAttributeQuantization(draco::GeometryAttribute::NORMAL, options.draco.quantBitsNormal);
encoder.SetAttributeQuantization(
draco::GeometryAttribute::NORMAL, options.draco.quantBitsNormal);
}
if (options.draco.quantBitsColor != -1) {
encoder.SetAttributeQuantization(draco::GeometryAttribute::COLOR, options.draco.quantBitsColor);
encoder.SetAttributeQuantization(
draco::GeometryAttribute::COLOR, options.draco.quantBitsColor);
}
if (options.draco.quantBitsGeneric != -1) {
encoder.SetAttributeQuantization(draco::GeometryAttribute::GENERIC, options.draco.quantBitsGeneric);
encoder.SetAttributeQuantization(
draco::GeometryAttribute::GENERIC, options.draco.quantBitsGeneric);
}
draco::EncoderBuffer dracoBuffer;
@ -560,8 +627,7 @@ ModelData *Raw2Gltf(
//
// Assign mesh to node
//
if (node.surfaceId > 0)
{
if (node.surfaceId > 0) {
int surfaceIndex = raw.GetSurfaceById(node.surfaceId);
const RawSurface& rawSurface = raw.GetSurface(surfaceIndex);
@ -675,16 +741,31 @@ ModelData *Raw2Gltf(
if (options.outputBinary) {
// note: glTF binary is little-endian
const char glbHeader[] = {
'g', 'l', 'T', 'F', // magic
0x02, 0x00, 0x00, 0x00, // version
0x00, 0x00, 0x00, 0x00, // total length: written in later
'g',
'l',
'T',
'F', // magic
0x02,
0x00,
0x00,
0x00, // version
0x00,
0x00,
0x00,
0x00, // total length: written in later
};
gltfOutStream.write(glbHeader, 12);
// binary glTF 2.0 has a sub-header for each of the JSON and BIN chunks
const char glb2JsonHeader[] = {
0x00, 0x00, 0x00, 0x00, // chunk length: written in later
'J', 'S', 'O', 'N', // chunk type: 0x4E4F534A aka JSON
0x00,
0x00,
0x00,
0x00, // chunk length: written in later
'J',
'S',
'O',
'N', // chunk type: 0x4E4F534A aka JSON
};
gltfOutStream.write(glb2JsonHeader, 8);
}
@ -702,12 +783,8 @@ ModelData *Raw2Gltf(
extensionsRequired.push_back(KHR_DRACO_MESH_COMPRESSION);
}
json glTFJson {
{ "asset", {
{ "generator", "FBX2glTF v" + FBX2GLTF_VERSION },
{ "version", "2.0" }}},
{ "scene", rootScene.ix }
};
json glTFJson{{"asset", {{"generator", "FBX2glTF v" + FBX2GLTF_VERSION}, {"version", "2.0"}}},
{"scene", rootScene.ix}};
if (!extensionsUsed.empty()) {
glTFJson["extensionsUsed"] = extensionsUsed;
}
@ -730,8 +807,14 @@ ModelData *Raw2Gltf(
uint32_t binHeader = (uint32_t)gltfOutStream.tellp();
// binary glTF 2.0 has a sub-header for each of the JSON and BIN chunks
const char glb2BinaryHeader[] = {
0x00, 0x00, 0x00, 0x00, // chunk length: written in later
'B', 'I', 'N', 0x00, // chunk type: 0x004E4942 aka BIN
0x00,
0x00,
0x00,
0x00, // chunk length: written in later
'B',
'I',
'N',
0x00, // chunk type: 0x004E4942 aka BIN
};
gltfOutStream.write(glb2BinaryHeader, 8);

View File

@ -27,8 +27,7 @@ const std::string extBufferFilename = "buffer.bin";
struct ComponentType {
// OpenGL Datatype enums
enum GL_DataType
{
enum GL_DataType {
GL_BYTE = 5120,
GL_UNSIGNED_BYTE,
GL_SHORT,
@ -49,14 +48,15 @@ const ComponentType CT_FLOAT = {ComponentType::GL_FLOAT, 4};
// Map our low-level data types for glTF output
struct GLType {
GLType(const ComponentType& componentType, unsigned int count, const std::string dataType)
: componentType(componentType),
count(count),
dataType(dataType)
{}
: componentType(componentType), count(count), dataType(dataType) {}
unsigned int byteStride() const { return componentType.size * count; }
unsigned int byteStride() const {
return componentType.size * count;
}
void write(uint8_t *buf, const float scalar) const { *((float *) buf) = scalar; }
void write(uint8_t* buf, const float scalar) const {
*((float*)buf) = scalar;
}
void write(uint8_t* buf, const uint32_t scalar) const {
switch (componentType.size) {
case 1:
@ -119,16 +119,14 @@ const GLType GLT_QUATF = {CT_FLOAT, 4, "VEC4"};
/**
* The base of any indexed glTF entity.
*/
struct Holdable
{
struct Holdable {
uint32_t ix;
virtual json serialize() const = 0;
};
template <class T>
struct AttributeDefinition
{
struct AttributeDefinition {
const std::string gltfName;
const T RawVertex::*rawAttributeIx;
const GLType glType;
@ -136,8 +134,11 @@ struct AttributeDefinition
const draco::DataType dracoComponentType;
AttributeDefinition(
const std::string gltfName, const T RawVertex::*rawAttributeIx, const GLType &_glType,
const draco::GeometryAttribute::Type dracoAttribute, const draco::DataType dracoComponentType)
const std::string gltfName,
const T RawVertex::*rawAttributeIx,
const GLType& _glType,
const draco::GeometryAttribute::Type dracoAttribute,
const draco::DataType dracoComponentType)
: gltfName(gltfName),
rawAttributeIx(rawAttributeIx),
glType(_glType),
@ -145,7 +146,9 @@ struct AttributeDefinition
dracoComponentType(dracoComponentType) {}
AttributeDefinition(
const std::string gltfName, const T RawVertex::*rawAttributeIx, const GLType &_glType)
const std::string gltfName,
const T RawVertex::*rawAttributeIx,
const GLType& _glType)
: gltfName(gltfName),
rawAttributeIx(rawAttributeIx),
glType(_glType),
@ -169,12 +172,9 @@ struct SceneData;
struct SkinData;
struct TextureData;
struct ModelData
{
struct ModelData {
explicit ModelData(std::shared_ptr<const std::vector<uint8_t>> const& _binary)
: binary(_binary)
{
}
: binary(_binary) {}
std::shared_ptr<const std::vector<uint8_t>> const binary;
};
@ -183,5 +183,4 @@ ModelData *Raw2Gltf(
std::ofstream& gltfOutStream,
const std::string& outputFolder,
const RawModel& raw,
const GltfOptions &options
);
const GltfOptions& options);

View File

@ -12,9 +12,9 @@
#include <stb_image.h>
#include <stb_image_write.h>
#include <utils/File_Utils.hpp>
#include <utils/Image_Utils.hpp>
#include <utils/String_Utils.hpp>
#include <utils/File_Utils.hpp>
#include <gltf/properties/ImageData.hpp>
#include <gltf/properties/TextureData.hpp>
@ -34,8 +34,7 @@ std::shared_ptr<TextureData> TextureBuilder::combine(
const std::vector<int>& ixVec,
const std::string& tag,
const pixel_merger& computePixel,
bool includeAlphaChannel)
{
bool includeAlphaChannel) {
const std::string key = texIndicesKey(ixVec, tag);
auto iter = textureByIndicesKey.find(key);
if (iter != textureByIndicesKey.end()) {
@ -50,21 +49,24 @@ std::shared_ptr<TextureData> TextureBuilder::combine(
if (rawTexIx >= 0) {
const RawTexture& rawTex = raw.GetTexture(rawTexIx);
const std::string& fileLoc = rawTex.fileLocation;
const std::string &name = StringUtils::GetFileBaseString(StringUtils::GetFileNameString(fileLoc));
const std::string& name =
StringUtils::GetFileBaseString(StringUtils::GetFileNameString(fileLoc));
if (!fileLoc.empty()) {
info.pixels = stbi_load(fileLoc.c_str(), &info.width, &info.height, &info.channels, 0);
if (!info.pixels) {
fmt::printf("Warning: merge texture [%d](%s) could not be loaded.\n",
rawTexIx,
name);
fmt::printf("Warning: merge texture [%d](%s) could not be loaded.\n", rawTexIx, name);
} else {
if (width < 0) {
width = info.width;
height = info.height;
} else if (width != info.width || height != info.height) {
fmt::printf("Warning: texture %s (%d, %d) can't be merged with previous texture(s) of dimension (%d, %d)\n",
fmt::printf(
"Warning: texture %s (%d, %d) can't be merged with previous texture(s) of dimension (%d, %d)\n",
name,
info.width, info.height, width, height);
info.width,
info.height,
width,
height);
// this is bad enough that we abort the whole merge
return nullptr;
}
@ -121,11 +123,17 @@ std::shared_ptr<TextureData> TextureBuilder::combine(
std::vector<char> imgBuffer;
int res;
if (png) {
res = stbi_write_png_to_func(WriteToVectorContext, &imgBuffer,
width, height, channels, mergedPixels.data(), width * channels);
res = stbi_write_png_to_func(
WriteToVectorContext,
&imgBuffer,
width,
height,
channels,
mergedPixels.data(),
width * channels);
} else {
res = stbi_write_jpg_to_func(WriteToVectorContext, &imgBuffer,
width, height, channels, mergedPixels.data(), 80);
res = stbi_write_jpg_to_func(
WriteToVectorContext, &imgBuffer, width, height, channels, mergedPixels.data(), 80);
}
if (!res) {
fmt::printf("Warning: failed to generate merge texture '%s'.\n", mergedFilename);
@ -134,7 +142,8 @@ std::shared_ptr<TextureData> TextureBuilder::combine(
ImageData* image;
if (options.outputBinary) {
const auto bufferView = gltf.AddRawBufferView(*gltf.defaultBuffer, imgBuffer.data(), imgBuffer.size());
const auto bufferView =
gltf.AddRawBufferView(*gltf.defaultBuffer, imgBuffer.data(), imgBuffer.size());
image = new ImageData(mergedName, *bufferView, png ? "image/png" : "image/jpeg");
} else {
const std::string imageFilename = mergedFilename + (png ? ".png" : ".jpg");
@ -146,7 +155,8 @@ std::shared_ptr<TextureData> TextureBuilder::combine(
}
if (fwrite(imgBuffer.data(), imgBuffer.size(), 1, fp) != 1) {
fmt::printf("Warning: Failed to write %lu bytes to file '%s'.\n", imgBuffer.size(), imagePath);
fmt::printf(
"Warning: Failed to write %lu bytes to file '%s'.\n", imgBuffer.size(), imagePath);
fclose(fp);
return nullptr;
}
@ -185,8 +195,7 @@ std::shared_ptr<TextureData> TextureBuilder::simple(int rawTexIndex, const std::
} else if (!relativeFilename.empty()) {
image = new ImageData(relativeFilename, relativeFilename);
std::string outputPath = outputFolder + StringUtils::NormalizePath(relativeFilename);
if (FileUtils::CopyFile(rawTexture.fileLocation, outputPath, true))
{
if (FileUtils::CopyFile(rawTexture.fileLocation, outputPath, true)) {
if (verboseOutput) {
fmt::printf("Copied texture '%s' to output folder: %s\n", textureName, outputPath);
}
@ -200,13 +209,11 @@ std::shared_ptr<TextureData> TextureBuilder::simple(int rawTexIndex, const std::
// fallback is tiny transparent PNG
image = new ImageData(
textureName,
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg=="
);
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==");
}
std::shared_ptr<TextureData> texDat = gltf.textures.hold(
new TextureData(textureName, *gltf.defaultSampler, *gltf.images.hold(image)));
textureByIndicesKey.insert(std::make_pair(key, texDat));
return texDat;
}

View File

@ -17,26 +17,24 @@
#include "GltfModel.hpp"
class TextureBuilder
{
class TextureBuilder {
public:
using pixel = std::array<float, 4>; // pixel components are floats in [0, 1]
using pixel_merger = std::function<pixel(const std::vector<const pixel*>)>;
TextureBuilder(const RawModel &raw, const GltfOptions &options, const std::string &outputFolder, GltfModel &gltf)
: raw(raw)
, options(options)
, outputFolder(outputFolder)
, gltf(gltf)
{}
TextureBuilder(
const RawModel& raw,
const GltfOptions& options,
const std::string& outputFolder,
GltfModel& gltf)
: raw(raw), options(options), outputFolder(outputFolder), gltf(gltf) {}
~TextureBuilder() {}
std::shared_ptr<TextureData> combine(
const std::vector<int>& ixVec,
const std::string& tag,
const pixel_merger& mergeFunction,
bool transparency
);
bool transparency);
std::shared_ptr<TextureData> simple(int rawTexIndex, const std::string& tag);
@ -50,10 +48,14 @@ public:
static std::string describeChannel(int channels) {
switch (channels) {
case 1: return "G";
case 2: return "GA";
case 3: return "RGB";
case 4: return "RGBA";
case 1:
return "G";
case 2:
return "GA";
case 3:
return "RGB";
case 4:
return "RGBA";
default:
return fmt::format("?%d?", channels);
}

View File

@ -16,26 +16,14 @@ AccessorData::AccessorData(const BufferViewData &bufferView, GLType type, std::s
type(std::move(type)),
byteOffset(0),
count(0),
name(name)
{
}
name(name) {}
AccessorData::AccessorData(GLType type)
: Holdable(),
bufferView(-1),
type(std::move(type)),
byteOffset(0),
count(0)
{
}
: Holdable(), bufferView(-1), type(std::move(type)), byteOffset(0), count(0) {}
json AccessorData::serialize() const
{
json AccessorData::serialize() const {
json result{
{ "componentType", type.componentType.glType },
{ "type", type.dataType },
{ "count", count }
};
{"componentType", type.componentType.glType}, {"type", type.dataType}, {"count", count}};
if (bufferView >= 0) {
result["bufferView"] = bufferView;
result["byteOffset"] = byteOffset;

View File

@ -11,16 +11,14 @@
#include "gltf/Raw2Gltf.hpp"
struct AccessorData : Holdable
{
struct AccessorData : Holdable {
AccessorData(const BufferViewData& bufferView, GLType type, std::string name);
explicit AccessorData(GLType type);
json serialize() const override;
template <class T>
void appendAsBinaryArray(const std::vector<T> &in, std::vector<uint8_t> &out)
{
void appendAsBinaryArray(const std::vector<T>& in, std::vector<uint8_t>& out) {
const unsigned int stride = type.byteStride();
const size_t offset = out.size();
const size_t count = in.size();
@ -33,7 +31,9 @@ struct AccessorData : Holdable
}
}
unsigned int byteLength() const { return type.byteStride() * count; }
unsigned int byteLength() const {
return type.byteStride() * count;
}
const int bufferView;
const GLType type;

View File

@ -15,50 +15,35 @@
#include "NodeData.hpp"
AnimationData::AnimationData(std::string name, const AccessorData& timeAccessor)
: Holdable(),
name(std::move(name)),
timeAccessor(timeAccessor.ix) {}
: Holdable(), name(std::move(name)), timeAccessor(timeAccessor.ix) {}
// assumption: 1-to-1 relationship between channels and samplers; this is a simplification on what
// glTF can express, but it means we can rely on samplerIx == channelIx throughout an animation
void AnimationData::AddNodeChannel(const NodeData &node, const AccessorData &accessor, std::string path)
{
void AnimationData::AddNodeChannel(
const NodeData& node,
const AccessorData& accessor,
std::string path) {
assert(channels.size() == samplers.size());
uint32_t ix = channels.size();
channels.emplace_back(channel_t(ix, node, std::move(path)));
samplers.emplace_back(sampler_t(timeAccessor, accessor.ix));
}
json AnimationData::serialize() const
{
return {
{ "name", name },
{ "channels", channels },
{ "samplers", samplers }
};
json AnimationData::serialize() const {
return {{"name", name}, {"channels", channels}, {"samplers", samplers}};
}
AnimationData::channel_t::channel_t(uint32_t ix, const NodeData& node, std::string path)
: ix(ix),
node(node.ix),
path(std::move(path))
{
}
: ix(ix), node(node.ix), path(std::move(path)) {}
AnimationData::sampler_t::sampler_t(uint32_t time, uint32_t output)
: time(time),
output(output)
{
}
AnimationData::sampler_t::sampler_t(uint32_t time, uint32_t output) : time(time), output(output) {}
void to_json(json& j, const AnimationData::channel_t& data) {
j = json {
{ "sampler", data.ix },
{ "target", {
{ "node", data.node },
{ "path", data.path }},
}
};
j = json{{"sampler", data.ix},
{
"target",
{{"node", data.node}, {"path", data.path}},
}};
}
void to_json(json& j, const AnimationData::sampler_t& data) {

View File

@ -11,8 +11,7 @@
#include "gltf/Raw2Gltf.hpp"
struct AnimationData : Holdable
{
struct AnimationData : Holdable {
AnimationData(std::string name, const AccessorData& timeAccessor);
// assumption: 1-to-1 relationship between channels and samplers; this is a simplification on what
@ -21,8 +20,7 @@ struct AnimationData : Holdable
json serialize() const override;
struct channel_t
{
struct channel_t {
channel_t(uint32_t _ix, const NodeData& node, std::string path);
const uint32_t ix;
@ -30,8 +28,7 @@ struct AnimationData : Holdable
const std::string path;
};
struct sampler_t
{
struct sampler_t {
sampler_t(uint32_t time, uint32_t output);
const uint32_t time;

View File

@ -12,25 +12,16 @@
#include "BufferData.hpp"
BufferData::BufferData(const std::shared_ptr<const std::vector<uint8_t>>& binData)
: Holdable(),
isGlb(true),
binData(binData)
{
}
: Holdable(), isGlb(true), binData(binData) {}
BufferData::BufferData(std::string uri, const std::shared_ptr<const std::vector<uint8_t> > &binData, bool isEmbedded)
: Holdable(),
isGlb(false),
uri(isEmbedded ? "" : std::move(uri)),
binData(binData)
{
}
BufferData::BufferData(
std::string uri,
const std::shared_ptr<const std::vector<uint8_t>>& binData,
bool isEmbedded)
: Holdable(), isGlb(false), uri(isEmbedded ? "" : std::move(uri)), binData(binData) {}
json BufferData::serialize() const
{
json result{
{"byteLength", binData->size()}
};
json BufferData::serialize() const {
json result{{"byteLength", binData->size()}};
if (!isGlb) {
if (!uri.empty()) {
result["uri"] = uri;

View File

@ -11,11 +11,13 @@
#include "gltf/Raw2Gltf.hpp"
struct BufferData : Holdable
{
struct BufferData : Holdable {
explicit BufferData(const std::shared_ptr<const std::vector<uint8_t>>& binData);
BufferData(std::string uri, const std::shared_ptr<const std::vector<uint8_t> > &binData, bool isEmbedded = false);
BufferData(
std::string uri,
const std::shared_ptr<const std::vector<uint8_t>>& binData,
bool isEmbedded = false);
json serialize() const override;

View File

@ -10,21 +10,14 @@
#include "BufferViewData.hpp"
#include "BufferData.hpp"
BufferViewData::BufferViewData(const BufferData &_buffer, const size_t _byteOffset, const GL_ArrayType _target)
: Holdable(),
buffer(_buffer.ix),
byteOffset((unsigned int) _byteOffset),
target(_target)
{
}
BufferViewData::BufferViewData(
const BufferData& _buffer,
const size_t _byteOffset,
const GL_ArrayType _target)
: Holdable(), buffer(_buffer.ix), byteOffset((unsigned int)_byteOffset), target(_target) {}
json BufferViewData::serialize() const
{
json result {
{ "buffer", buffer },
{ "byteLength", byteLength },
{ "byteOffset", byteOffset }
};
json BufferViewData::serialize() const {
json result{{"buffer", buffer}, {"byteLength", byteLength}, {"byteOffset", byteOffset}};
if (target != GL_ARRAY_NONE) {
result["target"] = target;
}

View File

@ -11,10 +11,8 @@
#include "gltf/Raw2Gltf.hpp"
struct BufferViewData : Holdable
{
enum GL_ArrayType
{
struct BufferViewData : Holdable {
enum GL_ArrayType {
GL_ARRAY_NONE = 0, // no GL buffer is being set
GL_ARRAY_BUFFER = 34962,
GL_ELEMENT_ARRAY_BUFFER = 34963

View File

@ -10,26 +10,14 @@
#include "CameraData.hpp"
CameraData::CameraData()
: Holdable(),
aspectRatio(0.0f),
yfov(0.0f),
xmag(0.0f),
ymag(0.0f),
znear(0.0f),
zfar(0.0f)
{
}
: Holdable(), aspectRatio(0.0f), yfov(0.0f), xmag(0.0f), ymag(0.0f), znear(0.0f), zfar(0.0f) {}
json CameraData::serialize() const
{
json CameraData::serialize() const {
json result{
{"name", name},
{"type", type},
};
json subResult {
{ "znear", znear },
{ "zfar", zfar }
};
json subResult{{"znear", znear}, {"zfar", zfar}};
if (type == "perspective") {
subResult["aspectRatio"] = aspectRatio;
subResult["yfov"] = yfov;

View File

@ -12,8 +12,7 @@
#include "gltf/Raw2Gltf.hpp"
// TODO: this class needs some work
struct CameraData : Holdable
{
struct CameraData : Holdable {
CameraData();
json serialize() const override;

View File

@ -14,32 +14,14 @@
#include "BufferViewData.hpp"
ImageData::ImageData(std::string name, std::string uri)
: Holdable(),
name(std::move(name)),
uri(std::move(uri)),
bufferView(-1)
{
}
: Holdable(), name(std::move(name)), uri(std::move(uri)), bufferView(-1) {}
ImageData::ImageData(std::string name, const BufferViewData& bufferView, std::string mimeType)
: Holdable(),
name(std::move(name)),
bufferView(bufferView.ix),
mimeType(std::move(mimeType))
{
}
: Holdable(), name(std::move(name)), bufferView(bufferView.ix), mimeType(std::move(mimeType)) {}
json ImageData::serialize() const
{
json ImageData::serialize() const {
if (bufferView < 0) {
return {
{ "name", name },
{ "uri", uri }
};
return {{"name", name}, {"uri", uri}};
}
return {
{ "name", name },
{ "bufferView", bufferView },
{ "mimeType", mimeType }
};
return {{"name", name}, {"bufferView", bufferView}, {"mimeType", mimeType}};
}

View File

@ -11,8 +11,7 @@
#include "gltf/Raw2Gltf.hpp"
struct ImageData : Holdable
{
struct ImageData : Holdable {
ImageData(std::string name, std::string uri);
ImageData(std::string name, const BufferViewData& bufferView, std::string mimeType);

View File

@ -10,24 +10,21 @@
#include "LightData.hpp"
LightData::LightData(
std::string name, Type type, Vec3f color, float intensity,
float innerConeAngle, float outerConeAngle)
std::string name,
Type type,
Vec3f color,
float intensity,
float innerConeAngle,
float outerConeAngle)
: Holdable(),
type(type),
color(color),
intensity(intensity),
innerConeAngle(innerConeAngle),
outerConeAngle(outerConeAngle)
{
}
outerConeAngle(outerConeAngle) {}
json LightData::serialize() const
{
json result {
{ "name", name },
{ "color", toStdVec(color) },
{ "intensity", intensity }
};
json LightData::serialize() const {
json result{{"name", name}, {"color", toStdVec(color)}, {"intensity", intensity}};
switch (type) {
case Directional:
result["type"] = "directional";

View File

@ -11,16 +11,20 @@
#include "gltf/Raw2Gltf.hpp"
struct LightData : Holdable
{
struct LightData : Holdable {
enum Type {
Directional,
Point,
Spot,
};
LightData(std::string name, Type type, Vec3f color, float intensity,
float innerConeAngle, float outerConeAngle);
LightData(
std::string name,
Type type,
Vec3f color,
float intensity,
float innerConeAngle,
float outerConeAngle);
json serialize() const override;

View File

@ -11,54 +11,47 @@
#include "TextureData.hpp"
// TODO: retrieve & pass in correct UV set from FBX
std::unique_ptr<Tex> Tex::ref(const TextureData *tex, uint32_t texCoord)
{
std::unique_ptr<Tex> Tex::ref(const TextureData* tex, uint32_t texCoord) {
return std::unique_ptr<Tex>{(tex != nullptr) ? new Tex(tex->ix, texCoord) : nullptr};
}
Tex::Tex(uint32_t texRef, uint32_t texCoord)
: texRef(texRef),
texCoord(texCoord) {}
Tex::Tex(uint32_t texRef, uint32_t texCoord) : texRef(texRef), texCoord(texCoord) {}
void to_json(json& j, const Tex& data) {
j = json {
{ "index", data.texRef },
{ "texCoord", data.texCoord }
};
j = json{{"index", data.texRef}, {"texCoord", data.texCoord}};
}
KHRCmnUnlitMaterial::KHRCmnUnlitMaterial()
{
}
KHRCmnUnlitMaterial::KHRCmnUnlitMaterial() {}
void to_json(json &j, const KHRCmnUnlitMaterial &d)
{
void to_json(json& j, const KHRCmnUnlitMaterial& d) {
j = json({});
}
inline float clamp(float d, float bottom = 0, float top = 1) {
return std::max(bottom, std::min(top, d));
}
inline Vec3f clamp(const Vec3f &vec, const Vec3f &bottom = VEC3F_ZERO, const Vec3f &top = VEC3F_ONE) {
inline Vec3f
clamp(const Vec3f& vec, const Vec3f& bottom = VEC3F_ZERO, const Vec3f& top = VEC3F_ONE) {
return Vec3f::Max(bottom, Vec3f::Min(top, vec));
}
inline Vec4f clamp(const Vec4f &vec, const Vec4f &bottom = VEC4F_ZERO, const Vec4f &top = VEC4F_ONE) {
inline Vec4f
clamp(const Vec4f& vec, const Vec4f& bottom = VEC4F_ZERO, const Vec4f& top = VEC4F_ONE) {
return Vec4f::Max(bottom, Vec4f::Min(top, vec));
}
PBRMetallicRoughness::PBRMetallicRoughness(
const TextureData *baseColorTexture, const TextureData *metRoughTexture,
const Vec4f &baseColorFactor, float metallic, float roughness)
const TextureData* baseColorTexture,
const TextureData* metRoughTexture,
const Vec4f& baseColorFactor,
float metallic,
float roughness)
: baseColorTexture(Tex::ref(baseColorTexture)),
metRoughTexture(Tex::ref(metRoughTexture)),
baseColorFactor(clamp(baseColorFactor)),
metallic(clamp(metallic)),
roughness(clamp(roughness))
{
}
roughness(clamp(roughness)) {}
void to_json(json &j, const PBRMetallicRoughness &d)
{
void to_json(json& j, const PBRMetallicRoughness& d) {
j = {};
if (d.baseColorTexture != nullptr) {
j["baseColorTexture"] = *d.baseColorTexture;
@ -79,9 +72,13 @@ void to_json(json &j, const PBRMetallicRoughness &d)
}
MaterialData::MaterialData(
std::string name, bool isTransparent, const RawShadingModel shadingModel,
const TextureData *normalTexture, const TextureData *occlusionTexture,
const TextureData *emissiveTexture, const Vec3f & emissiveFactor,
std::string name,
bool isTransparent,
const RawShadingModel shadingModel,
const TextureData* normalTexture,
const TextureData* occlusionTexture,
const TextureData* emissiveTexture,
const Vec3f& emissiveFactor,
std::shared_ptr<KHRCmnUnlitMaterial> const khrCmnConstantMaterial,
std::shared_ptr<PBRMetallicRoughness> const pbrMetallicRoughness)
: Holdable(),
@ -95,18 +92,13 @@ MaterialData::MaterialData(
khrCmnConstantMaterial(khrCmnConstantMaterial),
pbrMetallicRoughness(pbrMetallicRoughness) {}
json MaterialData::serialize() const
{
json result = {
{ "name", name },
json MaterialData::serialize() const {
json result = {{"name", name},
{"alphaMode", isTransparent ? "BLEND" : "OPAQUE"},
{ "extras", {
{ "fromFBX", {
{ "shadingModel", Describe(shadingModel) },
{ "isTruePBR", shadingModel == RAW_SHADING_MODEL_PBR_MET_ROUGH }
}}
}}
};
{"extras",
{{"fromFBX",
{{"shadingModel", Describe(shadingModel)},
{"isTruePBR", shadingModel == RAW_SHADING_MODEL_PBR_MET_ROUGH}}}}}};
if (normalTexture != nullptr) {
result["normalTexture"] = *normalTexture;
@ -129,13 +121,11 @@ json MaterialData::serialize() const
result["extensions"] = extensions;
}
for (const auto& i : userProperties)
{
for (const auto& i : userProperties) {
auto& prop_map = result["extras"]["fromFBX"]["userProperties"];
json j = json::parse(i);
for (const auto& k : json::iterator_wrapper(j))
{
for (const auto& k : json::iterator_wrapper(j)) {
prop_map[k.key()] = k.value();
}
}

View File

@ -13,8 +13,7 @@
#include "gltf/Raw2Gltf.hpp"
struct Tex
{
struct Tex {
static std::unique_ptr<Tex> ref(const TextureData* tex, uint32_t texCoord = 0);
explicit Tex(uint32_t texRef, uint32_t texCoord);
@ -22,16 +21,17 @@ struct Tex
const uint32_t texCoord;
};
struct KHRCmnUnlitMaterial
{
struct KHRCmnUnlitMaterial {
KHRCmnUnlitMaterial();
};
struct PBRMetallicRoughness
{
struct PBRMetallicRoughness {
PBRMetallicRoughness(
const TextureData *baseColorTexture, const TextureData *metRoughTexture,
const Vec4f &baseColorFactor, float metallic = 0.1f, float roughness = 0.6f);
const TextureData* baseColorTexture,
const TextureData* metRoughTexture,
const Vec4f& baseColorFactor,
float metallic = 0.1f,
float roughness = 0.6f);
std::unique_ptr<Tex> baseColorTexture;
std::unique_ptr<Tex> metRoughTexture;
@ -40,12 +40,15 @@ struct PBRMetallicRoughness
const float roughness;
};
struct MaterialData : Holdable
{
struct MaterialData : Holdable {
MaterialData(
std::string name, bool isTransparent, RawShadingModel shadingModel,
const TextureData *normalTexture, const TextureData *occlusionTexture,
const TextureData *emissiveTexture, const Vec3f &emissiveFactor,
std::string name,
bool isTransparent,
RawShadingModel shadingModel,
const TextureData* normalTexture,
const TextureData* occlusionTexture,
const TextureData* emissiveTexture,
const Vec3f& emissiveFactor,
std::shared_ptr<KHRCmnUnlitMaterial> const khrCmnConstantMaterial,
std::shared_ptr<PBRMetallicRoughness> const pbrMetallicRoughness);

View File

@ -11,22 +11,14 @@
#include "PrimitiveData.hpp"
MeshData::MeshData(const std::string& name, const std::vector<float>& weights)
: Holdable(),
name(name),
weights(weights)
{
}
: Holdable(), name(name), weights(weights) {}
json MeshData::serialize() const
{
json MeshData::serialize() const {
json jsonPrimitivesArray = json::array();
for (const auto& primitive : primitives) {
jsonPrimitivesArray.push_back(*primitive);
}
json result = {
{ "name", name },
{ "primitives", jsonPrimitivesArray }
};
json result = {{"name", name}, {"primitives", jsonPrimitivesArray}};
if (!weights.empty()) {
result["weights"] = weights;
}

View File

@ -17,12 +17,10 @@
#include "PrimitiveData.hpp"
struct MeshData : Holdable
{
struct MeshData : Holdable {
MeshData(const std::string& name, const std::vector<float>& weights);
void AddPrimitive(std::shared_ptr<PrimitiveData> primitive)
{
void AddPrimitive(std::shared_ptr<PrimitiveData> primitive) {
primitives.push_back(std::move(primitive));
}

View File

@ -10,8 +10,11 @@
#include "NodeData.hpp"
NodeData::NodeData(
std::string name, const Vec3f &translation,
const Quatf &rotation, const Vec3f &scale, bool isJoint)
std::string name,
const Vec3f& translation,
const Quatf& rotation,
const Vec3f& scale,
bool isJoint)
: Holdable(),
name(std::move(name)),
isJoint(isJoint),
@ -22,43 +25,35 @@ NodeData::NodeData(
mesh(-1),
camera(-1),
light(-1),
skin(-1)
{
}
skin(-1) {}
void NodeData::AddChildNode(uint32_t childIx)
{
void NodeData::AddChildNode(uint32_t childIx) {
children.push_back(childIx);
}
void NodeData::SetMesh(uint32_t meshIx)
{
void NodeData::SetMesh(uint32_t meshIx) {
assert(mesh < 0);
assert(!isJoint);
mesh = meshIx;
}
void NodeData::SetSkin(uint32_t skinIx)
{
void NodeData::SetSkin(uint32_t skinIx) {
assert(skin < 0);
assert(!isJoint);
skin = skinIx;
}
void NodeData::SetCamera(uint32_t cameraIndex)
{
void NodeData::SetCamera(uint32_t cameraIndex) {
assert(!isJoint);
camera = cameraIndex;
}
void NodeData::SetLight(uint32_t lightIndex)
{
void NodeData::SetLight(uint32_t lightIndex) {
assert(!isJoint);
light = lightIndex;
}
json NodeData::serialize() const
{
json NodeData::serialize() const {
json result = {{"name", name}};
// if any of the T/R/S have NaN components, just leave them out of the glTF
@ -96,13 +91,11 @@ json NodeData::serialize() const
}
}
for (const auto& i : userProperties)
{
for (const auto& i : userProperties) {
auto& prop_map = result["extras"]["fromFBX"]["userProperties"];
json j = json::parse(i);
for (const auto& k : json::iterator_wrapper(j))
{
for (const auto& k : json::iterator_wrapper(j)) {
prop_map[k.key()] = k.value();
}
}

View File

@ -11,9 +11,13 @@
#include "gltf/Raw2Gltf.hpp"
struct NodeData : Holdable
{
NodeData(std::string name, const Vec3f &translation, const Quatf &rotation, const Vec3f &scale, bool isJoint);
struct NodeData : Holdable {
NodeData(
std::string name,
const Vec3f& translation,
const Quatf& rotation,
const Vec3f& scale,
bool isJoint);
void AddChildNode(uint32_t childIx);
void SetMesh(uint32_t meshIx);

View File

@ -9,11 +9,14 @@
#include "PrimitiveData.hpp"
#include "MaterialData.hpp"
#include "AccessorData.hpp"
#include "BufferViewData.hpp"
#include "MaterialData.hpp"
PrimitiveData::PrimitiveData(const AccessorData &indices, const MaterialData &material, std::shared_ptr<draco::Mesh> dracoMesh)
PrimitiveData::PrimitiveData(
const AccessorData& indices,
const MaterialData& material,
std::shared_ptr<draco::Mesh> dracoMesh)
: indices(indices.ix),
material(material.ix),
mode(TRIANGLES),
@ -25,35 +28,28 @@ PrimitiveData::PrimitiveData(const AccessorData &indices, const MaterialData &ma
material(material.ix),
mode(TRIANGLES),
dracoMesh(nullptr),
dracoBufferView(-1)
{
}
dracoBufferView(-1) {}
void PrimitiveData::AddAttrib(std::string name, const AccessorData &accessor)
{
void PrimitiveData::AddAttrib(std::string name, const AccessorData& accessor) {
attributes[name] = accessor.ix;
}
void PrimitiveData::NoteDracoBuffer(const BufferViewData &data)
{
void PrimitiveData::NoteDracoBuffer(const BufferViewData& data) {
dracoBufferView = data.ix;
}
void PrimitiveData::AddTarget(const AccessorData *positions, const AccessorData *normals, const AccessorData *tangents)
{
void PrimitiveData::AddTarget(
const AccessorData* positions,
const AccessorData* normals,
const AccessorData* tangents) {
targetAccessors.push_back(std::make_tuple(
positions->ix,
normals != nullptr ? normals->ix : -1,
tangents != nullptr ? tangents ->ix : -1
));
tangents != nullptr ? tangents->ix : -1));
}
void to_json(json& j, const PrimitiveData& d) {
j = {
{ "material", d.material },
{ "mode", d.mode },
{ "attributes", d.attributes }
};
j = {{"material", d.material}, {"mode", d.mode}, {"attributes", d.attributes}};
if (d.indices >= 0) {
j["indices"] = d.indices;
}
@ -63,19 +59,21 @@ void to_json(json &j, const PrimitiveData &d) {
for (auto accessor : d.targetAccessors) {
std::tie(pIx, nIx, tIx) = accessor;
json target{};
if (pIx >= 0) { target["POSITION"] = pIx; }
if (nIx >= 0) { target["NORMAL"] = nIx; }
if (tIx >= 0) { target["TANGENT"] = tIx; }
if (pIx >= 0) {
target["POSITION"] = pIx;
}
if (nIx >= 0) {
target["NORMAL"] = nIx;
}
if (tIx >= 0) {
target["TANGENT"] = tIx;
}
targets.push_back(target);
}
j["targets"] = targets;
}
if (!d.dracoAttributes.empty()) {
j["extensions"] = {
{ KHR_DRACO_MESH_COMPRESSION, {
{ "bufferView", d.dracoBufferView },
{ "attributes", d.dracoAttributes }
}}
};
j["extensions"] = {{KHR_DRACO_MESH_COMPRESSION,
{{"bufferView", d.dracoBufferView}, {"attributes", d.dracoAttributes}}}};
}
}

View File

@ -11,10 +11,8 @@
#include "gltf/Raw2Gltf.hpp"
struct PrimitiveData
{
enum MeshMode
{
struct PrimitiveData {
enum MeshMode {
POINTS = 0,
LINES,
LINE_LOOP,
@ -24,22 +22,32 @@ struct PrimitiveData
TRIANGLE_FAN
};
PrimitiveData(const AccessorData &indices, const MaterialData &material, std::shared_ptr<draco::Mesh> dracoMesh);
PrimitiveData(
const AccessorData& indices,
const MaterialData& material,
std::shared_ptr<draco::Mesh> dracoMesh);
PrimitiveData(const AccessorData& indices, const MaterialData& material);
void AddAttrib(std::string name, const AccessorData& accessor);
void AddTarget(const AccessorData *positions, const AccessorData *normals, const AccessorData *tangents);
void AddTarget(
const AccessorData* positions,
const AccessorData* normals,
const AccessorData* tangents);
template <class T>
void AddDracoAttrib(const AttributeDefinition<T> attribute, const std::vector<T> &attribArr)
{
void AddDracoAttrib(const AttributeDefinition<T> attribute, const std::vector<T>& attribArr) {
draco::PointAttribute att;
int8_t componentCount = attribute.glType.count;
att.Init(
attribute.dracoAttribute, nullptr, componentCount, attribute.dracoComponentType,
false, componentCount * draco::DataTypeLength(attribute.dracoComponentType), 0);
attribute.dracoAttribute,
nullptr,
componentCount,
attribute.dracoComponentType,
false,
componentCount * draco::DataTypeLength(attribute.dracoComponentType),
0);
const int dracoAttId = dracoMesh->AddAttribute(att, true, attribArr.size());
draco::PointAttribute* attPtr = dracoMesh->attribute(dracoAttId);

View File

@ -11,13 +11,9 @@
#include "gltf/Raw2Gltf.hpp"
struct SamplerData : Holdable
{
struct SamplerData : Holdable {
// this is where magFilter, minFilter, wrapS and wrapT would go, should we want it
SamplerData()
: Holdable()
{
}
SamplerData() : Holdable() {}
json serialize() const override {
return json::object();

View File

@ -12,17 +12,9 @@
#include "NodeData.hpp"
SceneData::SceneData(std::string name, const NodeData& rootNode)
: Holdable(),
name(std::move(name)),
nodes({rootNode.ix})
{
}
: Holdable(), name(std::move(name)), nodes({rootNode.ix}) {}
json SceneData::serialize() const
{
json SceneData::serialize() const {
assert(nodes.size() <= 1);
return {
{ "name", name },
{ "nodes", nodes }
};
return {{"name", name}, {"nodes", nodes}};
}

View File

@ -11,8 +11,7 @@
#include "gltf/Raw2Gltf.hpp"
struct SceneData : Holdable
{
struct SceneData : Holdable {
SceneData(std::string name, const NodeData& rootNode);
json serialize() const override;

View File

@ -13,20 +13,16 @@
#include "NodeData.hpp"
SkinData::SkinData(
const std::vector<uint32_t> joints, const AccessorData &inverseBindMatricesAccessor,
const std::vector<uint32_t> joints,
const AccessorData& inverseBindMatricesAccessor,
const NodeData& skeletonRootNode)
: Holdable(),
joints(joints),
inverseBindMatrices(inverseBindMatricesAccessor.ix),
skeletonRootNode(skeletonRootNode.ix)
{
}
skeletonRootNode(skeletonRootNode.ix) {}
json SkinData::serialize() const
{
return {
{ "joints", joints },
json SkinData::serialize() const {
return {{"joints", joints},
{"inverseBindMatrices", inverseBindMatrices},
{ "skeleton", skeletonRootNode }
};
{"skeleton", skeletonRootNode}};
}

View File

@ -11,10 +11,10 @@
#include "gltf/Raw2Gltf.hpp"
struct SkinData : Holdable
{
struct SkinData : Holdable {
SkinData(
const std::vector<uint32_t> joints, const AccessorData &inverseBindMatricesAccessor,
const std::vector<uint32_t> joints,
const AccessorData& inverseBindMatricesAccessor,
const NodeData& skeletonRootNode);
json serialize() const override;

View File

@ -13,18 +13,8 @@
#include "SamplerData.hpp"
TextureData::TextureData(std::string name, const SamplerData& sampler, const ImageData& source)
: Holdable(),
name(std::move(name)),
sampler(sampler.ix),
source(source.ix)
{
}
: Holdable(), name(std::move(name)), sampler(sampler.ix), source(source.ix) {}
json TextureData::serialize() const
{
return {
{ "name", name },
{ "sampler", sampler },
{ "source", source }
};
json TextureData::serialize() const {
return {{"name", name}, {"sampler", sampler}, {"source", source}};
}

View File

@ -11,8 +11,7 @@
#include "gltf/Raw2Gltf.hpp"
struct TextureData : Holdable
{
struct TextureData : Holdable {
TextureData(std::string name, const SamplerData& sampler, const ImageData& source);
json serialize() const override;

View File

@ -11,18 +11,17 @@
#include <fbxsdk.h>
#include <mathfu/vector.h>
#include <mathfu/matrix.h>
#include <mathfu/quaternion.h>
#include <mathfu/rect.h>
#include <mathfu/vector.h>
/**
* All the mathfu:: implementations of our core data types.
*/
template <class T, int d>
struct Bounds
{
struct Bounds {
mathfu::Vector<T, d> min;
mathfu::Vector<T, d> max;
bool initialized = false;
@ -63,8 +62,8 @@ typedef Bounds<float, 3> Boundsf;
#define VEC4F_ONE (Vec4f{1.0f})
#define VEC4F_ZERO (Vec4f{0.0f})
template<class T, int d> inline std::vector<T> toStdVec(const mathfu::Vector <T, d> &vec)
{
template <class T, int d>
inline std::vector<T> toStdVec(const mathfu::Vector<T, d>& vec) {
std::vector<T> result(d);
for (int ii = 0; ii < d; ii++) {
result[ii] = vec[ii];
@ -72,7 +71,8 @@ template<class T, int d> inline std::vector<T> toStdVec(const mathfu::Vector <T,
return result;
}
template<class T> std::vector<T> toStdVec(const mathfu::Quaternion<T> &quat) {
template <class T>
std::vector<T> toStdVec(const mathfu::Quaternion<T>& quat) {
return std::vector<T>{quat.vector()[0], quat.vector()[1], quat.vector()[2], quat.scalar()};
}

View File

@ -9,64 +9,68 @@
#include "RawModel.hpp"
#include <vector>
#include <string>
#include <unordered_map>
#include <cmath>
#include <map>
#include <set>
#include <string>
#include <unordered_map>
#include <vector>
#if defined(__unix__)
#include <algorithm>
#endif
#include "utils/String_Utils.hpp"
#include "utils/Image_Utils.hpp"
#include "utils/String_Utils.hpp"
bool RawVertex::operator==(const RawVertex &other) const
{
return (position == other.position) &&
(normal == other.normal) &&
(tangent == other.tangent) &&
(binormal == other.binormal) &&
(color == other.color) &&
(uv0 == other.uv0) &&
(uv1 == other.uv1) &&
(jointIndices == other.jointIndices) &&
(jointWeights == other.jointWeights) &&
(polarityUv0 == other.polarityUv0) &&
(blendSurfaceIx == other.blendSurfaceIx) &&
(blends == other.blends);
bool RawVertex::operator==(const RawVertex& other) const {
return (position == other.position) && (normal == other.normal) && (tangent == other.tangent) &&
(binormal == other.binormal) && (color == other.color) && (uv0 == other.uv0) &&
(uv1 == other.uv1) && (jointIndices == other.jointIndices) &&
(jointWeights == other.jointWeights) && (polarityUv0 == other.polarityUv0) &&
(blendSurfaceIx == other.blendSurfaceIx) && (blends == other.blends);
}
size_t RawVertex::Difference(const RawVertex &other) const
{
size_t RawVertex::Difference(const RawVertex& other) const {
size_t attributes = 0;
if (position != other.position) { attributes |= RAW_VERTEX_ATTRIBUTE_POSITION; }
if (normal != other.normal) { attributes |= RAW_VERTEX_ATTRIBUTE_NORMAL; }
if (tangent != other.tangent) { attributes |= RAW_VERTEX_ATTRIBUTE_TANGENT; }
if (binormal != other.binormal) { attributes |= RAW_VERTEX_ATTRIBUTE_BINORMAL; }
if (color != other.color) { attributes |= RAW_VERTEX_ATTRIBUTE_COLOR; }
if (uv0 != other.uv0) { attributes |= RAW_VERTEX_ATTRIBUTE_UV0; }
if (uv1 != other.uv1) { attributes |= RAW_VERTEX_ATTRIBUTE_UV1; }
if (position != other.position) {
attributes |= RAW_VERTEX_ATTRIBUTE_POSITION;
}
if (normal != other.normal) {
attributes |= RAW_VERTEX_ATTRIBUTE_NORMAL;
}
if (tangent != other.tangent) {
attributes |= RAW_VERTEX_ATTRIBUTE_TANGENT;
}
if (binormal != other.binormal) {
attributes |= RAW_VERTEX_ATTRIBUTE_BINORMAL;
}
if (color != other.color) {
attributes |= RAW_VERTEX_ATTRIBUTE_COLOR;
}
if (uv0 != other.uv0) {
attributes |= RAW_VERTEX_ATTRIBUTE_UV0;
}
if (uv1 != other.uv1) {
attributes |= RAW_VERTEX_ATTRIBUTE_UV1;
}
// Always need both or neither.
if (jointIndices != other.jointIndices) { attributes |= RAW_VERTEX_ATTRIBUTE_JOINT_INDICES | RAW_VERTEX_ATTRIBUTE_JOINT_WEIGHTS; }
if (jointWeights != other.jointWeights) { attributes |= RAW_VERTEX_ATTRIBUTE_JOINT_INDICES | RAW_VERTEX_ATTRIBUTE_JOINT_WEIGHTS; }
if (jointIndices != other.jointIndices) {
attributes |= RAW_VERTEX_ATTRIBUTE_JOINT_INDICES | RAW_VERTEX_ATTRIBUTE_JOINT_WEIGHTS;
}
if (jointWeights != other.jointWeights) {
attributes |= RAW_VERTEX_ATTRIBUTE_JOINT_INDICES | RAW_VERTEX_ATTRIBUTE_JOINT_WEIGHTS;
}
return attributes;
}
RawModel::RawModel()
: vertexAttributes(0)
{
}
RawModel::RawModel() : vertexAttributes(0) {}
void RawModel::AddVertexAttribute(const RawVertexAttribute attrib)
{
void RawModel::AddVertexAttribute(const RawVertexAttribute attrib) {
vertexAttributes |= attrib;
}
int RawModel::AddVertex(const RawVertex &vertex)
{
int RawModel::AddVertex(const RawVertex& vertex) {
auto it = vertexHash.find(vertex);
if (it != vertexHash.end()) {
return it->second;
@ -76,15 +80,22 @@ int RawModel::AddVertex(const RawVertex &vertex)
return (int)vertices.size() - 1;
}
int RawModel::AddTriangle(const int v0, const int v1, const int v2, const int materialIndex, const int surfaceIndex)
{
int RawModel::AddTriangle(
const int v0,
const int v1,
const int v2,
const int materialIndex,
const int surfaceIndex) {
const RawTriangle triangle = {{v0, v1, v2}, materialIndex, surfaceIndex};
triangles.push_back(triangle);
return (int)triangles.size() - 1;
}
int RawModel::AddTexture(const std::string &name, const std::string &fileName, const std::string &fileLocation, RawTextureUsage usage)
{
int RawModel::AddTexture(
const std::string& name,
const std::string& fileName,
const std::string& fileLocation,
RawTextureUsage usage) {
if (name.empty()) {
return -1;
}
@ -94,26 +105,32 @@ int RawModel::AddTexture(const std::string &name, const std::string &fileName, c
}
}
const ImageUtils::ImageProperties
properties = ImageUtils::GetImageProperties(!fileLocation.empty() ? fileLocation.c_str() : fileName.c_str());
const ImageUtils::ImageProperties properties = ImageUtils::GetImageProperties(
!fileLocation.empty() ? fileLocation.c_str() : fileName.c_str());
RawTexture texture;
texture.name = name;
texture.width = properties.width;
texture.height = properties.height;
texture.mipLevels = (int) ceilf(log2f(std::max((float) properties.width, (float) properties.height)));
texture.mipLevels =
(int)ceilf(log2f(std::max((float)properties.width, (float)properties.height)));
texture.usage = usage;
texture.occlusion = (properties.occlusion == ImageUtils::IMAGE_TRANSPARENT) ?
RAW_TEXTURE_OCCLUSION_TRANSPARENT : RAW_TEXTURE_OCCLUSION_OPAQUE;
texture.occlusion = (properties.occlusion == ImageUtils::IMAGE_TRANSPARENT)
? RAW_TEXTURE_OCCLUSION_TRANSPARENT
: RAW_TEXTURE_OCCLUSION_OPAQUE;
texture.fileName = fileName;
texture.fileLocation = fileLocation;
textures.emplace_back(texture);
return (int)textures.size() - 1;
}
int RawModel::AddMaterial(const RawMaterial &material)
{
return AddMaterial(material.name.c_str(), material.type, material.textures, material.info, material.userProperties);
int RawModel::AddMaterial(const RawMaterial& material) {
return AddMaterial(
material.name.c_str(),
material.type,
material.textures,
material.info,
material.userProperties);
}
int RawModel::AddMaterial(
@ -121,8 +138,7 @@ int RawModel::AddMaterial(
const RawMaterialType materialType,
const int textures[RAW_TEXTURE_USAGE_MAX],
std::shared_ptr<RawMatProps> materialInfo,
const std::vector<std::string>& userProperties)
{
const std::vector<std::string>& userProperties) {
for (size_t i = 0; i < materials.size(); i++) {
if (materials[i].name != name) {
continue;
@ -139,8 +155,7 @@ int RawModel::AddMaterial(
}
if (materials[i].userProperties.size() != userProperties.size()) {
match = false;
}
else {
} else {
for (int j = 0; match && j < userProperties.size(); j++) {
match = match && (materials[i].userProperties[j] == userProperties[j]);
}
@ -171,8 +186,7 @@ int RawModel::AddLight(
const Vec3f color,
const float intensity,
const float innerConeAngle,
const float outerConeAngle)
{
const float outerConeAngle) {
for (size_t i = 0; i < lights.size(); i++) {
if (lights[i].name != name || lights[i].type != lightType) {
continue;
@ -198,9 +212,7 @@ int RawModel::AddLight(
return (int)lights.size() - 1;
}
int RawModel::AddSurface(const RawSurface &surface)
{
int RawModel::AddSurface(const RawSurface& surface) {
for (size_t i = 0; i < surfaces.size(); i++) {
if (StringUtils::CompareNoCase(surfaces[i].name, surface.name) == 0) {
return (int)i;
@ -211,8 +223,7 @@ int RawModel::AddSurface(const RawSurface &surface)
return (int)(surfaces.size() - 1);
}
int RawModel::AddSurface(const char *name, const long surfaceId)
{
int RawModel::AddSurface(const char* name, const long surfaceId) {
assert(name[0] != '\0');
for (size_t i = 0; i < surfaces.size(); i++) {
@ -230,14 +241,12 @@ int RawModel::AddSurface(const char *name, const long surfaceId)
return (int)(surfaces.size() - 1);
}
int RawModel::AddAnimation(const RawAnimation &animation)
{
int RawModel::AddAnimation(const RawAnimation& animation) {
animations.emplace_back(animation);
return (int)(animations.size() - 1);
}
int RawModel::AddNode(const RawNode &node)
{
int RawModel::AddNode(const RawNode& node) {
for (size_t i = 0; i < nodes.size(); i++) {
if (nodes[i].id == node.id) {
return (int)i;
@ -249,9 +258,13 @@ int RawModel::AddNode(const RawNode &node)
}
int RawModel::AddCameraPerspective(
const char *name, const long nodeId, const float aspectRatio, const float fovDegreesX, const float fovDegreesY, const float nearZ,
const float farZ)
{
const char* name,
const long nodeId,
const float aspectRatio,
const float fovDegreesX,
const float fovDegreesY,
const float nearZ,
const float farZ) {
RawCamera camera;
camera.name = name;
camera.nodeId = nodeId;
@ -266,8 +279,12 @@ int RawModel::AddCameraPerspective(
}
int RawModel::AddCameraOrthographic(
const char *name, const long nodeId, const float magX, const float magY, const float nearZ, const float farZ)
{
const char* name,
const long nodeId,
const float magX,
const float magY,
const float nearZ,
const float farZ) {
RawCamera camera;
camera.name = name;
camera.nodeId = nodeId;
@ -280,8 +297,7 @@ int RawModel::AddCameraOrthographic(
return (int)cameras.size() - 1;
}
int RawModel::AddNode(const long id, const char *name, const long parentId)
{
int RawModel::AddNode(const long id, const char* name, const long parentId) {
assert(name[0] != '\0');
for (size_t i = 0; i < nodes.size(); i++) {
@ -305,8 +321,7 @@ int RawModel::AddNode(const long id, const char *name, const long parentId)
return (int)nodes.size() - 1;
}
void RawModel::Condense()
{
void RawModel::Condense() {
// Only keep surfaces that are referenced by one or more triangles.
{
std::vector<RawSurface> oldSurfaces = surfaces;
@ -323,7 +338,8 @@ void RawModel::Condense()
}
// clear out references to meshes that no longer exist
for (auto& node : nodes) {
if (node.surfaceId != 0 && survivingSurfaceIds.find(node.surfaceId) == survivingSurfaceIds.end()) {
if (node.surfaceId != 0 &&
survivingSurfaceIds.find(node.surfaceId) == survivingSurfaceIds.end()) {
node.surfaceId = 0;
}
}
@ -353,7 +369,8 @@ void RawModel::Condense()
for (int j = 0; j < RAW_TEXTURE_USAGE_MAX; j++) {
if (material.textures[j] >= 0) {
const RawTexture& texture = oldTextures[material.textures[j]];
const int textureIndex = AddTexture(texture.name, texture.fileName, texture.fileLocation, texture.usage);
const int textureIndex =
AddTexture(texture.name, texture.fileName, texture.fileLocation, texture.usage);
textures[textureIndex] = texture;
material.textures[j] = textureIndex;
}
@ -376,8 +393,7 @@ void RawModel::Condense()
}
}
void RawModel::TransformGeometry(ComputeNormalsOption normals)
{
void RawModel::TransformGeometry(ComputeNormalsOption normals) {
switch (normals) {
case ComputeNormalsOption::NEVER:
break;
@ -404,8 +420,7 @@ void RawModel::TransformGeometry(ComputeNormalsOption normals)
}
}
void RawModel::TransformTextures(const std::vector<std::function<Vec2f(Vec2f)>> &transforms)
{
void RawModel::TransformTextures(const std::vector<std::function<Vec2f(Vec2f)>>& transforms) {
for (auto& vertice : vertices) {
if ((vertexAttributes & RAW_VERTEX_ATTRIBUTE_UV0) != 0) {
for (const auto& fun : transforms) {
@ -420,10 +435,8 @@ void RawModel::TransformTextures(const std::vector<std::function<Vec2f(Vec2f)>>
}
}
struct TriangleModelSortPos
{
static bool Compare(const RawTriangle &a, const RawTriangle &b)
{
struct TriangleModelSortPos {
static bool Compare(const RawTriangle& a, const RawTriangle& b) {
if (a.materialIndex != b.materialIndex) {
return a.materialIndex < b.materialIndex;
}
@ -434,10 +447,8 @@ struct TriangleModelSortPos
}
};
struct TriangleModelSortNeg
{
static bool Compare(const RawTriangle &a, const RawTriangle &b)
{
struct TriangleModelSortNeg {
static bool Compare(const RawTriangle& a, const RawTriangle& b) {
if (a.materialIndex != b.materialIndex) {
return a.materialIndex < b.materialIndex;
}
@ -449,8 +460,10 @@ struct TriangleModelSortNeg
};
void RawModel::CreateMaterialModels(
std::vector<RawModel> &materialModels, bool shortIndices, const int keepAttribs, const bool forceDiscrete) const
{
std::vector<RawModel>& materialModels,
bool shortIndices,
const int keepAttribs,
const bool forceDiscrete) const {
// Sort all triangles based on material first, then surface, then first vertex index.
std::vector<RawTriangle> sortedTriangles;
@ -487,7 +500,8 @@ void RawModel::CreateMaterialModels(
std::sort(opaqueTriangles.begin(), opaqueTriangles.end(), TriangleModelSortPos::Compare);
// Sort the transparent triangles in the reverse direction.
std::sort(transparentTriangles.begin(), transparentTriangles.end(), TriangleModelSortNeg::Compare);
std::sort(
transparentTriangles.begin(), transparentTriangles.end(), TriangleModelSortNeg::Compare);
// Add the triangles to the sorted list.
for (const auto& opaqueTriangle : opaqueTriangles) {
@ -515,13 +529,11 @@ void RawModel::CreateMaterialModels(
// Create a separate model for each material.
RawModel* model;
for (size_t i = 0; i < sortedTriangles.size(); i++) {
if (sortedTriangles[i].materialIndex < 0 || sortedTriangles[i].surfaceIndex < 0) {
continue;
}
if (i == 0 ||
(shortIndices && model->GetVertexCount() >= 0xFFFE) ||
if (i == 0 || (shortIndices && model->GetVertexCount() >= 0xFFFE) ||
sortedTriangles[i].materialIndex != sortedTriangles[i - 1].materialIndex ||
(sortedTriangles[i].surfaceIndex != sortedTriangles[i - 1].surfaceIndex &&
(forceDiscrete || surfaces[sortedTriangles[i].surfaceIndex].discrete ||
@ -565,28 +577,43 @@ void RawModel::CreateMaterialModels(
keep |= RAW_VERTEX_ATTRIBUTE_UV0;
}
if (mat.textures[RAW_TEXTURE_USAGE_NORMAL] != -1) {
keep |= RAW_VERTEX_ATTRIBUTE_NORMAL |
RAW_VERTEX_ATTRIBUTE_TANGENT |
RAW_VERTEX_ATTRIBUTE_BINORMAL |
RAW_VERTEX_ATTRIBUTE_UV0;
keep |= RAW_VERTEX_ATTRIBUTE_NORMAL | RAW_VERTEX_ATTRIBUTE_TANGENT |
RAW_VERTEX_ATTRIBUTE_BINORMAL | RAW_VERTEX_ATTRIBUTE_UV0;
}
if (mat.textures[RAW_TEXTURE_USAGE_SPECULAR] != -1) {
keep |= RAW_VERTEX_ATTRIBUTE_NORMAL |
RAW_VERTEX_ATTRIBUTE_UV0;
keep |= RAW_VERTEX_ATTRIBUTE_NORMAL | RAW_VERTEX_ATTRIBUTE_UV0;
}
if (mat.textures[RAW_TEXTURE_USAGE_EMISSIVE] != -1) {
keep |= RAW_VERTEX_ATTRIBUTE_UV1;
}
}
if ((keep & RAW_VERTEX_ATTRIBUTE_POSITION) == 0) { vertex.position = defaultVertex.position; }
if ((keep & RAW_VERTEX_ATTRIBUTE_NORMAL) == 0) { vertex.normal = defaultVertex.normal; }
if ((keep & RAW_VERTEX_ATTRIBUTE_TANGENT) == 0) { vertex.tangent = defaultVertex.tangent; }
if ((keep & RAW_VERTEX_ATTRIBUTE_BINORMAL) == 0) { vertex.binormal = defaultVertex.binormal; }
if ((keep & RAW_VERTEX_ATTRIBUTE_COLOR) == 0) { vertex.color = defaultVertex.color; }
if ((keep & RAW_VERTEX_ATTRIBUTE_UV0) == 0) { vertex.uv0 = defaultVertex.uv0; }
if ((keep & RAW_VERTEX_ATTRIBUTE_UV1) == 0) { vertex.uv1 = defaultVertex.uv1; }
if ((keep & RAW_VERTEX_ATTRIBUTE_JOINT_INDICES) == 0) { vertex.jointIndices = defaultVertex.jointIndices; }
if ((keep & RAW_VERTEX_ATTRIBUTE_JOINT_WEIGHTS) == 0) { vertex.jointWeights = defaultVertex.jointWeights; }
if ((keep & RAW_VERTEX_ATTRIBUTE_POSITION) == 0) {
vertex.position = defaultVertex.position;
}
if ((keep & RAW_VERTEX_ATTRIBUTE_NORMAL) == 0) {
vertex.normal = defaultVertex.normal;
}
if ((keep & RAW_VERTEX_ATTRIBUTE_TANGENT) == 0) {
vertex.tangent = defaultVertex.tangent;
}
if ((keep & RAW_VERTEX_ATTRIBUTE_BINORMAL) == 0) {
vertex.binormal = defaultVertex.binormal;
}
if ((keep & RAW_VERTEX_ATTRIBUTE_COLOR) == 0) {
vertex.color = defaultVertex.color;
}
if ((keep & RAW_VERTEX_ATTRIBUTE_UV0) == 0) {
vertex.uv0 = defaultVertex.uv0;
}
if ((keep & RAW_VERTEX_ATTRIBUTE_UV1) == 0) {
vertex.uv1 = defaultVertex.uv1;
}
if ((keep & RAW_VERTEX_ATTRIBUTE_JOINT_INDICES) == 0) {
vertex.jointIndices = defaultVertex.jointIndices;
}
if ((keep & RAW_VERTEX_ATTRIBUTE_JOINT_WEIGHTS) == 0) {
vertex.jointWeights = defaultVertex.jointWeights;
}
}
verts[j] = model->AddVertex(vertex);
@ -599,8 +626,7 @@ void RawModel::CreateMaterialModels(
}
}
int RawModel::GetNodeById(const long nodeId) const
{
int RawModel::GetNodeById(const long nodeId) const {
for (size_t i = 0; i < nodes.size(); i++) {
if (nodes[i].id == nodeId) {
return (int)i;
@ -609,8 +635,7 @@ int RawModel::GetNodeById(const long nodeId) const
return -1;
}
int RawModel::GetSurfaceById(const long surfaceId) const
{
int RawModel::GetSurfaceById(const long surfaceId) const {
for (size_t i = 0; i < surfaces.size(); i++) {
if (surfaces[i].id == surfaceId) {
return (int)i;
@ -619,8 +644,7 @@ int RawModel::GetSurfaceById(const long surfaceId) const
return -1;
}
Vec3f RawModel::getFaceNormal(int verts[3]) const
{
Vec3f RawModel::getFaceNormal(int verts[3]) const {
const float l0 = (vertices[verts[1]].position - vertices[verts[0]].position).LengthSquared();
const float l1 = (vertices[verts[2]].position - vertices[verts[1]].position).LengthSquared();
const float l2 = (vertices[verts[0]].position - vertices[verts[2]].position).LengthSquared();
@ -642,8 +666,7 @@ Vec3f RawModel::getFaceNormal(int verts[3]) const
return result.Normalized() * angle * area;
}
size_t RawModel::CalculateNormals(bool onlyBroken)
{
size_t RawModel::CalculateNormals(bool onlyBroken) {
Vec3f averagePos = Vec3f{0.0f};
std::set<int> brokenVerts;
for (int vertIx = 0; vertIx < vertices.size(); vertIx++) {

View File

@ -9,15 +9,13 @@
#pragma once
#include <unordered_map>
#include <functional>
#include <set>
#include <unordered_map>
#include "FBX2glTF.h"
enum RawVertexAttribute
{
enum RawVertexAttribute {
RAW_VERTEX_ATTRIBUTE_POSITION = 1 << 0,
RAW_VERTEX_ATTRIBUTE_NORMAL = 1 << 1,
RAW_VERTEX_ATTRIBUTE_TANGENT = 1 << 2,
@ -31,26 +29,18 @@ enum RawVertexAttribute
RAW_VERTEX_ATTRIBUTE_AUTO = 1 << 31
};
struct RawBlendVertex
{
struct RawBlendVertex {
Vec3f position{};
Vec3f normal{};
Vec4f tangent{};
bool operator==(const RawBlendVertex& other) const {
return position == other.position &&
normal == other.normal &&
tangent == other.tangent;
return position == other.position && normal == other.normal && tangent == other.tangent;
}
};
struct RawVertex
{
RawVertex() :
polarityUv0(false),
pad1(false),
pad2(false),
pad3(false) {}
struct RawVertex {
RawVertex() : polarityUv0(false), pad1(false), pad2(false), pad3(false) {}
Vec3f position{0.0f};
Vec3f normal{0.0f};
@ -63,9 +53,11 @@ struct RawVertex
Vec4f jointWeights{0.0f};
// end of members that directly correspond to vertex attributes
// if this vertex participates in a blend shape setup, the surfaceIx of its dedicated mesh; otherwise, -1
// if this vertex participates in a blend shape setup, the surfaceIx of its dedicated mesh;
// otherwise, -1
int blendSurfaceIx = -1;
// the size of this vector is always identical to the size of the corresponding RawSurface.blendChannels
// the size of this vector is always identical to the size of the corresponding
// RawSurface.blendChannels
std::vector<RawBlendVertex> blends{};
bool polarityUv0;
@ -77,11 +69,9 @@ struct RawVertex
size_t Difference(const RawVertex& other) const;
};
class VertexHasher
{
class VertexHasher {
public:
size_t operator()(const RawVertex &v) const
{
size_t operator()(const RawVertex& v) const {
size_t seed = 5381;
const auto hasher = std::hash<float>{};
seed ^= hasher(v.position[0]) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
@ -91,15 +81,13 @@ public:
}
};
struct RawTriangle
{
struct RawTriangle {
int verts[3];
int materialIndex;
int surfaceIndex;
};
enum RawShadingModel
{
enum RawShadingModel {
RAW_SHADING_MODEL_UNKNOWN = -1,
RAW_SHADING_MODEL_CONSTANT,
RAW_SHADING_MODEL_LAMBERT,
@ -111,18 +99,25 @@ enum RawShadingModel
inline std::string Describe(RawShadingModel model) {
switch (model) {
case RAW_SHADING_MODEL_UNKNOWN: return "<unknown>";
case RAW_SHADING_MODEL_CONSTANT: return "Constant";
case RAW_SHADING_MODEL_LAMBERT: return "Lambert";
case RAW_SHADING_MODEL_BLINN: return "Blinn";
case RAW_SHADING_MODEL_PHONG: return "Phong";
case RAW_SHADING_MODEL_PBR_MET_ROUGH: return "Metallic/Roughness";
case RAW_SHADING_MODEL_MAX: default: return "<unknown>";
case RAW_SHADING_MODEL_UNKNOWN:
return "<unknown>";
case RAW_SHADING_MODEL_CONSTANT:
return "Constant";
case RAW_SHADING_MODEL_LAMBERT:
return "Lambert";
case RAW_SHADING_MODEL_BLINN:
return "Blinn";
case RAW_SHADING_MODEL_PHONG:
return "Phong";
case RAW_SHADING_MODEL_PBR_MET_ROUGH:
return "Metallic/Roughness";
case RAW_SHADING_MODEL_MAX:
default:
return "<unknown>";
}
}
enum RawTextureUsage
{
enum RawTextureUsage {
RAW_TEXTURE_USAGE_NONE = -1,
RAW_TEXTURE_USAGE_AMBIENT,
RAW_TEXTURE_USAGE_DIFFUSE,
@ -138,32 +133,39 @@ enum RawTextureUsage
RAW_TEXTURE_USAGE_MAX
};
inline std::string Describe(RawTextureUsage usage)
{
inline std::string Describe(RawTextureUsage usage) {
switch (usage) {
case RAW_TEXTURE_USAGE_NONE: return "<none>";
case RAW_TEXTURE_USAGE_AMBIENT: return "ambient";
case RAW_TEXTURE_USAGE_DIFFUSE: return "diffuse";
case RAW_TEXTURE_USAGE_NORMAL: return "normal";
case RAW_TEXTURE_USAGE_SPECULAR: return "specular";
case RAW_TEXTURE_USAGE_SHININESS: return "shininess";
case RAW_TEXTURE_USAGE_EMISSIVE: return "emissive";
case RAW_TEXTURE_USAGE_REFLECTION: return "reflection";
case RAW_TEXTURE_USAGE_OCCLUSION: return "occlusion";
case RAW_TEXTURE_USAGE_ROUGHNESS: return "roughness";
case RAW_TEXTURE_USAGE_METALLIC: return "metallic";
case RAW_TEXTURE_USAGE_MAX:default: return "unknown";
case RAW_TEXTURE_USAGE_NONE:
return "<none>";
case RAW_TEXTURE_USAGE_AMBIENT:
return "ambient";
case RAW_TEXTURE_USAGE_DIFFUSE:
return "diffuse";
case RAW_TEXTURE_USAGE_NORMAL:
return "normal";
case RAW_TEXTURE_USAGE_SPECULAR:
return "specular";
case RAW_TEXTURE_USAGE_SHININESS:
return "shininess";
case RAW_TEXTURE_USAGE_EMISSIVE:
return "emissive";
case RAW_TEXTURE_USAGE_REFLECTION:
return "reflection";
case RAW_TEXTURE_USAGE_OCCLUSION:
return "occlusion";
case RAW_TEXTURE_USAGE_ROUGHNESS:
return "roughness";
case RAW_TEXTURE_USAGE_METALLIC:
return "metallic";
case RAW_TEXTURE_USAGE_MAX:
default:
return "unknown";
}
};
enum RawTextureOcclusion
{
RAW_TEXTURE_OCCLUSION_OPAQUE,
RAW_TEXTURE_OCCLUSION_TRANSPARENT
};
enum RawTextureOcclusion { RAW_TEXTURE_OCCLUSION_OPAQUE, RAW_TEXTURE_OCCLUSION_TRANSPARENT };
struct RawTexture
{
struct RawTexture {
std::string name; // logical name in FBX file
int width;
int height;
@ -174,8 +176,7 @@ struct RawTexture
std::string fileLocation; // inferred path in local filesystem, or ""
};
enum RawMaterialType
{
enum RawMaterialType {
RAW_MATERIAL_TYPE_OPAQUE,
RAW_MATERIAL_TYPE_TRANSPARENT,
RAW_MATERIAL_TYPE_SKINNED_OPAQUE,
@ -183,13 +184,15 @@ enum RawMaterialType
};
struct RawMatProps {
explicit RawMatProps(RawShadingModel shadingModel)
: shadingModel(shadingModel)
{}
explicit RawMatProps(RawShadingModel shadingModel) : shadingModel(shadingModel) {}
const RawShadingModel shadingModel;
virtual bool operator!=(const RawMatProps &other) const { return !(*this == other); }
virtual bool operator==(const RawMatProps &other) const { return shadingModel == other.shadingModel; };
virtual bool operator!=(const RawMatProps& other) const {
return !(*this == other);
}
virtual bool operator==(const RawMatProps& other) const {
return shadingModel == other.shadingModel;
};
};
struct RawTraditionalMatProps : RawMatProps {
@ -199,14 +202,13 @@ struct RawTraditionalMatProps : RawMatProps {
const Vec4f&& diffuseFactor,
const Vec3f&& emissiveFactor,
const Vec3f&& specularFactor,
const float shininess
) : RawMatProps(shadingModel),
const float shininess)
: RawMatProps(shadingModel),
ambientFactor(ambientFactor),
diffuseFactor(diffuseFactor),
emissiveFactor(emissiveFactor),
specularFactor(specularFactor),
shininess(shininess)
{}
shininess(shininess) {}
const Vec3f ambientFactor;
const Vec4f diffuseFactor;
@ -217,10 +219,8 @@ struct RawTraditionalMatProps : RawMatProps {
bool operator==(const RawMatProps& other) const override {
if (RawMatProps::operator==(other)) {
const auto& typed = (RawTraditionalMatProps&)other;
return ambientFactor == typed.ambientFactor &&
diffuseFactor == typed.diffuseFactor &&
specularFactor == typed.specularFactor &&
emissiveFactor == typed.emissiveFactor &&
return ambientFactor == typed.ambientFactor && diffuseFactor == typed.diffuseFactor &&
specularFactor == typed.specularFactor && emissiveFactor == typed.emissiveFactor &&
shininess == typed.shininess;
}
return false;
@ -234,14 +234,13 @@ struct RawMetRoughMatProps : RawMatProps {
const Vec3f&& emissiveFactor,
float emissiveIntensity,
float metallic,
float roughness
) : RawMatProps(shadingModel),
float roughness)
: RawMatProps(shadingModel),
diffuseFactor(diffuseFactor),
emissiveFactor(emissiveFactor),
emissiveIntensity(emissiveIntensity),
metallic(metallic),
roughness(roughness)
{}
roughness(roughness) {}
const Vec4f diffuseFactor;
const Vec3f emissiveFactor;
const float emissiveIntensity;
@ -251,19 +250,15 @@ struct RawMetRoughMatProps : RawMatProps {
bool operator==(const RawMatProps& other) const override {
if (RawMatProps::operator==(other)) {
const auto& typed = (RawMetRoughMatProps&)other;
return diffuseFactor == typed.diffuseFactor &&
emissiveFactor == typed.emissiveFactor &&
emissiveIntensity == typed.emissiveIntensity &&
metallic == typed.metallic &&
return diffuseFactor == typed.diffuseFactor && emissiveFactor == typed.emissiveFactor &&
emissiveIntensity == typed.emissiveIntensity && metallic == typed.metallic &&
roughness == typed.roughness;
}
return false;
}
};
struct RawMaterial
{
struct RawMaterial {
std::string name;
RawMaterialType type;
std::shared_ptr<RawMatProps> info;
@ -271,15 +266,13 @@ struct RawMaterial
std::vector<std::string> userProperties;
};
enum RawLightType
{
enum RawLightType {
RAW_LIGHT_TYPE_DIRECTIONAL,
RAW_LIGHT_TYPE_POINT,
RAW_LIGHT_TYPE_SPOT,
};
struct RawLight
{
struct RawLight {
std::string name;
RawLightType type;
Vec3f color;
@ -288,16 +281,14 @@ struct RawLight
float outerConeAngle; // only meaningful for spot
};
struct RawBlendChannel
{
struct RawBlendChannel {
float defaultDeform;
bool hasNormals;
bool hasTangents;
std::string name;
};
struct RawSurface
{
struct RawSurface {
long id;
std::string name; // The name of this surface
long skeletonRootId; // The id of the root node of the skeleton.
@ -310,8 +301,7 @@ struct RawSurface
bool discrete;
};
struct RawChannel
{
struct RawChannel {
int nodeIndex;
std::vector<Vec3f> translations;
std::vector<Quatf> rotations;
@ -319,26 +309,19 @@ struct RawChannel
std::vector<float> weights;
};
struct RawAnimation
{
struct RawAnimation {
std::string name;
std::vector<float> times;
std::vector<RawChannel> channels;
};
struct RawCamera
{
struct RawCamera {
std::string name;
long nodeId;
enum
{
CAMERA_MODE_PERSPECTIVE,
CAMERA_MODE_ORTHOGRAPHIC
} mode;
enum { CAMERA_MODE_PERSPECTIVE, CAMERA_MODE_ORTHOGRAPHIC } mode;
struct
{
struct {
float aspectRatio;
float fovDegreesX;
float fovDegreesY;
@ -346,8 +329,7 @@ struct RawCamera
float farZ;
} perspective;
struct
{
struct {
float magX;
float magY;
float nearZ;
@ -355,8 +337,7 @@ struct RawCamera
} orthographic;
};
struct RawNode
{
struct RawNode {
bool isJoint;
long id;
std::string name;
@ -370,36 +351,67 @@ struct RawNode
std::vector<std::string> userProperties;
};
class RawModel
{
class RawModel {
public:
RawModel();
// Add geometry.
void AddVertexAttribute(const RawVertexAttribute attrib);
int AddVertex(const RawVertex& vertex);
int AddTriangle(const int v0, const int v1, const int v2, const int materialIndex, const int surfaceIndex);
int AddTexture(const std::string &name, const std::string &fileName, const std::string &fileLocation, RawTextureUsage usage);
int AddTriangle(
const int v0,
const int v1,
const int v2,
const int materialIndex,
const int surfaceIndex);
int AddTexture(
const std::string& name,
const std::string& fileName,
const std::string& fileLocation,
RawTextureUsage usage);
int AddMaterial(const RawMaterial& material);
int AddMaterial(
const char *name, const RawMaterialType materialType, const int textures[RAW_TEXTURE_USAGE_MAX],
std::shared_ptr<RawMatProps> materialInfo, const std::vector<std::string>& userProperties);
int AddLight(const char *name, RawLightType lightType, Vec3f color, float intensity,
float innerConeAngle, float outerConeAngle);
const char* name,
const RawMaterialType materialType,
const int textures[RAW_TEXTURE_USAGE_MAX],
std::shared_ptr<RawMatProps> materialInfo,
const std::vector<std::string>& userProperties);
int AddLight(
const char* name,
RawLightType lightType,
Vec3f color,
float intensity,
float innerConeAngle,
float outerConeAngle);
int AddSurface(const RawSurface& suface);
int AddSurface(const char* name, long surfaceId);
int AddAnimation(const RawAnimation& animation);
int AddCameraPerspective(
const char *name, const long nodeId, const float aspectRatio, const float fovDegreesX, const float fovDegreesY,
const float nearZ, const float farZ);
int
AddCameraOrthographic(const char *name, const long nodeId, const float magX, const float magY, const float nearZ, const float farZ);
const char* name,
const long nodeId,
const float aspectRatio,
const float fovDegreesX,
const float fovDegreesY,
const float nearZ,
const float farZ);
int AddCameraOrthographic(
const char* name,
const long nodeId,
const float magX,
const float magY,
const float nearZ,
const float farZ);
int AddNode(const RawNode& node);
int AddNode(const long id, const char* name, const long parentId);
void SetRootNode(const long nodeId) { rootNodeId = nodeId; }
const long GetRootNode() const { return rootNodeId; }
void SetRootNode(const long nodeId) {
rootNodeId = nodeId;
}
const long GetRootNode() const {
return rootNodeId;
}
// Remove unused vertices, textures or materials after removing vertex attributes, textures, materials or surfaces.
// Remove unused vertices, textures or materials after removing vertex attributes, textures,
// materials or surfaces.
void Condense();
void TransformGeometry(ComputeNormalsOption);
@ -409,58 +421,104 @@ public:
size_t CalculateNormals(bool);
// Get the attributes stored per vertex.
int GetVertexAttributes() const { return vertexAttributes; }
int GetVertexAttributes() const {
return vertexAttributes;
}
// Iterate over the vertices.
int GetVertexCount() const { return (int) vertices.size(); }
const RawVertex &GetVertex(const int index) const { return vertices[index]; }
int GetVertexCount() const {
return (int)vertices.size();
}
const RawVertex& GetVertex(const int index) const {
return vertices[index];
}
// Iterate over the triangles.
int GetTriangleCount() const { return (int) triangles.size(); }
const RawTriangle &GetTriangle(const int index) const { return triangles[index]; }
int GetTriangleCount() const {
return (int)triangles.size();
}
const RawTriangle& GetTriangle(const int index) const {
return triangles[index];
}
// Iterate over the textures.
int GetTextureCount() const { return (int) textures.size(); }
const RawTexture &GetTexture(const int index) const { return textures[index]; }
int GetTextureCount() const {
return (int)textures.size();
}
const RawTexture& GetTexture(const int index) const {
return textures[index];
}
// Iterate over the materials.
int GetMaterialCount() const { return (int) materials.size(); }
const RawMaterial &GetMaterial(const int index) const { return materials[index]; }
int GetMaterialCount() const {
return (int)materials.size();
}
const RawMaterial& GetMaterial(const int index) const {
return materials[index];
}
// Iterate over the surfaces.
int GetSurfaceCount() const { return (int) surfaces.size(); }
const RawSurface &GetSurface(const int index) const { return surfaces[index]; }
RawSurface &GetSurface(const int index) { return surfaces[index]; }
int GetSurfaceCount() const {
return (int)surfaces.size();
}
const RawSurface& GetSurface(const int index) const {
return surfaces[index];
}
RawSurface& GetSurface(const int index) {
return surfaces[index];
}
int GetSurfaceById(const long id) const;
// Iterate over the animations.
int GetAnimationCount() const { return (int) animations.size(); }
const RawAnimation &GetAnimation(const int index) const { return animations[index]; }
int GetAnimationCount() const {
return (int)animations.size();
}
const RawAnimation& GetAnimation(const int index) const {
return animations[index];
}
// Iterate over the cameras.
int GetCameraCount() const { return (int) cameras.size(); }
const RawCamera &GetCamera(const int index) const { return cameras[index]; }
int GetCameraCount() const {
return (int)cameras.size();
}
const RawCamera& GetCamera(const int index) const {
return cameras[index];
}
// Iterate over the lights.
int GetLightCount() const { return (int) lights.size(); }
const RawLight &GetLight(const int index) const { return lights[index]; }
int GetLightCount() const {
return (int)lights.size();
}
const RawLight& GetLight(const int index) const {
return lights[index];
}
// Iterate over the nodes.
int GetNodeCount() const { return (int) nodes.size(); }
const RawNode &GetNode(const int index) const { return nodes[index]; }
RawNode &GetNode(const int index) { return nodes[index]; }
int GetNodeCount() const {
return (int)nodes.size();
}
const RawNode& GetNode(const int index) const {
return nodes[index];
}
RawNode& GetNode(const int index) {
return nodes[index];
}
int GetNodeById(const long nodeId) const;
// Create individual attribute arrays.
// Returns true if the vertices store the particular attribute.
template <typename _attrib_type_>
void GetAttributeArray(std::vector<_attrib_type_> &out, const _attrib_type_ RawVertex::* ptr) const;
void GetAttributeArray(std::vector<_attrib_type_>& out, const _attrib_type_ RawVertex::*ptr)
const;
// Create an array with a raw model for each material.
// Multiple surfaces with the same material will turn into a single model.
// However, surfaces that are marked as 'discrete' will turn into separate models.
void CreateMaterialModels(
std::vector<RawModel> &materialModels, bool shortIndices, const int keepAttribs, const bool forceDiscrete) const;
std::vector<RawModel>& materialModels,
bool shortIndices,
const int keepAttribs,
const bool forceDiscrete) const;
private:
Vec3f getFaceNormal(int verts[3]) const;
@ -480,8 +538,9 @@ private:
};
template <typename _attrib_type_>
void RawModel::GetAttributeArray(std::vector<_attrib_type_> &out, const _attrib_type_ RawVertex::* ptr) const
{
void RawModel::GetAttributeArray(
std::vector<_attrib_type_>& out,
const _attrib_type_ RawVertex::*ptr) const {
out.resize(vertices.size());
for (size_t i = 0; i < vertices.size(); i++) {
out[i] = vertices[i].*ptr;

View File

@ -9,20 +9,20 @@
#include "File_Utils.hpp"
#include <fstream>
#include <string>
#include <vector>
#include <fstream>
#include <stdint.h>
#include <stdio.h>
#if defined(__unix__) || defined(__APPLE__)
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#define _getcwd getcwd
#define _mkdir(a) mkdir(a, 0777)
@ -41,8 +41,7 @@
namespace FileUtils {
std::string GetCurrentFolder()
{
std::string GetCurrentFolder() {
char cwd[StringUtils::MAX_PATH_LENGTH];
if (!_getcwd(cwd, sizeof(cwd))) {
return std::string();
@ -57,14 +56,12 @@ namespace FileUtils {
return std::string(cwd);
}
bool FileExists(const std::string &filePath)
{
bool FileExists(const std::string& filePath) {
std::ifstream stream(filePath);
return stream.good();
}
bool FolderExists(const std::string &folderPath)
{
bool FolderExists(const std::string& folderPath) {
#if defined(__unix__) || defined(__APPLE__)
DIR* dir = opendir(folderPath.c_str());
if (dir) {
@ -74,16 +71,14 @@ namespace FileUtils {
return false;
#else
const DWORD ftyp = GetFileAttributesA(folderPath.c_str());
if ( ftyp == INVALID_FILE_ATTRIBUTES )
{
if (ftyp == INVALID_FILE_ATTRIBUTES) {
return false; // bad path
}
return (ftyp & FILE_ATTRIBUTE_DIRECTORY) != 0;
#endif
}
bool MatchExtension(const char *fileExtension, const char *matchExtensions)
{
bool MatchExtension(const char* fileExtension, const char* matchExtensions) {
if (matchExtensions[0] == '\0') {
return true;
}
@ -91,9 +86,11 @@ namespace FileUtils {
fileExtension++;
}
for (const char* end = matchExtensions; end[0] != '\0';) {
for (; end[0] == ';'; end++) {}
for (; end[0] == ';'; end++) {
}
const char* ext = end;
for (; end[0] != ';' && end[0] != '\0'; end++) {}
for (; end[0] != ';' && end[0] != '\0'; end++) {
}
#if defined(__unix__) || defined(__APPLE__)
if (strncasecmp(fileExtension, ext, end - ext) == 0)
#else
@ -106,8 +103,7 @@ namespace FileUtils {
return false;
}
std::vector<std::string> ListFolderFiles(const char *folder, const char *matchExtensions)
{
std::vector<std::string> ListFolderFiles(const char* folder, const char* matchExtensions) {
std::vector<std::string> fileList;
#if defined(__unix__) || defined(__APPLE__)
DIR* dir = opendir(strlen(folder) > 0 ? folder : ".");
@ -140,10 +136,8 @@ namespace FileUtils {
WIN32_FIND_DATA FindFileData;
HANDLE hFind = FindFirstFile(pathStr.c_str(), &FindFileData);
if ( hFind != INVALID_HANDLE_VALUE )
{
do
{
if (hFind != INVALID_HANDLE_VALUE) {
do {
if ((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) {
std::string fileName = FindFileData.cFileName;
std::string::size_type extPos = fileName.rfind('.');
@ -160,8 +154,7 @@ namespace FileUtils {
return fileList;
}
bool CreatePath(const char *path)
{
bool CreatePath(const char* path) {
#if defined(__unix__) || defined(__APPLE__)
StringUtils::PathSeparator separator = StringUtils::PATH_UNIX;
#else
@ -210,7 +203,12 @@ namespace FileUtils {
if (srcSize == dstSize) {
return true;
}
fmt::printf("Warning: Only copied %lu bytes to %s, when %s is %lu bytes long.\n", dstSize, dstFilename, srcFilename, srcSize);
fmt::printf(
"Warning: Only copied %lu bytes to %s, when %s is %lu bytes long.\n",
dstSize,
dstFilename,
srcFilename,
srcSize);
return false;
}
}
} // namespace FileUtils

View File

@ -24,5 +24,8 @@ namespace FileUtils {
bool CreatePath(const char* path);
bool CopyFile(const std::string &srcFilename, const std::string &dstFilename, bool createPath = false);
}
bool CopyFile(
const std::string& srcFilename,
const std::string& dstFilename,
bool createPath = false);
} // namespace FileUtils

View File

@ -9,8 +9,8 @@
#include "Image_Utils.hpp"
#include <string>
#include <algorithm>
#include <string>
#define STB_IMAGE_IMPLEMENTATION
@ -22,8 +22,7 @@
namespace ImageUtils {
static bool imageHasTransparentPixels(FILE *f)
{
static bool imageHasTransparentPixels(FILE* f) {
int width, height, channels;
// RGBA: we have to load the pixels to figure out if the image is fully opaque
uint8_t* pixels = stbi_load_from_file(f, &width, &height, &channels, 0);
@ -39,8 +38,7 @@ namespace ImageUtils {
return false;
}
ImageProperties GetImageProperties(char const *filePath)
{
ImageProperties GetImageProperties(char const* filePath) {
ImageProperties result = {
1,
1,
@ -61,8 +59,7 @@ namespace ImageUtils {
return result;
}
std::string suffixToMimeType(std::string suffix)
{
std::string suffixToMimeType(std::string suffix) {
std::transform(suffix.begin(), suffix.end(), suffix.begin(), ::tolower);
if (suffix == "jpg" || suffix == "jpeg") {
@ -74,4 +71,4 @@ namespace ImageUtils {
return "image/unknown";
}
}
} // namespace ImageUtils

View File

@ -13,14 +13,9 @@
namespace ImageUtils {
enum ImageOcclusion
{
IMAGE_OPAQUE,
IMAGE_TRANSPARENT
};
enum ImageOcclusion { IMAGE_OPAQUE, IMAGE_TRANSPARENT };
struct ImageProperties
{
struct ImageProperties {
int width;
int height;
ImageOcclusion occlusion;
@ -29,9 +24,9 @@ namespace ImageUtils {
ImageProperties GetImageProperties(char const* filePath);
/**
* Very simple method for mapping filename suffix to mime type. The glTF 2.0 spec only accepts values
* "image/jpeg" and "image/png" so we don't need to get too fancy.
* Very simple method for mapping filename suffix to mime type. The glTF 2.0 spec only accepts
* values "image/jpeg" and "image/png" so we don't need to get too fancy.
*/
std::string suffixToMimeType(std::string suffix);
}
} // namespace ImageUtils

View File

@ -11,8 +11,7 @@
namespace StringUtils {
PathSeparator operator!(const PathSeparator &s)
{
PathSeparator operator!(const PathSeparator& s) {
return (s == PATH_WIN) ? PATH_UNIX : PATH_WIN;
}
@ -23,54 +22,49 @@ namespace StringUtils {
return PATH_WIN;
#endif
}
const std::string NormalizePath(const std::string &path)
{
const std::string NormalizePath(const std::string& path) {
PathSeparator separator = GetPathSeparator();
char replace;
if (separator == PATH_WIN) {
replace = PATH_UNIX;
}
else {
} else {
replace = PATH_WIN;
}
std::string normalizedPath = path;
for (size_t s = normalizedPath.find(replace, 0); s != std::string::npos; s = normalizedPath.find(replace, s)) {
for (size_t s = normalizedPath.find(replace, 0); s != std::string::npos;
s = normalizedPath.find(replace, s)) {
normalizedPath[s] = separator;
}
return normalizedPath;
}
const std::string GetFolderString(const std::string &path)
{
const std::string GetFolderString(const std::string& path) {
size_t s = path.rfind(PATH_WIN);
s = (s != std::string::npos) ? s : path.rfind(PATH_UNIX);
return path.substr(0, s + 1);
}
const std::string GetCleanPathString(const std::string &path, const PathSeparator separator)
{
const std::string GetCleanPathString(const std::string& path, const PathSeparator separator) {
std::string cleanPath = path;
for (size_t s = cleanPath.find(!separator, 0); s != std::string::npos; s = cleanPath.find(!separator, s)) {
for (size_t s = cleanPath.find(!separator, 0); s != std::string::npos;
s = cleanPath.find(!separator, s)) {
cleanPath[s] = separator;
}
return cleanPath;
}
const std::string GetFileNameString(const std::string &path)
{
const std::string GetFileNameString(const std::string& path) {
size_t s = path.rfind(PATH_WIN);
s = (s != std::string::npos) ? s : path.rfind(PATH_UNIX);
return path.substr(s + 1, std::string::npos);
}
const std::string GetFileBaseString(const std::string &path)
{
const std::string GetFileBaseString(const std::string& path) {
const std::string fileName = GetFileNameString(path);
return fileName.substr(0, fileName.rfind('.')).c_str();
}
const std::string GetFileSuffixString(const std::string &path)
{
const std::string GetFileSuffixString(const std::string& path) {
const std::string fileName = GetFileNameString(path);
size_t pos = fileName.rfind('.');
if (pos == std::string::npos) {
@ -79,9 +73,8 @@ namespace StringUtils {
return fileName.substr(++pos);
}
int CompareNoCase(const std::string &s1, const std::string &s2)
{
int CompareNoCase(const std::string& s1, const std::string& s2) {
return strncasecmp(s1.c_str(), s2.c_str(), MAX_PATH_LENGTH);
}
}
} // namespace StringUtils

View File

@ -9,10 +9,10 @@
#pragma once
#include <string>
#include <cstdarg>
#include <cstdio>
#include <cstring>
#include <cstdarg>
#include <string>
#if defined(_MSC_VER)
#define strncasecmp _strnicmp
@ -23,22 +23,19 @@ namespace StringUtils {
static const unsigned int MAX_PATH_LENGTH = 1024;
enum PathSeparator
{
PATH_WIN = '\\',
PATH_UNIX = '/'
};
enum PathSeparator { PATH_WIN = '\\', PATH_UNIX = '/' };
PathSeparator operator!(const PathSeparator& s);
PathSeparator GetPathSeparator();
const std::string NormalizePath(const std::string& path);
const std::string GetCleanPathString(const std::string &path, const PathSeparator separator = PATH_WIN);
const std::string GetCleanPathString(
const std::string& path,
const PathSeparator separator = PATH_WIN);
template <size_t size>
void GetCleanPath(char (&dest)[size], const char *path, const PathSeparator separator = PATH_WIN)
{
void GetCleanPath(char (&dest)[size], const char* path, const PathSeparator separator = PATH_WIN) {
size_t len = size - 1;
strncpy(dest, path, len);
char* destPtr = dest;
@ -54,4 +51,4 @@ namespace StringUtils {
int CompareNoCase(const std::string& s1, const std::string& s2);
}
} // namespace StringUtils