vector<string> split(const string &str,const string &pattern)
{
//进行字符串的切割
//const char* convert to char*
char * strc = new char[strlen(str.c_str())+1];
strcpy(strc, str.c_str());
vector<string> resultVec;
char* tmpStr = strtok(strc, pattern.c_str());
while (tmpStr != NULL)
{
resultVec.push_back(string(tmpStr));
tmpStr = strtok(NULL, pattern.c_str());
}
delete[] strc;
return resultVec;
}
void OBj2OFF(string fname2, string offpath,vector<vector<double> >& vset,vector<vector<int> >& fset) {
string line;
fstream f;
f.open(fname2, ios::in);
if (!f.is_open())
cout << "文件打开出错" << endl;
int v_counter = 1;
int f_counter = 1;
while (!f.eof()) {
getline(f, line);//拿到obj文件中一行,作为一个字符串
vector<string>parameters;
string tailMark = " ";
string ans = "";
line = line.append(tailMark);
if(line[0]!='v'&&line[0]!='f'){
continue;
}
for (int i = 0; i < line.length(); i++) {
char ch = line[i];
if (ch != ' ') {
ans += ch;
}
else {
if(ans!=""){
parameters.push_back(ans); //取出字符串中的元素,以空格切分
ans = "";}
}
}
if (parameters[0] == "v") { //如果是顶点的话
vector<double>Point;
v_counter++;
Point.push_back(atof( parameters[1].c_str()));
Point.push_back(atof( parameters[2].c_str()));
Point.push_back(atof( parameters[3].c_str()));
vset.push_back(Point);
}
else if (parameters[0] == "f") { //如果是面的话,存放顶点的索引
vector<int>vIndexSets; //临时存放点的集合
for (int i = 1; i < 4; i++) {
string x = parameters[i];
string ans = "";
for (int j = 0; j < x.length(); j++) { //跳过‘/’
char ch = x[j];
if (ch != '/')
ans += ch;
else
break;
}
vector<string >res = split(ans,"/");
int index = atof(res[0].c_str());
index--;//因为顶点索引在obj文件中是从1开始的,而我们存放的顶点vector是从0开始的,因此要减1
vIndexSets.push_back(index);
}
fset.push_back(vIndexSets);
}
}
f.close();
int vert_number = vset.size();
int face_number = fset.size();
ofstream out(offpath);
out << "OFF"<< endl;
out << vset.size() <<" "<< fset.size() <<" 0"<< endl;
for (int j = 0; j <vset.size() ; ++j) {
out << (vset[j][0]) <<" " << vset[j][1]<< " "<< vset[j][2]<< endl;
}
for (int j = 0; j <fset.size() ; ++j) {
out <<"3 " << (fset[j][0]) <<" " << fset[j][1] <<" " << fset[j][2]<< endl;
}
out.close();
}
obj文件转off
最新推荐文章于 2025-03-17 15:59:14 发布