Files

1033 lines
44 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.
// VDE official COLLADA format plugin (P4-24 / WP-P4-24).
// COLLADA 1.4/1.5 XML triangle mesh read/write; pure C ABI (does not link the kernel).
//
// Supported subset (read + write):
// <COLLADA version="1.4.x|1.5.x">
// <library_geometries>
// <geometry id="...">
// <mesh>
// <source id="..."><float_array ...>x y z ...</float_array>
// <technique_common><accessor .../></technique_common></source>
// <vertices id="..."><input semantic="POSITION" source="#source-id"/></vertices>
// <triangles count="N"> ... </triangles> (P4-24)
// <polylist count="N"><vcount>...</vcount><p>...</p></polylist> (P4-31)
// <polygons count="N"><p>...</p>...</polygons> (P4-31; <ph> holes ignored)
// </mesh>
// </geometry>
// ... multiple <geometry> -> multiple bodies ...
// </library_geometries>
// </COLLADA>
//
// polylist/polygons:按 <vcount>/每 <p> 解析多边形(3=三角;4/>4 按扇形三角化),
// 支持多 <input> 的 offset/stride(VERTEX 可在任意 offset)。写出统一用 <triangles>。
//
// Not supported / ignored: <tristrips>/<trifans>/<lines>/<linestrips>(几何只有这些时明确报错),
// <library_nodes>/<instance_geometry>(instancing/transforms ignored — positions are used
// as-is), accessor stride != 3, animation/skinning/effects, external references.
// <asset><unit> is parsed-ignored: coordinates use the app's current unit.
// Malformed XML, missing positions/primitive, missing sources, vcount/p mismatch and
// out-of-range indices fail with VDE_PLUGIN_ERR_PARSE and an explicit host error message.
#include "../common/format_plugin_common.h"
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <map>
#include <string>
#include <vector>
namespace {
using vde_plugin_common::fail;
using vde_plugin_common::MeshAccumulator;
using vde_plugin_common::read_file_bytes;
using vde_plugin_common::validate_read_host;
using vde_plugin_common::validate_write_host;
using vde_plugin_common::write_file_bytes;
constexpr std::size_t kMaxFileBytes = 512u * 1024u * 1024u;
constexpr std::size_t kMaxGeometries = 4096;
constexpr std::size_t kMaxVertices = 20000000u;
constexpr std::size_t kMaxTriangles = 20000000u;
constexpr std::size_t kMaxPolygonVertices = 4096u;
constexpr double kWriteDeflection = 0.01;
// ── ASCII XML 轻量扫描(不引入 XML 库)────────────────────────────────
bool is_space(char c) {
return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\f' || c == '\v';
}
bool is_name_char(char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') || c == '_' || c == '-' || c == '.' || c == ':';
}
char lower_char(char c) {
return (c >= 'A' && c <= 'Z') ? static_cast<char>(c - 'A' + 'a') : c;
}
std::string lower_ascii(const std::string& text) {
std::string out = text;
for (char& c : out) c = lower_char(c);
return out;
}
bool starts_with_ci(const std::string& text, std::size_t at, const std::string& needle) {
if (at + needle.size() > text.size()) return false;
for (std::size_t i = 0; i < needle.size(); ++i) {
if (lower_char(text[at + i]) != needle[i]) return false;
}
return true;
}
std::size_t find_ci(const std::string& text, const std::string& needle, std::size_t from) {
if (needle.empty() || from >= text.size()) return std::string::npos;
for (std::size_t pos = from; pos + needle.size() <= text.size(); ++pos) {
if (starts_with_ci(text, pos, needle)) return pos;
}
return std::string::npos;
}
std::size_t find_tag_end(const std::string& text, std::size_t open_angle) {
bool in_quote = false;
char quote = '\0';
for (std::size_t i = open_angle + 1; i < text.size(); ++i) {
const char c = text[i];
if (in_quote) {
if (c == quote) in_quote = false;
continue;
}
if (c == '"' || c == '\'') {
in_quote = true;
quote = c;
} else if (c == '>') {
return i;
}
}
return std::string::npos;
}
std::size_t find_open_tag(const std::string& text, std::size_t from, const std::string& tag) {
const std::string needle = "<" + tag;
std::size_t pos = from;
while (true) {
pos = find_ci(text, needle, pos);
if (pos == std::string::npos) return std::string::npos;
const std::size_t name_end = pos + needle.size();
if (name_end >= text.size() || !is_name_char(text[name_end])) return pos;
pos = name_end;
}
}
/// 提取元素内容(同名标签深度配对;自闭合返回空内容)。
bool extract_element(const std::string& text, std::size_t start, const std::string& tag,
std::size_t* content_begin, std::size_t* content_end,
std::size_t* after_end) {
if (content_begin) *content_begin = 0;
if (content_end) *content_end = 0;
if (after_end) *after_end = 0;
const std::size_t open_end = find_tag_end(text, start);
if (open_end == std::string::npos) return false;
std::size_t back = open_end;
while (back > start && is_space(text[back - 1])) --back;
if (back > start && text[back - 1] == '/') {
if (content_begin) *content_begin = open_end + 1;
if (content_end) *content_end = open_end + 1;
if (after_end) *after_end = open_end + 1;
return true;
}
const std::string close_tag = "</" + tag;
int depth = 1;
std::size_t pos = open_end + 1;
while (depth > 0) {
const std::size_t next_open = find_open_tag(text, pos, tag);
const std::size_t close_pos = find_ci(text, close_tag, pos);
if (close_pos == std::string::npos) return false;
if (next_open != std::string::npos && next_open < close_pos) {
const std::size_t next_end = find_tag_end(text, next_open);
if (next_end == std::string::npos) return false;
std::size_t back2 = next_end;
while (back2 > next_open && is_space(text[back2 - 1])) --back2;
if (!(back2 > next_open && text[back2 - 1] == '/')) ++depth;
pos = next_end + 1;
continue;
}
--depth;
if (depth == 0) {
const std::size_t close_end = text.find('>', close_pos);
if (close_end == std::string::npos) return false;
if (content_begin) *content_begin = open_end + 1;
if (content_end) *content_end = close_pos;
if (after_end) *after_end = close_end + 1;
return true;
}
pos = close_pos + close_tag.size();
}
return false;
}
bool element_text(const std::string& text, const std::string& name, std::string* out) {
const std::size_t start = find_open_tag(text, 0, name);
if (start == std::string::npos) return false;
std::size_t begin = 0, end = 0, after = 0;
if (!extract_element(text, start, name, &begin, &end, &after)) return false;
*out = text.substr(begin, end - begin);
return true;
}
/// 读元素开标签内的属性(大小写不敏感)。
bool attribute_value(const std::string& text, std::size_t tag_start, const char* attr,
std::string* out) {
const std::size_t tag_end = find_tag_end(text, tag_start);
if (tag_end == std::string::npos) return false;
const std::string lower_attr = lower_ascii(attr);
const std::string body = text.substr(tag_start + 1, tag_end - tag_start - 1);
const std::string lower_body = lower_ascii(body);
std::size_t pos = 0;
while (true) {
pos = lower_body.find(lower_attr, pos);
if (pos == std::string::npos) return false;
const bool left_ok = pos == 0 || is_space(body[pos - 1]) || body[pos - 1] == '<';
const std::size_t after_name = pos + lower_attr.size();
const bool right_ok = after_name < body.size() &&
(is_space(body[after_name]) || body[after_name] == '=');
if (!left_ok || !right_ok) {
pos = after_name;
continue;
}
std::size_t cursor = after_name;
while (cursor < body.size() && is_space(body[cursor])) ++cursor;
if (cursor >= body.size() || body[cursor] != '=') {
pos = after_name;
continue;
}
++cursor;
while (cursor < body.size() && is_space(body[cursor])) ++cursor;
if (cursor >= body.size()) return false;
const char quote = body[cursor];
if (quote != '"' && quote != '\'') {
std::size_t value_end = cursor;
while (value_end < body.size() && !is_space(body[value_end]) &&
body[value_end] != '>' && body[value_end] != '/')
++value_end;
*out = body.substr(cursor, value_end - cursor);
return true;
}
++cursor;
const std::size_t closing = body.find(quote, cursor);
if (closing == std::string::npos) return false;
*out = body.substr(cursor, closing - cursor);
return true;
}
}
std::string strip_hash(const std::string& reference) {
return (!reference.empty() && reference[0] == '#') ? reference.substr(1) : reference;
}
bool parse_double_array(const std::string& text, std::vector<double>* values) {
values->clear();
std::size_t pos = 0;
while (pos < text.size()) {
while (pos < text.size() && is_space(text[pos])) ++pos;
if (pos >= text.size()) break;
const char* begin = text.c_str() + pos;
char* end = nullptr;
const double value = std::strtod(begin, &end);
if (end == begin || !std::isfinite(value)) return false;
values->push_back(value);
pos = static_cast<std::size_t>(end - text.c_str());
}
return !values->empty();
}
bool parse_int_array(const std::string& text, std::vector<long long>* values) {
values->clear();
std::size_t pos = 0;
while (pos < text.size()) {
while (pos < text.size() && is_space(text[pos])) ++pos;
if (pos >= text.size()) break;
const char* begin = text.c_str() + pos;
char* end = nullptr;
const long long value = std::strtoll(begin, &end, 10);
if (end == begin) return false;
values->push_back(value);
pos = static_cast<std::size_t>(end - text.c_str());
}
return !values->empty();
}
struct ColladaObject {
MeshAccumulator mesh;
};
struct InputRef {
std::string semantic;
std::string source;
std::size_t offset = 0;
};
/// 解析一个元素内所有 <input>(返回 VERTEX 对应的 positions source;不存在返回空)。
bool parse_inputs(const std::string& body, std::vector<InputRef>* inputs,
std::size_t* max_offset, std::string* error) {
std::size_t pos = 0;
while (true) {
const std::size_t input_start = find_open_tag(body, pos, "input");
if (input_start == std::string::npos) break;
const std::size_t input_end = find_tag_end(body, input_start);
if (input_end == std::string::npos) break;
pos = input_end + 1;
InputRef ref;
attribute_value(body, input_start, "semantic", &ref.semantic);
attribute_value(body, input_start, "source", &ref.source);
std::string offset_text;
if (attribute_value(body, input_start, "offset", &offset_text)) {
char* end_ptr = nullptr;
const long parsed = std::strtol(offset_text.c_str(), &end_ptr, 10);
if (end_ptr == offset_text.c_str() || *end_ptr != '\0' || parsed < 0) {
if (error) *error = "collada: <input> offset 非整数";
return false;
}
ref.offset = static_cast<std::size_t>(parsed);
}
*max_offset = std::max(*max_offset, ref.offset);
inputs->push_back(std::move(ref));
}
return true;
}
const std::vector<double>* lookup_positions(
const std::string& source_ref, const std::map<std::string, std::vector<double>>& sources,
const std::map<std::string, std::string>& vertices) {
const std::string source_id = strip_hash(source_ref);
auto direct = sources.find(source_id);
if (direct != sources.end()) return &direct->second;
auto vertex_it = vertices.find(source_id);
if (vertex_it != vertices.end() && !vertex_it->second.empty()) {
auto resolved = sources.find(vertex_it->second);
if (resolved != sources.end()) return &resolved->second;
}
return nullptr;
}
void append_mesh(ColladaObject* object, const std::vector<double>& positions,
const std::vector<std::uint32_t>& local_indices) {
const std::uint32_t base =
static_cast<std::uint32_t>(object->mesh.vertex_count());
object->mesh.positions.insert(object->mesh.positions.end(), positions.begin(),
positions.end());
for (const std::uint32_t index : local_indices) {
object->mesh.indices.push_back(base + index);
}
}
struct PrimitiveContext {
std::size_t stride = 1;
std::size_t vertex_offset = 0;
std::size_t vertex_count = 0;
const std::vector<double>* positions = nullptr;
};
/// 解析 primitive 的 <input> 列表并解析 VERTEX/POSITION(triangles/polylist/polygons 共用)。
bool prepare_primitive(const std::string& body, const char* tag,
const std::map<std::string, std::vector<double>>& sources,
const std::map<std::string, std::string>& vertices,
PrimitiveContext* context, std::string* error) {
std::vector<InputRef> inputs;
std::size_t max_offset = 0;
if (!parse_inputs(body, &inputs, &max_offset, error)) return false;
if (inputs.empty()) {
if (error) *error = std::string("collada: <") + tag + "> 缺少 <input>";
return false;
}
std::size_t vertex_offset = 0;
std::string vertex_source;
bool has_vertex_input = false;
for (const auto& input : inputs) {
const std::string semantic = lower_ascii(input.semantic);
if (semantic == "vertex" || semantic == "position") {
vertex_offset = input.offset;
vertex_source = input.source;
has_vertex_input = true;
if (semantic == "vertex") break;
}
}
if (!has_vertex_input) {
if (error) *error = std::string("collada: <") + tag + "> 缺少 VERTEX/POSITION input";
return false;
}
const std::vector<double>* positions = lookup_positions(vertex_source, sources, vertices);
if (!positions) {
if (error) *error = std::string("collada: <") + tag + "> 引用的 positions source 不存在";
return false;
}
if (positions->size() % 3 != 0) {
if (error) *error = "collada: positions float_array 数量不是 3 的倍数";
return false;
}
context->stride = max_offset + 1;
context->vertex_offset = vertex_offset;
context->vertex_count = positions->size() / 3;
context->positions = positions;
return true;
}
/// 把一面顶点索引(已为 0-based)扇形三角化;校验范围/去退化后追加到 local_indices。
bool triangulate_face(const std::vector<long long>& face, std::size_t vertex_count,
const char* tag, std::vector<std::uint32_t>* local_indices,
std::string* error) {
if (face.size() < 3 || face.size() > kMaxPolygonVertices) {
if (error) *error = std::string("collada: <") + tag + "> 面顶点数非法(需 3..4096)";
return false;
}
for (const long long value : face) {
if (value < 0 || static_cast<std::size_t>(value) >= vertex_count) {
if (error) *error = std::string("collada: <") + tag + "> 顶点索引越界";
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; // 退化三角面
local_indices->push_back(static_cast<std::uint32_t>(a));
local_indices->push_back(static_cast<std::uint32_t>(b));
local_indices->push_back(static_cast<std::uint32_t>(c));
}
return true;
}
/// 解析一个 <geometry> 的 <mesh>:triangles/polylist/polygons 合并;返回 false 表示结构错误。
bool parse_geometry(const std::string& geometry_body, ColladaObject* object,
std::string* error) {
const std::size_t mesh_start = find_open_tag(geometry_body, 0, "mesh");
if (mesh_start == std::string::npos) return true; // 非 mesh geometry(如 spline)跳过
std::size_t mesh_begin = 0, mesh_end = 0, mesh_after = 0;
if (!extract_element(geometry_body, mesh_start, "mesh", &mesh_begin, &mesh_end,
&mesh_after)) {
if (error) *error = "collada: <mesh> 标签不完整";
return false;
}
const std::string mesh_body =
geometry_body.substr(mesh_begin, mesh_end - mesh_begin);
// 1) <source id> → float_array 坐标
std::map<std::string, std::vector<double>> sources;
std::size_t pos = 0;
while (true) {
const std::size_t source_start = find_open_tag(mesh_body, pos, "source");
if (source_start == std::string::npos) break;
std::size_t begin = 0, end = 0, after = 0;
if (!extract_element(mesh_body, source_start, "source", &begin, &end, &after)) {
if (error) *error = "collada: <source> 标签不完整";
return false;
}
pos = after;
const std::string source_body = mesh_body.substr(begin, end - begin);
std::string source_id;
attribute_value(mesh_body, source_start, "id", &source_id);
std::string array_text;
if (!element_text(source_body, "float_array", &array_text)) continue;
std::vector<double> values;
if (!parse_double_array(array_text, &values)) {
if (error) *error = "collada: <float_array> 含非法数值";
return false;
}
if (!source_id.empty()) sources[source_id] = std::move(values);
}
// 2) <vertices id> → POSITION source
std::map<std::string, std::string> vertices;
pos = 0;
while (true) {
const std::size_t vertices_start = find_open_tag(mesh_body, pos, "vertices");
if (vertices_start == std::string::npos) break;
std::size_t begin = 0, end = 0, after = 0;
if (!extract_element(mesh_body, vertices_start, "vertices", &begin, &end, &after)) {
if (error) *error = "collada: <vertices> 标签不完整";
return false;
}
pos = after;
const std::string vertices_body = mesh_body.substr(begin, end - begin);
std::string vertices_id;
attribute_value(mesh_body, vertices_start, "id", &vertices_id);
std::string position_source;
std::size_t input_pos = 0;
while (true) {
const std::size_t input_start = find_open_tag(vertices_body, input_pos, "input");
if (input_start == std::string::npos) break;
const std::size_t input_end = find_tag_end(vertices_body, input_start);
if (input_end == std::string::npos) break;
input_pos = input_end + 1;
std::string semantic, source;
attribute_value(vertices_body, input_start, "semantic", &semantic);
attribute_value(vertices_body, input_start, "source", &source);
if (lower_ascii(semantic) == "position" && !source.empty()) {
position_source = strip_hash(source);
break;
}
}
if (!vertices_id.empty()) vertices[vertices_id] = position_source;
}
// 3) <triangles>(可多个)
pos = 0;
std::size_t triangles_elements = 0;
while (true) {
const std::size_t triangles_start = find_open_tag(mesh_body, pos, "triangles");
if (triangles_start == std::string::npos) break;
std::size_t begin = 0, end = 0, after = 0;
if (!extract_element(mesh_body, triangles_start, "triangles", &begin, &end,
&after)) {
if (error) *error = "collada: <triangles> 标签不完整";
return false;
}
pos = after;
++triangles_elements;
const std::string body = mesh_body.substr(begin, end - begin);
PrimitiveContext context;
if (!prepare_primitive(body, "triangles", sources, vertices, &context, error))
return false;
const std::size_t stride = context.stride;
const std::size_t vertex_offset = context.vertex_offset;
const std::size_t vertex_count = context.vertex_count;
const std::vector<double>* positions = context.positions;
std::string p_text;
if (!element_text(body, "p", &p_text)) {
if (error) *error = "collada: <triangles> 缺少 <p>";
return false;
}
std::vector<long long> indices;
if (!parse_int_array(p_text, &indices)) {
if (error) *error = "collada: <p> 索引非整数";
return false;
}
// 每个顶点由 stride 个索引构成;一个三角形 = 3 个连续 index tuple。
const std::size_t triangle_stride = stride * 3;
if (indices.size() % triangle_stride != 0) {
if (error) *error = "collada: <p> 索引数与 input stride 不匹配";
return false;
}
std::vector<std::uint32_t> local_indices;
local_indices.reserve(indices.size() / triangle_stride * 3);
for (std::size_t t = 0; t + triangle_stride <= indices.size();
t += triangle_stride) {
const long long a = indices[t + 0 * stride + vertex_offset];
const long long b = indices[t + 1 * stride + vertex_offset];
const long long c = indices[t + 2 * stride + vertex_offset];
if (a < 0 || b < 0 || c < 0 ||
static_cast<std::size_t>(a) >= vertex_count ||
static_cast<std::size_t>(b) >= vertex_count ||
static_cast<std::size_t>(c) >= vertex_count) {
if (error) *error = "collada: <p> 顶点索引越界";
return false;
}
if (a == b || b == c || a == c) continue; // 退化三角面
local_indices.push_back(static_cast<std::uint32_t>(a));
local_indices.push_back(static_cast<std::uint32_t>(b));
local_indices.push_back(static_cast<std::uint32_t>(c));
}
append_mesh(object, *positions, local_indices);
if (object->mesh.vertex_count() > kMaxVertices) {
if (error) *error = "collada: 顶点数超过上限";
return false;
}
if (object->mesh.triangle_count() > kMaxTriangles) {
if (error) *error = "collada: 三角面数超过上限";
return false;
}
}
// 4) <polylist count>:<vcount> 每面顶点数 + <p> 扁平索引(支持 offset/stride)
pos = 0;
std::size_t polylist_elements = 0;
while (true) {
const std::size_t element_start = find_open_tag(mesh_body, pos, "polylist");
if (element_start == std::string::npos) break;
std::size_t begin = 0, end = 0, after = 0;
if (!extract_element(mesh_body, element_start, "polylist", &begin, &end, &after)) {
if (error) *error = "collada: <polylist> 标签不完整";
return false;
}
pos = after;
++polylist_elements;
const std::string body = mesh_body.substr(begin, end - begin);
PrimitiveContext context;
if (!prepare_primitive(body, "polylist", sources, vertices, &context, error))
return false;
std::string vcount_text;
if (!element_text(body, "vcount", &vcount_text)) {
if (error) *error = "collada: <polylist> 缺少 <vcount>";
return false;
}
std::vector<long long> vcounts;
if (!parse_int_array(vcount_text, &vcounts)) {
if (error) *error = "collada: <polylist> <vcount> 非整数";
return false;
}
std::string count_text;
if (attribute_value(mesh_body, element_start, "count", &count_text)) {
char* count_end = nullptr;
const long long expected = std::strtoll(count_text.c_str(), &count_end, 10);
if (count_end == count_text.c_str() || *count_end != '\0' || expected < 0) {
if (error) *error = "collada: <polylist> count 非整数";
return false;
}
if (static_cast<std::size_t>(expected) != vcounts.size()) {
if (error) *error = "collada: <polylist> vcount 数量与 count 属性不匹配";
return false;
}
}
std::string p_text;
if (!element_text(body, "p", &p_text)) {
if (error) *error = "collada: <polylist> 缺少 <p>";
return false;
}
std::vector<long long> indices;
if (!parse_int_array(p_text, &indices)) {
if (error) *error = "collada: <polylist> <p> 索引非整数";
return false;
}
std::size_t expected_indices = 0;
for (const long long value : vcounts) {
if (value < 0) {
if (error) *error = "collada: <polylist> <vcount> 含负数";
return false;
}
expected_indices += static_cast<std::size_t>(value);
}
expected_indices *= context.stride;
if (expected_indices != indices.size()) {
if (error) *error = "collada: <polylist> vcount 与 <p> 数量不匹配";
return false;
}
std::vector<std::uint32_t> local_indices;
std::size_t cursor = 0;
for (const long long count_value : vcounts) {
std::vector<long long> face;
face.reserve(static_cast<std::size_t>(count_value));
for (long long k = 0; k < count_value; ++k) {
face.push_back(indices[cursor + context.vertex_offset]);
cursor += context.stride;
}
if (!triangulate_face(face, context.vertex_count, "polylist", &local_indices,
error))
return false;
}
append_mesh(object, *context.positions, local_indices);
if (object->mesh.vertex_count() > kMaxVertices) {
if (error) *error = "collada: 顶点数超过上限";
return false;
}
if (object->mesh.triangle_count() > kMaxTriangles) {
if (error) *error = "collada: 三角面数超过上限";
return false;
}
}
// 5) <polygons count>:每个 <p> 一个多边形(<ph> 洞忽略);n=3/4/>4 扇形三角化
pos = 0;
std::size_t polygons_elements = 0;
while (true) {
const std::size_t element_start = find_open_tag(mesh_body, pos, "polygons");
if (element_start == std::string::npos) break;
std::size_t begin = 0, end = 0, after = 0;
if (!extract_element(mesh_body, element_start, "polygons", &begin, &end, &after)) {
if (error) *error = "collada: <polygons> 标签不完整";
return false;
}
pos = after;
++polygons_elements;
const std::string body = mesh_body.substr(begin, end - begin);
PrimitiveContext context;
if (!prepare_primitive(body, "polygons", sources, vertices, &context, error))
return false;
std::size_t polygon_count = 0;
std::vector<std::uint32_t> local_indices;
std::size_t p_pos = 0;
while (true) {
const std::size_t p_start = find_open_tag(body, p_pos, "p");
if (p_start == std::string::npos) break;
std::size_t p_begin = 0, p_end = 0, p_after = 0;
if (!extract_element(body, p_start, "p", &p_begin, &p_end, &p_after)) break;
p_pos = p_after;
const std::string p_text = body.substr(p_begin, p_end - p_begin);
std::vector<long long> indices;
if (!parse_int_array(p_text, &indices)) {
if (error) *error = "collada: <polygons> <p> 索引非整数";
return false;
}
if (indices.size() % context.stride != 0) {
if (error) *error = "collada: <polygons> <p> 索引数与 input stride 不匹配";
return false;
}
const std::size_t vertex_count = indices.size() / context.stride;
if (vertex_count == 0) continue;
std::vector<long long> face;
face.reserve(vertex_count);
for (std::size_t i = 0; i < vertex_count; ++i) {
face.push_back(indices[i * context.stride + context.vertex_offset]);
}
if (!triangulate_face(face, context.vertex_count, "polygons", &local_indices,
error))
return false;
++polygon_count;
}
if (polygon_count == 0) {
if (error) *error = "collada: <polygons> 缺少 <p>";
return false;
}
std::string count_text;
if (attribute_value(mesh_body, element_start, "count", &count_text)) {
char* count_end = nullptr;
const long long expected = std::strtoll(count_text.c_str(), &count_end, 10);
if (count_end == count_text.c_str() || *count_end != '\0' || expected < 0) {
if (error) *error = "collada: <polygons> count 非整数";
return false;
}
if (static_cast<std::size_t>(expected) != polygon_count) {
if (error) *error = "collada: <polygons> <p> 数量与 count 属性不匹配";
return false;
}
}
append_mesh(object, *context.positions, local_indices);
if (object->mesh.vertex_count() > kMaxVertices) {
if (error) *error = "collada: 顶点数超过上限";
return false;
}
if (object->mesh.triangle_count() > kMaxTriangles) {
if (error) *error = "collada: 三角面数超过上限";
return false;
}
}
// 6) 只含不支持的 primitive 时明确报错(而不是当作非 mesh geometry 静默跳过)
if (triangles_elements == 0 && polylist_elements == 0 && polygons_elements == 0) {
const std::string lower_mesh = lower_ascii(mesh_body);
for (const char* unsupported : {"<tristrips", "<trifans", "<linestrips", "<lines"}) {
if (lower_mesh.find(unsupported) != std::string::npos) {
if (error) *error = std::string("collada: 不支持的 primitive 类型 ") +
unsupported + "(仅 triangles/polylist/polygons)";
return false;
}
}
}
return true;
}
struct GeometryParseResult {
std::vector<ColladaObject> objects;
};
bool parse_collada(const std::string& text, std::vector<ColladaObject>* objects,
std::string* error) {
objects->clear();
const std::string lower = lower_ascii(text);
const std::size_t root = find_open_tag(text, 0, "collada");
if (root == std::string::npos) {
if (error) *error = "collada: 缺少 <COLLADA> 根元素";
return false;
}
std::string version;
if (attribute_value(text, root, "version", &version) && !version.empty()) {
if (version.rfind("1.4", 0) != 0 && version.rfind("1.5", 0) != 0) {
if (error) *error = "collada: 不支持的 COLLADA version=" + version +
"(仅 1.4/1.5)";
return false;
}
}
if (lower.find("<library_geometries") == std::string::npos) {
if (error) *error = "collada: 缺少 <library_geometries>";
return false;
}
std::size_t pos = 0;
while (true) {
const std::size_t geometry_start = find_open_tag(text, pos, "geometry");
if (geometry_start == std::string::npos) break;
std::size_t begin = 0, end = 0, after = 0;
if (!extract_element(text, geometry_start, "geometry", &begin, &end, &after)) {
if (error) *error = "collada: <geometry> 标签不完整";
return false;
}
pos = after;
if (objects->size() >= kMaxGeometries) {
if (error) *error = "collada: geometry 数量超过上限";
return false;
}
const std::string geometry_body = text.substr(begin, end - begin);
ColladaObject object;
if (!parse_geometry(geometry_body, &object, error)) return false;
if (!object.mesh.empty()) objects->push_back(std::move(object));
}
if (objects->empty()) {
if (error) *error = "collada: 未找到含 triangles/polylist/polygons 的 <geometry>";
return false;
}
return true;
}
/// 多个 geometry → 多个实体(host->alloc 分配句柄数组)。
int publish_bodies(const VdePluginHost* host, const std::vector<ColladaObject>& objects,
VdeBody** out_bodies, std::size_t* out_count) {
if (out_bodies) *out_bodies = nullptr;
if (out_count) *out_count = 0;
if (!out_bodies || !out_count)
return fail(host, VDE_PLUGIN_ERR_INVALID_ARG, "collada: bodies/count 输出指针为空");
if (objects.empty())
return fail(host, VDE_PLUGIN_ERR_PARSE, "collada: 文件不含可用三角网格");
if (!vde_plugin_common::host_has_body_from_mesh(host))
return fail(host, VDE_PLUGIN_ERR_UNSUPPORTED,
"collada: 宿主未提供 body_from_mesh(需要插件 ABI minor >= 1)");
VdeBody* array = static_cast<VdeBody*>(host->alloc(sizeof(VdeBody) * objects.size()));
if (!array)
return fail(host, VDE_PLUGIN_ERR_BUFFER, "collada: 实体句柄数组分配失败");
std::size_t made = 0;
for (const auto& object : objects) {
VdeBody body = host->body_from_mesh(object.mesh.positions.data(),
object.mesh.vertex_count(),
object.mesh.indices.data(),
object.mesh.triangle_count());
if (!body) {
for (std::size_t i = 0; i < made; ++i) host->body_destroy(array[i]);
host->free(array);
return fail(host, VDE_PLUGIN_ERR_INTERNAL,
"collada: 宿主由网格创建实体失败(见 host 错误信息)");
}
array[made++] = body;
}
*out_bodies = array;
*out_count = made;
return VDE_PLUGIN_OK;
}
int read_impl(const VdePluginHost* host, const void* data, std::size_t size,
VdeBody** bodies, std::size_t* count) {
if (bodies) *bodies = nullptr;
if (count) *count = 0;
if (!bodies || !count)
return fail(host, VDE_PLUGIN_ERR_INVALID_ARG, "collada: bodies/count 输出指针为空");
if (!data || size == 0)
return fail(host, VDE_PLUGIN_ERR_PARSE, "collada: 文件为空");
if (size > kMaxFileBytes)
return fail(host, VDE_PLUGIN_ERR_PARSE, "collada: 文件超过大小上限");
const int host_rc = validate_read_host(host);
if (host_rc != VDE_PLUGIN_OK) return host_rc;
const std::string text(static_cast<const char*>(data), size);
std::vector<ColladaObject> objects;
std::string error;
if (!parse_collada(text, &objects, &error))
return fail(host, VDE_PLUGIN_ERR_PARSE, error.c_str());
return publish_bodies(host, objects, bodies, count);
}
int collada_read_file(const VdePluginHost* host, const char* path, VdeBody** bodies,
std::size_t* count) {
if (bodies) *bodies = nullptr;
if (count) *count = 0;
if (!bodies || !count)
return fail(host, VDE_PLUGIN_ERR_INVALID_ARG, "collada: bodies/count 输出指针为空");
if (!path)
return fail(host, VDE_PLUGIN_ERR_INVALID_ARG, "collada: path 为空");
std::string bytes;
if (!read_file_bytes(path, &bytes))
return fail(host, VDE_PLUGIN_ERR_IO, "collada: 无法读取输入文件");
return read_impl(host, bytes.data(), bytes.size(), bodies, count);
}
int collada_read_memory(const VdePluginHost* host, const void* data, std::size_t size,
VdeBody** bodies, std::size_t* count) {
return read_impl(host, data, size, bodies, count);
}
bool append_geometry_xml(const VdePluginHost* host, VdeBody body, std::size_t index,
std::string* xml) {
VdeMeshData mesh{};
mesh.struct_size = static_cast<std::uint32_t>(sizeof(VdeMeshData));
struct MeshReleaser {
const VdePluginHost* host;
VdeMeshData* mesh;
~MeshReleaser() {
if (!host || !mesh) return;
if (host->free_buffer) {
if (mesh->positions) host->free_buffer(mesh->positions);
if (mesh->indices) host->free_buffer(mesh->indices);
if (mesh->normals) host->free_buffer(mesh->normals);
}
}
} releaser{host, &mesh};
if (host->body_tessellate(body, kWriteDeflection, &mesh) != VDE_PLUGIN_OK)
return false;
if (!mesh.positions || mesh.num_vertices == 0 || !mesh.indices ||
mesh.num_triangles == 0)
return false;
char buffer[512];
const std::string base = "geometry-" + std::to_string(index + 1);
xml->append(" <geometry id=\"");
xml->append(base);
xml->append("\" name=\"body-");
std::snprintf(buffer, sizeof(buffer), "%zu", index + 1);
xml->append(buffer);
xml->append("\">\n <mesh>\n <source id=\"");
xml->append(base);
xml->append("-positions\">\n <float_array id=\"");
xml->append(base);
xml->append("-positions-array\" count=\"");
std::snprintf(buffer, sizeof(buffer), "%zu", mesh.num_vertices * 3);
xml->append(buffer);
xml->append("\">");
for (std::size_t i = 0; i < mesh.num_vertices; ++i) {
for (int axis = 0; axis < 3; ++axis) {
if (i != 0 || axis != 0) xml->push_back(' ');
std::snprintf(buffer, sizeof(buffer), "%.9g",
mesh.positions[i * 3 + axis]);
xml->append(buffer);
}
}
xml->append("</float_array>\n <technique_common>\n <accessor source=\"#");
xml->append(base);
xml->append("-positions-array\" count=\"");
std::snprintf(buffer, sizeof(buffer), "%zu", mesh.num_vertices);
xml->append(buffer);
xml->append("\" stride=\"3\">\n <param name=\"X\" type=\"float\"/>\n"
" <param name=\"Y\" type=\"float\"/>\n"
" <param name=\"Z\" type=\"float\"/>\n"
" </accessor>\n </technique_common>\n </source>\n"
" <vertices id=\"");
xml->append(base);
xml->append("-vertices\">\n <input semantic=\"POSITION\" source=\"#");
xml->append(base);
xml->append("-positions\"/>\n </vertices>\n <triangles count=\"");
std::snprintf(buffer, sizeof(buffer), "%zu", mesh.num_triangles);
xml->append(buffer);
xml->append("\">\n <input semantic=\"VERTEX\" source=\"#");
xml->append(base);
xml->append("-vertices\" offset=\"0\"/>\n <p>");
for (std::size_t i = 0; i < mesh.num_triangles; ++i) {
for (int corner = 0; corner < 3; ++corner) {
if (i != 0 || corner != 0) xml->push_back(' ');
std::snprintf(buffer, sizeof(buffer), "%u", mesh.indices[i * 3 + corner]);
xml->append(buffer);
}
}
xml->append("</p>\n </triangles>\n </mesh>\n </geometry>\n");
return true;
}
int write_impl(const VdePluginHost* host, const VdeBody* bodies, std::size_t count,
std::string* bytes) {
const int host_rc = validate_write_host(host);
if (host_rc != VDE_PLUGIN_OK) return host_rc;
if (!bodies || count == 0)
return fail(host, VDE_PLUGIN_ERR_INVALID_ARG, "collada: 无实体可写");
if (count > kMaxGeometries)
return fail(host, VDE_PLUGIN_ERR_BUFFER, "collada: 实体数超过上限");
std::string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
xml.append("<COLLADA xmlns=\"http://www.collada.org/2005/11/COLLADASchema\" "
"version=\"1.4.1\">\n <asset>\n <contributor><authoring_tool>VDE"
"</authoring_tool></contributor>\n <unit name=\"millimeter\" "
"meter=\"0.001\"/>\n <up_axis>Y_UP</up_axis>\n </asset>\n "
"<library_geometries>\n");
for (std::size_t i = 0; i < count; ++i) {
if (!append_geometry_xml(host, bodies[i], i, &xml))
return fail(host, VDE_PLUGIN_ERR_INTERNAL,
"collada: body_tessellate 失败或网格为空");
}
xml.append(" </library_geometries>\n</COLLADA>\n");
*bytes = std::move(xml);
return VDE_PLUGIN_OK;
}
int collada_write_file(const VdePluginHost* host, const char* path, const VdeBody* bodies,
std::size_t count) {
if (!path) return fail(host, VDE_PLUGIN_ERR_INVALID_ARG, "collada: path 为空");
std::string bytes;
const int rc = write_impl(host, bodies, count, &bytes);
if (rc != VDE_PLUGIN_OK) return rc;
if (!write_file_bytes(path, bytes.data(), bytes.size()))
return fail(host, VDE_PLUGIN_ERR_IO, "collada: 写文件失败");
return VDE_PLUGIN_OK;
}
int collada_write_memory(const VdePluginHost* host, const VdeBody* bodies,
std::size_t count, VdeBuffer* out) {
if (out) {
out->data = nullptr;
out->size = 0;
}
if (!out) return fail(host, VDE_PLUGIN_ERR_INVALID_ARG, "collada: 输出缓冲为空");
std::string bytes;
const int rc = write_impl(host, bodies, count, &bytes);
if (rc != VDE_PLUGIN_OK) return rc;
void* buffer = host->alloc(bytes.size());
if (!buffer) return fail(host, VDE_PLUGIN_ERR_BUFFER, "collada: 输出内存分配失败");
std::memcpy(buffer, bytes.data(), bytes.size());
out->data = buffer;
out->size = bytes.size();
return VDE_PLUGIN_OK;
}
int collada_probe(const void* head, std::size_t head_size) {
if (!head || head_size == 0) return 0;
const std::string head_text(static_cast<const char*>(head),
std::min<std::size_t>(head_size, 4096));
const std::string lower = lower_ascii(head_text);
return lower.find("<collada") != std::string::npos ? 92 : 0;
}
const char* collada_describe() {
return "VDE official COLLADA format (COLLADA 1.4/1.5 XML triangle mesh; read/write; "
"no kernel link)";
}
const VdeFormatPlugin kFormat = [] {
VdeFormatPlugin format{};
format.struct_size = static_cast<std::uint32_t>(sizeof(VdeFormatPlugin));
format.format_id = "dae";
format.extensions = ".dae";
format.probe = &collada_probe;
format.read_file = &collada_read_file;
format.read_memory = &collada_read_memory;
format.write_file = &collada_write_file;
format.write_memory = &collada_write_memory;
format.describe = &collada_describe;
return format;
}();
} // namespace
extern "C" {
VDE_PLUGIN_EXPORT int vde_plugin_query(uint32_t host_abi_major, VdePluginInfo* info) {
if (!info || info->struct_size < sizeof(VdePluginInfo)) return VDE_PLUGIN_ERR_ABI;
if (host_abi_major != VDE_PLUGIN_ABI_MAJOR) return VDE_PLUGIN_ERR_ABI;
info->id = "com.vde.official.collada";
info->name = "VDE Official COLLADA Format";
info->version = "1.0.0";
info->kind = VDE_PLUGIN_KIND_FORMAT;
info->abi_major = VDE_PLUGIN_ABI_MAJOR;
info->abi_minor = VDE_PLUGIN_ABI_MINOR;
info->capabilities = "format:dae.read;format:dae.write";
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 = vde_plugin_common::validate_common_host(host);
if (host_rc != VDE_PLUGIN_OK) return host_rc;
reg->kind = VDE_PLUGIN_KIND_FORMAT;
reg->format = &kFormat;
reg->generic = nullptr;
return VDE_PLUGIN_OK;
}
VDE_PLUGIN_EXPORT void vde_plugin_shutdown() {}
} // extern "C"