Files

2449 lines
100 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 官方 IO_BATCH 网格转换插件(VDE 微内核 P4 / 插件 ABI 1.5;纯 C ABI,不链接内核)。
//
// batch_id: io_batch.mesh;capability: io_batch:mesh_convert
// 支持 STL(binary/ascii 读,ascii 写)、OBJ(v/f 读写,多边形扇形三角化)、
// PLY(ASCII + binary_little_endian 读;输出 .ply 为 ASCII、.plyb 为 binary LE;
// float x/y/z + face list/索引类型)、OFF(ASCII v/f;COFF/NOFF 明确拒绝)之间的批量互转。
//
// 请求 JSON:
// {
// "items": [{"input":"a.stl","output":"a.obj","from":"stl","to":"obj"}, ...],
// "options": {"from":"stl","to":"obj","format":"stl","flags":0}
// }
// - items 必填非空;每项 input/output 必填;from/to 可省略(扩展名/options 推断);
// - options.flags 必须为 0;options.format 作为 to 默认值;
// - 每项独立处理:部分失败时返回 VDE_PLUGIN_OK,响应 JSON 中 "status"=-4
// (VDE_IO_BATCH_ERR_PARTIAL)且 ok=false/failed>0;全部失败同样为 partial。
// - 注意:当前 ABI 1.5 run 回调没有 VdeIoBatchResult 指针,无法直接回填
// result.status;插件用响应 JSON 的 "status" 字段表达 VDE_IO_BATCH_STATUS。
//
// 响应 JSON:{batch_id,status,ok,processed,failed,items:[{input,output,from,to,ok,error,
// vertices,triangles}],diagnostics}
// 限制:单文件 512MB、单网格 20M 三角面、items 4096。
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <string>
#include <vector>
#include "../common/format_plugin_common.h"
namespace {
using vde_plugin_common::fail;
using vde_plugin_common::read_file_bytes;
using vde_plugin_common::validate_common_host;
using vde_plugin_common::write_file_bytes;
constexpr std::size_t kMaxFileBytes = 512u * 1024u * 1024u;
constexpr std::size_t kMaxTriangles = 20000000u;
constexpr std::size_t kMaxVertices = 20000000u;
constexpr std::size_t kMaxItems = 4096u;
// P4-62:大文件流式阈值/块大小(小文件仍走内存路径以保持行为与性能)。
constexpr std::size_t kStreamInputThreshold = 8u * 1024u * 1024u;
constexpr std::size_t kStreamOutputTriangleThreshold = 50000u;
constexpr std::size_t kIoChunkBytes = 1u * 1024u * 1024u;
// ── 极简 JSON(对象/数组/字符串/数字/布尔/null)──────────────────────
struct JsonValue {
enum class Type { Null, Bool, Number, String, Array, Object };
Type type = Type::Null;
bool boolean = false;
double number = 0.0;
std::string text;
std::vector<JsonValue> array;
std::vector<std::pair<std::string, JsonValue>> object;
const JsonValue* find(const std::string& key) const {
if (type != Type::Object) return nullptr;
for (const auto& entry : object) {
if (entry.first == key) return &entry.second;
}
return nullptr;
}
};
class JsonParser {
public:
JsonParser(const char* data, std::size_t size)
: cursor_(data), end_(data + size) {}
bool parse(JsonValue* out) {
skip_ws();
if (!parse_value(out)) return false;
skip_ws();
return cursor_ == end_;
}
const std::string& error() const { return error_; }
private:
bool fail(const char* message) {
error_ = message;
return false;
}
void skip_ws() {
while (cursor_ < end_ && (*cursor_ == ' ' || *cursor_ == '\t' ||
*cursor_ == '\r' || *cursor_ == '\n'))
++cursor_;
}
bool parse_value(JsonValue* out) {
if (cursor_ >= end_) return fail("JSON 提前结束");
const char c = *cursor_;
if (c == '{') return parse_object(out);
if (c == '[') return parse_array(out);
if (c == '"') {
out->type = JsonValue::Type::String;
return parse_string(&out->text);
}
if (c == 't' || c == 'f') {
const char* word = (c == 't') ? "true" : "false";
const std::size_t length = std::strlen(word);
if (static_cast<std::size_t>(end_ - cursor_) < length ||
std::strncmp(cursor_, word, length) != 0)
return fail("非法 JSON 布尔值");
cursor_ += length;
out->type = JsonValue::Type::Bool;
out->boolean = (c == 't');
return true;
}
if (c == 'n') {
if (static_cast<std::size_t>(end_ - cursor_) < 4 ||
std::strncmp(cursor_, "null", 4) != 0)
return fail("非法 JSON null");
cursor_ += 4;
out->type = JsonValue::Type::Null;
return true;
}
return parse_number(out);
}
bool parse_string(std::string* out) {
out->clear();
if (cursor_ >= end_ || *cursor_ != '"') return fail("JSON 字符串缺少引号");
++cursor_;
while (cursor_ < end_) {
const char c = *cursor_++;
if (c == '"') return true;
if (c == '\\') {
if (cursor_ >= end_) return fail("JSON 转义不完整");
const char escape = *cursor_++;
switch (escape) {
case '"': out->push_back('"'); break;
case '\\': out->push_back('\\'); break;
case '/': out->push_back('/'); break;
case 'b': out->push_back('\b'); break;
case 'f': out->push_back('\f'); break;
case 'n': out->push_back('\n'); break;
case 'r': out->push_back('\r'); break;
case 't': out->push_back('\t'); break;
case 'u': {
if (end_ - cursor_ < 4) return fail("JSON unicode 转义不完整");
char hex[5] = {cursor_[0], cursor_[1], cursor_[2], cursor_[3], 0};
cursor_ += 4;
const long code = std::strtol(hex, nullptr, 16);
out->push_back((code < 0 || code > 0x7F) ? '?'
: static_cast<char>(code));
break;
}
default: return fail("非法 JSON 转义");
}
continue;
}
if (static_cast<unsigned char>(c) < 0x20) return fail("JSON 字符串含控制字符");
out->push_back(c);
}
return fail("JSON 字符串未闭合");
}
bool parse_number(JsonValue* out) {
const char* begin = cursor_;
if (cursor_ < end_ && (*cursor_ == '-' || *cursor_ == '+')) ++cursor_;
bool digits = false;
while (cursor_ < end_ && *cursor_ >= '0' && *cursor_ <= '9') {
digits = true;
++cursor_;
}
if (cursor_ < end_ && *cursor_ == '.') {
++cursor_;
while (cursor_ < end_ && *cursor_ >= '0' && *cursor_ <= '9') {
digits = true;
++cursor_;
}
}
if (!digits) return fail("非法 JSON 数字");
if (cursor_ < end_ && (*cursor_ == 'e' || *cursor_ == 'E')) {
++cursor_;
if (cursor_ < end_ && (*cursor_ == '-' || *cursor_ == '+')) ++cursor_;
bool exp_digits = false;
while (cursor_ < end_ && *cursor_ >= '0' && *cursor_ <= '9') {
exp_digits = true;
++cursor_;
}
if (!exp_digits) return fail("非法 JSON 指数");
}
const std::string text(begin, cursor_);
char* parse_end = nullptr;
out->number = std::strtod(text.c_str(), &parse_end);
if (parse_end == text.c_str() || *parse_end != '\0') return fail("非法 JSON 数字");
out->type = JsonValue::Type::Number;
return true;
}
bool parse_array(JsonValue* out) {
out->type = JsonValue::Type::Array;
++cursor_;
skip_ws();
if (cursor_ < end_ && *cursor_ == ']') {
++cursor_;
return true;
}
while (cursor_ < end_) {
JsonValue value;
skip_ws();
if (!parse_value(&value)) return false;
out->array.push_back(std::move(value));
skip_ws();
if (cursor_ >= end_) return fail("JSON 数组未闭合");
if (*cursor_ == ',') {
++cursor_;
continue;
}
if (*cursor_ == ']') {
++cursor_;
return true;
}
return fail("JSON 数组分隔符非法");
}
return fail("JSON 数组未闭合");
}
bool parse_object(JsonValue* out) {
out->type = JsonValue::Type::Object;
++cursor_;
skip_ws();
if (cursor_ < end_ && *cursor_ == '}') {
++cursor_;
return true;
}
while (cursor_ < end_) {
skip_ws();
std::string key;
if (!parse_string(&key)) return false;
skip_ws();
if (cursor_ >= end_ || *cursor_ != ':') return fail("JSON 对象缺少冒号");
++cursor_;
JsonValue value;
skip_ws();
if (!parse_value(&value)) return false;
out->object.emplace_back(std::move(key), std::move(value));
skip_ws();
if (cursor_ >= end_) return fail("JSON 对象未闭合");
if (*cursor_ == ',') {
++cursor_;
continue;
}
if (*cursor_ == '}') {
++cursor_;
return true;
}
return fail("JSON 对象分隔符非法");
}
return fail("JSON 对象未闭合");
}
const char* cursor_ = nullptr;
const char* end_ = nullptr;
std::string error_;
};
bool json_string(const JsonValue* parent, const char* key, std::string* out) {
if (!parent || !out) return false;
const JsonValue* value = parent->find(key);
if (!value || value->type != JsonValue::Type::String) return false;
*out = value->text;
return true;
}
bool json_uint(const JsonValue* parent, const char* key, std::uint32_t* out) {
if (!parent || !out) return false;
const JsonValue* value = parent->find(key);
if (!value || value->type != JsonValue::Type::Number) return false;
if (value->number < 0.0 || value->number > 4294967295.0) return false;
*out = static_cast<std::uint32_t>(value->number);
return true;
}
std::string json_escape(const std::string& text) {
std::string out;
out.reserve(text.size() + 8);
for (const char c : text) {
switch (c) {
case '"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if (static_cast<unsigned char>(c) < 0x20) {
char escape[8];
std::snprintf(escape, sizeof(escape), "\\u%04x",
static_cast<unsigned>(static_cast<unsigned char>(c)));
out += escape;
} else {
out.push_back(c);
}
}
}
return out;
}
std::string lower_ascii(const std::string& text) {
std::string out = text;
for (char& c : out) {
if (c >= 'A' && c <= 'Z') c = static_cast<char>(c - 'A' + 'a');
}
return out;
}
std::string extension_of(const std::string& path) {
const std::size_t dot = path.find_last_of('.');
if (dot == std::string::npos || dot + 1 >= path.size()) return std::string();
return lower_ascii(path.substr(dot + 1));
}
struct Mesh {
std::vector<double> positions;
std::vector<std::uint32_t> indices;
std::size_t vertex_count() const { return positions.size() / 3; }
std::size_t triangle_count() const { return indices.size() / 3; }
};
bool append_face(const std::vector<long long>& face, std::size_t vertex_count, Mesh* mesh,
std::string* error) {
if (face.size() < 3) {
if (error) *error = "面顶点数少于 3";
return false;
}
for (const long long value : face) {
if (value < 0 || static_cast<std::size_t>(value) >= vertex_count) {
if (error) *error = "面索引越界";
return false;
}
}
for (std::size_t i = 1; i + 1 < face.size(); ++i) {
const long long a = face[0];
const long long b = face[i];
const long long c = face[i + 1];
if (a == b || b == c || a == c) continue;
mesh->indices.push_back(static_cast<std::uint32_t>(a));
mesh->indices.push_back(static_cast<std::uint32_t>(b));
mesh->indices.push_back(static_cast<std::uint32_t>(c));
}
return true;
}
// ── STL ─────────────────────────────────────────────────────────────
bool parse_stl(const std::string& data, Mesh* mesh, std::string* error) {
if (data.size() >= 84) {
std::uint32_t triangle_count = 0;
std::memcpy(&triangle_count, data.data() + 80, sizeof(triangle_count));
const std::size_t expected = 84u + static_cast<std::size_t>(triangle_count) * 50u;
if (triangle_count > 0 && expected == data.size()) {
if (triangle_count > kMaxTriangles) {
if (error) *error = "STL 三角面数超过上限";
return false;
}
const unsigned char* cursor =
reinterpret_cast<const unsigned char*>(data.data()) + 84;
for (std::uint32_t t = 0; t < triangle_count; ++t) {
const std::uint32_t base = static_cast<std::uint32_t>(mesh->vertex_count());
for (int v = 0; v < 3; ++v) {
float xyz[3] = {0.0f, 0.0f, 0.0f};
std::memcpy(xyz, cursor, sizeof(xyz));
cursor += 12;
mesh->positions.push_back(static_cast<double>(xyz[0]));
mesh->positions.push_back(static_cast<double>(xyz[1]));
mesh->positions.push_back(static_cast<double>(xyz[2]));
}
cursor += 2;
mesh->indices.push_back(base);
mesh->indices.push_back(base + 1);
mesh->indices.push_back(base + 2);
}
return true;
}
}
if (data.rfind("solid", 0) != 0) {
if (error) *error = "不是 STL(ASCII 缺少 solid 头 / binary 长度不匹配)";
return false;
}
std::vector<double> facet;
std::size_t pos = 0;
while (pos < data.size()) {
const std::size_t eol = data.find('\n', pos);
const std::string line =
data.substr(pos, (eol == std::string::npos ? data.size() : eol) - pos);
pos = (eol == std::string::npos) ? data.size() : eol + 1;
const std::size_t first = line.find_first_not_of(" \t\r");
if (first == std::string::npos) continue;
if (line.compare(first, 6, "vertex") != 0) continue;
double xyz[3] = {0.0, 0.0, 0.0};
if (std::sscanf(line.c_str() + first + 6, "%lf %lf %lf", &xyz[0], &xyz[1],
&xyz[2]) != 3) {
if (error) *error = "STL 顶点行非法";
return false;
}
if (!std::isfinite(xyz[0]) || !std::isfinite(xyz[1]) || !std::isfinite(xyz[2])) {
if (error) *error = "STL 顶点含非有限数";
return false;
}
facet.push_back(xyz[0]);
facet.push_back(xyz[1]);
facet.push_back(xyz[2]);
if (facet.size() == 9) {
const std::uint32_t base = static_cast<std::uint32_t>(mesh->vertex_count());
mesh->positions.insert(mesh->positions.end(), facet.begin(), facet.end());
facet.clear();
mesh->indices.push_back(base);
mesh->indices.push_back(base + 1);
mesh->indices.push_back(base + 2);
}
}
if (!facet.empty()) {
if (error) *error = "STL 顶点数不是 3 的倍数";
return false;
}
if (mesh->indices.empty()) {
if (error) *error = "STL 不含三角面";
return false;
}
return true;
}
bool write_stl_ascii(const std::string& path, const Mesh& mesh, std::string* error) {
std::string text = "solid vde_io_batch_mesh\n";
char line[256];
for (std::size_t t = 0; t < mesh.triangle_count(); ++t) {
const double* a = &mesh.positions[mesh.indices[t * 3 + 0] * 3];
const double* b = &mesh.positions[mesh.indices[t * 3 + 1] * 3];
const double* c = &mesh.positions[mesh.indices[t * 3 + 2] * 3];
const double ux = b[0] - a[0], uy = b[1] - a[1], uz = b[2] - a[2];
const double vx = c[0] - a[0], vy = c[1] - a[1], vz = c[2] - a[2];
double nx = uy * vz - uz * vy;
double ny = uz * vx - ux * vz;
double nz = ux * vy - uy * vx;
const double length = std::sqrt(nx * nx + ny * ny + nz * nz);
if (length > 0.0) {
nx /= length;
ny /= length;
nz /= length;
}
std::snprintf(line, sizeof(line), "facet normal %.9g %.9g %.9g\n", nx, ny, nz);
text += line;
text += " outer loop\n";
for (const double* p : {a, b, c}) {
std::snprintf(line, sizeof(line), " vertex %.17g %.17g %.17g\n",
p[0], p[1], p[2]);
text += line;
}
text += " endloop\nendfacet\n";
}
text += "endsolid vde_io_batch_mesh\n";
if (!write_file_bytes(path.c_str(), text.data(), text.size())) {
if (error) *error = "无法写入 STL 文件";
return false;
}
return true;
}
// ── OBJ ─────────────────────────────────────────────────────────────
bool parse_obj(const std::string& data, Mesh* mesh, std::string* error) {
std::size_t pos = 0;
while (pos < data.size()) {
const std::size_t eol = data.find('\n', pos);
const std::string line =
data.substr(pos, (eol == std::string::npos ? data.size() : eol) - pos);
pos = (eol == std::string::npos) ? data.size() : eol + 1;
std::size_t cursor = line.find_first_not_of(" \t\r");
if (cursor == std::string::npos || line[cursor] == '#') continue;
if (line.compare(cursor, 1, "v") == 0) {
double xyz[3] = {0.0, 0.0, 0.0};
if (std::sscanf(line.c_str() + cursor + 1, "%lf %lf %lf", &xyz[0], &xyz[1],
&xyz[2]) != 3) {
if (error) *error = "OBJ 顶点行非法";
return false;
}
if (!std::isfinite(xyz[0]) || !std::isfinite(xyz[1]) || !std::isfinite(xyz[2])) {
if (error) *error = "OBJ 顶点含非有限数";
return false;
}
mesh->positions.push_back(xyz[0]);
mesh->positions.push_back(xyz[1]);
mesh->positions.push_back(xyz[2]);
} else if (line.compare(cursor, 1, "f") == 0) {
std::vector<long long> face;
cursor += 1;
const std::size_t vertex_count = mesh->vertex_count();
while (true) {
cursor = line.find_first_not_of(" \t\r", cursor);
if (cursor == std::string::npos) break;
const std::size_t end = line.find_first_of(" \t\r", cursor);
std::string token = line.substr(
cursor, (end == std::string::npos ? line.size() : end) - cursor);
cursor = (end == std::string::npos) ? line.size() : end;
const std::size_t slash = token.find('/');
if (slash != std::string::npos) token = token.substr(0, slash);
char* parse_end = nullptr;
long long index = std::strtoll(token.c_str(), &parse_end, 10);
if (parse_end == token.c_str() || *parse_end != '\0') {
if (error) *error = "OBJ 面索引非法";
return false;
}
// OBJ 正索引为 1-based;负索引为相对当前顶点数(-1 = 最后一个)。
if (index > 0) index -= 1;
else if (index < 0) index += static_cast<long long>(vertex_count);
if (index < 0 || static_cast<std::size_t>(index) >= vertex_count) {
if (error) *error = "OBJ 面索引越界";
return false;
}
face.push_back(index);
}
if (!append_face(face, mesh->vertex_count(), mesh, error)) return false;
}
}
if (mesh->indices.empty()) {
if (error) *error = "OBJ 不含三角面";
return false;
}
return true;
}
bool write_obj(const std::string& path, const Mesh& mesh, std::string* error) {
std::string text = "# VDE io_batch mesh\n";
char line[256];
for (std::size_t v = 0; v < mesh.vertex_count(); ++v) {
std::snprintf(line, sizeof(line), "v %.17g %.17g %.17g\n",
mesh.positions[v * 3], mesh.positions[v * 3 + 1],
mesh.positions[v * 3 + 2]);
text += line;
}
for (std::size_t t = 0; t < mesh.triangle_count(); ++t) {
std::snprintf(line, sizeof(line), "f %u %u %u\n", mesh.indices[t * 3] + 1,
mesh.indices[t * 3 + 1] + 1, mesh.indices[t * 3 + 2] + 1);
text += line;
}
if (!write_file_bytes(path.c_str(), text.data(), text.size())) {
if (error) *error = "无法写入 OBJ 文件";
return false;
}
return true;
}
// ── OFF(ASCII;COFF/NOFF 明确拒绝)─────────────────────────────────
bool parse_off(const std::string& data, Mesh* mesh, std::string* error) {
std::size_t pos = 0;
std::vector<std::string> tokens;
// OFF 头:OFF 后跟 nv nf ne(允许同行或下一行);支持 # 注释与空行。
while (pos < data.size() && tokens.size() < 4) {
const std::size_t eol = data.find('\n', pos);
std::string line =
data.substr(pos, (eol == std::string::npos ? data.size() : eol) - pos);
pos = (eol == std::string::npos) ? data.size() : eol + 1;
if (!line.empty() && line.back() == '\r') line.pop_back();
const std::size_t hash = line.find('#');
if (hash != std::string::npos) line = line.substr(0, hash);
std::size_t cursor = 0;
while (cursor < line.size()) {
cursor = line.find_first_not_of(" \t\r", cursor);
if (cursor == std::string::npos) break;
const std::size_t finish = line.find_first_of(" \t\r", cursor);
tokens.push_back(line.substr(
cursor, (finish == std::string::npos ? line.size() : finish) - cursor));
cursor = (finish == std::string::npos) ? line.size() : finish;
if (tokens.size() >= 4) break;
}
}
if (tokens.empty()) {
if (error) *error = "OFF 为空或缺少 OFF 头";
return false;
}
const std::string kind = tokens[0];
if (kind != "OFF") {
if (kind == "COFF" || kind == "NOFF" || kind == "4OFF" || kind == "nOFF") {
if (error) *error = "不支持 " + kind + "(仅 ASCII OFF v/f)";
} else {
if (error) *error = "不是 OFF(缺少 OFF 头)";
}
return false;
}
if (tokens.size() < 4) {
if (error) *error = "OFF 头缺少顶点/面/边数量";
return false;
}
char* end_ptr = nullptr;
const long long vertex_count = std::strtoll(tokens[1].c_str(), &end_ptr, 10);
if (end_ptr == tokens[1].c_str() || *end_ptr != '\0' || vertex_count < 0) {
if (error) *error = "OFF 顶点数量非法";
return false;
}
const long long face_count = std::strtoll(tokens[2].c_str(), &end_ptr, 10);
if (end_ptr == tokens[2].c_str() || *end_ptr != '\0' || face_count < 0) {
if (error) *error = "OFF 面数量非法";
return false;
}
if (static_cast<std::size_t>(vertex_count) > kMaxVertices ||
static_cast<std::size_t>(face_count) > kMaxTriangles) {
if (error) *error = "OFF 顶点/面数超过上限";
return false;
}
mesh->positions.reserve(static_cast<std::size_t>(vertex_count) * 3u);
for (long long v = 0; v < vertex_count; ++v) {
double xyz[3] = {0.0, 0.0, 0.0};
std::size_t read = 0;
while (pos < data.size() && read < 3) {
const std::size_t eol = data.find('\n', pos);
std::string line =
data.substr(pos, (eol == std::string::npos ? data.size() : eol) - pos);
pos = (eol == std::string::npos) ? data.size() : eol + 1;
if (!line.empty() && line.back() == '\r') line.pop_back();
const std::size_t hash = line.find('#');
if (hash != std::string::npos) line = line.substr(0, hash);
std::size_t cursor = line.find_first_not_of(" \t\r");
if (cursor == std::string::npos) continue;
while (cursor < line.size() && read < 3) {
char* parse_end = nullptr;
const double value = std::strtod(line.c_str() + cursor, &parse_end);
if (parse_end == line.c_str() + cursor) {
if (error) *error = "OFF 顶点行非法";
return false;
}
if (!std::isfinite(value)) {
if (error) *error = "OFF 顶点含非有限数";
return false;
}
xyz[read++] = value;
cursor = static_cast<std::size_t>(parse_end - line.c_str());
cursor = line.find_first_not_of(" \t\r", cursor);
if (cursor == std::string::npos) break;
}
}
if (read < 3) {
if (error) *error = "OFF 顶点数据不完整(截断)";
return false;
}
mesh->positions.push_back(xyz[0]);
mesh->positions.push_back(xyz[1]);
mesh->positions.push_back(xyz[2]);
}
for (long long f = 0; f < face_count; ++f) {
std::vector<long long> face;
bool have_count = false;
while (pos < data.size() && !have_count) {
const std::size_t eol = data.find('\n', pos);
std::string line =
data.substr(pos, (eol == std::string::npos ? data.size() : eol) - pos);
pos = (eol == std::string::npos) ? data.size() : eol + 1;
if (!line.empty() && line.back() == '\r') line.pop_back();
const std::size_t hash = line.find('#');
if (hash != std::string::npos) line = line.substr(0, hash);
std::size_t cursor = line.find_first_not_of(" \t\r");
if (cursor == std::string::npos) continue;
char* parse_end = nullptr;
const long long count = std::strtoll(line.c_str() + cursor, &parse_end, 10);
if (parse_end == line.c_str() + cursor || count < 0) {
if (error) *error = "OFF 面行非法";
return false;
}
if (count > static_cast<long long>(kMaxVertices)) {
if (error) *error = "OFF 面顶点数超过上限";
return false;
}
cursor = static_cast<std::size_t>(parse_end - line.c_str());
for (long long i = 0; i < count; ++i) {
cursor = line.find_first_not_of(" \t\r", cursor);
if (cursor == std::string::npos) break;
const long long index = std::strtoll(line.c_str() + cursor, &parse_end, 10);
if (parse_end == line.c_str() + cursor) break;
face.push_back(index);
cursor = static_cast<std::size_t>(parse_end - line.c_str());
}
have_count = true;
}
if (!have_count) {
if (error) *error = "OFF 面数据不完整(截断)";
return false;
}
if (!append_face(face, mesh->vertex_count(), mesh, error)) return false;
}
if (mesh->indices.empty()) {
if (error) *error = "OFF 不含三角面";
return false;
}
return true;
}
bool write_off_ascii(const std::string& path, const Mesh& mesh, std::string* error) {
std::string text;
char line[256];
std::snprintf(line, sizeof(line), "OFF\n%zu %zu 0\n", mesh.vertex_count(),
mesh.triangle_count());
text += line;
for (std::size_t v = 0; v < mesh.vertex_count(); ++v) {
std::snprintf(line, sizeof(line), "%.17g %.17g %.17g\n",
mesh.positions[v * 3], mesh.positions[v * 3 + 1],
mesh.positions[v * 3 + 2]);
text += line;
}
for (std::size_t t = 0; t < mesh.triangle_count(); ++t) {
std::snprintf(line, sizeof(line), "3 %u %u %u\n", mesh.indices[t * 3],
mesh.indices[t * 3 + 1], mesh.indices[t * 3 + 2]);
text += line;
}
if (!write_file_bytes(path.c_str(), text.data(), text.size())) {
if (error) *error = "无法写入 OFF 文件";
return false;
}
return true;
}
// ── PLY(ASCII + binary_little_endian;big-endian 拒绝)──────────────
enum class PlyScalarType {
Int8, UInt8, Int16, UInt16, Int32, UInt32, Float32, Float64, Unknown
};
std::size_t ply_scalar_size(PlyScalarType type) {
switch (type) {
case PlyScalarType::Int8:
case PlyScalarType::UInt8: return 1;
case PlyScalarType::Int16:
case PlyScalarType::UInt16: return 2;
case PlyScalarType::Int32:
case PlyScalarType::UInt32:
case PlyScalarType::Float32: return 4;
case PlyScalarType::Float64: return 8;
default: return 0;
}
}
PlyScalarType ply_scalar_from_name(const std::string& name) {
const std::string lower = lower_ascii(name);
if (lower == "char" || lower == "int8") return PlyScalarType::Int8;
if (lower == "uchar" || lower == "uint8") return PlyScalarType::UInt8;
if (lower == "short" || lower == "int16") return PlyScalarType::Int16;
if (lower == "ushort" || lower == "uint16") return PlyScalarType::UInt16;
if (lower == "int" || lower == "int32") return PlyScalarType::Int32;
if (lower == "uint" || lower == "uint32") return PlyScalarType::UInt32;
if (lower == "float" || lower == "float32") return PlyScalarType::Float32;
if (lower == "double" || lower == "float64") return PlyScalarType::Float64;
return PlyScalarType::Unknown;
}
bool ply_scalar_is_integer(PlyScalarType type) {
return type == PlyScalarType::Int8 || type == PlyScalarType::UInt8 ||
type == PlyScalarType::Int16 || type == PlyScalarType::UInt16 ||
type == PlyScalarType::Int32 || type == PlyScalarType::UInt32;
}
struct PlyProperty {
bool list = false;
PlyScalarType type = PlyScalarType::Unknown;
PlyScalarType count_type = PlyScalarType::Unknown;
PlyScalarType item_type = PlyScalarType::Unknown;
std::string name;
};
struct PlyElement {
std::string name;
std::size_t count = 0;
std::vector<PlyProperty> properties;
};
struct PlyHeader {
bool binary = false;
std::vector<PlyElement> elements;
std::size_t data_offset = 0;
int vertex_element = -1;
int face_element = -1;
};
bool parse_ply_header(const std::string& data, PlyHeader* header, std::string* error) {
if (data.rfind("ply", 0) != 0) {
if (error) *error = "不是 PLY(缺少 ply 头)";
return false;
}
std::size_t pos = 0;
bool saw_format = false;
bool saw_end = false;
PlyElement* current = nullptr;
while (pos < data.size()) {
const std::size_t eol = data.find('\n', pos);
std::string line =
data.substr(pos, (eol == std::string::npos ? data.size() : eol) - pos);
pos = (eol == std::string::npos) ? data.size() : eol + 1;
if (!line.empty() && line.back() == '\r') line.pop_back();
const std::size_t first = line.find_first_not_of(" \t");
if (first == std::string::npos) continue;
std::vector<std::string> tokens;
std::size_t cursor = first;
while (cursor < line.size()) {
const std::size_t finish = line.find_first_of(" \t", cursor);
tokens.push_back(line.substr(
cursor, (finish == std::string::npos ? line.size() : finish) - cursor));
cursor = (finish == std::string::npos) ? line.size() : finish;
cursor = line.find_first_not_of(" \t", cursor);
if (cursor == std::string::npos) break;
}
if (tokens.empty()) continue;
if (tokens[0] == "comment" || tokens[0] == "obj_info") continue;
if (tokens[0] == "format") {
if (tokens.size() < 2) {
if (error) *error = "PLY format 行缺少编码";
return false;
}
const std::string encoding = lower_ascii(tokens[1]);
if (encoding == "ascii") {
header->binary = false;
} else if (encoding == "binary_little_endian") {
header->binary = true;
} else if (encoding == "binary_big_endian") {
if (error) *error = "PLY binary_big_endian 不支持(仅 ascii/little-endian)";
return false;
} else {
if (error) *error = "不支持的 PLY 编码: " + tokens[1];
return false;
}
saw_format = true;
} else if (tokens[0] == "element") {
if (tokens.size() < 3) {
if (error) *error = "PLY element 行不完整";
return false;
}
PlyElement element;
element.name = tokens[1];
char* end_ptr = nullptr;
const long long count = std::strtoll(tokens[2].c_str(), &end_ptr, 10);
if (end_ptr == tokens[2].c_str() || *end_ptr != '\0' || count < 0) {
if (error) *error = "PLY element 数量非法";
return false;
}
element.count = static_cast<std::size_t>(count);
if (element.name == "vertex" && element.count > kMaxVertices) {
if (error) *error = "PLY 顶点数量超过上限(20M)";
return false;
}
if (element.name == "face" && element.count > kMaxTriangles) {
if (error) *error = "PLY 面数量超过上限(20M)";
return false;
}
if (element.count > 2000000000ull) {
if (error) *error = "PLY element 数量超过上限";
return false;
}
header->elements.push_back(std::move(element));
current = &header->elements.back();
} else if (tokens[0] == "property") {
if (!current) {
if (error) *error = "PLY property 出现在 element 之前";
return false;
}
PlyProperty property;
if (tokens.size() >= 5 && tokens[1] == "list") {
property.list = true;
property.count_type = ply_scalar_from_name(tokens[2]);
property.item_type = ply_scalar_from_name(tokens[3]);
property.name = tokens[4];
if (property.count_type == PlyScalarType::Unknown ||
property.item_type == PlyScalarType::Unknown) {
if (error) *error = "PLY property list 类型不支持";
return false;
}
} else if (tokens.size() >= 3) {
property.type = ply_scalar_from_name(tokens[1]);
property.name = tokens[2];
if (property.type == PlyScalarType::Unknown) {
if (error) *error = "PLY property 类型不支持: " + tokens[1];
return false;
}
} else {
if (error) *error = "PLY property 行不完整";
return false;
}
current->properties.push_back(std::move(property));
} else if (tokens[0] == "end_header") {
header->data_offset = pos;
saw_end = true;
break;
}
}
if (!saw_format || !saw_end) {
if (error) *error = "PLY 头部不完整(缺 format/end_header)";
return false;
}
for (std::size_t i = 0; i < header->elements.size(); ++i) {
if (header->elements[i].name == "vertex" && header->vertex_element < 0)
header->vertex_element = static_cast<int>(i);
else if (header->elements[i].name == "face" && header->face_element < 0)
header->face_element = static_cast<int>(i);
}
if (header->vertex_element < 0 || header->face_element < 0) {
if (error) *error = "PLY 头部缺少 vertex 或 face 元素";
return false;
}
if (header->vertex_element > header->face_element) {
if (error) *error = "PLY 不支持 face 先于 vertex 的元素顺序";
return false;
}
return true;
}
struct PlyReadState {
bool binary = false;
const unsigned char* binary_cursor = nullptr;
const unsigned char* binary_end = nullptr;
const char* text_cursor = nullptr;
const char* text_end = nullptr;
};
bool ply_read_scalar(PlyReadState& state, PlyScalarType type, double* out) {
if (state.binary) {
const std::size_t width = ply_scalar_size(type);
if (width == 0 || static_cast<std::size_t>(state.binary_end - state.binary_cursor) <
width)
return false;
unsigned char bytes[8] = {0, 0, 0, 0, 0, 0, 0, 0};
std::memcpy(bytes, state.binary_cursor, width);
state.binary_cursor += width;
switch (type) {
case PlyScalarType::Int8: {
std::int8_t v = 0;
std::memcpy(&v, bytes, 1);
*out = static_cast<double>(v);
return true;
}
case PlyScalarType::UInt8: *out = static_cast<double>(bytes[0]); return true;
case PlyScalarType::Int16: {
std::int16_t v = 0;
std::memcpy(&v, bytes, 2);
*out = static_cast<double>(v);
return true;
}
case PlyScalarType::UInt16: {
std::uint16_t v = 0;
std::memcpy(&v, bytes, 2);
*out = static_cast<double>(v);
return true;
}
case PlyScalarType::Int32: {
std::int32_t v = 0;
std::memcpy(&v, bytes, 4);
*out = static_cast<double>(v);
return true;
}
case PlyScalarType::UInt32: {
std::uint32_t v = 0;
std::memcpy(&v, bytes, 4);
*out = static_cast<double>(v);
return true;
}
case PlyScalarType::Float32: {
float v = 0.0f;
std::memcpy(&v, bytes, 4);
*out = static_cast<double>(v);
return true;
}
case PlyScalarType::Float64: {
double v = 0.0;
std::memcpy(&v, bytes, 8);
*out = v;
return true;
}
default: return false;
}
}
while (state.text_cursor < state.text_end &&
(*state.text_cursor == ' ' || *state.text_cursor == '\t' ||
*state.text_cursor == '\r' || *state.text_cursor == '\n'))
++state.text_cursor;
if (state.text_cursor >= state.text_end) return false;
char* parse_end = nullptr;
const double value = std::strtod(state.text_cursor, &parse_end);
if (parse_end == state.text_cursor) return false;
state.text_cursor = parse_end;
*out = value;
return true;
}
bool ply_read_uint(PlyReadState& state, PlyScalarType type, std::uint64_t* out) {
if (!ply_scalar_is_integer(type)) return false;
double value = 0.0;
if (!ply_read_scalar(state, type, &value)) return false;
if (value < 0.0 || !std::isfinite(value)) return false;
*out = static_cast<std::uint64_t>(value);
return true;
}
bool parse_ply(const std::string& data, Mesh* mesh, std::string* error) {
PlyHeader header;
if (!parse_ply_header(data, &header, error)) return false;
PlyReadState state;
state.binary = header.binary;
if (header.binary) {
state.binary_cursor =
reinterpret_cast<const unsigned char*>(data.data()) + header.data_offset;
state.binary_end = reinterpret_cast<const unsigned char*>(data.data()) + data.size();
} else {
state.text_cursor = data.data() + header.data_offset;
state.text_end = data.data() + data.size();
}
std::vector<double> positions;
positions.reserve(static_cast<std::size_t>(
header.elements[static_cast<std::size_t>(header.vertex_element)]
.count) *
3u);
bool vertices_ready = false;
for (const PlyElement& element : header.elements) {
const bool is_vertex = element.name == "vertex";
const bool is_face = element.name == "face";
for (std::size_t record = 0; record < element.count; ++record) {
std::vector<long long> face;
double xyz[3] = {0.0, 0.0, 0.0};
bool has_xyz[3] = {false, false, false};
std::size_t vertex_property_index = 0;
bool has_face_list = false;
for (const PlyProperty& property : element.properties) {
if (property.list) {
std::uint64_t list_count = 0;
if (!ply_read_uint(state, property.count_type, &list_count)) {
if (error) *error = "PLY list 计数读取失败(截断/类型错误)";
return false;
}
if (list_count > static_cast<std::uint64_t>(kMaxVertices)) {
if (error) *error = "PLY list 元素数量超过上限";
return false;
}
if (is_face && !has_face_list &&
ply_scalar_is_integer(property.item_type)) {
for (std::uint64_t i = 0; i < list_count; ++i) {
std::uint64_t index = 0;
if (!ply_read_uint(state, property.item_type, &index)) {
if (error) *error = "PLY 面索引读取失败";
return false;
}
face.push_back(static_cast<long long>(index));
}
has_face_list = true;
} else {
double ignored = 0.0;
for (std::uint64_t i = 0; i < list_count; ++i) {
if (!ply_read_scalar(state, property.item_type, &ignored)) {
if (error) *error = "PLY list 数据读取失败(截断)";
return false;
}
}
}
continue;
}
double value = 0.0;
if (!ply_read_scalar(state, property.type, &value)) {
if (error) *error = "PLY 标量属性读取失败(截断/类型错误)";
return false;
}
if (is_vertex) {
if (property.name == "x") {
xyz[0] = value;
has_xyz[0] = true;
} else if (property.name == "y") {
xyz[1] = value;
has_xyz[1] = true;
} else if (property.name == "z") {
xyz[2] = value;
has_xyz[2] = true;
}
++vertex_property_index;
}
}
if (is_vertex) {
if (!has_xyz[0] || !has_xyz[1] || !has_xyz[2]) {
if (error) *error = "PLY vertex 缺少 x/y/z 属性";
return false;
}
if (!std::isfinite(xyz[0]) || !std::isfinite(xyz[1]) ||
!std::isfinite(xyz[2])) {
if (error) *error = "PLY 顶点含非有限数";
return false;
}
if (positions.size() / 3 >= kMaxVertices) {
if (error) *error = "PLY 顶点数量超过上限(20M)";
return false;
}
positions.push_back(xyz[0]);
positions.push_back(xyz[1]);
positions.push_back(xyz[2]);
} else if (is_face) {
if (!vertices_ready) {
if (error) *error = "PLY face 数据出现在 vertex 之前";
return false;
}
if (!has_face_list) {
if (error) *error = "PLY face 缺少整数 list 索引属性";
return false;
}
if (!append_face(face, mesh->vertex_count(), mesh, error)) return false;
}
}
if (is_vertex) {
if (positions.empty()) {
if (error) *error = "PLY 顶点数据不完整(截断)";
return false;
}
mesh->positions = std::move(positions);
positions.clear();
vertices_ready = true;
}
}
if (mesh->indices.empty()) {
if (error) *error = "PLY 不含三角面";
return false;
}
return true;
}
bool write_ply_ascii(const std::string& path, const Mesh& mesh, std::string* error) {
std::string text;
char line[256];
std::snprintf(line, sizeof(line),
"ply\nformat ascii 1.0\ncomment VDE io_batch mesh\n"
"element vertex %zu\nproperty float x\nproperty float y\n"
"property float z\nelement face %zu\n"
"property list uchar int vertex_indices\nend_header\n",
mesh.vertex_count(), mesh.triangle_count());
text += line;
for (std::size_t v = 0; v < mesh.vertex_count(); ++v) {
std::snprintf(line, sizeof(line), "%.17g %.17g %.17g\n",
mesh.positions[v * 3], mesh.positions[v * 3 + 1],
mesh.positions[v * 3 + 2]);
text += line;
}
for (std::size_t t = 0; t < mesh.triangle_count(); ++t) {
std::snprintf(line, sizeof(line), "3 %u %u %u\n", mesh.indices[t * 3],
mesh.indices[t * 3 + 1], mesh.indices[t * 3 + 2]);
text += line;
}
if (!write_file_bytes(path.c_str(), text.data(), text.size())) {
if (error) *error = "无法写入 PLY 文件";
return false;
}
return true;
}
bool write_ply_binary_le(const std::string& path, const Mesh& mesh, std::string* error) {
std::string text;
char line[256];
std::snprintf(line, sizeof(line),
"ply\nformat binary_little_endian 1.0\ncomment VDE io_batch mesh\n"
"element vertex %zu\nproperty float x\nproperty float y\n"
"property float z\nelement face %zu\n"
"property list uchar int vertex_indices\nend_header\n",
mesh.vertex_count(), mesh.triangle_count());
text += line;
for (std::size_t v = 0; v < mesh.vertex_count(); ++v) {
for (int k = 0; k < 3; ++k) {
const float value = static_cast<float>(mesh.positions[v * 3 + k]);
unsigned char bytes[4];
std::memcpy(bytes, &value, 4);
text.append(reinterpret_cast<const char*>(bytes), 4);
}
}
for (std::size_t t = 0; t < mesh.triangle_count(); ++t) {
text.push_back(static_cast<char>(3));
for (int k = 0; k < 3; ++k) {
const std::uint32_t value = mesh.indices[t * 3 + k];
unsigned char bytes[4] = {static_cast<unsigned char>(value & 0xFFu),
static_cast<unsigned char>((value >> 8) & 0xFFu),
static_cast<unsigned char>((value >> 16) & 0xFFu),
static_cast<unsigned char>((value >> 24) & 0xFFu)};
text.append(reinterpret_cast<const char*>(bytes), 4);
}
}
if (!write_file_bytes(path.c_str(), text.data(), text.size())) {
if (error) *error = "无法写入 PLY binary 文件";
return false;
}
return true;
}
bool is_ply_binary_path(const std::string& path) {
return lower_ascii(extension_of(path)) == "plyb";
}
// ── 格式判定 / 读写分派 ─────────────────────────────────────────────
bool parse_format(const std::string& text, std::string* format) {
const std::string lower = lower_ascii(text);
const std::string normalized = (lower == "plyb") ? "ply" : lower;
if (normalized == "stl" || normalized == "obj" || normalized == "ply" ||
normalized == "off") {
if (format) *format = normalized;
return true;
}
return false;
}
// ── P4-62:流式 I/O(大文件;ASCII 逐行、binary 1MiB 块)───────────
class StreamLineReader {
public:
bool open(const std::string& path, std::string* error) {
in_.open(path, std::ios::binary);
if (!in_.good()) {
if (error) *error = "无法打开输入文件";
return false;
}
return true;
}
bool next() {
if (!std::getline(in_, line_)) return false;
if (!line_.empty() && line_.back() == '\r') line_.pop_back();
return true;
}
bool skip_lines(std::size_t count) {
for (std::size_t i = 0; i < count; ++i)
if (!std::getline(in_, line_)) return false;
return true;
}
const std::string& line() const { return line_; }
private:
std::ifstream in_;
std::string line_;
};
class StreamBlockReader {
public:
bool open(const std::string& path, std::uint64_t skip, std::string* error) {
in_.open(path, std::ios::binary);
if (!in_.good()) {
if (error) *error = "无法打开输入文件";
return false;
}
if (skip > 0) {
in_.seekg(static_cast<std::streamoff>(skip), std::ios::beg);
if (!in_.good()) {
if (error) *error = "无法定位二进制数据";
return false;
}
}
buffer_.resize(kIoChunkBytes);
return true;
}
bool read(void* destination, std::size_t bytes) {
unsigned char* out = static_cast<unsigned char*>(destination);
while (bytes > 0) {
if (pos_ >= length_ && !fill()) return false;
const std::size_t available = length_ - pos_;
const std::size_t take = std::min(available, bytes);
std::memcpy(out, buffer_.data() + pos_, take);
pos_ += take;
out += take;
bytes -= take;
}
return true;
}
bool skip(std::size_t bytes) {
unsigned char ignored[64];
while (bytes > 0) {
const std::size_t take = std::min(bytes, sizeof(ignored));
if (!read(ignored, take)) return false;
bytes -= take;
}
return true;
}
private:
bool fill() {
if (!in_.good() && !in_.eof()) return false;
in_.read(reinterpret_cast<char*>(buffer_.data()),
static_cast<std::streamsize>(buffer_.size()));
const std::streamsize got = in_.gcount();
if (got <= 0) {
length_ = 0;
pos_ = 0;
return false;
}
length_ = static_cast<std::size_t>(got);
pos_ = 0;
return true;
}
std::ifstream in_;
std::vector<unsigned char> buffer_;
std::size_t pos_ = 0;
std::size_t length_ = 0;
};
class StreamChunkWriter {
public:
bool open(const std::string& path, std::string* error) {
out_.open(path, std::ios::binary | std::ios::trunc);
if (!out_.good()) {
if (error) *error = "无法打开输出文件";
return false;
}
buffer_.reserve(kIoChunkBytes + 512);
return true;
}
void append(const void* data, std::size_t bytes) {
buffer_.append(static_cast<const char*>(data), bytes);
if (buffer_.size() >= kIoChunkBytes) flush();
}
void append(const std::string& text) { append(text.data(), text.size()); }
bool flush() {
if (buffer_.empty()) return true;
out_.write(buffer_.data(), static_cast<std::streamsize>(buffer_.size()));
const bool ok = out_.good();
buffer_.clear();
return ok;
}
bool close(std::string* error) {
const bool ok = flush() && out_.good();
out_.close();
if (!ok && error) *error = "写出文件失败";
return ok;
}
private:
std::ofstream out_;
std::string buffer_;
};
enum class StreamMode { Auto, Always, Never };
bool parse_stream_mode(const std::string& text, StreamMode* mode) {
const std::string value = lower_ascii(text);
if (value == "auto" || value.empty()) {
*mode = StreamMode::Auto;
} else if (value == "always" || value == "stream" || value == "1") {
*mode = StreamMode::Always;
} else if (value == "never" || value == "memory" || value == "0") {
*mode = StreamMode::Never;
} else {
return false;
}
return true;
}
/// 旧环境别名:VDE_IO_BATCH_FORCE_STREAM=1 等价 stream=always。
bool force_streaming_io() {
const char* env = std::getenv("VDE_IO_BATCH_FORCE_STREAM");
if (!env || !*env) return false;
const std::string value = lower_ascii(env);
return value != "0" && value != "false" && value != "no" && value != "off";
}
bool resolve_stream_mode_from_env(StreamMode* mode, std::string* error) {
*mode = StreamMode::Auto;
const char* env = std::getenv("VDE_IO_BATCH_STREAM_MODE");
if (env && *env) {
if (!parse_stream_mode(env, mode)) {
if (error) *error = "不支持的 VDE_IO_BATCH_STREAM_MODE '" +
std::string(env) + "'(auto|always|never)";
return false;
}
return true;
}
if (force_streaming_io()) *mode = StreamMode::Always;
return true;
}
bool stream_file_size(const std::string& path, std::uint64_t* size) {
std::ifstream in(path, std::ios::binary | std::ios::ate);
if (!in.good()) return false;
const std::streamoff end = in.tellg();
if (end < 0) return false;
*size = static_cast<std::uint64_t>(end);
return true;
}
bool load_stl_stream(const std::string& path, Mesh* mesh, std::string* error) {
std::uint64_t size = 0;
if (!stream_file_size(path, &size)) {
if (error) *error = "无法读取输入文件";
return false;
}
if (size >= 84) {
std::ifstream in(path, std::ios::binary);
std::uint32_t triangle_count = 0;
in.seekg(80, std::ios::beg);
in.read(reinterpret_cast<char*>(&triangle_count), sizeof(triangle_count));
if (in.good() && 84ull + static_cast<std::uint64_t>(triangle_count) * 50ull == size) {
if (triangle_count > kMaxTriangles) {
if (error) *error = "STL 三角面数超过上限";
return false;
}
StreamBlockReader reader;
if (!reader.open(path, 84, error)) return false;
unsigned char record[48];
for (std::uint32_t t = 0; t < triangle_count; ++t) {
if (!reader.read(record, sizeof(record)) || !reader.skip(2)) {
if (error) *error = "STL binary 数据截断";
return false;
}
const std::uint32_t base = static_cast<std::uint32_t>(mesh->vertex_count());
for (int v = 0; v < 3; ++v) {
float xyz[3] = {0.0f, 0.0f, 0.0f};
std::memcpy(xyz, record + 12 + v * 12, sizeof(xyz));
mesh->positions.push_back(static_cast<double>(xyz[0]));
mesh->positions.push_back(static_cast<double>(xyz[1]));
mesh->positions.push_back(static_cast<double>(xyz[2]));
}
mesh->indices.push_back(base);
mesh->indices.push_back(base + 1);
mesh->indices.push_back(base + 2);
}
return true;
}
}
StreamLineReader line_reader;
if (!line_reader.open(path, error)) return false;
if (!line_reader.next()) {
if (error) *error = "STL 文件为空";
return false;
}
if (line_reader.line().rfind("solid", 0) != 0) {
if (error) *error = "不是 STL(ASCII 缺少 solid 头 / binary 长度不匹配)";
return false;
}
std::vector<double> facet;
while (line_reader.next()) {
const std::string& line = line_reader.line();
const std::size_t first = line.find_first_not_of(" \t\r");
if (first == std::string::npos) continue;
if (line.compare(first, 6, "vertex") != 0) continue;
double xyz[3] = {0.0, 0.0, 0.0};
if (std::sscanf(line.c_str() + first + 6, "%lf %lf %lf", &xyz[0], &xyz[1],
&xyz[2]) != 3) {
if (error) *error = "STL 顶点行非法";
return false;
}
if (!std::isfinite(xyz[0]) || !std::isfinite(xyz[1]) || !std::isfinite(xyz[2])) {
if (error) *error = "STL 顶点含非有限数";
return false;
}
facet.push_back(xyz[0]);
facet.push_back(xyz[1]);
facet.push_back(xyz[2]);
if (facet.size() == 9) {
const std::uint32_t base = static_cast<std::uint32_t>(mesh->vertex_count());
mesh->positions.insert(mesh->positions.end(), facet.begin(), facet.end());
facet.clear();
mesh->indices.push_back(base);
mesh->indices.push_back(base + 1);
mesh->indices.push_back(base + 2);
if (mesh->triangle_count() > kMaxTriangles) {
if (error) *error = "STL 三角面数超过上限";
return false;
}
}
}
if (!facet.empty()) {
if (error) *error = "STL 顶点数不是 3 的倍数";
return false;
}
if (mesh->indices.empty()) {
if (error) *error = "STL 不含三角面";
return false;
}
return true;
}
bool load_obj_stream(const std::string& path, Mesh* mesh, std::string* error) {
StreamLineReader reader;
if (!reader.open(path, error)) return false;
while (reader.next()) {
const std::string& line = reader.line();
std::size_t cursor = line.find_first_not_of(" \t\r");
if (cursor == std::string::npos || line[cursor] == '#') continue;
if (line.compare(cursor, 1, "v") == 0) {
double xyz[3] = {0.0, 0.0, 0.0};
if (std::sscanf(line.c_str() + cursor + 1, "%lf %lf %lf", &xyz[0], &xyz[1],
&xyz[2]) != 3) {
if (error) *error = "OBJ 顶点行非法";
return false;
}
if (!std::isfinite(xyz[0]) || !std::isfinite(xyz[1]) || !std::isfinite(xyz[2])) {
if (error) *error = "OBJ 顶点含非有限数";
return false;
}
mesh->positions.push_back(xyz[0]);
mesh->positions.push_back(xyz[1]);
mesh->positions.push_back(xyz[2]);
} else if (line.compare(cursor, 1, "f") == 0) {
std::vector<long long> face;
cursor += 1;
const std::size_t vertex_count = mesh->vertex_count();
while (true) {
cursor = line.find_first_not_of(" \t\r", cursor);
if (cursor == std::string::npos) break;
const std::size_t finish = line.find_first_of(" \t\r", cursor);
std::string token = line.substr(
cursor, (finish == std::string::npos ? line.size() : finish) - cursor);
cursor = (finish == std::string::npos) ? line.size() : finish;
const std::size_t slash = token.find('/');
if (slash != std::string::npos) token = token.substr(0, slash);
char* parse_end = nullptr;
long long index = std::strtoll(token.c_str(), &parse_end, 10);
if (parse_end == token.c_str() || *parse_end != '\0') {
if (error) *error = "OBJ 面索引非法";
return false;
}
if (index > 0) index -= 1;
else if (index < 0) index += static_cast<long long>(vertex_count);
if (index < 0 || static_cast<std::size_t>(index) >= vertex_count) {
if (error) *error = "OBJ 面索引越界";
return false;
}
face.push_back(index);
}
if (!append_face(face, mesh->vertex_count(), mesh, error)) return false;
if (mesh->triangle_count() > kMaxTriangles) {
if (error) *error = "OBJ 三角面数超过上限";
return false;
}
}
}
if (mesh->indices.empty()) {
if (error) *error = "OBJ 不含三角面";
return false;
}
return true;
}
bool load_off_stream(const std::string& path, Mesh* mesh, std::string* error) {
StreamLineReader reader;
if (!reader.open(path, error)) return false;
// 头:OFF + nv nf ne(允许同行或后续行;跳过注释/空行)
std::vector<std::string> tokens;
while (tokens.size() < 4 && reader.next()) {
std::string line = reader.line();
const std::size_t hash = line.find('#');
if (hash != std::string::npos) line = line.substr(0, hash);
std::size_t cursor = 0;
while (cursor < line.size() && tokens.size() < 4) {
cursor = line.find_first_not_of(" \t\r", cursor);
if (cursor == std::string::npos) break;
const std::size_t finish = line.find_first_of(" \t\r", cursor);
tokens.push_back(line.substr(
cursor, (finish == std::string::npos ? line.size() : finish) - cursor));
cursor = (finish == std::string::npos) ? line.size() : finish;
}
}
if (tokens.empty()) {
if (error) *error = "OFF 为空或缺少 OFF 头";
return false;
}
const std::string kind = tokens[0];
if (kind != "OFF") {
if (kind == "COFF" || kind == "NOFF" || kind == "4OFF" || kind == "nOFF") {
if (error) *error = "不支持 " + kind + "(仅 ASCII OFF v/f)";
} else {
if (error) *error = "不是 OFF(缺少 OFF 头)";
}
return false;
}
if (tokens.size() < 4) {
if (error) *error = "OFF 头缺少顶点/面/边数量";
return false;
}
char* end_ptr = nullptr;
const long long vertex_count = std::strtoll(tokens[1].c_str(), &end_ptr, 10);
if (end_ptr == tokens[1].c_str() || *end_ptr != '\0' || vertex_count < 0) {
if (error) *error = "OFF 顶点数量非法";
return false;
}
const long long face_count = std::strtoll(tokens[2].c_str(), &end_ptr, 10);
if (end_ptr == tokens[2].c_str() || *end_ptr != '\0' || face_count < 0) {
if (error) *error = "OFF 面数量非法";
return false;
}
if (static_cast<std::size_t>(vertex_count) > kMaxVertices ||
static_cast<std::size_t>(face_count) > kMaxTriangles) {
if (error) *error = "OFF 顶点/面数超过上限";
return false;
}
mesh->positions.reserve(static_cast<std::size_t>(vertex_count) * 3u);
for (long long v = 0; v < vertex_count; ++v) {
bool got = false;
while (!got && reader.next()) {
std::string line = reader.line();
const std::size_t hash = line.find('#');
if (hash != std::string::npos) line = line.substr(0, hash);
std::size_t cursor = line.find_first_not_of(" \t\r");
if (cursor == std::string::npos) continue;
double xyz[3] = {0.0, 0.0, 0.0};
if (std::sscanf(line.c_str() + cursor, "%lf %lf %lf", &xyz[0], &xyz[1],
&xyz[2]) != 3) {
if (error) *error = "OFF 顶点行非法";
return false;
}
if (!std::isfinite(xyz[0]) || !std::isfinite(xyz[1]) || !std::isfinite(xyz[2])) {
if (error) *error = "OFF 顶点含非有限数";
return false;
}
mesh->positions.push_back(xyz[0]);
mesh->positions.push_back(xyz[1]);
mesh->positions.push_back(xyz[2]);
got = true;
}
if (!got) {
if (error) *error = "OFF 顶点数据不完整(截断)";
return false;
}
}
for (long long f = 0; f < face_count; ++f) {
bool got = false;
while (!got && reader.next()) {
std::string line = reader.line();
const std::size_t hash = line.find('#');
if (hash != std::string::npos) line = line.substr(0, hash);
std::size_t cursor = line.find_first_not_of(" \t\r");
if (cursor == std::string::npos) continue;
char* parse_end = nullptr;
const long long count = std::strtoll(line.c_str() + cursor, &parse_end, 10);
if (parse_end == line.c_str() + cursor || count < 0) {
if (error) *error = "OFF 面行非法";
return false;
}
cursor = static_cast<std::size_t>(parse_end - line.c_str());
std::vector<long long> face;
for (long long i = 0; i < count; ++i) {
cursor = line.find_first_not_of(" \t\r", cursor);
if (cursor == std::string::npos) break;
const long long index = std::strtoll(line.c_str() + cursor, &parse_end, 10);
if (parse_end == line.c_str() + cursor) break;
face.push_back(index);
cursor = static_cast<std::size_t>(parse_end - line.c_str());
}
if (static_cast<long long>(face.size()) != count) {
if (error) *error = "OFF 面索引不完整";
return false;
}
if (!append_face(face, mesh->vertex_count(), mesh, error)) return false;
got = true;
if (mesh->triangle_count() > kMaxTriangles) {
if (error) *error = "OFF 三角面数超过上限";
return false;
}
}
if (!got) {
if (error) *error = "OFF 面数据不完整(截断)";
return false;
}
}
if (mesh->indices.empty()) {
if (error) *error = "OFF 不含三角面";
return false;
}
return true;
}
bool load_ply_stream(const std::string& path, PlyHeader* header, std::string* error) {
StreamLineReader reader;
if (!reader.open(path, error)) return false;
std::string header_text;
std::size_t header_lines = 0;
bool saw_end = false;
while (reader.next()) {
header_text += reader.line();
header_text.push_back('\n');
++header_lines;
if (reader.line() == "end_header") {
saw_end = true;
break;
}
}
if (!saw_end) {
if (error) *error = "PLY 头部不完整(缺 end_header)";
return false;
}
if (!parse_ply_header(header_text, header, error)) return false;
(void)header_lines;
return true;
}
// 通用 PLY body 流式解析:ASCII 逐行 / binary 1MiB 块。
bool load_ply_body_stream(const std::string& path, const PlyHeader& header, Mesh* mesh,
std::string* error) {
StreamLineReader line_reader;
StreamBlockReader block_reader;
// ASCII:token 流(任意空白;多记录同行/记录跨行均可)。
class AsciiTokens {
public:
explicit AsciiTokens(StreamLineReader* lines) : lines_(lines) {}
bool next(std::string* token) {
while (true) {
if (cursor_ < line_.size()) {
const std::size_t begin =
line_.find_first_not_of(" \t\r", cursor_);
if (begin != std::string::npos) {
const std::size_t finish = line_.find_first_of(" \t\r", begin);
*token = line_.substr(
begin, (finish == std::string::npos ? line_.size() : finish) -
begin);
cursor_ = (finish == std::string::npos) ? line_.size() : finish;
return true;
}
}
if (!lines_->next()) return false;
line_ = lines_->line();
cursor_ = 0;
}
}
private:
StreamLineReader* lines_;
std::string line_;
std::size_t cursor_ = 0;
};
AsciiTokens tokens(&line_reader);
if (header.binary) {
std::uint64_t header_bytes = 0;
// header 文本长度即数据偏移(parse 时按 '\n' 解析)。
{
StreamLineReader counter;
if (!counter.open(path, error)) return false;
while (counter.next()) {
header_bytes += counter.line().size() + 1;
if (counter.line() == "end_header") break;
}
}
if (!block_reader.open(path, header_bytes, error)) return false;
} else {
if (!line_reader.open(path, error)) return false;
std::size_t skip = 0;
{
StreamLineReader counter;
if (!counter.open(path, error)) return false;
while (counter.next()) {
++skip;
if (counter.line() == "end_header") break;
}
}
if (!line_reader.skip_lines(skip)) {
if (error) *error = "PLY 头部定位失败";
return false;
}
}
const auto read_scalar = [&](PlyScalarType type, double* out) -> bool {
if (header.binary) {
const std::size_t width = ply_scalar_size(type);
if (width == 0) return false;
unsigned char bytes[8] = {0, 0, 0, 0, 0, 0, 0, 0};
if (!block_reader.read(bytes, width)) return false;
switch (type) {
case PlyScalarType::Int8: {
std::int8_t v = 0;
std::memcpy(&v, bytes, 1);
*out = static_cast<double>(v);
return true;
}
case PlyScalarType::UInt8: *out = static_cast<double>(bytes[0]); return true;
case PlyScalarType::Int16: {
std::int16_t v = 0;
std::memcpy(&v, bytes, 2);
*out = static_cast<double>(v);
return true;
}
case PlyScalarType::UInt16: {
std::uint16_t v = 0;
std::memcpy(&v, bytes, 2);
*out = static_cast<double>(v);
return true;
}
case PlyScalarType::Int32: {
std::int32_t v = 0;
std::memcpy(&v, bytes, 4);
*out = static_cast<double>(v);
return true;
}
case PlyScalarType::UInt32: {
std::uint32_t v = 0;
std::memcpy(&v, bytes, 4);
*out = static_cast<double>(v);
return true;
}
case PlyScalarType::Float32: {
float v = 0.0f;
std::memcpy(&v, bytes, 4);
*out = static_cast<double>(v);
return true;
}
case PlyScalarType::Float64: {
double v = 0.0;
std::memcpy(&v, bytes, 8);
*out = v;
return true;
}
default: return false;
}
}
std::string token;
if (!tokens.next(&token)) return false;
char* parse_end = nullptr;
const double value = std::strtod(token.c_str(), &parse_end);
if (parse_end == token.c_str() || *parse_end != '\0') return false;
*out = value;
return true;
};
const auto read_uint = [&](PlyScalarType type, std::uint64_t* out) -> bool {
if (!ply_scalar_is_integer(type)) return false;
double value = 0.0;
if (!read_scalar(type, &value)) return false;
if (value < 0.0 || !std::isfinite(value)) return false;
*out = static_cast<std::uint64_t>(value);
return true;
};
std::vector<double> positions;
positions.reserve(
header.elements[static_cast<std::size_t>(header.vertex_element)].count * 3u);
bool vertices_ready = false;
for (const PlyElement& element : header.elements) {
for (std::size_t record = 0; record < element.count; ++record) {
std::vector<long long> face;
double xyz[3] = {0.0, 0.0, 0.0};
bool has_xyz[3] = {false, false, false};
bool has_face_list = false;
for (const PlyProperty& property : element.properties) {
if (property.list) {
std::uint64_t list_count = 0;
if (!read_uint(property.count_type, &list_count)) {
if (error) *error = "PLY list 计数读取失败(截断/类型错误)";
return false;
}
if (list_count > static_cast<std::uint64_t>(kMaxVertices)) {
if (error) *error = "PLY list 元素数量超过上限";
return false;
}
if (element.name == "face" && !has_face_list &&
ply_scalar_is_integer(property.item_type)) {
for (std::uint64_t i = 0; i < list_count; ++i) {
std::uint64_t index = 0;
if (!read_uint(property.item_type, &index)) {
if (error) *error = "PLY 面索引读取失败";
return false;
}
face.push_back(static_cast<long long>(index));
}
has_face_list = true;
} else {
double ignored = 0.0;
for (std::uint64_t i = 0; i < list_count; ++i) {
if (!read_scalar(property.item_type, &ignored)) {
if (error) *error = "PLY list 数据读取失败(截断)";
return false;
}
}
}
continue;
}
double value = 0.0;
if (!read_scalar(property.type, &value)) {
if (error) *error = "PLY 标量属性读取失败(截断/类型错误)";
return false;
}
if (element.name == "vertex") {
if (property.name == "x") {
xyz[0] = value;
has_xyz[0] = true;
} else if (property.name == "y") {
xyz[1] = value;
has_xyz[1] = true;
} else if (property.name == "z") {
xyz[2] = value;
has_xyz[2] = true;
}
}
}
if (element.name == "vertex") {
if (!has_xyz[0] || !has_xyz[1] || !has_xyz[2]) {
if (error) *error = "PLY vertex 缺少 x/y/z 属性";
return false;
}
if (!std::isfinite(xyz[0]) || !std::isfinite(xyz[1]) ||
!std::isfinite(xyz[2])) {
if (error) *error = "PLY 顶点含非有限数";
return false;
}
if (positions.size() / 3 >= kMaxVertices) {
if (error) *error = "PLY 顶点数量超过上限(20M)";
return false;
}
positions.push_back(xyz[0]);
positions.push_back(xyz[1]);
positions.push_back(xyz[2]);
} else if (element.name == "face") {
if (!vertices_ready) {
if (error) *error = "PLY face 数据出现在 vertex 之前";
return false;
}
if (!has_face_list) {
if (error) *error = "PLY face 缺少整数 list 索引属性";
return false;
}
if (!append_face(face, mesh->vertex_count(), mesh, error)) return false;
if (mesh->triangle_count() > kMaxTriangles) {
if (error) *error = "PLY 三角面数超过上限";
return false;
}
}
}
if (element.name == "vertex") {
if (positions.empty()) {
if (error) *error = "PLY 顶点数据不完整(截断)";
return false;
}
mesh->positions = std::move(positions);
positions.clear();
vertices_ready = true;
}
}
if (mesh->indices.empty()) {
if (error) *error = "PLY 不含三角面";
return false;
}
return true;
}
bool load_mesh_streaming(const std::string& path, const std::string& format, Mesh* mesh,
std::string* error) {
if (format == "stl") return load_stl_stream(path, mesh, error);
if (format == "obj") return load_obj_stream(path, mesh, error);
if (format == "off") return load_off_stream(path, mesh, error);
if (format == "ply") {
PlyHeader header;
if (!load_ply_stream(path, &header, error)) return false;
return load_ply_body_stream(path, header, mesh, error);
}
if (error) *error = "不支持的输入格式: " + format;
return false;
}
// ── 流式写出(1MiB 块;格式与小文件路径字节一致)────────────────────
bool write_stl_streaming(const std::string& path, const Mesh& mesh, std::string* error) {
StreamChunkWriter writer;
if (!writer.open(path, error)) return false;
char line[256];
writer.append("solid vde_io_batch_mesh\n");
for (std::size_t t = 0; t < mesh.triangle_count(); ++t) {
const double* a = &mesh.positions[mesh.indices[t * 3 + 0] * 3];
const double* b = &mesh.positions[mesh.indices[t * 3 + 1] * 3];
const double* c = &mesh.positions[mesh.indices[t * 3 + 2] * 3];
const double ux = b[0] - a[0], uy = b[1] - a[1], uz = b[2] - a[2];
const double vx = c[0] - a[0], vy = c[1] - a[1], vz = c[2] - a[2];
double nx = uy * vz - uz * vy;
double ny = uz * vx - ux * vz;
double nz = ux * vy - uy * vx;
const double length = std::sqrt(nx * nx + ny * ny + nz * nz);
if (length > 0.0) {
nx /= length;
ny /= length;
nz /= length;
}
const int n = std::snprintf(line, sizeof(line), "facet normal %.9g %.9g %.9g\n", nx,
ny, nz);
writer.append(line, static_cast<std::size_t>(n));
writer.append(" outer loop\n");
for (const double* p : {a, b, c}) {
const int m = std::snprintf(line, sizeof(line), " vertex %.17g %.17g %.17g\n",
p[0], p[1], p[2]);
writer.append(line, static_cast<std::size_t>(m));
}
writer.append(" endloop\nendfacet\n");
}
writer.append("endsolid vde_io_batch_mesh\n");
return writer.close(error);
}
bool write_obj_streaming(const std::string& path, const Mesh& mesh, std::string* error) {
StreamChunkWriter writer;
if (!writer.open(path, error)) return false;
writer.append("# VDE io_batch mesh\n");
char line[256];
for (std::size_t v = 0; v < mesh.vertex_count(); ++v) {
const int n = std::snprintf(line, sizeof(line), "v %.17g %.17g %.17g\n",
mesh.positions[v * 3], mesh.positions[v * 3 + 1],
mesh.positions[v * 3 + 2]);
writer.append(line, static_cast<std::size_t>(n));
}
for (std::size_t t = 0; t < mesh.triangle_count(); ++t) {
const int n = std::snprintf(line, sizeof(line), "f %u %u %u\n",
mesh.indices[t * 3] + 1,
mesh.indices[t * 3 + 1] + 1,
mesh.indices[t * 3 + 2] + 1);
writer.append(line, static_cast<std::size_t>(n));
}
return writer.close(error);
}
bool write_off_streaming(const std::string& path, const Mesh& mesh, std::string* error) {
StreamChunkWriter writer;
if (!writer.open(path, error)) return false;
char line[256];
const int n = std::snprintf(line, sizeof(line), "OFF\n%zu %zu 0\n", mesh.vertex_count(),
mesh.triangle_count());
writer.append(line, static_cast<std::size_t>(n));
for (std::size_t v = 0; v < mesh.vertex_count(); ++v) {
const int m = std::snprintf(line, sizeof(line), "%.17g %.17g %.17g\n",
mesh.positions[v * 3], mesh.positions[v * 3 + 1],
mesh.positions[v * 3 + 2]);
writer.append(line, static_cast<std::size_t>(m));
}
for (std::size_t t = 0; t < mesh.triangle_count(); ++t) {
const int m = std::snprintf(line, sizeof(line), "3 %u %u %u\n", mesh.indices[t * 3],
mesh.indices[t * 3 + 1], mesh.indices[t * 3 + 2]);
writer.append(line, static_cast<std::size_t>(m));
}
return writer.close(error);
}
bool write_ply_ascii_streaming(const std::string& path, const Mesh& mesh,
std::string* error) {
StreamChunkWriter writer;
if (!writer.open(path, error)) return false;
char line[256];
const int n = std::snprintf(
line, sizeof(line),
"ply\nformat ascii 1.0\ncomment VDE io_batch mesh\n"
"element vertex %zu\nproperty float x\nproperty float y\n"
"property float z\nelement face %zu\n"
"property list uchar int vertex_indices\nend_header\n",
mesh.vertex_count(), mesh.triangle_count());
writer.append(line, static_cast<std::size_t>(n));
for (std::size_t v = 0; v < mesh.vertex_count(); ++v) {
const int m = std::snprintf(line, sizeof(line), "%.17g %.17g %.17g\n",
mesh.positions[v * 3], mesh.positions[v * 3 + 1],
mesh.positions[v * 3 + 2]);
writer.append(line, static_cast<std::size_t>(m));
}
for (std::size_t t = 0; t < mesh.triangle_count(); ++t) {
const int m = std::snprintf(line, sizeof(line), "3 %u %u %u\n", mesh.indices[t * 3],
mesh.indices[t * 3 + 1], mesh.indices[t * 3 + 2]);
writer.append(line, static_cast<std::size_t>(m));
}
return writer.close(error);
}
bool write_ply_binary_streaming(const std::string& path, const Mesh& mesh,
std::string* error) {
StreamChunkWriter writer;
if (!writer.open(path, error)) return false;
char line[256];
const int n = std::snprintf(
line, sizeof(line),
"ply\nformat binary_little_endian 1.0\ncomment VDE io_batch mesh\n"
"element vertex %zu\nproperty float x\nproperty float y\n"
"property float z\nelement face %zu\n"
"property list uchar int vertex_indices\nend_header\n",
mesh.vertex_count(), mesh.triangle_count());
writer.append(line, static_cast<std::size_t>(n));
for (std::size_t v = 0; v < mesh.vertex_count(); ++v) {
for (int k = 0; k < 3; ++k) {
const float value = static_cast<float>(mesh.positions[v * 3 + k]);
unsigned char bytes[4];
std::memcpy(bytes, &value, 4);
writer.append(bytes, 4);
}
}
unsigned char face_record[13] = {3};
for (std::size_t t = 0; t < mesh.triangle_count(); ++t) {
for (int k = 0; k < 3; ++k) {
const std::uint32_t value = mesh.indices[t * 3 + k];
face_record[1 + k * 4 + 0] = static_cast<unsigned char>(value & 0xFFu);
face_record[1 + k * 4 + 1] = static_cast<unsigned char>((value >> 8) & 0xFFu);
face_record[1 + k * 4 + 2] = static_cast<unsigned char>((value >> 16) & 0xFFu);
face_record[1 + k * 4 + 3] = static_cast<unsigned char>((value >> 24) & 0xFFu);
}
writer.append(face_record, sizeof(face_record));
}
return writer.close(error);
}
bool save_mesh_streaming(const std::string& path, const std::string& format,
const Mesh& mesh, std::string* error) {
if (format == "stl") return write_stl_streaming(path, mesh, error);
if (format == "obj") return write_obj_streaming(path, mesh, error);
if (format == "off") return write_off_streaming(path, mesh, error);
if (format == "ply")
return is_ply_binary_path(path) ? write_ply_binary_streaming(path, mesh, error)
: write_ply_ascii_streaming(path, mesh, error);
if (error) *error = "不支持的输出格式: " + format;
return false;
}
bool load_mesh(const std::string& path, const std::string& format, Mesh* mesh,
StreamMode stream_mode, std::string* error) {
if (path.empty()) {
if (error) *error = "input 路径为空";
return false;
}
if (format != "stl" && format != "obj" && format != "ply" && format != "off") {
if (error) *error = "不支持的输入格式: " + format;
return false;
}
std::uint64_t file_size = 0;
if (!stream_file_size(path, &file_size)) {
if (error) *error = "无法读取输入文件";
return false;
}
if (file_size == 0) {
if (error) *error = "输入文件为空";
return false;
}
if (file_size > kMaxFileBytes) {
if (error) *error = "输入文件超过 512MB 上限";
return false;
}
const bool force_stream = stream_mode == StreamMode::Always ||
(stream_mode == StreamMode::Auto && force_streaming_io());
// PLY ASCII 读取无论大小都走 token 流(多记录/任意空白;不再要求每记录一行);
// stream=never 仍可显式选择旧内存路径。
if (stream_mode != StreamMode::Never &&
(format == "ply" || file_size >= kStreamInputThreshold || force_stream)) {
return load_mesh_streaming(path, format, mesh, error);
}
std::string bytes;
if (!read_file_bytes(path.c_str(), &bytes)) {
if (error) *error = "无法读取输入文件";
return false;
}
if (format == "stl") return parse_stl(bytes, mesh, error);
if (format == "obj") return parse_obj(bytes, mesh, error);
if (format == "ply") return parse_ply(bytes, mesh, error);
if (format == "off") return parse_off(bytes, mesh, error);
return false;
}
bool save_mesh(const std::string& path, const std::string& format, const Mesh& mesh,
StreamMode stream_mode, std::string* error) {
if (path.empty()) {
if (error) *error = "output 路径为空";
return false;
}
if (mesh.indices.empty()) {
if (error) *error = "网格不含三角面";
return false;
}
if (mesh.triangle_count() > kMaxTriangles) {
if (error) *error = "三角面数超过 20M 上限";
return false;
}
const bool force_stream = stream_mode == StreamMode::Always ||
(stream_mode == StreamMode::Auto && force_streaming_io());
if (stream_mode != StreamMode::Never &&
(mesh.triangle_count() >= kStreamOutputTriangleThreshold || force_stream)) {
return save_mesh_streaming(path, format, mesh, error);
}
if (format == "stl") return write_stl_ascii(path, mesh, error);
if (format == "obj") return write_obj(path, mesh, error);
if (format == "ply")
return is_ply_binary_path(path) ? write_ply_binary_le(path, mesh, error)
: write_ply_ascii(path, mesh, error);
if (format == "off") return write_off_ascii(path, mesh, error);
if (error) *error = "不支持的输出格式: " + format;
return false;
}
// ── 批处理执行 ──────────────────────────────────────────────────────
struct ItemResult {
std::string input;
std::string output;
std::string from;
std::string to;
bool ok = false;
std::string error;
std::size_t vertices = 0;
std::size_t triangles = 0;
};
int run_batch(const VdePluginHost* host, const char* options_json, const char* request_json,
size_t request_size, VdeBuffer* response_json, char* error_message,
size_t error_message_size) {
const auto set_error = [&](const std::string& text) {
if (host && host->set_error) host->set_error(text.c_str());
if (error_message && error_message_size > 0)
std::snprintf(error_message, error_message_size, "%s", text.c_str());
};
if (response_json) {
response_json->data = nullptr;
response_json->size = 0;
}
if (!host || !host->alloc || !response_json || !request_json || request_size == 0) {
set_error("io_batch_mesh: 空请求/输出参数或宿主缺少 alloc");
return VDE_PLUGIN_ERR_INVALID_ARG;
}
if (error_message && error_message_size > 0) error_message[0] = '\0';
StreamMode stream_mode = StreamMode::Auto;
{
std::string stream_error;
if (!resolve_stream_mode_from_env(&stream_mode, &stream_error)) {
set_error("io_batch_mesh: " + stream_error);
return VDE_PLUGIN_ERR_INVALID_ARG;
}
}
std::string global_from;
std::string global_to;
if (options_json && *options_json) {
JsonValue options;
JsonParser parser(options_json, std::strlen(options_json));
if (!parser.parse(&options)) {
set_error("io_batch_mesh: options JSON 非法: " + parser.error());
return VDE_PLUGIN_ERR_INVALID_ARG;
}
std::uint32_t flags = 0;
if (json_uint(&options, "flags", &flags) && flags != 0) {
set_error("io_batch_mesh: options.flags must be 0");
return VDE_PLUGIN_ERR_INVALID_ARG;
}
std::string text;
if (json_string(&options, "format", &text)) {
if (!parse_format(text, &global_to)) {
set_error("io_batch_mesh: 不支持的 options.format: " + text);
return VDE_PLUGIN_ERR_INVALID_ARG;
}
}
if (json_string(&options, "to", &text) && parse_format(text, &global_to))
global_to = lower_ascii(text);
if (json_string(&options, "from", &text) && parse_format(text, &global_from))
global_from = lower_ascii(text);
if (json_string(&options, "stream", &text)) {
if (!parse_stream_mode(text, &stream_mode)) {
set_error("io_batch_mesh: 不支持的 options.stream '" + text +
"'(auto|always|never)");
return VDE_PLUGIN_ERR_INVALID_ARG;
}
}
}
JsonParser parser(request_json, request_size);
JsonValue request;
if (!parser.parse(&request)) {
set_error("io_batch_mesh: request JSON 非法: " + parser.error());
return VDE_PLUGIN_ERR_INVALID_ARG;
}
if (request.type != JsonValue::Type::Object) {
set_error("io_batch_mesh: request 根必须是对象");
return VDE_PLUGIN_ERR_INVALID_ARG;
}
const JsonValue* items = request.find("items");
if (!items || items->type != JsonValue::Type::Array || items->array.empty()) {
set_error("io_batch_mesh: request.items 必须是非空数组");
return VDE_PLUGIN_ERR_INVALID_ARG;
}
if (items->array.size() > kMaxItems) {
set_error("io_batch_mesh: items 超过 4096 上限");
return VDE_PLUGIN_ERR_INVALID_ARG;
}
std::vector<ItemResult> results;
std::size_t processed = 0;
std::size_t failed = 0;
for (const JsonValue& item : items->array) {
ItemResult result;
if (item.type != JsonValue::Type::Object) {
result.error = "item 必须是对象";
++failed;
results.push_back(std::move(result));
continue;
}
json_string(&item, "input", &result.input);
json_string(&item, "output", &result.output);
std::string from_text;
std::string to_text;
if (json_string(&item, "from", &from_text)) {
if (!parse_format(from_text, &result.from)) result.from = lower_ascii(from_text);
}
if (json_string(&item, "to", &to_text)) {
if (!parse_format(to_text, &result.to)) result.to = lower_ascii(to_text);
}
if (result.from.empty()) result.from = global_from;
if (result.to.empty()) result.to = global_to;
if (result.from.empty()) result.from = extension_of(result.input);
if (result.to.empty()) result.to = extension_of(result.output);
if (!parse_format(result.from, &result.from)) {
result.error = "不支持的 from 格式: " + result.from;
++failed;
results.push_back(std::move(result));
continue;
}
if (!parse_format(result.to, &result.to)) {
result.error = "不支持的 to 格式: " + result.to;
++failed;
results.push_back(std::move(result));
continue;
}
if (result.input.empty() || result.output.empty()) {
result.error = "item 缺少 input/output";
++failed;
results.push_back(std::move(result));
continue;
}
Mesh mesh;
std::string error;
if (!load_mesh(result.input, result.from, &mesh, stream_mode, &error)) {
result.error = "读取失败: " + error;
++failed;
results.push_back(std::move(result));
continue;
}
if (mesh.indices.size() / 3 > kMaxTriangles) {
result.error = "三角面数超过上限";
++failed;
results.push_back(std::move(result));
continue;
}
if (!save_mesh(result.output, result.to, mesh, stream_mode, &error)) {
result.error = "写出失败: " + error;
++failed;
results.push_back(std::move(result));
continue;
}
result.ok = true;
result.vertices = mesh.vertex_count();
result.triangles = mesh.triangle_count();
++processed;
results.push_back(std::move(result));
}
std::string response;
response.reserve(256 + results.size() * 160);
response += "{\"batch_id\":\"io_batch.mesh\",\"status\":";
response += std::to_string(failed == 0 ? static_cast<int>(VDE_IO_BATCH_OK)
: static_cast<int>(VDE_IO_BATCH_ERR_PARTIAL));
response += ",\"ok\":";
response += (failed == 0) ? "true" : "false";
response += ",\"processed\":";
response += std::to_string(processed);
response += ",\"failed\":";
response += std::to_string(failed);
response += ",\"items\":[";
for (std::size_t i = 0; i < results.size(); ++i) {
const ItemResult& item = results[i];
if (i != 0) response += ",";
response += "{\"input\":\"" + json_escape(item.input) + "\",\"output\":\"" +
json_escape(item.output) + "\",\"from\":\"" + json_escape(item.from) +
"\",\"to\":\"" + json_escape(item.to) + "\",\"ok\":";
response += item.ok ? "true" : "false";
response += ",\"error\":\"" + json_escape(item.error) + "\"";
if (item.ok) {
response += ",\"vertices\":" + std::to_string(item.vertices) +
",\"triangles\":" + std::to_string(item.triangles);
}
response += "}";
}
response += "],\"diagnostics\":[";
bool first_diag = true;
for (const ItemResult& item : results) {
if (item.ok || item.error.empty()) continue;
if (!first_diag) response += ",";
first_diag = false;
response += "\"" + json_escape(item.error) + "\"";
}
response += "]}";
void* data = host->alloc(response.size() + 1);
if (!data) {
set_error("io_batch_mesh: 响应缓冲分配失败");
return VDE_PLUGIN_ERR_BUFFER;
}
std::memcpy(data, response.c_str(), response.size() + 1);
response_json->data = data;
response_json->size = response.size();
return VDE_PLUGIN_OK;
}
// ABI 1.6:结果回填版 run。复用 run_batch(旧 run),从响应 JSON 解析
// status/processed/failed 回填 VdeIoBatchResult;response_json 保留。
int run_v2(const VdePluginHost* host, const char* options_json, const char* request_json,
size_t request_size, VdeIoBatchResult* result, VdeBuffer* response_json,
char* error_message, size_t error_message_size) {
if (!result || result->struct_size < sizeof(VdeIoBatchResult)) {
if (host && host->set_error) host->set_error("io_batch_mesh: result 结构过小");
return VDE_PLUGIN_ERR_INVALID_ARG;
}
const int rc = run_batch(host, options_json, request_json, request_size, response_json,
error_message, error_message_size);
if (rc != VDE_PLUGIN_OK) return rc;
result->status = static_cast<std::uint32_t>(VDE_IO_BATCH_OK);
result->processed = 0;
result->failed = 0;
result->reserved = 0;
if (response_json && response_json->data && response_json->size > 0) {
const std::string text(static_cast<const char*>(response_json->data),
response_json->size);
const auto extract = [&](const char* key, long* out) {
const std::string pattern = std::string("\"") + key + "\":";
const std::size_t pos = text.find(pattern);
if (pos == std::string::npos) return;
*out = std::strtol(text.c_str() + pos + pattern.size(), nullptr, 10);
};
long status = 0, processed = 0, failed = 0;
extract("status", &status);
extract("processed", &processed);
extract("failed", &failed);
result->status = static_cast<std::uint32_t>(status);
result->processed = processed > 0 ? static_cast<std::uint32_t>(processed) : 0;
result->failed = failed > 0 ? static_cast<std::uint32_t>(failed) : 0;
}
return VDE_PLUGIN_OK;
}
const char* describe() {
return "VDE official IO_BATCH mesh converter (STL/OBJ/PLY batch convert; ABI 1.6)";
}
const VdeIoBatchPlugin kIoBatch = [] {
VdeIoBatchPlugin plugin{};
plugin.struct_size = static_cast<std::uint32_t>(sizeof(VdeIoBatchPlugin));
plugin.batch_id = "io_batch.mesh";
plugin.capabilities_json =
"{\"formats\":[\"stl\",\"obj\",\"ply\",\"off\"],\"directions\":[\"import\",\"export\"],"
"\"level\":\"official\"}";
plugin.run = &run_batch;
plugin.run_v2 = &run_v2;
plugin.describe = &describe;
return plugin;
}();
} // namespace
extern "C" {
VDE_PLUGIN_EXPORT int vde_plugin_query(std::uint32_t host_abi_major, VdePluginInfo* info) {
if (!info || info->struct_size < sizeof(VdePluginInfo)) return VDE_PLUGIN_ERR_INVALID_ARG;
if (host_abi_major != VDE_PLUGIN_ABI_MAJOR) return VDE_PLUGIN_ERR_ABI;
info->id = "com.vde.official.io_batch.mesh";
info->name = "VDE Official IO Batch Mesh Converter";
info->version = "1.0.0";
info->kind = VDE_PLUGIN_KIND_IO_BATCH;
info->abi_major = VDE_PLUGIN_ABI_MAJOR;
info->abi_minor = VDE_PLUGIN_ABI_MINOR;
info->capabilities = "io_batch:mesh_convert";
info->license = "Apache-2.0";
return VDE_PLUGIN_OK;
}
VDE_PLUGIN_EXPORT int vde_plugin_init(const VdePluginHost* host,
VdePluginRegistration* reg) {
if (!reg || reg->struct_size < sizeof(VdePluginRegistration)) return VDE_PLUGIN_ERR_ABI;
const int host_rc = validate_common_host(host);
if (host_rc != VDE_PLUGIN_OK) return host_rc;
reg->kind = VDE_PLUGIN_KIND_IO_BATCH;
reg->format = nullptr;
reg->generic = nullptr;
reg->cae_solver = nullptr;
reg->cam_strategy = nullptr;
reg->gcs_solver = nullptr;
reg->mesher = nullptr;
reg->optimizer = nullptr;
reg->io_batch = &kIoBatch;
return VDE_PLUGIN_OK;
}
VDE_PLUGIN_EXPORT void vde_plugin_shutdown() {}
} // extern "C"