全是文件操作,没什么困难的,稍微有点坑是obj的face对应的vertex的idx要加1,下面上代码。
思路是找到POINTS把点坐标都读出来,找到CELLS把面片都读出来,然后根据obj的格式写一下数据。
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <OpenMesh/Core/IO/MeshIO.hh>
#include <OpenMesh/Core/Mesh/TriMesh_ArrayKernelT.hh>
using namespace std;
struct TriMesh {
vector<OpenMesh::Vec3d> points;
vector<OpenMesh::Vec3i> faces;
}MyMesh;
void readVtk(std::string input)
{
ifstream input_file(input);
if (!input_file.is_open()) {
std::cout << "Unable to open file";
return;
}
std::string ss[3];
std::string line;
char str[10];
double xt, yt, zt;
int a, b, c, d, tc, t;
while (getline(input_file, line)) {
istringstream iss(line);
if (line.find("POINTS") != std::string::npos) {
iss >> str >> a >> str;
MyMesh.points.resize(a);
break;
}
}
double x, y, z, xx, yy, zz;
for (int i = 0; i < a; ++i) {
std::getline(input_file, line);
std::istringstream iss(line);
iss >> x >> y >> z;
MyMesh.points[i][0] = x;
MyMesh.points[i][1] = y;
MyMesh.points[i][2] = z;
}
while (std::getline(input_file, line)) {
std::istringstream iss(line);
if (line.find("CELLS") != std::string::npos) {
iss >> str >> tc >> b;
MyMesh.faces.resize(tc);
break;
}
}
for (int i = 0; i < tc; ++i) {
std::getline(input_file, line);
std::istringstream iss(line);
iss >> t >> a >> b >> c >> d;
MyMesh.faces[i][0] = a + 1;
MyMesh.faces[i][1] = b + 1;
MyMesh.faces[i][2] = c + 1;
}
input_file.close();
}
void VtkToObj(string outfile)
{
ofstream stream;
stream.open(outfile);
stream << "g object" << "\n";
for (int i = 0; i < MyMesh.points.size(); ++i) {
stream << "v " << MyMesh.points[i][0] << " " << MyMesh.points[i][1] << " " << MyMesh.points[i][2] << "\n";
}
for (int i = 0; i < MyMesh.faces.size(); ++i) {
stream << "f " << MyMesh.faces[i][0] << " " << MyMesh.faces[i][1] << " " << MyMesh.faces[i][2] << "\n";
}
stream.close();
}
int main(int argc, char** argv)
{
if (3 != argc) {
cout << "Program InputFile OutputFile";
return -1;
}
readVtk(argv[1]);
VtkToObj(argv[2]);
return 0;
}
转载请注明原文地址:https://blackberry.8miu.com/read-31588.html