简体   繁体   English

用C ++编写二进制.stl文件

[英]Writing binary .stl files in C++

I want to write data from an vector of coordinates into a binary .stl 3d geometry file. 我想将坐标向量中的数据写入二进制.stl 3d几何文件中。

I need to have a 80 bit header, 24bit number of triangles. 我需要一个80位标题,24位三角形。 Each triangle is supposed to be defined by 3 points and one normal, each of which coordinate values is 32 bit.In addition, each triangle may have an attribute, which I wanted to leave empty. 每个三角形应该由3个点和一个法线来定义,每个点的坐标值为32位。此外,每个三角形可能都有一个属性,我想保留为空。 (See wiki ) (请参阅Wiki

I guess I am still having misunderstanding about char and binary mode. 我想我仍然对char和二进制模式有误解。

The file that is produced in the end has the same size as my original file but cannot be read by the graphics programme, so there needs to be a logical mistake still... 最后生成的文件与我的原始文件大小相同,但是无法由图形程序读取,因此仍然需要逻辑上的错误...

My point coordinates are double valued before casting to char*, is this ok to do so?? 我的点坐标在转换为char *之前是双值的,这样做可以吗??

排在二进制文件之外

My code: 我的代码:

void write_stl(std::string filename, std::vector<tri> triangles){

//binary file
std::string header_info = "solid " + filename + "-output";
char head[80];
std::strncpy(head,header_info.c_str(),sizeof(head)-1);
char attribute[2] = "0";
unsigned long nTriLong = triangles.size() ;

std::ofstream myfile;

myfile.open((Filename + "-out.stl").c_str(),  std::ios::out | std::ios::binary);
myfile.write(head,sizeof(head));
myfile.write((char*)&nTriLong,4);

    //write down every triangle
for (std::vector<tri>::iterator it = triangles.begin(); it!=triangles.end(); it++){
    //normal vector coordinates

    myfile.write((char*)&it->m_n.m_x, 4);
    myfile.write((char*)&it->m_n.m_y, 4);
    myfile.write((char*)&it->m_n.m_z, 4);

    //p1 coordinates
    myfile.write((char*)&it->m_p1.m_x, 4);
    myfile.write((char*)&it->m_p1.m_y, 4);
    myfile.write((char*)&it->m_p1.m_z, 4);

    //p2 coordinates
    myfile.write((char*)&it->m_p2.m_x, 4);
    myfile.write((char*)&it->m_p2.m_y, 4);
    myfile.write((char*)&it->m_p2.m_z, 4);

    //p3 coordinates
    myfile.write((char*)&it->m_p3.m_x, 4);
    myfile.write((char*)&it->m_p3.m_y, 4);
    myfile.write((char*)&it->m_p3.m_z, 4);

    myfile.write(attribute,2);
}

myfile.close();

} }

Where tri is just a structure for a triangle containing the 3 points and the normal as "3D vectors" (ie Structures with x,y,z, value) ... 其中tri只是一个三角形的结构,该三角形包含3个点和法线作为“ 3D向量”(即具有x,y,z,值的结构)...

The size argument to write() is the size in bytes, not in bits. write()的size参数是以字节为单位的大小,而不是以位为单位。 You are passing 32 for a float when you should be passing 4. 您应该通过4时才通过32 float

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM