C++/Qt读取二进制STL文件

  • STL文件结构(没必要看)
  • C++版本
  • QT版本

STL文件结构(没必要看)

二进制STL文件用固定的字节数来给出三角面片的几何信息。

【80】80个字节的文件头,用于存贮文件名
【4】 4 个字节的int描述模型的三角面片个数(小端存储)
【50*n】一个三角面片占用固定的50个字节(小端存储),依次是:
【12】3个4字节浮点数(角面片的法矢量)
【12】3个4字节浮点数(1个顶点的坐标)
【12】3个4字节浮点数(2个顶点的坐标)
【12】3个4字节浮点数(3个顶点的坐标)个
【2】三角面片的最后2个字节用来描述三角面片的属性信息。
一个完整二进制STL文件的大小为三角形面片数乘以 50再加上84个字节。

C++版本

struct CTriangle
{
    float normal[3];
    float v1[3];
    float v2[3];
    float v3[3];
    uint16_t attribute;
};

void readSTL(std::vector<CTriangle>& data, std::string filename)
{
    // Open the file as a binary file
    std::ifstream file(filename, std::ios::binary);
    if (file.is_open())
    {
    	//标题,可以不用但不能删
        char header[80];
        file.read(header, 80);
        
        //面片数量
        uint32_t num_triangles;
        file.read((char*)&num_triangles, 4);
        
        //防止拷贝
        data.resize(num_triangles * 3);
        // Loop over each triangle
        for (uint32_t i = 0; i < num_triangles; i++)
        {
            //CTriangle m_cTriangle;
            //file.read((char*)&m_cTriangle, 50);
            file.read((char*)&data[i], 50);
        }
        // Close the file
        file.close();
    }
    else
    {
        // Print an error message
        std::cout << "Unable to open file" << endl;
    }
}

QT版本

struct BTriangle
{
    QVector3D normal;
    QVector3D v1;
    QVector3D v2;
    QVector3D v3;
    uint16_t attribute;
};

void readSTL(QVector<BTriangle>& data, std::string filename)
{
    // Open the file as a binary file
    std::ifstream file(filename, std::ios::binary);
    if (file.is_open())
    {
    	//标题,可以不用但不能删
        char header[80];
        file.read(header, 80);
        
        //面片数量
        uint32_t num_triangles;
        file.read((char*)&num_triangles, 4);
        
        //防止拷贝
        data.resize(num_triangles * 3);
        // Loop over each triangle
        for (uint32_t i = 0; i < num_triangles; i++) 
            file.read((char*)&data[i], 50);
            
        // Close the file
        file.close();
    }
    else
    {
        // Print an error message
        std::cout << "Unable to open file" << endl;
    }
}



#废话篇
其实两套没啥区别,只是为了让广大网友ctrl c方便,说实话我觉得其他网友写的太复杂了
要转载无需告知,随便转载

参考:
[1]https://blog.csdn/id145/article/details/85219466
[2]new bing & chatGPT

更多推荐

C++/Qt读取二进制STL文件