Files

2376 lines
98 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.
// 官方 glTF 2.0 / GLB 格式插件(P4-06;纯 C ABI,不链接内核)。
//
// 读:.gltf(JSON,buffer 可为 base64 data URI 或相对路径外部 .bin)
// 与 .glb(GLB 容器)→ accessors/bufferViews → POSITION/indices
// → 每个三角 primitive 经 host->body_from_mesh 创建一个实体。
// 支持多 mesh / 多 primitive;只支持 mode=4(TRIANGLES)。
// 写:实体 → host->body_tessellate → 合并为一个 glTF buffer:
// .glb 输出 JSON+BIN 两个 chunk;.gltf 输出内嵌 base64 data URI
// (单文件、原子写出)。每个实体一个 mesh/primitive。
// 几何能力全部经宿主服务表;不链接 vde_kernel / vde_brep,不使用外部 JSON 库。
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <functional>
#include <locale>
#include <new>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include "../common/format_plugin_common.h"
namespace {
using vde_plugin_common::fail;
using vde_plugin_common::host_has_body_from_mesh;
using vde_plugin_common::read_file_bytes;
using vde_plugin_common::validate_common_host;
using vde_plugin_common::validate_write_host;
using vde_plugin_common::write_file_bytes;
constexpr std::uint32_t kGlbMagic = 0x46546C67u; // "glTF"
constexpr std::uint32_t kGlbVersion = 2u;
constexpr std::uint32_t kChunkJson = 0x4E4F534Au; // "JSON"
constexpr std::uint32_t kChunkBin = 0x004E4942u; // "BIN\0"
constexpr std::size_t kMaxJsonDepth = 128u;
constexpr std::size_t kMaxAccessorCount = 50000000u;
// ─────────────────────────────────────────────────────────────────────
// 最小 JSON DOM / 解析器(不依赖外部库,够读 glTF 文档)
// ─────────────────────────────────────────────────────────────────────
int json_hex_digit(char c) {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
return -1;
}
struct JsonValue {
enum Type { Null, Bool, Number, String, Array, Object };
Type type = Null;
bool boolean = false;
double number = 0.0;
std::string string;
std::vector<JsonValue> array;
std::vector<std::pair<std::string, JsonValue>> object;
const JsonValue* member(const char* key) const {
if (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)
: begin_(data), cursor_(data), end_(data + size) {}
bool parse(JsonValue* out, std::string* error) {
skip_ws();
if (!parse_value(out, 0)) {
*error = error_;
return false;
}
skip_ws();
if (cursor_ != end_) {
fail("trailing characters after JSON value");
*error = error_;
return false;
}
return true;
}
private:
bool fail(const char* message) {
if (error_.empty()) {
error_ = std::string("JSON parse error: ") + message + " (byte " +
std::to_string(static_cast<std::size_t>(cursor_ - begin_)) + ")";
}
return false;
}
void skip_ws() {
while (cursor_ < end_ &&
(*cursor_ == ' ' || *cursor_ == '\t' || *cursor_ == '\r' ||
*cursor_ == '\n'))
++cursor_;
}
bool parse_value(JsonValue* out, std::size_t depth) {
if (depth > kMaxJsonDepth) return fail("nesting too deep");
if (cursor_ >= end_) return fail("unexpected end of input");
switch (*cursor_) {
case '{': return parse_object(out, depth);
case '[': return parse_array(out, depth);
case '"': {
out->type = JsonValue::String;
return parse_string(&out->string);
}
case 't':
if (end_ - cursor_ < 4 || std::memcmp(cursor_, "true", 4) != 0)
return fail("invalid literal (expected true)");
cursor_ += 4;
out->type = JsonValue::Bool;
out->boolean = true;
return true;
case 'f':
if (end_ - cursor_ < 5 || std::memcmp(cursor_, "false", 5) != 0)
return fail("invalid literal (expected false)");
cursor_ += 5;
out->type = JsonValue::Bool;
out->boolean = false;
return true;
case 'n':
if (end_ - cursor_ < 4 || std::memcmp(cursor_, "null", 4) != 0)
return fail("invalid literal (expected null)");
cursor_ += 4;
out->type = JsonValue::Null;
return true;
default:
if (*cursor_ == '-' || (*cursor_ >= '0' && *cursor_ <= '9'))
return parse_number(out);
return fail("unexpected character");
}
}
bool parse_object(JsonValue* out, std::size_t depth) {
++cursor_; // '{'
out->type = JsonValue::Object;
skip_ws();
if (cursor_ < end_ && *cursor_ == '}') {
++cursor_;
return true;
}
while (true) {
skip_ws();
if (cursor_ >= end_ || *cursor_ != '"') return fail("expected object key string");
std::string key;
if (!parse_string(&key)) return false;
skip_ws();
if (cursor_ >= end_ || *cursor_ != ':') return fail("expected ':' after object key");
++cursor_;
skip_ws();
JsonValue value;
if (!parse_value(&value, depth + 1)) return false;
out->object.emplace_back(std::move(key), std::move(value));
skip_ws();
if (cursor_ >= end_) return fail("unterminated object");
if (*cursor_ == ',') {
++cursor_;
continue;
}
if (*cursor_ == '}') {
++cursor_;
return true;
}
return fail("expected ',' or '}' in object");
}
}
bool parse_array(JsonValue* out, std::size_t depth) {
++cursor_; // '['
out->type = JsonValue::Array;
skip_ws();
if (cursor_ < end_ && *cursor_ == ']') {
++cursor_;
return true;
}
while (true) {
skip_ws();
JsonValue value;
if (!parse_value(&value, depth + 1)) return false;
out->array.push_back(std::move(value));
skip_ws();
if (cursor_ >= end_) return fail("unterminated array");
if (*cursor_ == ',') {
++cursor_;
continue;
}
if (*cursor_ == ']') {
++cursor_;
return true;
}
return fail("expected ',' or ']' in array");
}
}
bool parse_hex4(std::uint32_t* out) {
if (end_ - cursor_ < 4) return fail("truncated \\u escape");
std::uint32_t value = 0;
for (int i = 0; i < 4; ++i) {
const int digit = json_hex_digit(cursor_[i]);
if (digit < 0) return fail("invalid \\u escape");
value = (value << 4) | static_cast<std::uint32_t>(digit);
}
cursor_ += 4;
*out = value;
return true;
}
static void append_utf8(std::string* out, std::uint32_t cp) {
if (cp <= 0x7F) {
out->push_back(static_cast<char>(cp));
} else if (cp <= 0x7FF) {
out->push_back(static_cast<char>(0xC0 | (cp >> 6)));
out->push_back(static_cast<char>(0x80 | (cp & 0x3F)));
} else if (cp <= 0xFFFF) {
out->push_back(static_cast<char>(0xE0 | (cp >> 12)));
out->push_back(static_cast<char>(0x80 | ((cp >> 6) & 0x3F)));
out->push_back(static_cast<char>(0x80 | (cp & 0x3F)));
} else {
out->push_back(static_cast<char>(0xF0 | (cp >> 18)));
out->push_back(static_cast<char>(0x80 | ((cp >> 12) & 0x3F)));
out->push_back(static_cast<char>(0x80 | ((cp >> 6) & 0x3F)));
out->push_back(static_cast<char>(0x80 | (cp & 0x3F)));
}
}
bool parse_string(std::string* out) {
++cursor_; // opening quote
out->clear();
while (cursor_ < end_) {
const unsigned char c = static_cast<unsigned char>(*cursor_);
if (c == '"') {
++cursor_;
return true;
}
if (c < 0x20) return fail("unescaped control character in string");
if (c != '\\') {
out->push_back(static_cast<char>(c));
++cursor_;
continue;
}
++cursor_;
if (cursor_ >= end_) return fail("unterminated escape");
const char esc = *cursor_++;
switch (esc) {
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': {
std::uint32_t cp = 0;
if (!parse_hex4(&cp)) return false;
if (cp >= 0xD800 && cp <= 0xDBFF) {
if (end_ - cursor_ < 2 || cursor_[0] != '\\' || cursor_[1] != 'u')
return fail("high surrogate without low surrogate");
cursor_ += 2;
std::uint32_t low = 0;
if (!parse_hex4(&low)) return false;
if (low < 0xDC00 || low > 0xDFFF)
return fail("invalid low surrogate");
cp = 0x10000u + ((cp - 0xD800u) << 10) + (low - 0xDC00u);
} else if (cp >= 0xDC00 && cp <= 0xDFFF) {
return fail("unexpected low surrogate");
}
append_utf8(out, cp);
break;
}
default: return fail("invalid escape sequence");
}
}
return fail("unterminated string");
}
bool parse_number(JsonValue* out) {
const char* start = cursor_;
if (cursor_ < end_ && *cursor_ == '-') ++cursor_;
if (cursor_ >= end_) return fail("truncated number");
if (*cursor_ == '0') {
++cursor_;
} else if (*cursor_ >= '1' && *cursor_ <= '9') {
while (cursor_ < end_ && *cursor_ >= '0' && *cursor_ <= '9') ++cursor_;
} else {
return fail("invalid number");
}
if (cursor_ < end_ && *cursor_ == '.') {
++cursor_;
if (cursor_ >= end_ || *cursor_ < '0' || *cursor_ > '9')
return fail("invalid number fraction");
while (cursor_ < end_ && *cursor_ >= '0' && *cursor_ <= '9') ++cursor_;
}
if (cursor_ < end_ && (*cursor_ == 'e' || *cursor_ == 'E')) {
++cursor_;
if (cursor_ < end_ && (*cursor_ == '+' || *cursor_ == '-')) ++cursor_;
if (cursor_ >= end_ || *cursor_ < '0' || *cursor_ > '9')
return fail("invalid number exponent");
while (cursor_ < end_ && *cursor_ >= '0' && *cursor_ <= '9') ++cursor_;
}
const std::string token(start, static_cast<std::size_t>(cursor_ - start));
char* parse_end = nullptr;
const double value = std::strtod(token.c_str(), &parse_end);
if (parse_end != token.c_str() + token.size() || !std::isfinite(value))
return fail("number out of range");
out->type = JsonValue::Number;
out->number = value;
return true;
}
const char* begin_ = nullptr;
const char* cursor_ = nullptr;
const char* end_ = nullptr;
std::string error_;
};
bool json_to_int(const JsonValue& value, long long* out) {
if (value.type != JsonValue::Number || !std::isfinite(value.number)) return false;
const double rounded = std::floor(value.number);
if (rounded != value.number) return false;
if (rounded < -9007199254740992.0 || rounded > 9007199254740992.0) return false;
*out = static_cast<long long>(rounded);
return true;
}
bool json_to_size(const JsonValue& value, std::size_t* out) {
long long parsed = 0;
if (!json_to_int(value, &parsed) || parsed < 0) return false;
*out = static_cast<std::size_t>(parsed);
return true;
}
// ─────────────────────────────────────────────────────────────────────
// glTF 文档模型
// ─────────────────────────────────────────────────────────────────────
struct GltfBuffer {
std::string uri;
std::size_t byte_length = 0;
};
struct GltfBufferView {
int buffer = -1;
std::size_t byte_offset = 0;
std::size_t byte_length = 0;
std::size_t byte_stride = 0;
};
struct GltfSparse {
bool present = false;
std::size_t count = 0;
int index_buffer_view = -1;
std::size_t index_byte_offset = 0;
int index_component_type = 0;
int value_buffer_view = -1;
std::size_t value_byte_offset = 0;
};
struct GltfAccessor {
int buffer_view = -1;
std::size_t byte_offset = 0;
int component_type = 0;
std::size_t count = 0;
std::string type;
GltfSparse sparse;
};
struct GltfPrimitive {
int position = -1;
int indices = -1;
int mode = 4;
std::vector<int> targets;
};
struct GltfMesh {
std::string name;
std::vector<GltfPrimitive> primitives;
std::vector<double> weights;
};
struct GltfNode {
int mesh = -1;
std::vector<int> children;
bool has_matrix = false;
double matrix[16] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1};
bool has_trs = false;
double translation[3] = {0, 0, 0};
double rotation[4] = {0, 0, 0, 1};
double scale[3] = {1, 1, 1};
bool has_weights = false;
std::vector<double> weights;
};
struct GltfScene {
std::vector<int> nodes;
};
struct GltfDocument {
std::vector<GltfBuffer> buffers;
std::vector<GltfBufferView> buffer_views;
std::vector<GltfAccessor> accessors;
std::vector<GltfMesh> meshes;
std::vector<GltfNode> nodes;
std::vector<GltfScene> scenes;
int default_scene = -1;
};
struct GltfTransform {
double m[16] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1};
static GltfTransform identity() { return GltfTransform{}; }
static GltfTransform multiply(const GltfTransform& a, const GltfTransform& b) {
GltfTransform r;
for (int col = 0; col < 4; ++col) {
for (int row = 0; row < 4; ++row) {
double sum = 0.0;
for (int k = 0; k < 4; ++k)
sum += a.m[k * 4 + row] * b.m[col * 4 + k];
r.m[col * 4 + row] = sum;
}
}
return r;
}
static GltfTransform from_node(const GltfNode& node) {
GltfTransform t;
if (node.has_matrix) {
std::copy(node.matrix, node.matrix + 16, t.m);
return t;
}
if (!node.has_trs) return t;
const double x = node.rotation[0], y = node.rotation[1];
const double z = node.rotation[2], w = node.rotation[3];
const double xx = x * x, yy = y * y, zz = z * z;
const double xy = x * y, xz = x * z, yz = y * z;
const double wx = w * x, wy = w * y, wz = w * z;
double r[3][3] = {
{1 - 2 * (yy + zz), 2 * (xy - wz), 2 * (xz + wy)},
{2 * (xy + wz), 1 - 2 * (xx + zz), 2 * (yz - wx)},
{2 * (xz - wy), 2 * (yz + wx), 1 - 2 * (xx + yy)},
};
r[0][0] *= node.scale[0]; r[0][1] *= node.scale[0]; r[0][2] *= node.scale[0];
r[1][0] *= node.scale[1]; r[1][1] *= node.scale[1]; r[1][2] *= node.scale[1];
r[2][0] *= node.scale[2]; r[2][1] *= node.scale[2]; r[2][2] *= node.scale[2];
t.m[0] = r[0][0]; t.m[1] = r[1][0]; t.m[2] = r[2][0]; t.m[3] = 0;
t.m[4] = r[0][1]; t.m[5] = r[1][1]; t.m[6] = r[2][1]; t.m[7] = 0;
t.m[8] = r[0][2]; t.m[9] = r[1][2]; t.m[10] = r[2][2]; t.m[11] = 0;
t.m[12] = node.translation[0]; t.m[13] = node.translation[1];
t.m[14] = node.translation[2]; t.m[15] = 1;
return t;
}
void apply(double x, double y, double z, double* ox, double* oy, double* oz) const {
*ox = m[0] * x + m[4] * y + m[8] * z + m[12];
*oy = m[1] * x + m[5] * y + m[9] * z + m[13];
*oz = m[2] * x + m[6] * y + m[10] * z + m[14];
}
};
std::size_t component_size(int component_type) {
switch (component_type) {
case 5120: // BYTE
case 5121: // UNSIGNED_BYTE
return 1;
case 5122: // SHORT
case 5123: // UNSIGNED_SHORT
return 2;
case 5125: // UNSIGNED_INT
case 5126: // FLOAT
return 4;
default:
return 0;
}
}
std::size_t type_components(const std::string& type) {
if (type == "SCALAR") return 1;
if (type == "VEC2") return 2;
if (type == "VEC3") return 3;
if (type == "VEC4") return 4;
if (type == "MAT2") return 4;
if (type == "MAT3") return 9;
if (type == "MAT4") return 16;
return 0;
}
bool parse_index_value(const JsonValue* value, int* out, const std::string& context,
std::string* error) {
long long parsed = 0;
if (!value || !json_to_int(*value, &parsed) || parsed < 0 || parsed > 0x7FFFFFFFll) {
*error = "gltf: " + context + " must be a non-negative integer";
return false;
}
*out = static_cast<int>(parsed);
return true;
}
bool parse_size_value(const JsonValue* value, std::size_t* out, const std::string& context,
std::string* error) {
if (!value || !json_to_size(*value, out)) {
*error = "gltf: " + context + " must be a non-negative integer";
return false;
}
return true;
}
bool parse_number_array(const JsonValue* value, double* out, std::size_t count,
const std::string& context, std::string* error) {
if (!value || value->type != JsonValue::Array || value->array.size() != count) {
*error = "gltf: " + context + " must be an array of " + std::to_string(count) +
" numbers";
return false;
}
for (std::size_t i = 0; i < count; ++i) {
if (value->array[i].type != JsonValue::Number ||
!std::isfinite(value->array[i].number)) {
*error = "gltf: " + context + "[" + std::to_string(i) +
"] must be a finite number";
return false;
}
out[i] = value->array[i].number;
}
return true;
}
bool parse_number_list(const JsonValue* value, std::vector<double>* out,
const std::string& context, std::string* error) {
if (!value || value->type != JsonValue::Array) {
*error = "gltf: " + context + " must be an array";
return false;
}
out->clear();
out->reserve(value->array.size());
for (std::size_t i = 0; i < value->array.size(); ++i) {
if (value->array[i].type != JsonValue::Number ||
!std::isfinite(value->array[i].number)) {
*error = "gltf: " + context + "[" + std::to_string(i) +
"] must be a finite number";
return false;
}
out->push_back(value->array[i].number);
}
return true;
}
bool parse_gltf_document(const std::string& json_text, GltfDocument* doc,
std::string* error) {
std::size_t offset = 0;
if (json_text.size() >= 3 &&
static_cast<unsigned char>(json_text[0]) == 0xEF &&
static_cast<unsigned char>(json_text[1]) == 0xBB &&
static_cast<unsigned char>(json_text[2]) == 0xBF)
offset = 3;
JsonValue root;
JsonParser parser(json_text.data() + offset, json_text.size() - offset);
if (!parser.parse(&root, error)) return false;
if (root.type != JsonValue::Object) {
*error = "gltf: top-level JSON value is not an object";
return false;
}
const JsonValue* asset = root.member("asset");
if (!asset || asset->type != JsonValue::Object) {
*error = "gltf: missing asset object";
return false;
}
const JsonValue* version = asset->member("version");
if (!version || version->type != JsonValue::String ||
version->string.compare(0, 2, "2.") != 0) {
*error = "gltf: unsupported or missing asset.version (expected 2.x)";
return false;
}
const JsonValue* buffers = root.member("buffers");
if (buffers) {
if (buffers->type != JsonValue::Array) {
*error = "gltf: buffers must be an array";
return false;
}
for (std::size_t i = 0; i < buffers->array.size(); ++i) {
const JsonValue& item = buffers->array[i];
const std::string context = "buffers[" + std::to_string(i) + "]";
if (item.type != JsonValue::Object) {
*error = "gltf: " + context + " must be an object";
return false;
}
GltfBuffer buffer;
const JsonValue* uri = item.member("uri");
if (uri) {
if (uri->type != JsonValue::String) {
*error = "gltf: " + context + ".uri must be a string";
return false;
}
buffer.uri = uri->string;
}
if (!parse_size_value(item.member("byteLength"), &buffer.byte_length,
context + ".byteLength", error))
return false;
doc->buffers.push_back(std::move(buffer));
}
}
const JsonValue* buffer_views = root.member("bufferViews");
if (buffer_views) {
if (buffer_views->type != JsonValue::Array) {
*error = "gltf: bufferViews must be an array";
return false;
}
for (std::size_t i = 0; i < buffer_views->array.size(); ++i) {
const JsonValue& item = buffer_views->array[i];
const std::string context = "bufferViews[" + std::to_string(i) + "]";
if (item.type != JsonValue::Object) {
*error = "gltf: " + context + " must be an object";
return false;
}
GltfBufferView view;
if (!parse_index_value(item.member("buffer"), &view.buffer,
context + ".buffer", error))
return false;
if (const JsonValue* value = item.member("byteOffset")) {
if (!parse_size_value(value, &view.byte_offset,
context + ".byteOffset", error))
return false;
}
if (!parse_size_value(item.member("byteLength"), &view.byte_length,
context + ".byteLength", error))
return false;
if (const JsonValue* value = item.member("byteStride")) {
if (!parse_size_value(value, &view.byte_stride,
context + ".byteStride", error))
return false;
if (view.byte_stride < 4 || view.byte_stride > 252 ||
view.byte_stride % 4 != 0) {
*error = "gltf: " + context +
".byteStride must be a multiple of 4 in [4, 252]";
return false;
}
}
if (view.byte_offset > SIZE_MAX - view.byte_length) {
*error = "gltf: " + context + " byte range overflows";
return false;
}
if (view.buffer >= static_cast<int>(doc->buffers.size())) {
*error = "gltf: " + context + ".buffer index out of range";
return false;
}
doc->buffer_views.push_back(view);
}
}
const JsonValue* accessors = root.member("accessors");
if (accessors) {
if (accessors->type != JsonValue::Array) {
*error = "gltf: accessors must be an array";
return false;
}
for (std::size_t i = 0; i < accessors->array.size(); ++i) {
const JsonValue& item = accessors->array[i];
const std::string context = "accessors[" + std::to_string(i) + "]";
if (item.type != JsonValue::Object) {
*error = "gltf: " + context + " must be an object";
return false;
}
GltfAccessor accessor;
if (const JsonValue* value = item.member("bufferView")) {
if (!parse_index_value(value, &accessor.buffer_view,
context + ".bufferView", error))
return false;
if (accessor.buffer_view >= static_cast<int>(doc->buffer_views.size())) {
*error = "gltf: " + context + ".bufferView index out of range";
return false;
}
}
if (const JsonValue* value = item.member("byteOffset")) {
if (!parse_size_value(value, &accessor.byte_offset,
context + ".byteOffset", error))
return false;
}
long long component = 0;
if (!item.member("componentType") ||
!json_to_int(*item.member("componentType"), &component) ||
component < 0 || component > 0x7FFFFFFFll) {
*error = "gltf: " + context + ".componentType is required";
return false;
}
accessor.component_type = static_cast<int>(component);
if (component_size(accessor.component_type) == 0) {
*error = "gltf: " + context + ".componentType is unsupported";
return false;
}
if (!parse_size_value(item.member("count"), &accessor.count,
context + ".count", error))
return false;
if (accessor.count > kMaxAccessorCount) {
*error = "gltf: " + context + ".count exceeds supported limit";
return false;
}
const JsonValue* type = item.member("type");
if (!type || type->type != JsonValue::String ||
type_components(type->string) == 0) {
*error = "gltf: " + context + ".type is missing or unsupported";
return false;
}
accessor.type = type->string;
if (const JsonValue* sparse = item.member("sparse")) {
const std::string sctx = context + ".sparse";
if (sparse->type != JsonValue::Object) {
*error = "gltf: " + sctx + " must be an object";
return false;
}
accessor.sparse.present = true;
if (!parse_size_value(sparse->member("count"), &accessor.sparse.count,
sctx + ".count", error))
return false;
if (accessor.sparse.count == 0 || accessor.sparse.count > accessor.count) {
*error = "gltf: " + sctx + ".count must be in [1, accessor.count]";
return false;
}
const JsonValue* indices = sparse->member("indices");
if (!indices || indices->type != JsonValue::Object) {
*error = "gltf: " + sctx + ".indices is required";
return false;
}
if (!parse_index_value(indices->member("bufferView"),
&accessor.sparse.index_buffer_view,
sctx + ".indices.bufferView", error))
return false;
if (accessor.sparse.index_buffer_view < 0 ||
accessor.sparse.index_buffer_view >=
static_cast<int>(doc->buffer_views.size())) {
*error = "gltf: " + sctx + ".indices.bufferView out of range";
return false;
}
if (const JsonValue* value = indices->member("byteOffset")) {
if (!parse_size_value(value, &accessor.sparse.index_byte_offset,
sctx + ".indices.byteOffset", error))
return false;
}
long long index_component = 0;
if (!indices->member("componentType") ||
!json_to_int(*indices->member("componentType"), &index_component) ||
(index_component != 5121 && index_component != 5123 &&
index_component != 5125)) {
*error = "gltf: " + sctx + ".indices.componentType must be U8/U16/U32";
return false;
}
accessor.sparse.index_component_type = static_cast<int>(index_component);
const JsonValue* values = sparse->member("values");
if (!values || values->type != JsonValue::Object) {
*error = "gltf: " + sctx + ".values is required";
return false;
}
if (!parse_index_value(values->member("bufferView"),
&accessor.sparse.value_buffer_view,
sctx + ".values.bufferView", error))
return false;
if (accessor.sparse.value_buffer_view < 0 ||
accessor.sparse.value_buffer_view >=
static_cast<int>(doc->buffer_views.size())) {
*error = "gltf: " + sctx + ".values.bufferView out of range";
return false;
}
if (const JsonValue* value = values->member("byteOffset")) {
if (!parse_size_value(value, &accessor.sparse.value_byte_offset,
sctx + ".values.byteOffset", error))
return false;
}
}
doc->accessors.push_back(std::move(accessor));
}
}
const JsonValue* meshes = root.member("meshes");
if (!meshes || meshes->type != JsonValue::Array || meshes->array.empty()) {
*error = "gltf: no meshes array (or it is empty)";
return false;
}
for (std::size_t i = 0; i < meshes->array.size(); ++i) {
const JsonValue& item = meshes->array[i];
const std::string context = "meshes[" + std::to_string(i) + "]";
if (item.type != JsonValue::Object) {
*error = "gltf: " + context + " must be an object";
return false;
}
GltfMesh mesh;
if (const JsonValue* name = item.member("name")) {
if (name->type == JsonValue::String) mesh.name = name->string;
}
if (const JsonValue* weights = item.member("weights")) {
if (!parse_number_list(weights, &mesh.weights,
context + ".weights", error))
return false;
}
const JsonValue* primitives = item.member("primitives");
if (!primitives || primitives->type != JsonValue::Array ||
primitives->array.empty()) {
*error = "gltf: " + context + ".primitives is missing or empty";
return false;
}
for (std::size_t j = 0; j < primitives->array.size(); ++j) {
const JsonValue& prim = primitives->array[j];
const std::string pctx = context + ".primitives[" + std::to_string(j) + "]";
if (prim.type != JsonValue::Object) {
*error = "gltf: " + pctx + " must be an object";
return false;
}
GltfPrimitive primitive;
const JsonValue* attributes = prim.member("attributes");
if (!attributes || attributes->type != JsonValue::Object) {
*error = "gltf: " + pctx + ".attributes is missing";
return false;
}
if (!parse_index_value(attributes->member("POSITION"), &primitive.position,
pctx + ".attributes.POSITION", error))
return false;
if (primitive.position >= static_cast<int>(doc->accessors.size())) {
*error = "gltf: " + pctx + ".attributes.POSITION index out of range";
return false;
}
if (const JsonValue* value = prim.member("indices")) {
if (!parse_index_value(value, &primitive.indices, pctx + ".indices", error))
return false;
if (primitive.indices >= static_cast<int>(doc->accessors.size())) {
*error = "gltf: " + pctx + ".indices index out of range";
return false;
}
}
if (const JsonValue* value = prim.member("mode")) {
long long mode = 0;
if (!json_to_int(*value, &mode) || mode < 0 || mode > 6) {
*error = "gltf: " + pctx + ".mode is invalid";
return false;
}
primitive.mode = static_cast<int>(mode);
}
if (const JsonValue* targets = prim.member("targets")) {
if (targets->type != JsonValue::Array) {
*error = "gltf: " + pctx + ".targets must be an array";
return false;
}
for (std::size_t k = 0; k < targets->array.size(); ++k) {
const std::string tctx = pctx + ".targets[" + std::to_string(k) + "]";
if (targets->array[k].type != JsonValue::Object) {
*error = "gltf: " + tctx + " must be an object";
return false;
}
int target = -1;
if (!parse_index_value(targets->array[k].member("POSITION"), &target,
tctx + ".POSITION", error))
return false;
if (target < 0 || target >= static_cast<int>(doc->accessors.size())) {
*error = "gltf: " + tctx + ".POSITION accessor out of range";
return false;
}
primitive.targets.push_back(target);
}
}
mesh.primitives.push_back(primitive);
}
doc->meshes.push_back(std::move(mesh));
}
const JsonValue* nodes = root.member("nodes");
if (nodes) {
if (nodes->type != JsonValue::Array) {
*error = "gltf: nodes must be an array";
return false;
}
for (std::size_t i = 0; i < nodes->array.size(); ++i) {
const JsonValue& item = nodes->array[i];
const std::string context = "nodes[" + std::to_string(i) + "]";
if (item.type != JsonValue::Object) {
*error = "gltf: " + context + " must be an object";
return false;
}
GltfNode node;
if (const JsonValue* value = item.member("mesh")) {
if (!parse_index_value(value, &node.mesh, context + ".mesh", error))
return false;
if (node.mesh >= static_cast<int>(doc->meshes.size())) {
*error = "gltf: " + context + ".mesh index out of range";
return false;
}
}
if (const JsonValue* value = item.member("matrix")) {
if (!parse_number_array(value, node.matrix, 16, context + ".matrix", error))
return false;
node.has_matrix = true;
}
if (const JsonValue* value = item.member("translation")) {
if (!parse_number_array(value, node.translation, 3,
context + ".translation", error))
return false;
node.has_trs = true;
}
if (const JsonValue* value = item.member("rotation")) {
if (!parse_number_array(value, node.rotation, 4, context + ".rotation", error))
return false;
node.has_trs = true;
}
if (const JsonValue* value = item.member("scale")) {
if (!parse_number_array(value, node.scale, 3, context + ".scale", error))
return false;
node.has_trs = true;
}
if (const JsonValue* value = item.member("weights")) {
if (!parse_number_list(value, &node.weights, context + ".weights", error))
return false;
node.has_weights = true;
}
if (const JsonValue* value = item.member("children")) {
if (value->type != JsonValue::Array) {
*error = "gltf: " + context + ".children must be an array";
return false;
}
for (std::size_t j = 0; j < value->array.size(); ++j) {
int child = 0;
if (!parse_index_value(&value->array[j], &child,
context + ".children[" + std::to_string(j) + "]",
error))
return false;
node.children.push_back(child);
}
}
doc->nodes.push_back(std::move(node));
}
}
const JsonValue* scenes = root.member("scenes");
if (scenes) {
if (scenes->type != JsonValue::Array) {
*error = "gltf: scenes must be an array";
return false;
}
for (std::size_t i = 0; i < scenes->array.size(); ++i) {
const JsonValue& item = scenes->array[i];
const std::string context = "scenes[" + std::to_string(i) + "]";
if (item.type != JsonValue::Object) {
*error = "gltf: " + context + " must be an object";
return false;
}
GltfScene scene;
if (const JsonValue* value = item.member("nodes")) {
if (value->type != JsonValue::Array) {
*error = "gltf: " + context + ".nodes must be an array";
return false;
}
for (std::size_t j = 0; j < value->array.size(); ++j) {
int node = 0;
if (!parse_index_value(&value->array[j], &node,
context + ".nodes[" + std::to_string(j) + "]",
error))
return false;
scene.nodes.push_back(node);
}
}
doc->scenes.push_back(std::move(scene));
}
}
if (const JsonValue* value = root.member("scene")) {
if (!parse_index_value(value, &doc->default_scene, "scene", error)) return false;
if (doc->default_scene >= static_cast<int>(doc->scenes.size())) {
*error = "gltf: scene index out of range";
return false;
}
}
return true;
}
// ─────────────────────────────────────────────────────────────────────
// 字节读取 / base64 / GLB 容器
// ─────────────────────────────────────────────────────────────────────
std::uint32_t read_u32_le(const unsigned char* data) {
return static_cast<std::uint32_t>(data[0]) |
(static_cast<std::uint32_t>(data[1]) << 8) |
(static_cast<std::uint32_t>(data[2]) << 16) |
(static_cast<std::uint32_t>(data[3]) << 24);
}
bool parse_glb(const unsigned char* data, std::size_t size, std::string* json,
std::string* bin, bool* has_bin, std::string* error) {
if (size < 12 || read_u32_le(data) != kGlbMagic) {
*error = "gltf: not a GLB container";
return false;
}
if (read_u32_le(data + 4) != kGlbVersion) {
*error = "gltf: unsupported GLB version " +
std::to_string(read_u32_le(data + 4));
return false;
}
const std::uint32_t declared = read_u32_le(data + 8);
if (declared < 12) {
*error = "gltf: invalid GLB declared length";
return false;
}
if (static_cast<std::size_t>(declared) > size) {
*error = "gltf: truncated GLB (declared " + std::to_string(declared) +
" bytes, have " + std::to_string(size) + ")";
return false;
}
if (static_cast<std::size_t>(declared) != size) {
*error = "gltf: GLB declared length does not match file size";
return false;
}
bool found_json = false;
std::size_t offset = 12;
while (offset + 8 <= size) {
const std::uint32_t chunk_length = read_u32_le(data + offset);
const std::uint32_t chunk_type = read_u32_le(data + offset + 4);
offset += 8;
if (static_cast<std::size_t>(chunk_length) > size - offset) {
*error = "gltf: truncated GLB chunk";
return false;
}
if (chunk_type == kChunkJson) {
if (found_json) {
*error = "gltf: GLB has more than one JSON chunk";
return false;
}
json->assign(reinterpret_cast<const char*>(data + offset), chunk_length);
found_json = true;
} else if (chunk_type == kChunkBin) {
if (*has_bin) {
*error = "gltf: GLB has more than one BIN chunk";
return false;
}
bin->assign(reinterpret_cast<const char*>(data + offset), chunk_length);
*has_bin = true;
}
offset += chunk_length;
}
if (offset != size) {
*error = "gltf: GLB trailing bytes after chunks";
return false;
}
if (!found_json) {
*error = "gltf: GLB has no JSON chunk";
return false;
}
return true;
}
int base64_value(char c) {
if (c >= 'A' && c <= 'Z') return c - 'A';
if (c >= 'a' && c <= 'z') return c - 'a' + 26;
if (c >= '0' && c <= '9') return c - '0' + 52;
if (c == '+') return 62;
if (c == '/') return 63;
return -1;
}
bool decode_base64(const std::string& text, std::string* out, std::string* error) {
out->clear();
if (text.empty()) return true;
if (text.size() % 4 != 0) {
*error = "gltf: base64 data length is not a multiple of 4";
return false;
}
for (std::size_t i = 0; i < text.size(); i += 4) {
int values[4] = {-1, -1, -1, -1};
int padding = 0;
for (int k = 0; k < 4; ++k) {
const char c = text[i + static_cast<std::size_t>(k)];
if (c == '=') {
if (k < 2) {
*error = "gltf: invalid base64 padding";
return false;
}
++padding;
continue;
}
if (padding > 0) {
*error = "gltf: invalid base64 padding position";
return false;
}
values[k] = base64_value(c);
if (values[k] < 0) {
*error = "gltf: invalid base64 character in buffer URI";
return false;
}
}
if (i + 4 != text.size() && padding > 0) {
*error = "gltf: invalid base64 padding before end";
return false;
}
out->push_back(static_cast<char>((values[0] << 2) | (values[1] >> 4)));
if (padding < 2)
out->push_back(static_cast<char>(((values[1] & 0x0F) << 4) |
(values[2] >> 2)));
if (padding < 1)
out->push_back(static_cast<char>(((values[2] & 0x03) << 6) | values[3]));
}
return true;
}
std::string encode_base64(const unsigned char* data, std::size_t size) {
static const char kAlphabet[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string out;
out.reserve(((size + 2) / 3) * 4);
for (std::size_t i = 0; i < size; i += 3) {
const std::uint32_t b0 = data[i];
const std::uint32_t b1 = (i + 1 < size) ? data[i + 1] : 0;
const std::uint32_t b2 = (i + 2 < size) ? data[i + 2] : 0;
const std::uint32_t triple = (b0 << 16) | (b1 << 8) | b2;
out.push_back(kAlphabet[(triple >> 18) & 0x3F]);
out.push_back(kAlphabet[(triple >> 12) & 0x3F]);
out.push_back(i + 1 < size ? kAlphabet[(triple >> 6) & 0x3F] : '=');
out.push_back(i + 2 < size ? kAlphabet[triple & 0x3F] : '=');
}
return out;
}
// ─────────────────────────────────────────────────────────────────────
// buffer / accessor 读取
// ─────────────────────────────────────────────────────────────────────
bool decode_percent_path(const std::string& text, std::string* out, std::string* error) {
out->clear();
for (std::size_t i = 0; i < text.size(); ++i) {
if (text[i] != '%') {
out->push_back(text[i]);
continue;
}
if (i + 2 >= text.size()) {
*error = "gltf: truncated percent escape in buffer URI";
return false;
}
const int hi = json_hex_digit(text[i + 1]);
const int lo = json_hex_digit(text[i + 2]);
if (hi < 0 || lo < 0) {
*error = "gltf: invalid percent escape in buffer URI";
return false;
}
out->push_back(static_cast<char>((hi << 4) | lo));
i += 2;
}
return true;
}
std::string directory_of(const char* path) {
if (!path) return std::string();
const std::string text(path);
const std::size_t slash = text.find_last_of("/\\");
return slash == std::string::npos ? std::string() : text.substr(0, slash + 1);
}
bool load_buffer_data(const VdePluginHost* host, const char* source_path,
const GltfDocument& doc, std::size_t index, bool is_glb,
const std::string& glb_bin, bool has_glb_bin,
std::string* out, std::string* error) {
const GltfBuffer& buffer = doc.buffers[index];
if (is_glb && index == 0 && buffer.uri.empty()) {
if (!has_glb_bin) {
*error = "gltf: GLB buffer 0 has no URI and no BIN chunk";
return false;
}
*out = glb_bin;
return true;
}
if (buffer.uri.empty()) {
*error = "gltf: buffer " + std::to_string(index) + " has no uri";
return false;
}
if (buffer.uri.compare(0, 5, "data:") == 0) {
const std::size_t marker = buffer.uri.find(";base64,");
if (marker == std::string::npos) {
*error = "gltf: buffer " + std::to_string(index) +
" uses an unsupported data URI (base64 expected)";
return false;
}
const std::string payload = buffer.uri.substr(marker + 8);
return decode_base64(payload, out, error);
}
if (buffer.uri.find("://") != std::string::npos) {
*error = "gltf: buffer " + std::to_string(index) +
" uses an unsupported absolute URI";
return false;
}
std::string relative;
if (!decode_percent_path(buffer.uri, &relative, error)) return false;
if (relative.empty() || relative[0] == '/' || relative[0] == '\\' ||
(relative.size() >= 2 && relative[1] == ':')) {
*error = "gltf: buffer " + std::to_string(index) +
" path is absolute or empty";
return false;
}
if (!source_path || !*source_path) {
*error = "gltf: external buffer '" + relative +
"' cannot be resolved from memory (use read_file)";
return false;
}
const std::string resolved = directory_of(source_path) + relative;
if (!read_file_bytes(resolved.c_str(), out)) {
*error = "gltf: cannot read external buffer '" + resolved + "'";
return false;
}
(void)host;
return true;
}
bool read_index_component(const unsigned char* data, int component_type,
std::uint32_t* out) {
switch (component_type) {
case 5121:
*out = data[0];
return true;
case 5123: {
std::uint16_t value = 0;
std::memcpy(&value, data, 2);
*out = value;
return true;
}
case 5125: {
std::uint32_t value = 0;
std::memcpy(&value, data, 4);
*out = value;
return true;
}
default:
return false;
}
}
struct AccessorLayout {
std::size_t base = 0;
std::size_t stride = 0;
std::size_t element_size = 0;
std::size_t components = 0;
std::size_t component_width = 0;
};
bool prepare_accessor(const GltfDocument& doc, int accessor_index,
const std::vector<std::string>& buffer_data,
AccessorLayout* layout, std::string* error) {
if (accessor_index < 0 ||
accessor_index >= static_cast<int>(doc.accessors.size())) {
*error = "gltf: accessor index out of range";
return false;
}
const GltfAccessor& accessor = doc.accessors[accessor_index];
if (accessor.buffer_view < 0) {
*error = "gltf: sparse/zero-filled accessors are not supported";
return false;
}
const GltfBufferView& view = doc.buffer_views[accessor.buffer_view];
if (view.buffer < 0 || view.buffer >= static_cast<int>(doc.buffers.size())) {
*error = "gltf: bufferView buffer index out of range";
return false;
}
const std::string& data = buffer_data[static_cast<std::size_t>(view.buffer)];
const std::size_t declared = doc.buffers[static_cast<std::size_t>(view.buffer)].byte_length;
if (declared > data.size()) {
*error = "gltf: buffer " + std::to_string(view.buffer) +
" is shorter than its declared byteLength";
return false;
}
if (view.byte_offset > declared || view.byte_length > declared - view.byte_offset) {
*error = "gltf: bufferView exceeds buffer bounds";
return false;
}
const std::size_t component_width = component_size(accessor.component_type);
const std::size_t components = type_components(accessor.type);
if (component_width == 0 || components == 0) {
*error = "gltf: unsupported accessor component/type";
return false;
}
const std::size_t element_size = component_width * components;
const std::size_t stride = view.byte_stride > 0 ? view.byte_stride : element_size;
if (stride < element_size) {
*error = "gltf: bufferView byteStride is smaller than the accessor element";
return false;
}
if (accessor.count > 0) {
if (accessor.byte_offset > view.byte_length ||
stride * (accessor.count - 1) > view.byte_length - accessor.byte_offset ||
element_size > view.byte_length - accessor.byte_offset -
stride * (accessor.count - 1)) {
*error = "gltf: accessor data exceeds bufferView bounds";
return false;
}
}
layout->base = view.byte_offset + accessor.byte_offset;
layout->stride = stride;
layout->element_size = element_size;
layout->components = components;
layout->component_width = component_width;
return true;
}
bool read_positions(const GltfDocument& doc, int accessor_index,
const std::vector<std::string>& buffer_data,
std::vector<double>* positions, std::string* error) {
if (accessor_index < 0 ||
accessor_index >= static_cast<int>(doc.accessors.size())) {
*error = "gltf: POSITION accessor index out of range";
return false;
}
const GltfAccessor& accessor = doc.accessors[accessor_index];
if (accessor.component_type != 5126 || accessor.type != "VEC3") {
*error = "gltf: POSITION accessor must be FLOAT VEC3";
return false;
}
if (accessor.count == 0) {
*error = "gltf: POSITION accessor is empty";
return false;
}
positions->assign(accessor.count * 3, 0.0);
if (accessor.buffer_view >= 0) {
AccessorLayout layout;
if (!prepare_accessor(doc, accessor_index, buffer_data, &layout, error))
return false;
const std::string& data = buffer_data[static_cast<std::size_t>(
doc.buffer_views[accessor.buffer_view].buffer)];
for (std::size_t i = 0; i < accessor.count; ++i) {
const unsigned char* element =
reinterpret_cast<const unsigned char*>(data.data()) + layout.base +
i * layout.stride;
for (int k = 0; k < 3; ++k) {
float value = 0.0f;
std::memcpy(&value, element + static_cast<std::size_t>(k) * 4, 4);
if (!std::isfinite(value)) {
*error = "gltf: POSITION contains a non-finite coordinate";
return false;
}
(*positions)[i * 3 + static_cast<std::size_t>(k)] =
static_cast<double>(value);
}
}
} else if (!accessor.sparse.present) {
*error = "gltf: POSITION accessor has neither bufferView nor sparse data";
return false;
}
if (accessor.sparse.present) {
const GltfSparse& sparse = accessor.sparse;
const GltfBufferView& index_view =
doc.buffer_views[static_cast<std::size_t>(sparse.index_buffer_view)];
const GltfBufferView& value_view =
doc.buffer_views[static_cast<std::size_t>(sparse.value_buffer_view)];
if (index_view.buffer < 0 ||
index_view.buffer >= static_cast<int>(buffer_data.size()) ||
value_view.buffer < 0 ||
value_view.buffer >= static_cast<int>(buffer_data.size())) {
*error = "gltf: sparse bufferView buffer index out of range";
return false;
}
const std::size_t index_size =
component_size(sparse.index_component_type);
if (index_size == 0 ||
sparse.index_byte_offset > index_view.byte_length ||
sparse.count > (index_view.byte_length - sparse.index_byte_offset) /
index_size) {
*error = "gltf: sparse indices exceed bufferView bounds";
return false;
}
if (sparse.value_byte_offset > value_view.byte_length ||
sparse.count > (value_view.byte_length - sparse.value_byte_offset) / 12) {
*error = "gltf: sparse values exceed bufferView bounds";
return false;
}
const std::string& index_data = buffer_data[static_cast<std::size_t>(
index_view.buffer)];
const std::string& value_data = buffer_data[static_cast<std::size_t>(
value_view.buffer)];
const unsigned char* index_base =
reinterpret_cast<const unsigned char*>(index_data.data()) +
index_view.byte_offset + sparse.index_byte_offset;
const unsigned char* value_base =
reinterpret_cast<const unsigned char*>(value_data.data()) +
value_view.byte_offset + sparse.value_byte_offset;
for (std::size_t s = 0; s < sparse.count; ++s) {
std::uint32_t index = 0;
if (!read_index_component(index_base + s * index_size,
sparse.index_component_type, &index)) {
*error = "gltf: failed to read a sparse index";
return false;
}
if (static_cast<std::size_t>(index) >= accessor.count) {
*error = "gltf: sparse index is out of range for POSITION count";
return false;
}
for (int k = 0; k < 3; ++k) {
float value = 0.0f;
std::memcpy(&value, value_base + s * 12 + static_cast<std::size_t>(k) * 4,
4);
if (!std::isfinite(value)) {
*error = "gltf: sparse POSITION contains a non-finite coordinate";
return false;
}
(*positions)[static_cast<std::size_t>(index) * 3 +
static_cast<std::size_t>(k)] = static_cast<double>(value);
}
}
}
return true;
}
bool read_indices(const GltfDocument& doc, int accessor_index,
const std::vector<std::string>& buffer_data,
std::size_t vertex_count, std::vector<std::uint32_t>* indices,
bool require_multiple_of_three, std::string* error) {
const GltfAccessor& accessor = doc.accessors[accessor_index];
if (accessor.type != "SCALAR") {
*error = "gltf: indices accessor must be SCALAR";
return false;
}
if (accessor.component_type != 5121 && accessor.component_type != 5123 &&
accessor.component_type != 5125) {
*error = "gltf: indices accessor must be UNSIGNED_BYTE/SHORT/INT";
return false;
}
if (require_multiple_of_three && accessor.count % 3 != 0) {
*error = "gltf: index count is not a multiple of 3 (TRIANGLES)";
return false;
}
std::vector<std::uint32_t> values(accessor.count, 0);
if (accessor.buffer_view >= 0) {
AccessorLayout layout;
if (!prepare_accessor(doc, accessor_index, buffer_data, &layout, error))
return false;
const std::string& data = buffer_data[static_cast<std::size_t>(
doc.buffer_views[accessor.buffer_view].buffer)];
const unsigned char* base = reinterpret_cast<const unsigned char*>(data.data());
for (std::size_t i = 0; i < accessor.count; ++i) {
if (!read_index_component(base + layout.base + i * layout.stride,
accessor.component_type, &values[i])) {
*error = "gltf: failed to read an index value";
return false;
}
}
} else if (!accessor.sparse.present) {
*error = "gltf: indices accessor has neither bufferView nor sparse data";
return false;
}
if (accessor.sparse.present) {
const GltfSparse& sparse = accessor.sparse;
const GltfBufferView& index_view =
doc.buffer_views[static_cast<std::size_t>(sparse.index_buffer_view)];
const GltfBufferView& value_view =
doc.buffer_views[static_cast<std::size_t>(sparse.value_buffer_view)];
if (index_view.buffer < 0 ||
index_view.buffer >= static_cast<int>(buffer_data.size()) ||
value_view.buffer < 0 ||
value_view.buffer >= static_cast<int>(buffer_data.size())) {
*error = "gltf: sparse index bufferView buffer index out of range";
return false;
}
const std::size_t sparse_index_size = component_size(sparse.index_component_type);
const std::size_t value_size = component_size(accessor.component_type);
if (sparse_index_size == 0 || value_size == 0 ||
sparse.index_byte_offset > index_view.byte_length ||
sparse.count > (index_view.byte_length - sparse.index_byte_offset) /
sparse_index_size ||
sparse.value_byte_offset > value_view.byte_length ||
sparse.count > (value_view.byte_length - sparse.value_byte_offset) / value_size) {
*error = "gltf: sparse index data exceeds bufferView bounds";
return false;
}
const std::string& index_data = buffer_data[static_cast<std::size_t>(
index_view.buffer)];
const std::string& value_data = buffer_data[static_cast<std::size_t>(
value_view.buffer)];
const unsigned char* index_base =
reinterpret_cast<const unsigned char*>(index_data.data()) +
index_view.byte_offset + sparse.index_byte_offset;
const unsigned char* value_base =
reinterpret_cast<const unsigned char*>(value_data.data()) +
value_view.byte_offset + sparse.value_byte_offset;
for (std::size_t s = 0; s < sparse.count; ++s) {
std::uint32_t sparse_index = 0;
std::uint32_t replacement = 0;
if (!read_index_component(index_base + s * sparse_index_size,
sparse.index_component_type, &sparse_index) ||
!read_index_component(value_base + s * value_size,
accessor.component_type, &replacement)) {
*error = "gltf: failed to read a sparse index value";
return false;
}
if (static_cast<std::size_t>(sparse_index) >= values.size()) {
*error = "gltf: sparse index is out of range for indices count";
return false;
}
values[static_cast<std::size_t>(sparse_index)] = replacement;
}
}
indices->clear();
indices->reserve(values.size());
for (std::uint32_t index : values) {
if (static_cast<std::size_t>(index) >= vertex_count) {
*error = "gltf: index " + std::to_string(index) +
" is out of range for " + std::to_string(vertex_count) +
" vertices";
return false;
}
indices->push_back(index);
}
return true;
}
bool build_primitive_mesh(const GltfDocument& doc,
const std::vector<std::string>& buffer_data,
const GltfPrimitive& primitive, std::size_t mesh_index,
std::size_t primitive_index,
const std::vector<double>& morph_weights,
vde_plugin_common::MeshAccumulator* mesh,
std::string* skip_reason, std::string* error) {
const std::string where = "meshes[" + std::to_string(mesh_index) +
"].primitives[" + std::to_string(primitive_index) + "]";
if (primitive.mode != 4 && primitive.mode != 5 && primitive.mode != 6) {
*skip_reason = where + " uses mode=" + std::to_string(primitive.mode) +
" (supported: TRIANGLES/STRIP/FAN)";
return true;
}
std::vector<double> positions;
if (!read_positions(doc, primitive.position, buffer_data, &positions, error))
return false;
const std::size_t vertex_count = positions.size() / 3;
for (std::size_t target_index = 0; target_index < primitive.targets.size();
++target_index) {
const double weight = target_index < morph_weights.size()
? morph_weights[target_index]
: 0.0;
if (weight == 0.0) continue;
std::vector<double> delta;
if (!read_positions(doc, primitive.targets[target_index], buffer_data, &delta,
error))
return false;
if (delta.size() != positions.size()) {
*error = "gltf: morph target POSITION count differs from base POSITION";
return false;
}
for (std::size_t i = 0; i < positions.size(); ++i)
positions[i] += weight * delta[i];
}
std::vector<std::uint32_t> indices;
if (primitive.indices >= 0) {
if (!read_indices(doc, primitive.indices, buffer_data, vertex_count, &indices,
primitive.mode == 4, error))
return false;
} else {
if (primitive.mode == 4 && vertex_count % 3 != 0) {
*error = "gltf: non-indexed TRIANGLES vertex count is not a multiple of 3";
return false;
}
indices.reserve(vertex_count);
for (std::size_t i = 0; i < vertex_count; ++i)
indices.push_back(static_cast<std::uint32_t>(i));
}
std::vector<std::uint32_t> triangles;
if (primitive.mode == 4) {
triangles = indices;
} else if (primitive.mode == 5) {
for (std::size_t i = 0; i + 2 < indices.size(); ++i) {
if ((i & 1u) == 0) {
triangles.push_back(indices[i]);
triangles.push_back(indices[i + 1]);
triangles.push_back(indices[i + 2]);
} else {
triangles.push_back(indices[i + 1]);
triangles.push_back(indices[i]);
triangles.push_back(indices[i + 2]);
}
}
} else {
for (std::size_t i = 1; i + 1 < indices.size(); ++i) {
triangles.push_back(indices[0]);
triangles.push_back(indices[i]);
triangles.push_back(indices[i + 1]);
}
}
mesh->positions = std::move(positions);
for (std::size_t i = 0; i + 2 < triangles.size(); i += 3) {
mesh->add_triangle(triangles[i], triangles[i + 1], triangles[i + 2]);
}
if (mesh->triangle_count() == 0) {
*skip_reason = where + " has no non-degenerate triangles";
return true;
}
return true;
}
bool publish_bodies(const VdePluginHost* host,
const std::vector<vde_plugin_common::MeshAccumulator>& meshes,
VdeBody** out_bodies, std::size_t* out_count) {
std::vector<VdeBody> created;
created.reserve(meshes.size());
for (std::size_t i = 0; i < meshes.size(); ++i) {
const auto& mesh = meshes[i];
VdeBody body = host->body_from_mesh(mesh.positions.data(), mesh.vertex_count(),
mesh.indices.data(), mesh.triangle_count());
if (!body) {
for (VdeBody existing : created) host->body_destroy(existing);
return fail(host, VDE_PLUGIN_ERR_INTERNAL,
("gltf: host body_from_mesh failed for mesh " +
std::to_string(i))
.c_str());
}
created.push_back(body);
}
VdeBody* array = static_cast<VdeBody*>(host->alloc(sizeof(VdeBody) * created.size()));
if (!array) {
for (VdeBody body : created) host->body_destroy(body);
return fail(host, VDE_PLUGIN_ERR_BUFFER, "gltf: body handle array allocation failed");
}
for (std::size_t i = 0; i < created.size(); ++i) array[i] = created[i];
*out_bodies = array;
*out_count = created.size();
return VDE_PLUGIN_OK;
}
int read_impl(const VdePluginHost* host, const char* source_path, const void* data,
std::size_t size, bool from_memory, 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, "gltf: bodies/count output is null");
(void)from_memory;
const int host_rc = validate_common_host(host);
if (host_rc != VDE_PLUGIN_OK) return host_rc;
if (!host_has_body_from_mesh(host))
return fail(host, VDE_PLUGIN_ERR_UNSUPPORTED,
"gltf: host lacks body_from_mesh (ABI minor >= 1 required)");
if (!data || size == 0)
return fail(host, VDE_PLUGIN_ERR_PARSE, "gltf: empty input");
const unsigned char* bytes = static_cast<const unsigned char*>(data);
bool is_glb = false;
std::string json;
std::string glb_bin;
bool has_glb_bin = false;
if (size >= 4 && read_u32_le(bytes) == kGlbMagic) {
is_glb = true;
std::string error;
if (!parse_glb(bytes, size, &json, &glb_bin, &has_glb_bin, &error))
return fail(host, VDE_PLUGIN_ERR_PARSE, error.c_str());
} else {
json.assign(reinterpret_cast<const char*>(data), size);
}
GltfDocument doc;
std::string error;
if (!parse_gltf_document(json, &doc, &error))
return fail(host, VDE_PLUGIN_ERR_PARSE, error.c_str());
std::vector<std::string> buffer_data(doc.buffers.size());
for (std::size_t i = 0; i < doc.buffers.size(); ++i) {
if (!load_buffer_data(host, source_path, doc, i, is_glb, glb_bin, has_glb_bin,
&buffer_data[i], &error))
return fail(host, VDE_PLUGIN_ERR_PARSE, error.c_str());
if (doc.buffers[i].byte_length > buffer_data[i].size())
return fail(host, VDE_PLUGIN_ERR_PARSE,
"gltf: buffer byteLength exceeds available data");
}
std::vector<vde_plugin_common::MeshAccumulator> meshes;
std::string first_skip;
const auto append_mesh = [&](int mesh_index, const GltfTransform& world,
const std::vector<double>& weights) -> bool {
if (mesh_index < 0 || mesh_index >= static_cast<int>(doc.meshes.size())) {
error = "gltf: node references mesh index out of range";
return false;
}
for (std::size_t j = 0; j < doc.meshes[mesh_index].primitives.size(); ++j) {
vde_plugin_common::MeshAccumulator mesh;
std::string skip_reason;
if (!build_primitive_mesh(doc, buffer_data, doc.meshes[mesh_index].primitives[j],
static_cast<std::size_t>(mesh_index), j, weights,
&mesh, &skip_reason, &error))
return false;
if (!skip_reason.empty()) {
if (first_skip.empty()) first_skip = skip_reason;
if (host->log) host->log(VDE_PLUGIN_LOG_WARN, skip_reason.c_str());
continue;
}
for (std::size_t v = 0; v + 2 < mesh.positions.size(); v += 3) {
double x = 0, y = 0, z = 0;
world.apply(mesh.positions[v], mesh.positions[v + 1], mesh.positions[v + 2],
&x, &y, &z);
mesh.positions[v] = x;
mesh.positions[v + 1] = y;
mesh.positions[v + 2] = z;
}
meshes.push_back(std::move(mesh));
}
return true;
};
if (doc.nodes.empty()) {
for (std::size_t i = 0; i < doc.meshes.size(); ++i) {
if (!append_mesh(static_cast<int>(i), GltfTransform::identity(),
doc.meshes[i].weights))
return fail(host, VDE_PLUGIN_ERR_PARSE, error.c_str());
}
} else {
std::vector<int> roots;
if (!doc.scenes.empty()) {
const std::size_t scene_index =
doc.default_scene >= 0 ? static_cast<std::size_t>(doc.default_scene) : 0;
if (scene_index < doc.scenes.size()) roots = doc.scenes[scene_index].nodes;
}
if (roots.empty()) {
std::vector<bool> has_parent(doc.nodes.size(), false);
for (const auto& node : doc.nodes) {
for (int child : node.children) {
if (child >= 0 && child < static_cast<int>(doc.nodes.size()))
has_parent[child] = true;
}
}
for (std::size_t i = 0; i < doc.nodes.size(); ++i) {
if (!has_parent[i]) roots.push_back(static_cast<int>(i));
}
}
std::vector<int> stack;
std::function<bool(int, const GltfTransform&)> visit =
[&](int node_index, const GltfTransform& parent) -> bool {
if (node_index < 0 || node_index >= static_cast<int>(doc.nodes.size())) {
error = "gltf: node index out of range";
return false;
}
if (std::find(stack.begin(), stack.end(), node_index) != stack.end() ||
stack.size() > 64) {
error = "gltf: node hierarchy cycle or depth exceeds 64";
return false;
}
stack.push_back(node_index);
const GltfNode& node = doc.nodes[node_index];
const GltfTransform world = GltfTransform::multiply(parent,
GltfTransform::from_node(node));
if (node.mesh >= 0 &&
!append_mesh(node.mesh, world,
node.has_weights ? node.weights
: doc.meshes[static_cast<std::size_t>(node.mesh)].weights))
return false;
for (int child : node.children) {
if (!visit(child, world)) return false;
}
stack.pop_back();
return true;
};
for (int root : roots) {
if (!visit(root, GltfTransform::identity()))
return fail(host, VDE_PLUGIN_ERR_PARSE, error.c_str());
}
}
if (meshes.empty()) {
std::string message = "gltf: no usable triangle primitives";
if (!first_skip.empty()) message += " (" + first_skip + ")";
return fail(host, VDE_PLUGIN_ERR_PARSE, message.c_str());
}
return publish_bodies(host, meshes, bodies, count);
}
int gltf_read_file(const VdePluginHost* host, const char* path, VdeBody** bodies,
std::size_t* count) {
if (bodies) *bodies = nullptr;
if (count) *count = 0;
if (!path || !*path)
return fail(host, VDE_PLUGIN_ERR_INVALID_ARG, "gltf: input path is empty");
try {
std::string bytes;
if (!read_file_bytes(path, &bytes))
return fail(host, VDE_PLUGIN_ERR_IO, "gltf: cannot read input file");
return read_impl(host, path, bytes.data(), bytes.size(), false, bodies, count);
} catch (const std::bad_alloc&) {
return fail(host, VDE_PLUGIN_ERR_BUFFER, "gltf: out of memory while reading");
} catch (const std::exception& e) {
const std::string message = std::string("gltf: internal error: ") + e.what();
return fail(host, VDE_PLUGIN_ERR_INTERNAL, message.c_str());
} catch (...) {
return fail(host, VDE_PLUGIN_ERR_INTERNAL, "gltf: unknown internal error");
}
}
int gltf_read_memory(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 (!data || size == 0)
return fail(host, VDE_PLUGIN_ERR_INVALID_ARG, "gltf: empty memory input");
try {
return read_impl(host, nullptr, data, size, true, bodies, count);
} catch (const std::bad_alloc&) {
return fail(host, VDE_PLUGIN_ERR_BUFFER, "gltf: out of memory while reading");
} catch (const std::exception& e) {
const std::string message = std::string("gltf: internal error: ") + e.what();
return fail(host, VDE_PLUGIN_ERR_INTERNAL, message.c_str());
} catch (...) {
return fail(host, VDE_PLUGIN_ERR_INTERNAL, "gltf: unknown internal error");
}
}
// ─────────────────────────────────────────────────────────────────────
// 写出:实体三角化 → glTF JSON / GLB
// ─────────────────────────────────────────────────────────────────────
struct WriteBody {
std::vector<float> positions;
std::vector<float> normals;
std::vector<std::uint32_t> indices;
float bounds_min[3] = {0.0f, 0.0f, 0.0f};
float bounds_max[3] = {0.0f, 0.0f, 0.0f};
};
float finite_float(double value, bool* ok) {
if (!std::isfinite(value) || std::fabs(value) > 3.402823466e+38) {
*ok = false;
return 0.0f;
}
return static_cast<float>(value);
}
bool append_tessellated_body(const VdePluginHost* host, VdeBody body,
WriteBody* out, std::string* error) {
if (!body) {
*error = "gltf: body handle is null";
return false;
}
VdeMeshData mesh{};
mesh.struct_size = static_cast<std::uint32_t>(sizeof(VdeMeshData));
const int rc = host->body_tessellate(body, 0.01, &mesh);
struct Guard {
const VdePluginHost* host;
VdeMeshData* mesh;
~Guard() {
if (!host || !host->free_buffer) return;
host->free_buffer(mesh->positions);
host->free_buffer(mesh->indices);
host->free_buffer(mesh->normals);
}
} guard{host, &mesh};
if (rc != VDE_PLUGIN_OK) {
*error = "gltf: body_tessellate failed";
return false;
}
if (!mesh.positions || !mesh.indices || mesh.num_vertices == 0 ||
mesh.num_triangles == 0) {
*error = "gltf: body tessellation is empty";
return false;
}
bool ok = true;
out->positions.resize(mesh.num_vertices * 3);
for (std::size_t i = 0; i < mesh.num_vertices * 3; ++i) {
out->positions[i] = finite_float(mesh.positions[i], &ok);
if (!ok) {
*error = "gltf: body tessellation contains a non-finite coordinate";
return false;
}
}
out->normals.resize(mesh.num_vertices * 3);
if (mesh.normals) {
for (std::size_t i = 0; i < mesh.num_vertices * 3; ++i) {
out->normals[i] = finite_float(mesh.normals[i], &ok);
if (!ok) {
*error = "gltf: body tessellation contains a non-finite normal";
return false;
}
}
} else {
std::vector<double> sums(mesh.num_vertices * 3, 0.0);
for (std::size_t t = 0; t < mesh.num_triangles; ++t) {
std::uint32_t ids[3] = {0, 0, 0};
for (int k = 0; k < 3; ++k) {
ids[k] = mesh.indices[3 * t + static_cast<std::size_t>(k)];
if (static_cast<std::size_t>(ids[k]) >= mesh.num_vertices) {
*error = "gltf: host tessellation returned an out-of-range index";
return false;
}
}
const float* p0 = &out->positions[static_cast<std::size_t>(ids[0]) * 3];
const float* p1 = &out->positions[static_cast<std::size_t>(ids[1]) * 3];
const float* p2 = &out->positions[static_cast<std::size_t>(ids[2]) * 3];
const double nx = (static_cast<double>(p1[1]) - p0[1]) *
(static_cast<double>(p2[2]) - p0[2]) -
(static_cast<double>(p1[2]) - p0[2]) *
(static_cast<double>(p2[1]) - p0[1]);
const double ny = (static_cast<double>(p1[2]) - p0[2]) *
(static_cast<double>(p2[0]) - p0[0]) -
(static_cast<double>(p1[0]) - p0[0]) *
(static_cast<double>(p2[2]) - p0[2]);
const double nz = (static_cast<double>(p1[0]) - p0[0]) *
(static_cast<double>(p2[1]) - p0[1]) -
(static_cast<double>(p1[1]) - p0[1]) *
(static_cast<double>(p2[0]) - p0[0]);
for (int k = 0; k < 3; ++k) {
sums[static_cast<std::size_t>(ids[k]) * 3 + 0] += nx;
sums[static_cast<std::size_t>(ids[k]) * 3 + 1] += ny;
sums[static_cast<std::size_t>(ids[k]) * 3 + 2] += nz;
}
}
for (std::size_t i = 0; i < mesh.num_vertices; ++i) {
const double nx = sums[i * 3 + 0];
const double ny = sums[i * 3 + 1];
const double nz = sums[i * 3 + 2];
const double length = std::sqrt(nx * nx + ny * ny + nz * nz);
out->normals[i * 3 + 0] = length > 1e-12 ? static_cast<float>(nx / length) : 0.0f;
out->normals[i * 3 + 1] = length > 1e-12 ? static_cast<float>(ny / length) : 0.0f;
out->normals[i * 3 + 2] = length > 1e-12 ? static_cast<float>(nz / length) : 0.0f;
}
}
out->indices.resize(mesh.num_triangles * 3);
std::size_t cursor = 0;
for (std::size_t t = 0; t < mesh.num_triangles; ++t) {
for (int k = 0; k < 3; ++k) {
const std::uint32_t index = mesh.indices[3 * t + static_cast<std::size_t>(k)];
if (static_cast<std::size_t>(index) >= mesh.num_vertices) {
*error = "gltf: host tessellation returned an out-of-range index";
return false;
}
out->indices[cursor++] = index;
}
}
for (int k = 0; k < 3; ++k) {
out->bounds_min[k] = out->positions[k];
out->bounds_max[k] = out->positions[k];
}
for (std::size_t i = 1; i < mesh.num_vertices; ++i) {
for (int k = 0; k < 3; ++k) {
out->bounds_min[k] = std::min(out->bounds_min[k], out->positions[i * 3 + k]);
out->bounds_max[k] = std::max(out->bounds_max[k], out->positions[i * 3 + k]);
}
}
return true;
}
struct BlobLayout {
std::size_t position_offset = 0;
std::size_t position_bytes = 0;
std::size_t normal_offset = 0;
std::size_t normal_bytes = 0;
std::size_t index_offset = 0;
std::size_t index_bytes = 0;
};
void append_u32_le(std::vector<unsigned char>* out, std::uint32_t value) {
out->push_back(static_cast<unsigned char>(value & 0xFFu));
out->push_back(static_cast<unsigned char>((value >> 8) & 0xFFu));
out->push_back(static_cast<unsigned char>((value >> 16) & 0xFFu));
out->push_back(static_cast<unsigned char>((value >> 24) & 0xFFu));
}
void append_float_le(std::vector<unsigned char>* out, float value) {
std::uint32_t bits = 0;
std::memcpy(&bits, &value, 4);
append_u32_le(out, bits);
}
void align_blob(std::vector<unsigned char>* out) {
while (out->size() % 4 != 0) out->push_back(0);
}
bool collect_write_meshes(const VdePluginHost* host, const VdeBody* bodies,
std::size_t count, std::vector<WriteBody>* meshes,
std::vector<BlobLayout>* layouts,
std::vector<unsigned char>* bin, std::string* error) {
if (!bodies || count == 0) {
*error = "gltf: no bodies to write";
return false;
}
const int host_rc = validate_write_host(host);
if (host_rc != VDE_PLUGIN_OK) {
*error = "gltf: host lacks body_tessellate/free_buffer";
return false;
}
for (std::size_t i = 0; i < count; ++i) {
WriteBody body;
if (!append_tessellated_body(host, bodies[i], &body, error)) {
*error = "body " + std::to_string(i) + ": " + *error;
return false;
}
BlobLayout layout;
align_blob(bin);
layout.position_offset = bin->size();
layout.position_bytes = body.positions.size() * 4;
for (float value : body.positions) append_float_le(bin, value);
align_blob(bin);
layout.normal_offset = bin->size();
layout.normal_bytes = body.normals.size() * 4;
for (float value : body.normals) append_float_le(bin, value);
align_blob(bin);
layout.index_offset = bin->size();
layout.index_bytes = body.indices.size() * 4;
for (std::uint32_t index : body.indices) append_u32_le(bin, index);
meshes->push_back(std::move(body));
layouts->push_back(layout);
}
return true;
}
std::string format_float(float value) {
char buffer[64];
std::snprintf(buffer, sizeof(buffer), "%.9g", static_cast<double>(value));
return std::string(buffer);
}
std::string encode_uri_component(const std::string& text) {
static const char kHex[] = "0123456789ABCDEF";
std::string out;
for (unsigned char c : text) {
const bool unreserved = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
(c >= '0' && c <= '9') || c == '-' || c == '.' ||
c == '_' || c == '~';
if (unreserved) {
out.push_back(static_cast<char>(c));
} else {
out.push_back('%');
out.push_back(kHex[(c >> 4) & 0x0F]);
out.push_back(kHex[c & 0x0F]);
}
}
return out;
}
std::string file_name_of(const std::string& path) {
const std::size_t slash = path.find_last_of("/\\");
return slash == std::string::npos ? path : path.substr(slash + 1);
}
std::string sidecar_bin_path(const std::string& path) {
const std::size_t slash = path.find_last_of("/\\");
const std::size_t dot = path.find_last_of('.');
if (dot != std::string::npos && (slash == std::string::npos || dot > slash + 1))
return path.substr(0, dot) + ".bin";
return path + ".bin";
}
std::string build_gltf_json(const std::vector<WriteBody>& meshes,
const std::vector<BlobLayout>& layouts,
std::size_t buffer_byte_length,
const std::string& buffer_uri) {
std::ostringstream json;
json.imbue(std::locale::classic());
json << "{\n";
json << " \"asset\":{\"version\":\"2.0\",\"generator\":\"VDE official glTF plugin\"},\n";
json << " \"scene\":0,\n";
json << " \"scenes\":[{\"nodes\":[";
for (std::size_t i = 0; i < meshes.size(); ++i) {
if (i) json << ",";
json << i;
}
json << "]}],\n";
json << " \"nodes\":[";
for (std::size_t i = 0; i < meshes.size(); ++i) {
if (i) json << ",";
json << "{\"mesh\":" << i << "}";
}
json << "],\n";
json << " \"meshes\":[";
for (std::size_t i = 0; i < meshes.size(); ++i) {
if (i) json << ",";
json << "{\"name\":\"body_" << i
<< "\",\"primitives\":[{\"attributes\":{\"POSITION\":" << (i * 3)
<< ",\"NORMAL\":" << (i * 3 + 1) << "},\"indices\":" << (i * 3 + 2)
<< ",\"mode\":4}]}";
}
json << "],\n";
json << " \"buffers\":[{\"byteLength\":" << buffer_byte_length;
if (!buffer_uri.empty()) {
json << ",\"uri\":\"" << buffer_uri << "\"";
}
json << "}],\n";
json << " \"bufferViews\":[\n";
bool first_view = true;
const auto begin_view = [&]() {
if (!first_view) json << ",\n";
first_view = false;
};
for (std::size_t i = 0; i < meshes.size(); ++i) {
const BlobLayout& layout = layouts[i];
begin_view();
json << " {\"buffer\":0,\"byteOffset\":" << layout.position_offset
<< ",\"byteLength\":" << layout.position_bytes << ",\"target\":34962}";
begin_view();
json << " {\"buffer\":0,\"byteOffset\":" << layout.normal_offset
<< ",\"byteLength\":" << layout.normal_bytes << ",\"target\":34962}";
begin_view();
json << " {\"buffer\":0,\"byteOffset\":" << layout.index_offset
<< ",\"byteLength\":" << layout.index_bytes << ",\"target\":34963}";
}
json << "\n ],\n";
json << " \"accessors\":[\n";
bool first_accessor = true;
const auto begin_accessor = [&]() {
if (!first_accessor) json << ",\n";
first_accessor = false;
};
for (std::size_t i = 0; i < meshes.size(); ++i) {
const WriteBody& body = meshes[i];
const std::size_t vertex_count = body.positions.size() / 3;
begin_accessor();
json << " {\"bufferView\":" << (i * 3) << ",\"componentType\":5126,\"count\":"
<< vertex_count << ",\"type\":\"VEC3\",\"min\":["
<< format_float(body.bounds_min[0]) << "," << format_float(body.bounds_min[1])
<< "," << format_float(body.bounds_min[2]) << "],\"max\":["
<< format_float(body.bounds_max[0]) << "," << format_float(body.bounds_max[1])
<< "," << format_float(body.bounds_max[2]) << "]}";
begin_accessor();
json << " {\"bufferView\":" << (i * 3 + 1) << ",\"componentType\":5126,\"count\":"
<< vertex_count << ",\"type\":\"VEC3\"}";
begin_accessor();
json << " {\"bufferView\":" << (i * 3 + 2)
<< ",\"componentType\":5125,\"count\":" << (body.indices.size())
<< ",\"type\":\"SCALAR\"}";
}
json << "\n ]\n}\n";
return json.str();
}
std::vector<unsigned char> build_glb(const std::string& json,
const std::vector<unsigned char>& bin) {
std::string padded_json = json;
while (padded_json.size() % 4 != 0) padded_json.push_back(' ');
std::vector<unsigned char> padded_bin = bin;
while (padded_bin.size() % 4 != 0) padded_bin.push_back(0);
const std::size_t total = 12 + 8 + padded_json.size() + 8 + padded_bin.size();
std::vector<unsigned char> glb;
glb.reserve(total);
append_u32_le(&glb, kGlbMagic);
append_u32_le(&glb, kGlbVersion);
append_u32_le(&glb, static_cast<std::uint32_t>(total));
append_u32_le(&glb, static_cast<std::uint32_t>(padded_json.size()));
append_u32_le(&glb, kChunkJson);
glb.insert(glb.end(), padded_json.begin(), padded_json.end());
append_u32_le(&glb, static_cast<std::uint32_t>(padded_bin.size()));
append_u32_le(&glb, kChunkBin);
glb.insert(glb.end(), padded_bin.begin(), padded_bin.end());
return glb;
}
int build_output(const VdePluginHost* host, const VdeBody* bodies, std::size_t count,
bool binary, std::vector<unsigned char>* out) {
const int host_rc = validate_write_host(host);
if (host_rc != VDE_PLUGIN_OK) return host_rc;
std::vector<WriteBody> meshes;
std::vector<BlobLayout> layouts;
std::vector<unsigned char> bin;
std::string error;
if (!collect_write_meshes(host, bodies, count, &meshes, &layouts, &bin, &error))
return fail(host, VDE_PLUGIN_ERR_INTERNAL, error.c_str());
if (binary) {
const std::string json = build_gltf_json(meshes, layouts, bin.size(), "");
const std::size_t json_padded = (json.size() + 3u) & ~static_cast<std::size_t>(3u);
const std::size_t bin_padded = (bin.size() + 3u) & ~static_cast<std::size_t>(3u);
const std::size_t total = 12u + 8u + json_padded + 8u + bin_padded;
if (total > 0xFFFFFFFFu)
return fail(host, VDE_PLUGIN_ERR_BUFFER,
"gltf: GLB output exceeds the 32-bit container limit");
*out = build_glb(json, bin);
} else {
const std::string base64 = encode_base64(bin.data(), bin.size());
const std::string json =
build_gltf_json(meshes, layouts, bin.size(),
"data:application/octet-stream;base64," + base64);
out->assign(json.begin(), json.end());
}
return VDE_PLUGIN_OK;
}
bool ends_with_ci(const std::string& text, const char* suffix) {
const std::string tail(suffix);
if (text.size() < tail.size()) return false;
const std::size_t start = text.size() - tail.size();
for (std::size_t i = 0; i < tail.size(); ++i) {
char a = text[start + i];
char b = tail[i];
if (a >= 'A' && a <= 'Z') a = static_cast<char>(a - 'A' + 'a');
if (b >= 'A' && b <= 'Z') b = static_cast<char>(b - 'A' + 'a');
if (a != b) return false;
}
return true;
}
bool write_binary_for_path(const char* path) {
if (path) {
const std::string text(path);
if (ends_with_ci(text, ".glb")) return true;
if (ends_with_ci(text, ".gltf")) return false;
}
const char* env = std::getenv("VDE_GLTF_WRITE_FORMAT");
if (!env || !*env) return false;
std::string value(env);
for (char& c : value) {
if (c >= 'A' && c <= 'Z') c = static_cast<char>(c - 'A' + 'a');
}
return value == "glb" || value == "binary" || value == "gltf-binary";
}
int write_gltf_sidecar(const VdePluginHost* host, const char* path,
const VdeBody* bodies, std::size_t count) {
const int host_rc = validate_write_host(host);
if (host_rc != VDE_PLUGIN_OK) return host_rc;
std::vector<WriteBody> meshes;
std::vector<BlobLayout> layouts;
std::vector<unsigned char> bin;
std::string error;
if (!collect_write_meshes(host, bodies, count, &meshes, &layouts, &bin, &error))
return fail(host, VDE_PLUGIN_ERR_INTERNAL, error.c_str());
const std::string bin_path = sidecar_bin_path(path);
const std::string bin_name = encode_uri_component(file_name_of(bin_path));
const std::string json = build_gltf_json(meshes, layouts, bin.size(), bin_name);
if (!write_file_bytes(bin_path.c_str(), bin.data(), bin.size()))
return fail(host, VDE_PLUGIN_ERR_IO, "gltf: cannot write sidecar .bin file");
if (!write_file_bytes(path, json.data(), json.size())) {
std::remove(bin_path.c_str());
return fail(host, VDE_PLUGIN_ERR_IO, "gltf: cannot write .gltf file");
}
return VDE_PLUGIN_OK;
}
int gltf_write_file(const VdePluginHost* host, const char* path, const VdeBody* bodies,
std::size_t count) {
if (!path || !*path)
return fail(host, VDE_PLUGIN_ERR_INVALID_ARG, "gltf: output path is empty");
try {
if (!write_binary_for_path(path))
return write_gltf_sidecar(host, path, bodies, count);
std::vector<unsigned char> output;
const int rc = build_output(host, bodies, count, true, &output);
if (rc != VDE_PLUGIN_OK) return rc;
if (output.empty())
return fail(host, VDE_PLUGIN_ERR_INTERNAL, "gltf: generated output is empty");
if (!write_file_bytes(path, output.data(), output.size()))
return fail(host, VDE_PLUGIN_ERR_IO, "gltf: cannot write output file");
return VDE_PLUGIN_OK;
} catch (const std::bad_alloc&) {
return fail(host, VDE_PLUGIN_ERR_BUFFER, "gltf: out of memory while writing");
} catch (const std::exception& e) {
const std::string message = std::string("gltf: internal error: ") + e.what();
return fail(host, VDE_PLUGIN_ERR_INTERNAL, message.c_str());
} catch (...) {
return fail(host, VDE_PLUGIN_ERR_INTERNAL, "gltf: unknown internal error");
}
}
int gltf_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, "gltf: output buffer is null");
try {
std::vector<unsigned char> output;
const int rc = build_output(host, bodies, count, false, &output);
if (rc != VDE_PLUGIN_OK) return rc;
if (output.empty())
return fail(host, VDE_PLUGIN_ERR_INTERNAL, "gltf: generated output is empty");
void* buffer = host->alloc(output.size());
if (!buffer)
return fail(host, VDE_PLUGIN_ERR_BUFFER, "gltf: output allocation failed");
std::memcpy(buffer, output.data(), output.size());
out->data = buffer;
out->size = output.size();
return VDE_PLUGIN_OK;
} catch (const std::bad_alloc&) {
return fail(host, VDE_PLUGIN_ERR_BUFFER, "gltf: out of memory while writing");
} catch (const std::exception& e) {
const std::string message = std::string("gltf: internal error: ") + e.what();
return fail(host, VDE_PLUGIN_ERR_INTERNAL, message.c_str());
} catch (...) {
return fail(host, VDE_PLUGIN_ERR_INTERNAL, "gltf: unknown internal error");
}
}
// ─────────────────────────────────────────────────────────────────────
// 探测 / 描述 / 注册
// ─────────────────────────────────────────────────────────────────────
bool head_contains(const char* data, std::size_t size, const char* needle) {
const std::size_t length = std::strlen(needle);
if (length == 0 || size < length) return false;
for (std::size_t i = 0; i + length <= size; ++i) {
if (std::memcmp(data + i, needle, length) == 0) return true;
}
return false;
}
int gltf_probe(const void* head, std::size_t head_size) {
if (!head || head_size == 0) return 0;
const unsigned char* bytes = static_cast<const unsigned char*>(head);
if (head_size >= 4 && read_u32_le(bytes) == kGlbMagic) return 100;
const char* text = static_cast<const char*>(head);
const std::size_t probe_size = std::min<std::size_t>(head_size, 4096u);
if (!head_contains(text, probe_size, "\"asset\"") ||
!head_contains(text, probe_size, "\"meshes\""))
return 0;
const std::size_t first = [&]() {
for (std::size_t i = 0; i < probe_size; ++i) {
if (text[i] == '{') return i;
}
return probe_size;
}();
return first < probe_size ? 80 : 0;
}
const char* gltf_describe() {
return "VDE official glTF 2.0/GLB format (core triangle mesh read/write; "
"mode=4 only; embedded base64 .gltf buffers)";
}
const VdeFormatPlugin kFormat = [] {
VdeFormatPlugin format{};
format.struct_size = static_cast<std::uint32_t>(sizeof(VdeFormatPlugin));
format.format_id = "gltf";
format.extensions = ".gltf;.glb";
format.probe = &gltf_probe;
format.read_file = &gltf_read_file;
format.read_memory = &gltf_read_memory;
format.write_file = &gltf_write_file;
format.write_memory = &gltf_write_memory;
format.describe = &gltf_describe;
return format;
}();
} // 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_ABI;
if (host_abi_major != VDE_PLUGIN_ABI_MAJOR) return VDE_PLUGIN_ERR_ABI;
info->id = "com.vde.official.gltf";
info->name = "VDE Official glTF 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:gltf.read;format:gltf.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 = 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"