fbx_to_3dtiles/cpp_src/fbx_wrap.cpp

97 lines
3.0 KiB
C++

#include "fbx_wrap.h"
#include <stdio.h>
#include <iostream>
using namespace std;
int load_triangles(fbxsdk::FbxNodeAttribute* attr, std::vector<Triangle>& triangles) {
FbxMesh* mesh = static_cast<FbxMesh*>(attr);
// 顶点数据
// int ctrlPointCount = mesh->GetControlPointsCount();
// vertices.assign(mesh->GetControlPoints(), mesh->GetControlPoints() + ctrlPointCount);
// 三角化并提取三角形索引
FbxGeometryConverter converter(mesh->GetFbxManager());
if (!converter.Triangulate(mesh, true)) return false; // 强制三角化
int polyCount = mesh->GetPolygonCount();
triangles.reserve(polyCount);
for (int i = 0; i < polyCount; ++i) {
if (mesh->GetPolygonSize(i) != 3) continue; // 跳过非三角形(理论上不会存在)
int i0 = mesh->GetPolygonVertex(i, 0);
int i1 = mesh->GetPolygonVertex(i, 1);
int i2 = mesh->GetPolygonVertex(i, 2);
triangles.emplace_back(i0, i1, i2);
}
return true;
}
FbxNode* get_fbx_root_node(const char* fbx_path)
{
printf("loading fbx file: %s\n", fbx_path);
FbxManager* lSdkManager = FbxManager::Create();
if (lSdkManager){
printf("FbxManager created successfully.\n");
} else{
printf("FbxManager creation failed.\n");
}
FbxScene* lScene = FbxScene::Create(lSdkManager, "myScene");
if (lScene){
printf("FbxScene created successfully.\n");
} else{
printf("FbxScene creation failed.\n");
}
FbxImporter* lImporter = FbxImporter::Create(lSdkManager, "");
bool s = lImporter->Initialize(fbx_path, -1, lSdkManager->GetIOSettings());
if (s){
printf("FbxImporter initialized successfully.\n");
} else{
printf("FbxImporter initialization failed.\n");
}
lImporter->Import(lScene);
lImporter->Destroy();
return lScene->GetRootNode();
}
void each_node(const FttContext* ctx, FbxNode* parent_node, int level)
{
// info
print_node_info(parent_node, level);
// data
for (int i = 0; i < parent_node->GetNodeAttributeCount(); i++)
{
FbxNodeAttribute* attr = parent_node->GetNodeAttributeByIndex(i);
if (attr && attr->GetAttributeType() == FbxNodeAttribute::eMesh)
{
std::vector<Triangle> triangles;
int count = load_triangles(attr, triangles);
printf("triangles: %ld\n", triangles.size());
// save data to database
}
}
// children
if (parent_node->GetChildCount())
{
for (int i = 0; i < parent_node->GetChildCount(); i++)
{
FbxNode* child = parent_node->GetChild(i);
each_node(ctx, child, level + 1);
}
}
}
void print_node_info(FbxNode* node, int level)
{
// 打印一下节点信息
printf("|");
for (int i = 0; i < level; i++)
{
printf("-");
}
printf("> ");
printf("[%ld]: %s\n", node->GetUniqueID(), node->GetNameOnly().Buffer());
}