-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
usdc-reader.cc
2579 lines (2219 loc) · 83.9 KB
/
usdc-reader.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: MIT
// Copyright 2020-Present Syoyo Fujita.
//
// USDC(Crate) reader
//
// TODO:
//
// - [ ] Validate the existence of connection Paths(Connection) and target
// Paths(Relation)
// - [ ] GeomSubset
//
#ifdef _MSC_VER
#ifndef NOMINMAX
#define NOMINMAX
#endif
#endif
#include "usdc-reader.hh"
#if !defined(TINYUSDZ_DISABLE_MODULE_USDC_READER)
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include "prim-types.hh"
#include "tinyusdz.hh"
#include "value-types.hh"
#if defined(__wasi__)
#else
#include <thread>
#endif
#include "crate-format.hh"
#include "crate-pprint.hh"
#include "crate-reader.hh"
#include "integerCoding.h"
#include "lz4-compression.hh"
#include "path-util.hh"
#include "pprinter.hh"
#include "prim-reconstruct.hh"
#include "str-util.hh"
#include "stream-reader.hh"
#include "tiny-format.hh"
#include "value-pprint.hh"
//
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Weverything"
#endif
#include "nonstd/expected.hpp"
#ifdef __clang__
#pragma clang diagnostic pop
#endif
//
#include "common-macros.inc"
namespace tinyusdz {
namespace prim {
// template specialization forward decls.
// implimentations will be located in prim-reconstruct.cc
#define RECONSTRUCT_PRIM_DECL(__ty) \
template <> \
bool ReconstructPrim<__ty>(const PropertyMap &, const ReferenceList &, \
__ty *, std::string *, std::string *)
RECONSTRUCT_PRIM_DECL(Xform);
RECONSTRUCT_PRIM_DECL(Model);
RECONSTRUCT_PRIM_DECL(Scope);
RECONSTRUCT_PRIM_DECL(GeomPoints);
RECONSTRUCT_PRIM_DECL(GeomMesh);
RECONSTRUCT_PRIM_DECL(GeomCapsule);
RECONSTRUCT_PRIM_DECL(GeomCube);
RECONSTRUCT_PRIM_DECL(GeomCone);
RECONSTRUCT_PRIM_DECL(GeomCylinder);
RECONSTRUCT_PRIM_DECL(GeomSphere);
RECONSTRUCT_PRIM_DECL(GeomBasisCurves);
RECONSTRUCT_PRIM_DECL(GeomCamera);
RECONSTRUCT_PRIM_DECL(SphereLight);
RECONSTRUCT_PRIM_DECL(DomeLight);
RECONSTRUCT_PRIM_DECL(DiskLight);
RECONSTRUCT_PRIM_DECL(DistantLight);
RECONSTRUCT_PRIM_DECL(CylinderLight);
RECONSTRUCT_PRIM_DECL(SkelRoot);
RECONSTRUCT_PRIM_DECL(SkelAnimation);
RECONSTRUCT_PRIM_DECL(Skeleton);
RECONSTRUCT_PRIM_DECL(BlendShape);
RECONSTRUCT_PRIM_DECL(Material);
RECONSTRUCT_PRIM_DECL(Shader);
#undef RECONSTRUCT_PRIM_DECL
} // namespace prim
namespace usdc {
constexpr auto kTag = "[USDC]";
#if 0
struct PrimNode {
value::Value
prim; // Usually stores reconstructed(composed) concrete Prim(e.g. Xform)
int64_t parent{-1}; // -1 = root node
std::vector<size_t> children; // index to USDCReader::Impl::._prim_nodes[]
//
//
//
std::vector<value::token> primChildren;
#if 0
//
// For Variants
///
// SpecType::VariantSet
std::vector<value::token> variantChildren;
// TODO: Variants
std::map<std::string, value::Value> variants;
#else
#endif
};
struct VariantPrimNode {
int64_t parent{-1}; // -1 = root node
//
// For Variants
///
// SpecType::VariantSet
std::vector<value::token> variantChildren;
value::Value prim; // Usually stores reconstructed Prim(e.g. Xform)
};
#endif
class USDCReader::Impl {
public:
Impl(StreamReader *sr, const USDCReaderConfig &config) : _sr(sr) {
_config = config;
#if defined(__wasi__)
_config.numThreads = 1;
#else
if (_config.numThreads == -1) {
_config.numThreads =
(std::max)(1, int(std::thread::hardware_concurrency()));
}
// Limit to 1024 threads.
_config.numThreads = (std::min)(1024, _config.numThreads);
#endif
}
~Impl() {
delete crate_reader;
crate_reader = nullptr;
}
bool ReadUSDC();
using PathIndexToSpecIndexMap = std::unordered_map<uint32_t, uint32_t>;
///
/// Construct Property(Attribute, Relationship/Connection) from
/// FieldValuePairs
///
bool ParseProperty(const SpecType specType,
const crate::FieldValuePairVector &fvs, Property *prop);
#if 0 // TODO: Remove
// For simple, non animatable and non `.connect` types. e.g. "token[]"
template <typename T>
bool ReconstructSimpleAttribute(int parent,
const crate::FieldValuePairVector &fvs,
T *attr, bool *custom_out = nullptr,
Variability *variability_out = nullptr);
#endif
#if 0
// For attribute which maybe a value, connection or TimeSamples.
template <typename T>
bool ReconstructTypedProperty(int parent,
const crate::FieldValuePairVector &fvs,
TypedProperty<T> *attr);
#endif
///
/// Parse Prim spec from FieldValuePairs
///
bool ParsePrimSpec(const crate::FieldValuePairVector &fvs,
nonstd::optional<std::string> &typeName, /* out */
nonstd::optional<Specifier> &specifier, /* out */
std::vector<value::token> &primChildren, /* out */
std::vector<value::token> &properties, /* out */
PrimMeta &primMeta); /* out */
bool ParseVariantSetFields(
const crate::FieldValuePairVector &fvs,
std::vector<value::token> &variantChildren); /* out */
template <typename T>
bool ReconstructPrim(const crate::CrateReader::Node &node,
const PathIndexToSpecIndexMap &psmap, T *prim);
///
/// Reconstrcut Prim node.
/// Returns reconstruct Prim to `primOut`
/// When `current` is 0(StageMeta), `primOut` is not set.
/// `is_parent_variant` : True when parent path is Variant
///
bool ReconstructPrimNode(int parent, int current, int level,
bool is_parent_variant,
const PathIndexToSpecIndexMap &psmap, Stage *stage,
nonstd::optional<Prim> *primOut);
///
/// Reconstruct Prim from given `typeName` string(e.g. "Xform")
///
nonstd::optional<Prim> ReconstructPrimFromTypeName(
const std::string &typeName, const std::string &prim_name,
const crate::CrateReader::Node &node, const Specifier spec,
const std::vector<value::token> &primChildren,
const std::vector<value::token> &properties,
const PathIndexToSpecIndexMap &psmap, const PrimMeta &meta);
bool ReconstructPrimRecursively(int parent_id, int current_id, Prim *rootPrim,
int level,
const PathIndexToSpecIndexMap &psmap,
Stage *stage);
bool ReconstructPrimTree(Prim *rootPrim, const PathIndexToSpecIndexMap &psmap,
Stage *stage);
bool ReconstructStage(Stage *stage);
///
/// --------------------------------------------------
///
void PushError(const std::string &s) { _err += s; }
void PushWarn(const std::string &s) { _warn += s; }
std::string GetError() { return _err; }
std::string GetWarning() { return _warn; }
// Approximated memory usage in [mb]
size_t GetMemoryUsage() const { return memory_used / (1024 * 1024); }
private:
nonstd::expected<APISchemas, std::string> ToAPISchemas(
const ListOp<value::token> &);
// ListOp<T> -> (ListEditOp, [T])
template <typename T>
std::vector<std::pair<ListEditQual, std::vector<T>>> DecodeListOp(
const ListOp<T> &);
///
/// Builds std::map<std::string, Property> from the list of Path(Spec)
/// indices.
///
bool BuildPropertyMap(const std::vector<size_t> &pathIndices,
const PathIndexToSpecIndexMap &psmap,
prim::PropertyMap *props);
bool ReconstrcutStageMeta(const crate::FieldValuePairVector &fvs,
StageMetas *out);
bool AddVariantChildrenToPrimNode(
int32_t prim_idx, const std::vector<value::token> &variantChildren) {
if (prim_idx < 0) {
return false;
}
if (_variantChildren.count(uint32_t(prim_idx))) {
PUSH_WARN("Multiple Field with VariantSet SpecType detected.");
}
_variantChildren[uint32_t(prim_idx)] = variantChildren;
return true;
}
bool AddVariantToPrimNode(int32_t prim_idx, const value::Value &variant);
crate::CrateReader *crate_reader{nullptr};
StreamReader *_sr = nullptr;
std::string _err;
std::string _warn;
USDCReaderConfig _config;
// Tracks the memory used(In advisorily manner since counting memory usage is
// done by manually, so not all memory consumption could be tracked)
size_t memory_used{0}; // in bytes.
nonstd::optional<Path> GetPath(crate::Index index) const {
if (index.value <= _paths.size()) {
return _paths[index.value];
}
return nonstd::nullopt;
}
nonstd::optional<Path> GetElemPath(crate::Index index) const {
if (index.value <= _elemPaths.size()) {
return _elemPaths[index.value];
}
return nonstd::nullopt;
}
// TODO: Do not copy data from crate_reader.
std::vector<crate::CrateReader::Node> _nodes;
std::vector<crate::Spec> _specs;
std::vector<crate::Field> _fields;
std::vector<crate::Index> _fieldset_indices;
std::vector<crate::Index> _string_indices;
std::vector<Path> _paths;
std::vector<Path> _elemPaths;
std::map<crate::Index, crate::FieldValuePairVector>
_live_fieldsets; // <fieldset index, List of field with unpacked Values>
// std::vector<PrimNode> _prim_nodes;
// VariantSet Spec. variantChildren
std::map<uint32_t, std::vector<value::token>> _variantChildren;
// For Prim/Props defined as Variant(SpecType::VariantSet)
// key = path index.
std::map<int32_t, Prim> _variantPrims;
std::map<uint32_t, Property> _variantAttributeNodes;
// Check if given node_id is a prim node.
std::set<int32_t> _prim_table;
};
//
// -- Impl
//
#if 0
bool USDCReader::Impl::ReconstructGeomSubset(
const Node &node, const FieldValuePairVector &fields,
const std::unordered_map<uint32_t, uint32_t> &path_index_to_spec_index_map,
GeomSubset *geom_subset) {
DCOUT("Reconstruct GeomSubset");
for (const auto &fv : fields) {
if (fv.first == "properties") {
FIELDVALUE_DATATYPE_CHECK(fv, "properties", crate::kTokenVector)
// for (size_t i = 0; i < fv.second.GetStringArray().size(); i++) {
// // if (fv.second.GetStringArray()[i] == "points") {
// // }
// }
}
}
for (size_t i = 0; i < node.GetChildren().size(); i++) {
int child_index = int(node.GetChildren()[i]);
if ((child_index < 0) || (child_index >= int(_nodes.size()))) {
PUSH_ERROR("Invalid child node id: " + std::to_string(child_index) +
". Must be in range [0, " + std::to_string(_nodes.size()) +
")");
return false;
}
// const Node &child_node = _nodes[size_t(child_index)];
if (!path_index_to_spec_index_map.count(uint32_t(child_index))) {
// No specifier assigned to this child node.
// TODO: Should we report an error?
continue;
}
uint32_t spec_index =
path_index_to_spec_index_map.at(uint32_t(child_index));
if (spec_index >= _specs.size()) {
PUSH_ERROR("Invalid specifier id: " + std::to_string(spec_index) +
". Must be in range [0, " + std::to_string(_specs.size()) +
")");
return false;
}
const crate::Spec &spec = _specs[spec_index];
Path path = GetPath(spec.path_index);
DCOUT("Path prim part: " << path.prim_part()
<< ", prop part: " << path.prop_part()
<< ", spec_index = " << spec_index);
if (!_live_fieldsets.count(spec.fieldset_index)) {
_err += "FieldSet id: " + std::to_string(spec.fieldset_index.value) +
" must exist in live fieldsets.\n";
return false;
}
const FieldValuePairVector &child_fields =
_live_fieldsets.at(spec.fieldset_index);
{
std::string prop_name = path.prop_part();
Attribute attr;
bool ret = ParseAttribute(child_fields, &attr, prop_name);
DCOUT("prop: " << prop_name << ", ret = " << ret);
if (ret) {
// TODO(syoyo): Support more prop names
if (prop_name == "elementType") {
auto p = attr.var.get_value<tinyusdz::value::token>();
if (p) {
std::string str = p->str();
if (str == "face") {
geom_subset->elementType = GeomSubset::ElementType::Face;
} else {
PUSH_ERROR("`elementType` must be `face`, but got `" + str + "`");
return false;
}
} else {
PUSH_ERROR("`elementType` must be token type, but got " +
value::GetTypeName(attr.var.type_id()));
return false;
}
} else if (prop_name == "faces") {
auto p = attr.var.get_value<std::vector<int>>();
if (p) {
geom_subset->faces = (*p);
}
DCOUT("faces.num = " << geom_subset->faces.size());
} else {
// Assume Primvar.
if (geom_subset->attribs.count(prop_name)) {
_err += "Duplicated property name found: " + prop_name + "\n";
return false;
}
#ifdef TINYUSDZ_LOCAL_DEBUG_PRINT
std::cout << "add [" << prop_name << "] to generic attrs\n";
#endif
geom_subset->attribs[prop_name] = std::move(attr);
}
}
}
}
return true;
}
#endif
namespace {}
nonstd::expected<APISchemas, std::string> USDCReader::Impl::ToAPISchemas(
const ListOp<value::token> &arg) {
APISchemas schemas;
auto SchemaHandler =
[](const value::token &tok) -> nonstd::optional<APISchemas::APIName> {
if (tok.str() == "MaterialBindingAPI") {
return APISchemas::APIName::MaterialBindingAPI;
} else if (tok.str() == "SkelBindingAPI") {
return APISchemas::APIName::SkelBindingAPI;
} else if (tok.str() == "Preliminary_AnchoringAPI") {
return APISchemas::APIName::Preliminary_AnchoringAPI;
} else if (tok.str() == "Preliminary_PhysicsColliderAPI") {
return APISchemas::APIName::Preliminary_PhysicsColliderAPI;
} else if (tok.str() == "Preliminary_PhysicsMaterialAPI") {
return APISchemas::APIName::Preliminary_PhysicsMaterialAPI;
} else if (tok.str() == "Preliminary_PhysicsRigidBodyAPI") {
return APISchemas::APIName::Preliminary_PhysicsRigidBodyAPI;
} else {
return nonstd::nullopt;
}
};
if (arg.IsExplicit()) { // fast path
for (auto &item : arg.GetExplicitItems()) {
if (auto pv = SchemaHandler(item)) {
std::string instanceName = ""; // TODO
schemas.names.push_back({pv.value(), instanceName});
} else {
return nonstd::make_unexpected("Invalid or Unsupported API schema: " +
item.str());
}
}
schemas.listOpQual = ListEditQual::ResetToExplicit;
} else {
// Assume all items have same ListEdit qualifier.
if (arg.GetExplicitItems().size()) {
if (arg.GetAddedItems().size() || arg.GetAppendedItems().size() ||
arg.GetDeletedItems().size() || arg.GetPrependedItems().size() ||
arg.GetOrderedItems().size()) {
return nonstd::make_unexpected(
"Currently TinyUSDZ does not support ListOp with different "
"ListEdit qualifiers.");
}
for (auto &&item : arg.GetExplicitItems()) {
if (auto pv = SchemaHandler(item)) {
std::string instanceName = ""; // TODO
schemas.names.push_back({pv.value(), instanceName});
} else {
return nonstd::make_unexpected("Invalid or Unsupported API schema: " +
item.str());
}
}
schemas.listOpQual = ListEditQual::ResetToExplicit;
} else if (arg.GetAddedItems().size()) {
if (arg.GetExplicitItems().size() || arg.GetAppendedItems().size() ||
arg.GetDeletedItems().size() || arg.GetPrependedItems().size() ||
arg.GetOrderedItems().size()) {
return nonstd::make_unexpected(
"Currently TinyUSDZ does not support ListOp with different "
"ListEdit qualifiers.");
}
for (auto &item : arg.GetAddedItems()) {
if (auto pv = SchemaHandler(item)) {
std::string instanceName = ""; // TODO
schemas.names.push_back({pv.value(), instanceName});
} else {
return nonstd::make_unexpected("Invalid or Unsupported API schema: " +
item.str());
}
}
schemas.listOpQual = ListEditQual::Add;
} else if (arg.GetAppendedItems().size()) {
if (arg.GetExplicitItems().size() || arg.GetAddedItems().size() ||
arg.GetDeletedItems().size() || arg.GetPrependedItems().size() ||
arg.GetOrderedItems().size()) {
return nonstd::make_unexpected(
"Currently TinyUSDZ does not support ListOp with different "
"ListEdit qualifiers.");
}
for (auto &&item : arg.GetAppendedItems()) {
if (auto pv = SchemaHandler(item)) {
std::string instanceName = ""; // TODO
schemas.names.push_back({pv.value(), instanceName});
} else {
return nonstd::make_unexpected("Invalid or Unsupported API schema: " +
item.str());
}
}
schemas.listOpQual = ListEditQual::Append;
} else if (arg.GetDeletedItems().size()) {
if (arg.GetExplicitItems().size() || arg.GetAddedItems().size() ||
arg.GetAppendedItems().size() || arg.GetPrependedItems().size() ||
arg.GetOrderedItems().size()) {
return nonstd::make_unexpected(
"Currently TinyUSDZ does not support ListOp with different "
"ListEdit qualifiers.");
}
for (auto &&item : arg.GetDeletedItems()) {
if (auto pv = SchemaHandler(item)) {
std::string instanceName = ""; // TODO
schemas.names.push_back({pv.value(), instanceName});
} else {
return nonstd::make_unexpected("Invalid or Unsupported API schema: " +
item.str());
}
}
schemas.listOpQual = ListEditQual::Delete;
} else if (arg.GetPrependedItems().size()) {
if (arg.GetExplicitItems().size() || arg.GetAddedItems().size() ||
arg.GetAppendedItems().size() || arg.GetDeletedItems().size() ||
arg.GetOrderedItems().size()) {
return nonstd::make_unexpected(
"Currently TinyUSDZ does not support ListOp with different "
"ListEdit qualifiers.");
}
for (auto &&item : arg.GetPrependedItems()) {
if (auto pv = SchemaHandler(item)) {
std::string instanceName = ""; // TODO
schemas.names.push_back({pv.value(), instanceName});
} else {
return nonstd::make_unexpected("Invalid or Unsupported API schema: " +
item.str());
}
}
schemas.listOpQual = ListEditQual::Prepend;
} else if (arg.GetOrderedItems().size()) {
if (arg.GetExplicitItems().size() || arg.GetAddedItems().size() ||
arg.GetAppendedItems().size() || arg.GetDeletedItems().size() ||
arg.GetPrependedItems().size()) {
return nonstd::make_unexpected(
"Currently TinyUSDZ does not support ListOp with different "
"ListEdit qualifiers.");
}
// schemas.qual = ListEditQual::Order;
return nonstd::make_unexpected("TODO: Ordered ListOp items.");
} else {
// ??? This should not happend.
return nonstd::make_unexpected("Internal error: ListOp conversion.");
}
}
return std::move(schemas);
}
template <typename T>
std::vector<std::pair<ListEditQual, std::vector<T>>>
USDCReader::Impl::DecodeListOp(const ListOp<T> &arg) {
std::vector<std::pair<ListEditQual, std::vector<T>>> dst;
if (arg.IsExplicit()) { // fast path
dst.push_back({ListEditQual::ResetToExplicit, arg.GetExplicitItems()});
} else {
// Assume all items have same ListEdit qualifier.
if (arg.GetExplicitItems().size()) {
dst.push_back({ListEditQual::ResetToExplicit, arg.GetExplicitItems()});
}
if (arg.GetAddedItems().size()) {
dst.push_back({ListEditQual::Add, arg.GetAddedItems()});
}
if (arg.GetAppendedItems().size()) {
dst.push_back({ListEditQual::Append, arg.GetAppendedItems()});
}
if (arg.GetDeletedItems().size()) {
dst.push_back({ListEditQual::Delete, arg.GetDeletedItems()});
}
if (arg.GetPrependedItems().size()) {
dst.push_back({ListEditQual::Prepend, arg.GetPrependedItems()});
}
if (arg.GetOrderedItems().size()) {
dst.push_back({ListEditQual::Order, arg.GetOrderedItems()});
}
}
return std::move(dst);
}
bool USDCReader::Impl::BuildPropertyMap(const std::vector<size_t> &pathIndices,
const PathIndexToSpecIndexMap &psmap,
prim::PropertyMap *props) {
for (size_t i = 0; i < pathIndices.size(); i++) {
int child_index = int(pathIndices[i]);
if ((child_index < 0) || (child_index >= int(_nodes.size()))) {
PUSH_ERROR("Invalid child node id: " + std::to_string(child_index) +
". Must be in range [0, " + std::to_string(_nodes.size()) +
")");
return false;
}
if (!psmap.count(uint32_t(child_index))) {
// No specifier assigned to this child node.
// Should we report an error?
continue;
}
uint32_t spec_index = psmap.at(uint32_t(child_index));
if (spec_index >= _specs.size()) {
PUSH_ERROR("Invalid specifier id: " + std::to_string(spec_index) +
". Must be in range [0, " + std::to_string(_specs.size()) +
")");
return false;
}
const crate::Spec &spec = _specs[spec_index];
// Property must be Attribute or Relationship
if ((spec.spec_type == SpecType::Attribute) ||
(spec.spec_type == SpecType::Relationship)) {
// OK
} else {
continue;
}
nonstd::optional<Path> path = GetPath(spec.path_index);
if (!path) {
PUSH_ERROR_AND_RETURN_TAG(kTag, "Invalid PathIndex.");
}
DCOUT("Path prim part: " << path.value().prim_part()
<< ", prop part: " << path.value().prop_part()
<< ", spec_index = " << spec_index);
if (!_live_fieldsets.count(spec.fieldset_index)) {
PUSH_ERROR("FieldSet id: " + std::to_string(spec.fieldset_index.value) +
" must exist in live fieldsets.");
return false;
}
const crate::FieldValuePairVector &child_fvs =
_live_fieldsets.at(spec.fieldset_index);
{
std::string prop_name = path.value().prop_part();
if (prop_name.empty()) {
// ???
PUSH_ERROR_AND_RETURN_TAG(kTag, "Property Prop.PropPart is empty");
}
Property prop;
if (!ParseProperty(spec.spec_type, child_fvs, &prop)) {
PUSH_ERROR_AND_RETURN_TAG(
kTag,
fmt::format(
"Failed to construct Property `{}` from FieldValuePairVector.",
prop_name));
}
props->emplace(prop_name, prop);
DCOUT("Add property : " << prop_name);
}
}
return true;
}
/// Attrib/Property fieldSet example
///
/// specTyppe = SpecTypeConnection
///
/// - typeName(token) : type name of Attribute(e.g. `float`)
/// - custom(bool) : `custom` qualifier
/// - variability(variability) : Variability(meta?)
/// <value>
/// - default : Default(fallback) value.
/// - timeSample(TimeSamples) : `.timeSamples` data.
/// - connectionPaths(type = ListOpPath) : `.connect`
/// - (Empty) : Define only(Neiher connection nor value assigned. e.g.
/// "float outputs:rgb")
bool USDCReader::Impl::ParseProperty(const SpecType spec_type,
const crate::FieldValuePairVector &fvs,
Property *prop) {
if (fvs.size() > _config.kMaxFieldValuePairs) {
PUSH_ERROR_AND_RETURN_TAG(kTag, "Too much FieldValue pairs.");
}
bool custom{false};
nonstd::optional<value::token> typeName;
nonstd::optional<Interpolation> interpolation;
nonstd::optional<int> elementSize;
nonstd::optional<bool> hidden;
nonstd::optional<CustomDataType> customData;
nonstd::optional<value::StringData> comment;
Property::Type propType{Property::Type::EmptyAttrib};
Attribute attr;
bool is_scalar{false};
value::Value scalar;
Relationship rel;
// for consistency check
bool hasConnectionChildren{false};
bool hasConnectionPaths{false};
bool hasTargetChildren{false};
bool hasTargetPaths{false};
DCOUT("== List of Fields");
for (auto &fv : fvs) {
DCOUT(" fv name " << fv.first << "(type = " << fv.second.type_name()
<< ")");
if (fv.first == "custom") {
if (auto pv = fv.second.get_value<bool>()) {
custom = pv.value();
DCOUT(" custom = " << pv.value());
} else {
PUSH_ERROR_AND_RETURN_TAG(kTag, "`custom` field is not `bool` type.");
}
} else if (fv.first == "variability") {
if (auto pv = fv.second.get_value<Variability>()) {
attr.variability() = pv.value();
DCOUT(" variability = " << to_string(attr.variability()));
} else {
PUSH_ERROR_AND_RETURN_TAG(
kTag, "`variability` field is not `varibility` type.");
}
} else if (fv.first == "typeName") {
if (auto pv = fv.second.get_value<value::token>()) {
DCOUT(" typeName = " << pv.value().str());
typeName = pv.value();
} else {
PUSH_ERROR_AND_RETURN_TAG(kTag,
"`typeName` field is not `token` type.");
}
} else if (fv.first == "default") {
propType = Property::Type::Attrib;
// Set scalar
// TODO: Easier CrateValue to Attribute.var conversion
scalar = fv.second.get_raw();
is_scalar = true;
} else if (fv.first == "timeSamples") {
propType = Property::Type::Attrib;
if (auto pv = fv.second.get_value<value::TimeSamples>()) {
primvar::PrimVar var;
var.set_timesamples(pv.value());
attr.set_var(std::move(var));
} else {
PUSH_ERROR_AND_RETURN_TAG(kTag,
"`timeSamples` is not TimeSamples data.");
}
} else if (fv.first == "interpolation") {
propType = Property::Type::Attrib;
if (auto pv = fv.second.get_value<value::token>()) {
DCOUT(" interpolation = " << pv.value().str());
if (auto interp = InterpolationFromString(pv.value().str())) {
interpolation = interp.value();
} else {
PUSH_ERROR_AND_RETURN_TAG(kTag, "Invalid token for `interpolation`.");
}
} else {
PUSH_ERROR_AND_RETURN_TAG(kTag,
"`interpolation` field is not `token` type.");
}
} else if (fv.first == "connectionPaths") {
// .connect
propType = Property::Type::Connection;
hasConnectionPaths = true;
if (auto pv = fv.second.get_value<ListOp<Path>>()) {
auto p = pv.value();
DCOUT("connectionPaths = " << to_string(p));
if (!p.IsExplicit()) {
PUSH_ERROR_AND_RETURN_TAG(
kTag, "`connectionPaths` must be composed of Explicit items.");
}
// Must be explicit_items for now.
auto items = p.GetExplicitItems();
if (items.size() == 0) {
PUSH_ERROR_AND_RETURN_TAG(
kTag, "`connectionPaths` have empty Explicit items.");
}
if (items.size() == 1) {
// Single
const Path path = items[0];
rel.set(path);
} else {
rel.set(items); // [Path]
}
} else {
PUSH_ERROR_AND_RETURN_TAG(
kTag, "`connectionPaths` field is not `ListOp[Path]` type.");
}
} else if (fv.first == "targetPaths") {
// `rel`
propType = Property::Type::Relation;
hasTargetPaths = true;
if (auto pv = fv.second.get_value<ListOp<Path>>()) {
const ListOp<Path> &p = pv.value();
DCOUT("targetPaths = " << to_string(p));
auto ps = DecodeListOp<Path>(p);
if (ps.empty()) {
// Empty `targetPaths`
PUSH_ERROR_AND_RETURN_TAG(kTag, "`targetPaths` is empty.");
}
if (ps.size() > 1) {
// This should not happen though.
PUSH_WARN(
"ListOp with multiple ListOpType is not supported for now. Use "
"the first one: " +
to_string(std::get<0>(ps[0])));
}
auto qual = std::get<0>(ps[0]);
auto items = std::get<1>(ps[0]);
if (items.size() == 1) {
// Single
const Path path = items[0];
rel.set(path);
} else {
rel.set(items); // [Path]
}
rel.set_listedit_qual(qual);
} else {
PUSH_ERROR_AND_RETURN_TAG(
kTag, "`targetPaths` field is not `ListOp[Path]` type.");
}
} else if (fv.first == "hidden") {
// Attribute hidden param
if (auto pv = fv.second.get_value<bool>()) {
auto p = pv.value();
DCOUT("hidden = " << to_string(p));
hidden = p;
} else {
PUSH_ERROR_AND_RETURN_TAG(kTag,
"`elementSize` field is not `int` type.");
}
} else if (fv.first == "elementSize") {
// Attribute Meta
if (auto pv = fv.second.get_value<int>()) {
auto p = pv.value();
DCOUT("elementSize = " << to_string(p));
if ((p < 1) || (uint32_t(p) > _config.kMaxElementSize)) {
PUSH_ERROR_AND_RETURN_TAG(
kTag,
fmt::format("`elementSize` must be within [{}, {}), but got {}",
1, _config.kMaxElementSize, p));
}
elementSize = p;
} else {
PUSH_ERROR_AND_RETURN_TAG(kTag,
"`elementSize` field is not `int` type.");
}
} else if (fv.first == "targetChildren") {
// `targetChildren` seems optionally exist to validate the existence of
// target Paths when `targetPaths` field exists.
// TODO: validate path of `targetChildren`
hasTargetChildren = true;
// Path vector
if (auto pv = fv.second.get_value<std::vector<Path>>()) {
DCOUT("targetChildren = " << pv.value());
// PUSH_WARN("TODO: targetChildren");
} else {
PUSH_ERROR_AND_RETURN_TAG(
kTag, "`targetChildren` field is not `PathVector` type.");
}
} else if (fv.first == "connectionChildren") {
// `connectionChildren` seems optionally exist to validate the existence
// of connection Paths when `connectiontPaths` field exists.
// TODO: validate path of `connetionChildren`
hasConnectionChildren = true;
// Path vector
if (auto pv = fv.second.get_value<std::vector<Path>>()) {
DCOUT("connectionChildren = " << pv.value());
// PUSH_WARN("TODO: connectionChildren");
} else {
PUSH_ERROR_AND_RETURN_TAG(
kTag, "`connectionChildren` field is not `PathVector` type.");
}
} else if (fv.first == "customData") {
// CustomData(dict)
if (auto pv = fv.second.get_value<CustomDataType>()) {
customData = pv.value();
} else {
PUSH_ERROR_AND_RETURN_TAG(
kTag, "`customData` must be type `dictionary`, but got type `"
<< fv.second.type_name() << "`");
}
} else if (fv.first == "comment") {
if (auto pv = fv.second.get_value<std::string>()) {
value::StringData s;
s.value = pv.value();
s.is_triple_quoted = hasNewline(s.value);
comment = s;
} else {
PUSH_ERROR_AND_RETURN_TAG(
kTag, "`comment` must be type `string`, but got type `"
<< fv.second.type_name() << "`");
}
} else {
PUSH_WARN("TODO: " << fv.first);
DCOUT("TODO: " << fv.first);
}
}