C++获取vtk二进制文件中每个粒子点坐标

我们知道在.vtk文件中存储了粒子的点坐标,标量,元索引等的数字信息,由于我的vtk是二进制存储,无法直接看到粒子坐标。
在这里插入图片描述

那么就需要C++二进制读取文件进行查看。下边是读取的代码


#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
    
    qDebug() << "begin to show vtk pointsssssssssssss";
    std::ifstream infile("E:/a-sph_out/TwoSimpleTank/SimpleTank_out/particles/Particle_inert_0001.vtk", std::ios::binary);
    if (!infile) {
        std::cerr << "Error opening file!" << std::endl;
    }

    std::string line;
    std::vector<float> particleCoords;

    // Read the file line by line
    while (std::getline(infile, line)) {
        // Find the line that starts with "POINTS"
        if (line.find("POINTS") != std::string::npos) {
            // Extract the number of points
            int numPoints;
            sscanf_s(line.c_str(), "POINTS %d", &numPoints);

            // Read the point coordinates
            for (int i = 0; i < numPoints; ++i) {
                float x, y, z;
                infile.read(reinterpret_cast<char*>(&x), sizeof(float));
                infile.read(reinterpret_cast<char*>(&y), sizeof(float));
                infile.read(reinterpret_cast<char*>(&z), sizeof(float));
                particleCoords.push_back(x);
                particleCoords.push_back(y);
                particleCoords.push_back(z);
            }
            break; // Stop reading after points are read
        }
    }

    // Display the particle coordinates
    std::cout << "Particle Coordinates: " << std::endl;
    for (size_t i = 0; i < particleCoords.size(); i += 3) {
        std::cout << "Particle " << i / 3 << ": "
                  << particleCoords[i] << ", "
                  << particleCoords[i + 1] << ", "
                  << particleCoords[i + 2] << std::endl;
    }

    infile.close();

之后看控制台输出,就可以看到每个粒子坐标了
在这里插入图片描述

但是有个问题,可以看到粒子的坐标范围很大,比如Particle 2的z坐标是1.19845e+26,直接是26数量级的坐标。而ParaView系统系统检测出的粒子集边界如下:
在这里插入图片描述
很明显所显示的粒子坐标不在这个边界范围内。显示的坐标有问题。。

最后找到原因,是字节序问题:
不同的计算机架构有不同的字节序,即大端(Big Endian)和小端(Little Endian)。如果文件是在一个字节序架构上创建的,然后在另一个架构上读取,没有进行适当的转换,那么读取的数据会是错误的。
大白话的意思就是,在二进制里,有时候是大端存储,有时候是小端存储,所以读出来的数据不一样。
改正方法就是反转字节:

                char* valuePtr_x = reinterpret_cast<char*>(&x);
                std::reverse(valuePtr_x, valuePtr_x + sizeof(x));
                char* valuePtr_y = reinterpret_cast<char*>(&y);
                std::reverse(valuePtr_y, valuePtr_y + sizeof(y));
                char* valuePtr_z = reinterpret_cast<char*>(&z);
                std::reverse(valuePtr_z, valuePtr_z + sizeof(z));

上边这段放置的位置如下图:
在这里插入图片描述
然后再进行输出查看。可以看到输出正确:
在这里插入图片描述

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值