MayaFlux 1.0.0
Digital-First Multimedia Processing Framework
Loading...
Searching...
No Matches
VDBArchive.cpp
Go to the documentation of this file.
1#include "VDBArchive.hpp"
2
4
5extern "C" {
6#include "tinyvdb_ray.h"
7#include "tinyvdb_sparse_tree.h"
8}
9
10#include <deque>
11
12namespace MayaFlux::IO::Detail {
13
14namespace {
15
16 // NOLINTBEGIN(cppcoreguidelines-no-malloc, cppcoreguidelines-owning-memory)
17 // tinyvdb takes its allocator as three C function pointers. A container
18 // or smart pointer cannot be substituted at this boundary.
19
20 void* sys_malloc(size_t size, void* /*user_ctx*/)
21 {
22 return std::malloc(size);
23 }
24
25 void* sys_realloc(void* ptr, size_t /*old_size*/, size_t size, void* /*user_ctx*/)
26 {
27 return std::realloc(ptr, size);
28 }
29
30 void sys_free(void* ptr, size_t /*size*/, void* /*user_ctx*/)
31 {
32 std::free(ptr);
33 }
34
35 // NOLINTEND(cppcoreguidelines-no-malloc, cppcoreguidelines-owning-memory)
36
37 /**
38 * @brief Allocator handed to the writer.
39 *
40 * tvdb_file_t carries its own allocator and the write path dereferences
41 * it without a null check, so a zeroed struct faults on the first stream
42 * write rather than falling back to malloc.
43 */
44 tvdb_allocator_t make_allocator()
45 {
46 tvdb_allocator_t alloc;
47 std::memset(&alloc, 0, sizeof(alloc));
48 alloc.malloc_fn = &sys_malloc;
49 alloc.realloc_fn = &sys_realloc;
50 alloc.free_fn = &sys_free;
51 alloc.user_ctx = nullptr;
52 return alloc;
53 }
54
55 constexpr const char* grid_type_token(bool is_vector)
56 {
57 return is_vector ? "Tree_vec3s_5_4_3" : "Tree_float_5_4_3";
58 }
59
60 // -------------------------------------------------------------------------
61 // Read path
62 // -------------------------------------------------------------------------
63
64 /**
65 * @brief The value type leaf-level cells of a grid are stored as.
66 */
67 tvdb_value_type_t leaf_value_type(const tvdb_grid_t& grid)
68 {
69 const int levels = grid.tree.layout.num_levels;
70 if (levels <= 0) {
71 return TVDB_VALUE_NULL;
72 }
73 return grid.tree.layout.levels[levels - 1].value_type;
74 }
75
76 constexpr bool is_vector_type(tvdb_value_type_t vt)
77 {
78 return vt == TVDB_VALUE_VEC3F || vt == TVDB_VALUE_VEC3D || vt == TVDB_VALUE_VEC3I;
79 }
80
81 constexpr bool needs_narrowing(tvdb_value_type_t vt)
82 {
83 return vt != TVDB_VALUE_FLOAT && vt != TVDB_VALUE_VEC3F;
84 }
85
86 /**
87 * @brief Per-axis voxel size from a grid's transform.
88 *
89 * SCALE_TRANSLATE — what add_grid writes — carries independent per-axis
90 * values directly. AFFINE, which no MayaFlux-written file uses, falls
91 * back to the matrix diagonal: exact for an axis-aligned scale, wrong
92 * for a sheared or rotated one, which this reader does not attempt to
93 * represent.
94 */
95 glm::vec3 grid_voxel_size(const tvdb_transform_t& t)
96 {
97 switch (t.type) {
98 case TVDB_TRANSFORM_UNIFORM_SCALE:
99 case TVDB_TRANSFORM_UNIFORM_SCALE_TRANSLATE:
100 return glm::vec3(static_cast<float>(t.voxel_size[0]));
101 case TVDB_TRANSFORM_SCALE:
102 case TVDB_TRANSFORM_SCALE_TRANSLATE:
103 return {
104 static_cast<float>(t.voxel_size[0]),
105 static_cast<float>(t.voxel_size[1]),
106 static_cast<float>(t.voxel_size[2]),
107 };
108 case TVDB_TRANSFORM_AFFINE:
109 return {
110 static_cast<float>(t.matrix[0][0]),
111 static_cast<float>(t.matrix[1][1]),
112 static_cast<float>(t.matrix[2][2]),
113 };
114 case TVDB_TRANSFORM_TRANSLATION:
115 default:
116 return glm::vec3(1.0F);
117 }
118 }
119
120 /**
121 * @brief World-space translation from a grid's transform.
122 *
123 * AFFINE's translation is read from the last column, rows 0-2 — the
124 * standard [R | t; 0 0 0 1] row-major layout, confirmed directly
125 * against tinyvdb's own AffineMap read/write (tvdb->translation[i] =
126 * matrix[i][3], both directions), not assumed.
127 */
128 glm::vec3 grid_translation(const tvdb_transform_t& t)
129 {
130 switch (t.type) {
131 case TVDB_TRANSFORM_UNIFORM_SCALE_TRANSLATE:
132 case TVDB_TRANSFORM_SCALE_TRANSLATE:
133 case TVDB_TRANSFORM_TRANSLATION:
134 return {
135 static_cast<float>(t.translation[0]),
136 static_cast<float>(t.translation[1]),
137 static_cast<float>(t.translation[2]),
138 };
139 case TVDB_TRANSFORM_AFFINE:
140 return {
141 static_cast<float>(t.matrix[0][3]),
142 static_cast<float>(t.matrix[1][3]),
143 static_cast<float>(t.matrix[2][3]),
144 };
145 default:
146 return glm::vec3(0.0F);
147 }
148 }
149
150 /**
151 * @brief Convert one raw scalar element to float via MayaFlux::try_convert.
152 *
153 * HALF is the one source type try_convert cannot see: it is a bit
154 * pattern, not a type try_convert's arithmetic concepts recognise, so
155 * it keeps its own decode. It is also the one case with no precision
156 * question to answer — float has strictly more range and mantissa bits
157 * than half, so widening it is always exact.
158 */
159 CastResult<float> narrow_scalar(tvdb_value_type_t vt, const void* bytes)
160 {
161 switch (vt) {
162 case TVDB_VALUE_FLOAT: {
163 float v {};
164 std::memcpy(&v, bytes, sizeof(v));
165 return try_convert<float>(v);
166 }
167 case TVDB_VALUE_DOUBLE: {
168 double v {};
169 std::memcpy(&v, bytes, sizeof(v));
170 return try_convert<float>(v);
171 }
172 case TVDB_VALUE_INT32: {
173 int32_t v {};
174 std::memcpy(&v, bytes, sizeof(v));
175 return try_convert<float>(v);
176 }
177 case TVDB_VALUE_INT64: {
178 int64_t v {};
179 std::memcpy(&v, bytes, sizeof(v));
180 return try_convert<float>(v);
181 }
182 case TVDB_VALUE_BOOL: {
183 uint8_t v {};
184 std::memcpy(&v, bytes, sizeof(v));
185 return try_convert<float>(v != 0);
186 }
187 case TVDB_VALUE_HALF: {
188 uint16_t v {};
189 std::memcpy(&v, bytes, sizeof(v));
190 CastResult<float> result;
191 result.value = Kakshya::half_to_float(v);
192 return result;
193 }
194 default: {
195 CastResult<float> result;
196 result.value = 0.0F;
197 return result;
198 }
199 }
200 }
201
202 /**
203 * @brief narrow_vector's result: the converted glm::vec3 and whether
204 * any of its three components lost precision.
205 *
206 * A plain glm::vec3 cannot also carry precision_loss, and
207 * try_convert does not itself understand GLM types (it
208 * converts one arithmetic scalar at a time) so this aggregates three
209 * per-component try_convert calls rather than making one call over the
210 * vector as a whole.
211 */
212 struct VectorNarrowResult {
213 glm::vec3 value { 0.0F };
214 bool precision_loss { false };
215 };
216
217 VectorNarrowResult narrow_vector(tvdb_value_type_t vt, const void* bytes)
218 {
219 switch (vt) {
220 case TVDB_VALUE_VEC3F: {
221 float v[3];
222 std::memcpy(v, bytes, sizeof(v));
223 return { { v[0], v[1], v[2] }, false };
224 }
225 case TVDB_VALUE_VEC3D: {
226 double v[3];
227 std::memcpy(v, bytes, sizeof(v));
228 const auto cx = try_convert<float>(v[0]);
229 const auto cy = try_convert<float>(v[1]);
230 const auto cz = try_convert<float>(v[2]);
231 return {
232 { cx.value.value_or(0.0F), cy.value.value_or(0.0F), cz.value.value_or(0.0F) },
233 cx.precision_loss || cy.precision_loss || cz.precision_loss,
234 };
235 }
236 case TVDB_VALUE_VEC3I: {
237 int32_t v[3];
238 std::memcpy(v, bytes, sizeof(v));
239 const auto cx = try_convert<float>(v[0]);
240 const auto cy = try_convert<float>(v[1]);
241 const auto cz = try_convert<float>(v[2]);
242 return {
243 { cx.value.value_or(0.0F), cy.value.value_or(0.0F), cz.value.value_or(0.0F) },
244 cx.precision_loss || cy.precision_loss || cz.precision_loss,
245 };
246 }
247 default:
248 return {};
249 }
250 }
251
252 /**
253 * @brief The root tile's background value, narrowed to float.
254 *
255 * Root index 0 is not a convention this reader invents: tinyvdb's own
256 * tvdb_grid_set_background writes through tree.nodes[0].u.root, so a
257 * well-formed grid always has its root there. Background precision loss
258 * is not tracked separately from the active-cell kind read_dense_scalar/
259 * read_dense_vector report; a lossy background is rare enough (it is one
260 * value, not a whole grid's worth) that this returns the converted value
261 * only.
262 */
263 float grid_background_scalar(const tvdb_grid_t& grid)
264 {
265 if (grid.tree.num_nodes == 0) {
266 return 0.0F;
267 }
268 const tvdb_value_t& bg = grid.tree.nodes[0].u.root.background;
269 return narrow_scalar(bg.type, &bg.u).value.value_or(0.0F);
270 }
271
272 glm::vec3 grid_background_vector(const tvdb_grid_t& grid)
273 {
274 if (grid.tree.num_nodes == 0) {
275 return glm::vec3(0.0F);
276 }
277 const tvdb_value_t& bg = grid.tree.nodes[0].u.root.background;
278 return narrow_vector(bg.type, &bg.u).value;
279 }
280
281 /**
282 * @brief Union of every leaf's voxel-index extent, tinyvdb's own
283 * active-bbox definition, generalized past its float-only
284 * tvdb_grid_active_bbox.
285 */
286 struct BBoxAcc {
287 glm::ivec3 min { 0 };
288 glm::ivec3 max { 0 };
289 bool has_any { false };
290 };
291
292 int bbox_visit(const tvdb_leaf_view_t* leaf, void* user)
293 {
294 auto* acc = static_cast<BBoxAcc*>(user);
295 const int32_t dim = 1 << leaf->log2dim;
296 const glm::ivec3 lo(leaf->origin[0], leaf->origin[1], leaf->origin[2]);
297 const glm::ivec3 hi = lo + glm::ivec3(dim);
298
299 if (!acc->has_any) {
300 acc->min = lo;
301 acc->max = hi;
302 acc->has_any = true;
303 } else {
304 acc->min = glm::min(acc->min, lo);
305 acc->max = glm::max(acc->max, hi);
306 }
307 return 0;
308 }
309
310 /**
311 * @brief Shared context for the dense-fill visitors.
312 *
313 * region_max is exclusive. elem_size is the leaf's own on-disk element
314 * width, used to stride into the raw byte buffer regardless of what
315 * that element narrows to. precision_lost, when non-null, accumulates
316 * across every element the visit touches — set true the first time any
317 * one of them loses precision and left alone afterward.
318 */
319 struct DenseCtx {
320 glm::ivec3 region_min;
321 glm::ivec3 region_max;
322 tvdb_value_type_t vt;
323 size_t elem_size;
324 bool* precision_lost { nullptr };
325 };
326
327 struct DenseScalarCtx : DenseCtx {
328 std::vector<float>* out;
329 };
330
331 struct DenseVectorCtx : DenseCtx {
332 std::vector<glm::vec3>* out;
333 };
334
335 /**
336 * @brief World-voxel coordinate of leaf slot s, OpenVDB's own
337 * (x<<2L)|(y<<L)|z packing within a dim^3 block.
338 */
339 glm::ivec3 leaf_slot_coord(const tvdb_leaf_view_t& leaf, int32_t s)
340 {
341 const int32_t log2dim = leaf.log2dim;
342 const int32_t mask = (1 << log2dim) - 1;
343 return {
344 leaf.origin[0] + ((s >> (2 * log2dim)) & mask),
345 leaf.origin[1] + ((s >> log2dim) & mask),
346 leaf.origin[2] + (s & mask),
347 };
348 }
349
350 int dense_scalar_visit(const tvdb_leaf_view_t* leaf, void* user)
351 {
352 auto* ctx = static_cast<DenseScalarCtx*>(user);
353 const int32_t nslots = 1 << (3 * leaf->log2dim);
354 const auto* base = reinterpret_cast<const uint8_t*>(leaf->data);
355 const glm::ivec3 res = ctx->region_max - ctx->region_min;
356
357 for (int32_t s = 0; s < nslots; ++s) {
358 if (!tvdb_nodemask_is_on(leaf->value_mask, s)) {
359 continue;
360 }
361 const glm::ivec3 world = leaf_slot_coord(*leaf, s);
362 if (glm::any(glm::lessThan(world, ctx->region_min))
363 || glm::any(glm::greaterThanEqual(world, ctx->region_max))) {
364 continue;
365 }
366 const glm::ivec3 local = world - ctx->region_min;
367 const size_t index = (static_cast<size_t>(local.z) * res.y + local.y) * res.x + local.x;
368 const auto converted = narrow_scalar(ctx->vt, base + static_cast<size_t>(s) * ctx->elem_size);
369 (*ctx->out)[index] = converted.value.value_or(0.0F);
370 if (converted.precision_loss && ctx->precision_lost) {
371 *ctx->precision_lost = true;
372 }
373 }
374 return 0;
375 }
376
377 int dense_vector_visit(const tvdb_leaf_view_t* leaf, void* user)
378 {
379 auto* ctx = static_cast<DenseVectorCtx*>(user);
380 const int32_t nslots = 1 << (3 * leaf->log2dim);
381 const auto* base = reinterpret_cast<const uint8_t*>(leaf->data);
382 const glm::ivec3 res = ctx->region_max - ctx->region_min;
383
384 for (int32_t s = 0; s < nslots; ++s) {
385 if (!tvdb_nodemask_is_on(leaf->value_mask, s)) {
386 continue;
387 }
388 const glm::ivec3 world = leaf_slot_coord(*leaf, s);
389 if (glm::any(glm::lessThan(world, ctx->region_min))
390 || glm::any(glm::greaterThanEqual(world, ctx->region_max))) {
391 continue;
392 }
393 const glm::ivec3 local = world - ctx->region_min;
394 const size_t index = (static_cast<size_t>(local.z) * res.y + local.y) * res.x + local.x;
395 const auto converted = narrow_vector(ctx->vt, base + static_cast<size_t>(s) * ctx->elem_size);
396 (*ctx->out)[index] = converted.value;
397 if (converted.precision_loss && ctx->precision_lost) {
398 *ctx->precision_lost = true;
399 }
400 }
401 return 0;
402 }
403
404 constexpr size_t element_width(bool is_vector)
405 {
406 return is_vector ? sizeof(glm::vec3) : sizeof(float);
407 }
408
409 /**
410 * @brief Synthesize the 5-4-3 template the builder reads layout, grid
411 * type and transform from.
412 *
413 * The template's own tree is unused. grid_type must outlive the builder
414 * call; the builder duplicates the string but borrows it until it does.
415 */
416 tvdb_grid_t make_template(
417 const Kinesis::Lattice3D& lattice, bool is_vector, char* grid_type)
418 {
419 tvdb_grid_t tmpl;
420 std::memset(&tmpl, 0, sizeof(tmpl));
421
422 std::strcpy(grid_type, grid_type_token(is_vector));
423 tmpl.descriptor.grid_type = grid_type;
424
425 const tvdb_value_type_t vt = is_vector ? TVDB_VALUE_VEC3F : TVDB_VALUE_FLOAT;
426
427 tmpl.tree.layout.num_levels = 4;
428 tmpl.tree.layout.levels[0].node_type = TVDB_NODE_ROOT;
429 tmpl.tree.layout.levels[1].node_type = TVDB_NODE_INTERNAL;
430 tmpl.tree.layout.levels[2].node_type = TVDB_NODE_INTERNAL;
431 tmpl.tree.layout.levels[3].node_type = TVDB_NODE_LEAF;
432 tmpl.tree.layout.levels[0].log2dim = 0;
433 tmpl.tree.layout.levels[1].log2dim = 5;
434 tmpl.tree.layout.levels[2].log2dim = 4;
435 tmpl.tree.layout.levels[3].log2dim = 3;
436 for (int lv = 0; lv < 4; ++lv) {
437 tmpl.tree.layout.levels[lv].value_type = vt;
438 }
439
440 const glm::vec3 cell = lattice.cell_size();
441 const glm::vec3 origin = lattice.bounds.min + 0.5F * cell;
442
443 tmpl.transform.type = TVDB_TRANSFORM_SCALE_TRANSLATE;
444 for (int axis = 0; axis < 3; ++axis) {
445 tmpl.transform.scale_values[axis] = cell[axis];
446 tmpl.transform.voxel_size[axis] = cell[axis];
447 tmpl.transform.translation[axis] = origin[axis];
448 }
449
450 return tmpl;
451 }
452
453} // namespace
454
455/**
456 * @struct VDBArchive::State
457 * @brief Built grids and the storage their borrowed pointers refer into.
458 *
459 * tvdb_meta_entry_t holds bare char pointers and tvdb_grid_destroy_owned
460 * frees whatever the grid owns. Metadata strings therefore live here and the
461 * entry array is detached from each grid before destroying it, so tinyvdb
462 * never frees memory it did not allocate.
463 *
464 * Deques rather than vectors: entry arrays hold pointers into the string
465 * storage, and grids hold pointers into the entry storage, so neither may
466 * reallocate as more grids are added.
467 *
468 * read_file/read_file_open are the read path's entire state: open() parses
469 * a file into read_file and every accessor below indexes into it directly.
470 * Independent of the write-side members above — an instance may open() for
471 * reading without ever having called add_grid.
472 */
474 std::vector<tvdb_grid_t> grids;
475 std::deque<std::string> strings;
476 std::deque<std::vector<tvdb_meta_entry_t>> entries;
477 std::deque<std::array<char, 32>> type_tokens;
478
479 tvdb_file_t read_file {};
480 bool read_file_open { false };
481};
482
484 : m_state(std::make_unique<State>())
485{
486}
487
489{
490 for (auto& grid : m_state->grids) {
491 grid.metadata.entries = nullptr;
492 grid.metadata.count = 0;
493 grid.metadata.capacity = 0;
494 tvdb_grid_destroy_owned(&grid);
495 }
496
497 if (m_state->read_file_open) {
498 tvdb_file_close(&m_state->read_file);
499 }
500}
501
503{
504 return m_state->grids.size();
505}
506
508 const Kinesis::Lattice3D& lattice, const VDBGridSpec& spec)
509{
510 const size_t width = element_width(spec.is_vector);
511 if (spec.values.size() != spec.coords.size() * width) {
512 m_last_error = "grid '" + std::string(spec.name)
513 + "': value bytes do not match coordinate count";
514 return false;
515 }
516 if (spec.background.size() != width) {
517 m_last_error = "grid '" + std::string(spec.name)
518 + "': background is the wrong width";
519 return false;
520 }
521
522 static_assert(sizeof(glm::ivec3) == sizeof(tvdb_vec3i),
523 "glm::ivec3 and tvdb_vec3i must be layout compatible for the "
524 "coordinate span to be passed through without a copy");
525
526 auto& type_token = m_state->type_tokens.emplace_back();
527 tvdb_grid_t tmpl = make_template(lattice, spec.is_vector, type_token.data());
528
529 const std::string name(spec.name);
530
531 tvdb_grid_t grid;
532 const bool ok = tvdb_grid_from_sparse_typed_using_template(
533 &tmpl,
534 reinterpret_cast<const tvdb_vec3i*>(spec.coords.data()),
535 spec.values.data(),
536 spec.coords.size(),
537 spec.is_vector ? TVDB_VALUE_VEC3F : TVDB_VALUE_FLOAT,
538 spec.background.data(),
539 name.c_str(),
540 &grid);
541
542 if (!ok) {
543 m_last_error = "grid '" + name + "': tree build failed";
544 return false;
545 }
546
547 auto& list = m_state->entries.emplace_back();
548 list.reserve(spec.metadata.size() + 1);
549
550 auto add_entry = [&](std::string_view key, std::string_view value) {
551 std::string& k = m_state->strings.emplace_back(key);
552 std::string& t = m_state->strings.emplace_back("string");
553 std::string& v = m_state->strings.emplace_back(value);
554
555 tvdb_meta_entry_t entry;
556 std::memset(&entry, 0, sizeof(entry));
557 entry.name = k.data();
558 entry.type_name = t.data();
559 entry.value.type = TVDB_VALUE_STRING;
560 entry.value.u.s.str = v.data();
561 entry.value.u.s.len = v.size();
562 list.push_back(entry);
563 };
564
565 // OpenVDB reads a grid's name from metadata, not from the archive's grid
566 // descriptor. Without this entry vdb_print and every DCC show it unnamed.
567 add_entry("name", spec.name);
568
569 for (const auto& [key, value] : spec.metadata) {
570 add_entry(key, value);
571 }
572
573 grid.metadata.entries = list.data();
574 grid.metadata.count = list.size();
575 grid.metadata.capacity = list.size();
576 grid.metadata.alloc = nullptr;
577
578 m_state->grids.push_back(grid);
579 return true;
580}
581
582bool VDBArchive::save(const std::string& path, uint32_t compression, int level)
583{
584 if (m_state->grids.empty()) {
585 m_last_error = "no grids to save";
586 return false;
587 }
588
589 tvdb_file_t out;
590 std::memset(&out, 0, sizeof(out));
591 out.alloc = make_allocator();
592 out.num_grids = m_state->grids.size();
593 out.grids = m_state->grids.data();
594
595 tvdb_error_t err;
596 std::memset(&err, 0, sizeof(err));
597
598 const tvdb_status_t st = tvdb_file_save(
599 &out, path.c_str(), compression, level, /*use_mmap=*/0, &err);
600
601 if (st != TVDB_OK) {
602 m_last_error = std::string("save failed: ")
603 + (err.message[0] != '\0' ? err.message : "unknown");
604 return false;
605 }
606
607 return true;
608}
609
610// =============================================================================
611// Read path
612// =============================================================================
613
614bool VDBArchive::open(const std::string& path)
615{
616 if (m_state->read_file_open) {
617 tvdb_file_close(&m_state->read_file);
618 m_state->read_file_open = false;
619 }
620
621 tvdb_error_t err;
622 std::memset(&err, 0, sizeof(err));
623
624 if (tvdb_file_open(&m_state->read_file, path.c_str(), nullptr, &err) != TVDB_OK) {
625 m_last_error = std::string("open failed: ")
626 + (err.message[0] != '\0' ? err.message : "unknown");
627 return false;
628 }
629 m_state->read_file_open = true;
630
631 if (tvdb_read_all_grids(&m_state->read_file, &err) != TVDB_OK) {
632 m_last_error = std::string("grid read failed: ")
633 + (err.message[0] != '\0' ? err.message : "unknown");
634 tvdb_file_close(&m_state->read_file);
635 m_state->read_file_open = false;
636 return false;
637 }
638
639 return true;
640}
641
643{
644 return m_state->read_file_open ? tvdb_grid_count(&m_state->read_file) : 0;
645}
646
648{
649 VDBGridSummary out;
650
651 if (!m_state->read_file_open || index >= m_state->read_file.num_grids) {
652 return out;
653 }
654
655 const tvdb_grid_t& grid = m_state->read_file.grids[index];
656
657 const char* name = tvdb_grid_name(&m_state->read_file, index);
658 out.name = name ? name : "";
659
660 const tvdb_value_type_t vt = leaf_value_type(grid);
661 out.is_vector = is_vector_type(vt);
662 out.narrowed = needs_narrowing(vt);
663
664 out.voxel_size = grid_voxel_size(grid.transform);
665 out.translation = grid_translation(grid.transform);
666
667 BBoxAcc acc;
668 tvdb_grid_visit_leaves(&grid, bbox_visit, &acc);
669 out.has_active = acc.has_any;
670 out.active_min = acc.min;
671 out.active_max = acc.max;
672
673 out.background_scalar = grid_background_scalar(grid);
674 out.background_vector = grid_background_vector(grid);
675
676 return out;
677}
678
679std::string VDBArchive::grid_metadata(size_t index, std::string_view key) const
680{
681 if (!m_state->read_file_open || index >= m_state->read_file.num_grids) {
682 return {};
683 }
684
685 const tvdb_grid_t& grid = m_state->read_file.grids[index];
686
687 for (size_t i = 0; i < grid.metadata.count; ++i) {
688 const tvdb_meta_entry_t& entry = grid.metadata.entries[i];
689 if (!entry.name || key != entry.name) {
690 continue;
691 }
692 if (entry.value.type != TVDB_VALUE_STRING || !entry.value.u.s.str) {
693 return {};
694 }
695 return { entry.value.u.s.str, entry.value.u.s.len };
696 }
697 return {};
698}
699
701 size_t index,
702 const glm::ivec3& region_min,
703 const glm::uvec3& resolution,
704 float background,
705 std::vector<float>& out,
706 bool* precision_lost) const
707{
708 if (!m_state->read_file_open || index >= m_state->read_file.num_grids) {
709 m_last_error = "read_dense_scalar: grid index out of range";
710 return false;
711 }
712 if (resolution.x == 0 || resolution.y == 0 || resolution.z == 0) {
713 m_last_error = "read_dense_scalar: zero resolution";
714 return false;
715 }
716
717 const tvdb_grid_t& grid = m_state->read_file.grids[index];
718 const tvdb_value_type_t vt = leaf_value_type(grid);
719
720 if (is_vector_type(vt)) {
721 const char* name = tvdb_grid_name(&m_state->read_file, index);
722 m_last_error = "read_dense_scalar: grid '" + std::string(name ? name : "") + "' is vector-typed";
723 return false;
724 }
725 const size_t elem_size = tvdb_value_type_size(vt);
726 if (elem_size == 0) {
727 m_last_error = "read_dense_scalar: grid has an unsupported leaf value type";
728 return false;
729 }
730
731 if (precision_lost) {
732 *precision_lost = false;
733 }
734
735 out.assign(static_cast<size_t>(resolution.x) * resolution.y * resolution.z, background);
736
737 DenseScalarCtx ctx {};
738 ctx.region_min = region_min;
739 ctx.region_max = region_min + glm::ivec3(resolution);
740 ctx.vt = vt;
741 ctx.elem_size = elem_size;
742 ctx.precision_lost = precision_lost;
743 ctx.out = &out;
744
745 tvdb_grid_visit_leaves(&grid, dense_scalar_visit, &ctx);
746 return true;
747}
748
750 size_t index,
751 const glm::ivec3& region_min,
752 const glm::uvec3& resolution,
753 const glm::vec3& background,
754 std::vector<glm::vec3>& out,
755 bool* precision_lost) const
756{
757 if (!m_state->read_file_open || index >= m_state->read_file.num_grids) {
758 m_last_error = "read_dense_vector: grid index out of range";
759 return false;
760 }
761 if (resolution.x == 0 || resolution.y == 0 || resolution.z == 0) {
762 m_last_error = "read_dense_vector: zero resolution";
763 return false;
764 }
765
766 const tvdb_grid_t& grid = m_state->read_file.grids[index];
767 const tvdb_value_type_t vt = leaf_value_type(grid);
768
769 if (!is_vector_type(vt)) {
770 const char* name = tvdb_grid_name(&m_state->read_file, index);
771 m_last_error = "read_dense_vector: grid '" + std::string(name ? name : "") + "' is scalar-typed";
772 return false;
773 }
774 const size_t elem_size = tvdb_value_type_size(vt);
775 if (elem_size == 0) {
776 m_last_error = "read_dense_vector: grid has an unsupported leaf value type";
777 return false;
778 }
779
780 if (precision_lost) {
781 *precision_lost = false;
782 }
783
784 out.assign(static_cast<size_t>(resolution.x) * resolution.y * resolution.z, background);
785
786 DenseVectorCtx ctx {};
787 ctx.region_min = region_min;
788 ctx.region_max = region_min + glm::ivec3(resolution);
789 ctx.vt = vt;
790 ctx.elem_size = elem_size;
791 ctx.precision_lost = precision_lost;
792 ctx.out = &out;
793
794 tvdb_grid_visit_leaves(&grid, dense_vector_visit, &ctx);
795 return true;
796}
797
798} // namespace MayaFlux::IO::Detail
bool save(const std::string &path, uint32_t compression, int level)
Write every added grid to one file.
std::string grid_metadata(size_t index, std::string_view key) const
Look up a string-typed metadata entry on a grid.
bool read_dense_scalar(size_t index, const glm::ivec3 &region_min, const glm::uvec3 &resolution, float background, std::vector< float > &out, bool *precision_lost=nullptr) const
Materialize a scalar grid's cells over an explicit region.
std::string m_last_error
Set from the const read-path accessors too.
std::unique_ptr< State > m_state
bool read_dense_vector(size_t index, const glm::ivec3 &region_min, const glm::uvec3 &resolution, const glm::vec3 &background, std::vector< glm::vec3 > &out, bool *precision_lost=nullptr) const
Materialize a vector grid's cells over an explicit region.
VDBGridSummary grid_summary(size_t index) const
Summarize one grid: name, value kind, transform, active bounds.
bool add_grid(const Kinesis::Lattice3D &lattice, const VDBGridSpec &spec)
Build one grid from active cells and retain it for saving.
bool open(const std::string &path)
Open a .vdb and read every grid's tree into memory.
size_t read_grid_count() const
Number of grids in the opened file, or 0 if none is open.
float half_to_float(uint16_t bits) noexcept
IEEE 754 binary16 to binary32.
Definition SmallFloat.cpp:5
std::deque< std::string > strings
std::deque< std::vector< tvdb_meta_entry_t > > entries
std::vector< tvdb_grid_t > grids
std::deque< std::array< char, 32 > > type_tokens
Built grids and the storage their borrowed pointers refer into.
std::span< const std::byte > values
std::span< const glm::ivec3 > coords
std::span< const std::byte > background
std::span< const std::pair< std::string, std::string > > metadata
One grid's worth of input to VDBArchive::add_grid.
What a reader needs to know about one grid in an opened file, before deciding how to materialize it.
A regular subdivision of an AABB3D into a cell count per axis.
Definition Lattice.hpp:25