huhb3d-viewer / src /core /generate_stl.cpp
Hgodwarrior's picture
Deploy: Huhb3D Generator with Docker
1dd0e3b
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <cmath>
// 二进制STL文件格式:
// 1. 80字节文件头
// 2. 4字节三角形数量
// 3. 每个三角形:
// - 3个4字节浮点数:法向量
// - 3个顶点,每个顶点3个4字节浮点数
// - 2字节属性计数(通常为0)
// 生成随机浮点数
float random_float(float min, float max) {
return min + static_cast<float>(rand()) / RAND_MAX * (max - min);
}
// 计算法向量
void compute_normal(const float* v1, const float* v2, const float* v3, float* normal) {
float v12[3] = {v2[0] - v1[0], v2[1] - v1[1], v2[2] - v1[2]};
float v13[3] = {v3[0] - v1[0], v3[1] - v1[1], v3[2] - v1[2]};
normal[0] = v12[1] * v13[2] - v12[2] * v13[1];
normal[1] = v12[2] * v13[0] - v12[0] * v13[2];
normal[2] = v12[0] * v13[1] - v12[1] * v13[0];
// 归一化
float length = sqrt(normal[0] * normal[0] + normal[1] * normal[1] + normal[2] * normal[2]);
if (length > 1e-6) {
normal[0] /= length;
normal[1] /= length;
normal[2] /= length;
}
}
int main() {
const size_t TRIANGLE_COUNT = 10000000; // 1000万个三角形
const char* filename = "random_10m.stl";
// 初始化随机数生成器
srand(static_cast<unsigned int>(time(nullptr)));
// 打开文件
std::ofstream file(filename, std::ios::binary);
if (!file) {
std::cerr << "Failed to open file: " << filename << std::endl;
return 1;
}
// 写入文件头(80字节)
char header[80] = "Generated by Huhb-Utopia-Project";
file.write(header, 80);
// 写入三角形数量(4字节)
file.write(reinterpret_cast<const char*>(&TRIANGLE_COUNT), sizeof(TRIANGLE_COUNT));
// 生成并写入三角形
for (size_t i = 0; i < TRIANGLE_COUNT; ++i) {
// 生成三个随机顶点
float v1[3] = {random_float(-100.0f, 100.0f), random_float(-100.0f, 100.0f), random_float(-100.0f, 100.0f)};
float v2[3] = {random_float(-100.0f, 100.0f), random_float(-100.0f, 100.0f), random_float(-100.0f, 100.0f)};
float v3[3] = {random_float(-100.0f, 100.0f), random_float(-100.0f, 100.0f), random_float(-100.0f, 100.0f)};
// 计算法向量
float normal[3];
compute_normal(v1, v2, v3, normal);
// 写入法向量
file.write(reinterpret_cast<const char*>(normal), sizeof(normal));
// 写入顶点
file.write(reinterpret_cast<const char*>(v1), sizeof(v1));
file.write(reinterpret_cast<const char*>(v2), sizeof(v2));
file.write(reinterpret_cast<const char*>(v3), sizeof(v3));
// 写入属性计数(2字节,通常为0)
uint16_t attribute_count = 0;
file.write(reinterpret_cast<const char*>(&attribute_count), sizeof(attribute_count));
// 每100万个三角形输出一次进度
if ((i + 1) % 1000000 == 0) {
std::cout << "Generated " << (i + 1) << " triangles..." << std::endl;
}
}
// 关闭文件
file.close();
std::cout << "Successfully generated " << TRIANGLE_COUNT << " triangles in " << filename << std::endl;
return 0;
}