forked from PixarAnimationStudios/OpenUSD
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fileIO_Common.h
1149 lines (987 loc) · 42.8 KB
/
fileIO_Common.h
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
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_FILE_IO_COMMON_H
#define PXR_USD_SDF_FILE_IO_COMMON_H
/// \file sdf/fileIO_Common.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/attributeSpec.h"
#include "pxr/usd/sdf/declareHandles.h"
#include "pxr/usd/sdf/fileIO.h"
#include "pxr/usd/sdf/layer.h"
#include "pxr/usd/sdf/layerOffset.h"
#include "pxr/usd/sdf/path.h"
#include "pxr/usd/sdf/primSpec.h"
#include "pxr/usd/sdf/reference.h"
#include "pxr/usd/sdf/relationshipSpec.h"
#include "pxr/usd/sdf/schema.h"
#include "pxr/usd/sdf/types.h"
#include "pxr/usd/sdf/variantSetSpec.h"
#include "pxr/usd/sdf/variantSpec.h"
#include "pxr/base/vt/dictionary.h"
#include "pxr/base/vt/value.h"
#include "pxr/base/tf/stringUtils.h"
#include "pxr/base/tf/token.h"
#include <algorithm>
#include <iosfwd>
#include <map>
#include <set>
#include <string>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
////////////////////////////////////////////////////////////////////////
// Simple FileIO Utilities
class Sdf_FileIOUtility {
public:
// === Stream output helpers
// Non-formatted string output
static void Puts(Sdf_TextOutput &out,
size_t indent, const std::string &str);
// Printf-style formatted string output
static void Write(Sdf_TextOutput &out,
size_t indent, const char *fmt, ...);
static bool OpenParensIfNeeded(Sdf_TextOutput &out,
bool didParens, bool multiLine);
static void CloseParensIfNeeded(Sdf_TextOutput &out,
size_t indent, bool didParens, bool multiLine);
static void WriteQuotedString(Sdf_TextOutput &out,
size_t indent, const std::string &str);
static void WriteAssetPath(Sdf_TextOutput &out,
size_t indent, const std::string &str);
static void WriteDefaultValue(Sdf_TextOutput &out,
size_t indent, VtValue value);
static void WriteSdfPath(Sdf_TextOutput &out,
size_t indent, const SdfPath &path);
static bool WriteNameVector(Sdf_TextOutput &out,
size_t indent, const std::vector<std::string> &vec);
static bool WriteNameVector(Sdf_TextOutput &out,
size_t indent, const std::vector<TfToken> &vec);
static bool WriteTimeSamples(Sdf_TextOutput &out,
size_t indent, const SdfPropertySpec &);
static bool WriteRelocates(Sdf_TextOutput &out,
size_t indent, bool multiLine,
const SdfRelocatesMap &reloMap);
static void WriteDictionary(Sdf_TextOutput &out,
size_t indent, bool multiLine,
const VtDictionary &dictionary,
bool stringValuesOnly=false);
template <class T>
static void WriteListOp(Sdf_TextOutput &out,
size_t indent,
const TfToken& fieldName,
const SdfListOp<T>& listOp);
static void WriteLayerOffset(Sdf_TextOutput &out,
size_t indent, bool multiline,
const SdfLayerOffset& offset);
// === String production and transformation helpers
/// Quote \p str, adding quotes before and after and escaping
/// unprintable characters and the quote character itself. If
/// the string contains newlines it's quoted with triple quotes
/// and the newlines are not escaped.
static std::string Quote(const std::string &str);
static std::string Quote(const TfToken &token);
// Create a string from a value
static std::string StringFromVtValue(const VtValue &value);
// Convert enums to strings for use in sdf text format syntax.
// Note that in some cases we use empty strings to represent the
// default values of these enums.
static const char* Stringify( SdfPermission val );
static const char* Stringify( SdfSpecifier val );
static const char* Stringify( SdfVariability val );
private:
// Helper types to write a VtDictionary so that its keys are ordered.
struct _StringLessThan {
bool operator()(const std::string *lhs, const std::string *rhs) const {
return *lhs < *rhs;
}
};
typedef std::map<const std::string *, const VtValue *, _StringLessThan>
_OrderedDictionary;
static void _WriteDictionary(
Sdf_TextOutput &out,
size_t indent, bool multiLine, _OrderedDictionary &dictionary,
bool stringValuesOnly);
};
////////////////////////////////////////////////////////////////////////
// Helpers for determining if a field should be included in a spec's
// metadata section.
struct Sdf_IsMetadataField
{
Sdf_IsMetadataField(const SdfSpecType specType)
: _specDef(SdfSchema::GetInstance().GetSpecDefinition(specType))
{ }
bool operator()(const TfToken& field) const
{
// Allow fields tagged explicitly as metadata, or fields
// that are invalid, as these may be unrecognized plugin
// metadata fields. In this case, there may be a string
// representation that needs to be written out.
return (!_specDef->IsValidField(field) ||
_specDef->IsMetadataField(field));
}
const SdfSchema::SpecDefinition* _specDef;
};
////////////////////////////////////////////////////////////////////////
static inline bool
Sdf_WritePrim(
const SdfPrimSpec &prim, Sdf_TextOutput &out, size_t indent);
static inline bool
Sdf_WriteAttribute(
const SdfAttributeSpec &attr, Sdf_TextOutput &out, size_t indent);
static inline bool
Sdf_WriteRelationship(
const SdfRelationshipSpec &rel, Sdf_TextOutput &out, size_t indent);
static bool
Sdf_WriteVariantSet(
const SdfVariantSetSpec &spec, Sdf_TextOutput &out, size_t indent);
static bool
Sdf_WriteVariant(
const SdfVariantSpec &variantSpec, Sdf_TextOutput &out, size_t indent);
////////////////////////////////////////////////////////////////////////
static bool
Sdf_WritePrimPreamble(
const SdfPrimSpec &prim, Sdf_TextOutput &out, size_t indent)
{
SdfSpecifier spec = prim.GetSpecifier();
bool writeTypeName = true;
if (!SdfIsDefiningSpecifier(spec)) {
// For non-defining specifiers, we write typeName only if we have
// a setting.
writeTypeName = prim.HasField(SdfFieldKeys->TypeName);
}
TfToken typeName;
if (writeTypeName) {
typeName = prim.GetTypeName();
if (typeName == SdfTokens->AnyTypeToken){
typeName = TfToken();
}
}
Sdf_FileIOUtility::Write( out, indent, "%s%s%s ",
Sdf_FileIOUtility::Stringify(spec),
!typeName.IsEmpty() ? " " : "",
!typeName.IsEmpty() ? typeName.GetText() : "" );
Sdf_FileIOUtility::WriteQuotedString( out, 0, prim.GetName().c_str() );
return true;
}
template <class ListOpType>
static bool
Sdf_WriteIfListOp(
Sdf_TextOutput& out, size_t indent,
const TfToken& field, const VtValue& value)
{
if (value.IsHolding<ListOpType>()) {
Sdf_FileIOUtility::WriteListOp(
out, indent, field, value.UncheckedGet<ListOpType>());
return true;
}
return false;
}
static void
Sdf_WriteSimpleField(
Sdf_TextOutput &out, size_t indent,
const SdfSpec& spec, const TfToken& field)
{
const VtValue& value = spec.GetField(field);
if (Sdf_WriteIfListOp<SdfIntListOp>(out, indent, field, value) ||
Sdf_WriteIfListOp<SdfInt64ListOp>(out, indent, field, value) ||
Sdf_WriteIfListOp<SdfUIntListOp>(out, indent, field, value) ||
Sdf_WriteIfListOp<SdfUInt64ListOp>(out, indent, field, value) ||
Sdf_WriteIfListOp<SdfStringListOp>(out, indent, field, value) ||
Sdf_WriteIfListOp<SdfTokenListOp>(out, indent, field, value)) {
return;
}
bool isUnregisteredValue = value.IsHolding<SdfUnregisteredValue>();
if (isUnregisteredValue) {
// The value boxed inside a SdfUnregisteredValue can either be a
// std::string, a VtDictionary, or an SdfUnregisteredValueListOp.
const VtValue &boxedValue = value.Get<SdfUnregisteredValue>().GetValue();
if (boxedValue.IsHolding<SdfUnregisteredValueListOp>()) {
Sdf_FileIOUtility::WriteListOp(
out, indent, field,
boxedValue.UncheckedGet<SdfUnregisteredValueListOp>());
}
else {
Sdf_FileIOUtility::Write(out, indent, "%s = ", field.GetText());
if (boxedValue.IsHolding<VtDictionary>()) {
Sdf_FileIOUtility::WriteDictionary(out, indent, true, boxedValue.Get<VtDictionary>());
}
else if (boxedValue.IsHolding<std::string>()) {
Sdf_FileIOUtility::Write(out, 0, "%s\n", boxedValue.Get<std::string>().c_str());
}
}
return;
}
Sdf_FileIOUtility::Write(out, indent, "%s = ", field.GetText());
if (value.IsHolding<VtDictionary>()) {
Sdf_FileIOUtility::WriteDictionary(out, indent, true, value.Get<VtDictionary>());
}
else if (value.IsHolding<bool>()) {
Sdf_FileIOUtility::Write(out, 0, "%s\n", TfStringify(value.Get<bool>()).c_str());
}
else {
Sdf_FileIOUtility::Write(out, 0, "%s\n", Sdf_FileIOUtility::StringFromVtValue(value).c_str());
}
}
// Predicate for determining fields that should be included in a
// prim's metadata section.
struct Sdf_IsPrimMetadataField : public Sdf_IsMetadataField
{
Sdf_IsPrimMetadataField() : Sdf_IsMetadataField(SdfSpecTypePrim) { }
bool operator()(const TfToken& field) const
{
// Typename is registered as metadata for a prim, but is written
// outside the metadata section.
if (field == SdfFieldKeys->TypeName) {
return false;
}
return (Sdf_IsMetadataField::operator()(field) ||
field == SdfFieldKeys->Payload ||
field == SdfFieldKeys->References ||
field == SdfFieldKeys->Relocates ||
field == SdfFieldKeys->InheritPaths ||
field == SdfFieldKeys->Specializes ||
field == SdfFieldKeys->VariantSetNames ||
field == SdfFieldKeys->VariantSelection);
}
};
static bool
Sdf_WritePrimMetadata(
const SdfPrimSpec &prim, Sdf_TextOutput &out, size_t indent)
{
// Partition this prim's fields so that all fields to write out are
// in the range [fields.begin(), metadataFieldsEnd).
TfTokenVector fields = prim.ListFields();
TfTokenVector::iterator metadataFieldsEnd =
std::partition(fields.begin(), fields.end(), Sdf_IsPrimMetadataField());
// Comment isn't tagged as a metadata field but gets special cased
// because it wants to be at the top of the metadata section.
std::string comment = prim.GetComment();
bool hasComment = !comment.empty();
bool didParens = false;
// As long as there's anything to write in the metadata section, we'll
// always use the multi-line format.
bool multiLine = hasComment || (fields.begin() != metadataFieldsEnd);
// Write comment at the top of the metadata section for readability.
if (hasComment) {
didParens =
Sdf_FileIOUtility::OpenParensIfNeeded(out, didParens, multiLine);
Sdf_FileIOUtility::WriteQuotedString(out, indent+1, comment);
Sdf_FileIOUtility::Puts(out, 0, "\n");
}
// Write out remaining fields in the metadata section in dictionary-sorted
// order.
std::sort(fields.begin(), metadataFieldsEnd, TfDictionaryLessThan());
for (TfTokenVector::const_iterator fieldIt = fields.begin();
fieldIt != metadataFieldsEnd; ++fieldIt) {
didParens =
Sdf_FileIOUtility::OpenParensIfNeeded(out, didParens, multiLine);
const TfToken& field = *fieldIt;
if (field == SdfFieldKeys->Documentation) {
Sdf_FileIOUtility::Puts(out, indent+1, "doc = ");
Sdf_FileIOUtility::WriteQuotedString(out, 0, prim.GetDocumentation());
Sdf_FileIOUtility::Puts(out, 0, "\n");
}
else if (field == SdfFieldKeys->Permission) {
if (multiLine) {
Sdf_FileIOUtility::Write(out, indent+1, "permission = %s\n",
Sdf_FileIOUtility::Stringify(prim.GetPermission()) );
} else {
Sdf_FileIOUtility::Write(out, 0, "permission = %s",
Sdf_FileIOUtility::Stringify(prim.GetPermission()) );
}
}
else if (field == SdfFieldKeys->SymmetryFunction) {
Sdf_FileIOUtility::Write(out, multiLine ? indent+1 : 0, "symmetryFunction = %s%s",
prim.GetSymmetryFunction().GetText(),
multiLine ? "\n" : "");
}
else if (field == SdfFieldKeys->Payload) {
const VtValue v = prim.GetField(field);
if (!Sdf_WriteIfListOp<SdfPayloadListOp>(
out, indent+1, TfToken("payload"), v)) {
TF_CODING_ERROR(
"'%s' field holding unexpected type '%s'",
field.GetText(), v.GetTypeName().c_str());
}
}
else if (field == SdfFieldKeys->References) {
const VtValue v = prim.GetField(field);
if (!Sdf_WriteIfListOp<SdfReferenceListOp>(
out, indent+1, TfToken("references"), v)) {
TF_CODING_ERROR(
"'%s' field holding unexpected type '%s'",
field.GetText(), v.GetTypeName().c_str());
}
}
else if (field == SdfFieldKeys->VariantSetNames) {
SdfVariantSetNamesProxy variantSetNameList = prim.GetVariantSetNameList();
if (variantSetNameList.IsExplicit()) {
// Explicit list
SdfVariantSetNamesProxy::ListProxy setNames = variantSetNameList.GetExplicitItems();
Sdf_FileIOUtility::Puts(out, indent+1, "variantSets = ");
Sdf_FileIOUtility::WriteNameVector(out, indent+1, setNames);
Sdf_FileIOUtility::Puts(out, 0, "\n");
} else {
// List operations
SdfVariantSetNamesProxy::ListProxy setNames = variantSetNameList.GetDeletedItems();
if (!setNames.empty()) {
Sdf_FileIOUtility::Puts(out, indent+1, "delete variantSets = ");
Sdf_FileIOUtility::WriteNameVector(out, indent+1, setNames);
Sdf_FileIOUtility::Puts(out, 0, "\n");
}
setNames = variantSetNameList.GetAddedItems();
if (!setNames.empty()) {
Sdf_FileIOUtility::Puts(out, indent+1, "add variantSets = ");
Sdf_FileIOUtility::WriteNameVector(out, indent+1, setNames);
Sdf_FileIOUtility::Puts(out, 0, "\n");
}
setNames = variantSetNameList.GetPrependedItems();
if (!setNames.empty()) {
Sdf_FileIOUtility::Puts(out, indent+1, "prepend variantSets = ");
Sdf_FileIOUtility::WriteNameVector(out, indent+1, setNames);
Sdf_FileIOUtility::Puts(out, 0, "\n");
}
setNames = variantSetNameList.GetAppendedItems();
if (!setNames.empty()) {
Sdf_FileIOUtility::Puts(out, indent+1, "append variantSets = ");
Sdf_FileIOUtility::WriteNameVector(out, indent+1, setNames);
Sdf_FileIOUtility::Puts(out, 0, "\n");
}
setNames = variantSetNameList.GetOrderedItems();
if (!setNames.empty()) {
Sdf_FileIOUtility::Puts(out, indent+1, "reorder variantSets = ");
Sdf_FileIOUtility::WriteNameVector(out, indent+1, setNames);
Sdf_FileIOUtility::Puts(out, 0, "\n");
}
}
}
else if (field == SdfFieldKeys->InheritPaths) {
const VtValue v = prim.GetField(field);
if (!Sdf_WriteIfListOp<SdfPathListOp>(
out, indent+1, TfToken("inherits"), v)) {
TF_CODING_ERROR(
"'%s' field holding unexpected type '%s'",
field.GetText(), v.GetTypeName().c_str());
}
}
else if (field == SdfFieldKeys->Specializes) {
const VtValue v = prim.GetField(field);
if (!Sdf_WriteIfListOp<SdfPathListOp>(
out, indent+1, TfToken("specializes"), v)) {
TF_CODING_ERROR(
"'%s' field holding unexpected type '%s'",
field.GetText(), v.GetTypeName().c_str());
}
}
else if (field == SdfFieldKeys->Relocates) {
// Relativize all paths in the relocates.
SdfRelocatesMap result;
SdfPath primPath = prim.GetPath();
SdfRelocatesMap finalRelocates;
const SdfRelocatesMapProxy relocates = prim.GetRelocates();
TF_FOR_ALL(mapIt, relocates) {
finalRelocates[mapIt->first.MakeRelativePath(primPath)] =
mapIt->second.MakeRelativePath(primPath);
}
Sdf_FileIOUtility::WriteRelocates(
out, indent+1, multiLine, finalRelocates);
}
else if (field == SdfFieldKeys->PrefixSubstitutions) {
VtDictionary prefixSubstitutions = prim.GetPrefixSubstitutions();
Sdf_FileIOUtility::Puts(out, indent+1, "prefixSubstitutions = ");
Sdf_FileIOUtility::WriteDictionary(out, indent+1, multiLine,
prefixSubstitutions, /* stringValuesOnly = */ true );
}
else if (field == SdfFieldKeys->SuffixSubstitutions) {
VtDictionary suffixSubstitutions = prim.GetSuffixSubstitutions();
Sdf_FileIOUtility::Puts(out, indent+1, "suffixSubstitutions = ");
Sdf_FileIOUtility::WriteDictionary(out, indent+1, multiLine,
suffixSubstitutions, /* stringValuesOnly = */ true );
}
else if (field == SdfFieldKeys->VariantSelection) {
SdfVariantSelectionMap refVariants = prim.GetVariantSelections();
if (refVariants.size() > 0) {
VtDictionary dictionary;
TF_FOR_ALL(it, refVariants) {
dictionary[it->first] = VtValue(it->second);
}
Sdf_FileIOUtility::Puts(out, indent+1, "variants = ");
Sdf_FileIOUtility::WriteDictionary(out, indent+1, multiLine, dictionary);
}
}
else {
Sdf_WriteSimpleField(out, indent+1, prim, field);
}
} // end for each field
Sdf_FileIOUtility::CloseParensIfNeeded(out, indent, didParens, multiLine);
return true;
}
namespace {
struct _SortByNameThenType {
template <class T>
bool operator()(T const &lhs, T const &rhs) const {
// If the names are identical, order by spectype. This puts Attributes
// before Relationships (if identically named).
std::string const &lhsName = lhs->GetName();
std::string const &rhsName = rhs->GetName();
return (lhsName == rhsName && lhs->GetSpecType() < rhs->GetSpecType())
|| TfDictionaryLessThan()(lhsName, rhsName);
}
};
}
static bool
Sdf_WritePrimProperties(
const SdfPrimSpec &prim, Sdf_TextOutput &out, size_t indent)
{
std::vector<SdfPropertySpecHandle> properties =
prim.GetProperties().values_as<std::vector<SdfPropertySpecHandle> >();
std::sort(properties.begin(), properties.end(), _SortByNameThenType());
for (const SdfPropertySpecHandle& specHandle : properties) {
const SdfPropertySpec& spec = specHandle.GetSpec();
const SdfSpecType specType = spec.GetSpecType();
if (specType == SdfSpecTypeAttribute) {
Sdf_WriteAttribute(
Sdf_CastAccess::CastSpec<
SdfAttributeSpec, SdfPropertySpec>(spec),
out, indent+1);
}
else {
Sdf_WriteRelationship(
Sdf_CastAccess::CastSpec<
SdfRelationshipSpec, SdfPropertySpec>(spec),
out, indent+1);
}
}
return true;
}
static bool
Sdf_WritePrimNamespaceReorders(
const SdfPrimSpec &prim, Sdf_TextOutput &out, size_t indent)
{
const std::vector<TfToken>& propertyNames = prim.GetPropertyOrder();
if ( propertyNames.size() > 1 ) {
Sdf_FileIOUtility::Puts( out, indent+1, "reorder properties = " );
Sdf_FileIOUtility::WriteNameVector( out, indent+1, propertyNames );
Sdf_FileIOUtility::Puts( out, 0, "\n" );
}
const std::vector<TfToken>& childrenNames = prim.GetNameChildrenOrder();
if ( childrenNames.size() > 1 ) {
Sdf_FileIOUtility::Puts( out, indent+1, "reorder nameChildren = " );
Sdf_FileIOUtility::WriteNameVector( out, indent+1, childrenNames );
Sdf_FileIOUtility::Puts( out, 0, "\n" );
}
return true;
}
static bool
Sdf_WritePrimChildren(
const SdfPrimSpec &prim, Sdf_TextOutput &out, size_t indent)
{
bool newline = false;
for (const SdfPrimSpecHandle& childPrim : prim.GetNameChildren()) {
if (newline) {
Sdf_FileIOUtility::Puts(out, 0, "\n");
}
else {
newline = true;
}
Sdf_WritePrim(childPrim.GetSpec(), out, indent+1);
}
return true;
}
static bool
Sdf_WritePrimVariantSets(
const SdfPrimSpec &prim, Sdf_TextOutput &out, size_t indent)
{
SdfVariantSetsProxy variantSets = prim.GetVariantSets();
if (variantSets) {
for (const auto& variantNameAndSet : variantSets) {
const SdfVariantSetSpecHandle& vset = variantNameAndSet.second;
Sdf_WriteVariantSet(vset.GetSpec(), out, indent+1);
}
}
return true;
}
static bool
Sdf_WritePrimBody(
const SdfPrimSpec &prim, Sdf_TextOutput &out, size_t indent)
{
Sdf_WritePrimNamespaceReorders( prim, out, indent );
Sdf_WritePrimProperties( prim, out, indent );
if (!prim.GetProperties().empty() && !prim.GetNameChildren().empty())
Sdf_FileIOUtility::Puts(out, 0, "\n");
Sdf_WritePrimChildren( prim, out, indent );
Sdf_WritePrimVariantSets( prim, out, indent );
return true;
}
static inline bool
Sdf_WritePrim(
const SdfPrimSpec &prim, Sdf_TextOutput &out, size_t indent)
{
Sdf_WritePrimPreamble( prim, out, indent );
Sdf_WritePrimMetadata( prim, out, indent );
Sdf_FileIOUtility::Puts(out, 0, "\n");
Sdf_FileIOUtility::Puts(out, indent, "{\n");
Sdf_WritePrimBody( prim, out, indent );
Sdf_FileIOUtility::Puts(out, indent, "}\n");
return true;
}
static bool
Sdf_WriteVariant(
const SdfVariantSpec &variantSpec, Sdf_TextOutput &out, size_t indent)
{
SdfPrimSpec primSpec = variantSpec.GetPrimSpec().GetSpec();
Sdf_FileIOUtility::WriteQuotedString(out, indent, variantSpec.GetName());
Sdf_WritePrimMetadata( primSpec, out, indent );
Sdf_FileIOUtility::Write(out, 0, " {\n");
Sdf_WritePrimBody( primSpec, out, indent );
Sdf_FileIOUtility::Write(out, 0, "\n");
Sdf_FileIOUtility::Write(out, indent, "}\n");
return true;
}
static bool
Sdf_WriteVariantSet(
const SdfVariantSetSpec &spec, Sdf_TextOutput &out, size_t indent)
{
SdfVariantSpecHandleVector variants = spec.GetVariantList();
std::sort(
variants.begin(), variants.end(),
[](const SdfVariantSpecHandle& a, const SdfVariantSpecHandle& b) {
return a->GetName() < b->GetName();
});
if (!variants.empty()) {
Sdf_FileIOUtility::Write(out, indent, "variantSet ");
Sdf_FileIOUtility::WriteQuotedString(out, 0, spec.GetName());
Sdf_FileIOUtility::Write(out, 0, " = {\n");
for (const SdfVariantSpecHandle& v : variants) {
Sdf_WriteVariant(v.GetSpec(), out, indent+1);
}
Sdf_FileIOUtility::Write(out, indent, "}\n");
}
return true;
}
static bool
Sdf_WriteConnectionStatement(
Sdf_TextOutput &out,
size_t indent, const SdfConnectionsProxy::ListProxy &connections,
const std::string &opStr,
const std::string &variabilityStr,
const std::string &typeStr, const std::string &nameStr,
const SdfAttributeSpec* attrOwner)
{
Sdf_FileIOUtility::Write(out, indent, "%s%s%s %s.connect = ",
opStr.c_str(),
variabilityStr.c_str(),
typeStr.c_str(), nameStr.c_str());
if (connections.size() == 0) {
Sdf_FileIOUtility::Puts(out, 0, "None\n");
}
else if (connections.size() == 1) {
Sdf_FileIOUtility::WriteSdfPath(out, 0, connections.front());
Sdf_FileIOUtility::Puts(out, 0, "\n");
}
else {
Sdf_FileIOUtility::Puts(out, 0, "[\n");
TF_FOR_ALL(it, connections) {
Sdf_FileIOUtility::WriteSdfPath(out, indent+1, (*it));
Sdf_FileIOUtility::Puts(out, 0, ",\n");
}
Sdf_FileIOUtility::Puts(out, indent, "]\n");
}
return true;
}
static bool
Sdf_WriteConnectionList(
Sdf_TextOutput &out,
size_t indent, const SdfConnectionsProxy &connList,
const std::string &variabilityStr,
const std::string &typeStr, const std::string &nameStr,
const SdfAttributeSpec *attrOwner)
{
if (connList.IsExplicit()) {
SdfConnectionsProxy::ListProxy vec = connList.GetExplicitItems();
Sdf_WriteConnectionStatement(out, indent, vec, "",
variabilityStr,
typeStr, nameStr, attrOwner);
} else {
SdfConnectionsProxy::ListProxy vec = connList.GetDeletedItems();
if (!vec.empty()) {
Sdf_WriteConnectionStatement(out, indent, vec, "delete ",
variabilityStr, typeStr, nameStr,
NULL);
}
vec = connList.GetAddedItems();
if (!vec.empty()) {
Sdf_WriteConnectionStatement(out, indent, vec, "add ",
variabilityStr, typeStr,
nameStr, attrOwner);
}
vec = connList.GetPrependedItems();
if (!vec.empty()) {
Sdf_WriteConnectionStatement(out, indent, vec, "prepend ",
variabilityStr, typeStr,
nameStr, attrOwner);
}
vec = connList.GetAppendedItems();
if (!vec.empty()) {
Sdf_WriteConnectionStatement(out, indent, vec, "append ",
variabilityStr, typeStr,
nameStr, attrOwner);
}
vec = connList.GetOrderedItems();
if (!vec.empty()) {
Sdf_WriteConnectionStatement(out, indent, vec, "reorder ",
variabilityStr, typeStr, nameStr,
NULL);
}
}
return true;
}
// Predicate for determining fields that should be included in an
// attribute's metadata section.
struct Sdf_IsAttributeMetadataField : public Sdf_IsMetadataField
{
Sdf_IsAttributeMetadataField() : Sdf_IsMetadataField(SdfSpecTypeAttribute)
{ }
bool operator()(const TfToken& field) const
{
return (Sdf_IsMetadataField::operator()(field) ||
field == SdfFieldKeys->DisplayUnit);
}
};
static inline bool
Sdf_WriteAttribute(
const SdfAttributeSpec &attr, Sdf_TextOutput &out, size_t indent)
{
std::string variabilityStr =
Sdf_FileIOUtility::Stringify( attr.GetVariability() );
if (!variabilityStr.empty())
variabilityStr += ' ';
bool hasComment = !attr.GetComment().empty();
bool hasDefault = attr.HasField(SdfFieldKeys->Default);
bool hasCustomDeclaration = attr.IsCustom();
bool hasConnections = attr.HasField(SdfFieldKeys->ConnectionPaths);
bool hasTimeSamples = attr.HasField(SdfFieldKeys->TimeSamples);
std::string typeName =
SdfValueTypeNames->GetSerializationName(attr.GetTypeName()).GetString();
// Partition this attribute's fields so that all fields to write in the
// metadata section are in the range [fields.begin(), metadataFieldsEnd).
TfTokenVector fields = attr.ListFields();
TfTokenVector::iterator metadataFieldsEnd = std::partition(
fields.begin(), fields.end(), Sdf_IsAttributeMetadataField());
// As long as there's anything to write in the metadata section, we'll
// always use the multi-line format.
bool hasInfo = hasComment || (fields.begin() != metadataFieldsEnd);
bool multiLine = hasInfo;
bool didParens = false;
// Write the basic line if we have info or a default or if we
// have nothing else to write.
if (hasInfo || hasDefault || hasCustomDeclaration ||
(!hasConnections && !hasTimeSamples))
{
VtValue value;
if(hasDefault)
value = attr.GetDefaultValue();
Sdf_FileIOUtility::Write( out, indent, "%s%s%s %s",
(hasCustomDeclaration ? "custom " : ""),
variabilityStr.c_str(),
typeName.c_str(),
attr.GetName().c_str() );
// If we have a default value, write it...
if (!value.IsEmpty()) {
Sdf_FileIOUtility::WriteDefaultValue(out, indent, value);
}
// Write comment at the top of the metadata section for readability.
if (hasComment) {
didParens = Sdf_FileIOUtility::OpenParensIfNeeded(out, didParens, multiLine);
Sdf_FileIOUtility::WriteQuotedString(out, indent+1, attr.GetComment());
Sdf_FileIOUtility::Puts(out, 0, "\n");
}
// Write out remaining fields in the metadata section in
// dictionary-sorted order.
std::sort(fields.begin(), metadataFieldsEnd, TfDictionaryLessThan());
for (TfTokenVector::const_iterator fieldIt = fields.begin();
fieldIt != metadataFieldsEnd; ++fieldIt) {
didParens =
Sdf_FileIOUtility::OpenParensIfNeeded(out, didParens, multiLine);
const TfToken& field = *fieldIt;
if (field == SdfFieldKeys->Documentation) {
Sdf_FileIOUtility::Puts(out, indent+1, "doc = ");
Sdf_FileIOUtility::WriteQuotedString(out, 0, attr.GetDocumentation());
Sdf_FileIOUtility::Puts(out, 0, "\n");
}
else if (field == SdfFieldKeys->Permission) {
Sdf_FileIOUtility::Write(out, multiLine ? indent+1 : 0, "permission = %s%s",
Sdf_FileIOUtility::Stringify(attr.GetPermission()),
multiLine ? "\n" : "");
}
else if (field == SdfFieldKeys->SymmetryFunction) {
Sdf_FileIOUtility::Write(out, multiLine ? indent+1 : 0, "symmetryFunction = %s%s",
attr.GetSymmetryFunction().GetText(),
multiLine ? "\n" : "");
}
else if (field == SdfFieldKeys->DisplayUnit) {
Sdf_FileIOUtility::Write(out, multiLine ? indent+1 : 0, "displayUnit = %s%s",
SdfGetNameForUnit(attr.GetDisplayUnit()).c_str(),
multiLine ? "\n" : "");
}
else {
Sdf_WriteSimpleField(out, indent+1, attr, field);
}
} // end for each field
Sdf_FileIOUtility::CloseParensIfNeeded(out, indent, didParens, multiLine);
Sdf_FileIOUtility::Puts(out, 0, "\n");
}
if (hasTimeSamples) {
Sdf_FileIOUtility::Write(out, indent, "%s%s %s.timeSamples = {\n",
variabilityStr.c_str(),
typeName.c_str(), attr.GetName().c_str() );
Sdf_FileIOUtility::WriteTimeSamples(out, indent, attr);
Sdf_FileIOUtility::Puts(out, indent, "}\n");
}
if (hasConnections) {
Sdf_WriteConnectionList(out, indent, attr.GetConnectionPathList(),
variabilityStr, typeName,
attr.GetName(), &attr);
}
return true;
}
enum Sdf_WriteFlag {
Sdf_WriteFlagDefault = 0,
Sdf_WriteFlagAttributes = 1,
Sdf_WriteFlagNoLastNewline = 2,
};
inline Sdf_WriteFlag operator |(Sdf_WriteFlag a, Sdf_WriteFlag b)
{
return (Sdf_WriteFlag)(static_cast<int>(a) | static_cast<int>(b));
}
static bool
Sdf_WriteRelationshipTargetList(
const SdfRelationshipSpec &rel,
const SdfTargetsProxy::ListProxy &targetPaths,
Sdf_TextOutput &out, size_t indent, Sdf_WriteFlag flags)
{
if (targetPaths.size() > 1) {
Sdf_FileIOUtility::Write(out, 0," = [\n");
++indent;
} else {
Sdf_FileIOUtility::Write(out, 0," = ");
}
for (size_t i=0; i < targetPaths.size(); ++i) {
if (targetPaths.size() > 1) {
Sdf_FileIOUtility::Write(out, indent, "");
}
Sdf_FileIOUtility::WriteSdfPath( out, 0, targetPaths[i] );
if (targetPaths.size() > 1) {
Sdf_FileIOUtility::Write(out, 0,",\n");
}
}
if (targetPaths.size() > 1) {
--indent;
Sdf_FileIOUtility::Write(out, indent, "]");
}
if (!(flags & Sdf_WriteFlagNoLastNewline)) {
Sdf_FileIOUtility::Write(out, 0,"\n");
}
return true;
}
// Predicate for determining fields that should be included in an
// relationship's metadata section.
struct Sdf_IsRelationshipMetadataField : public Sdf_IsMetadataField
{
Sdf_IsRelationshipMetadataField()
: Sdf_IsMetadataField(SdfSpecTypeRelationship) { }
bool operator()(const TfToken& field) const
{
return Sdf_IsMetadataField::operator()(field);
}
};
static inline bool
Sdf_WriteRelationship(
const SdfRelationshipSpec &rel, Sdf_TextOutput &out, size_t indent)
{
// When a new metadata field is added to the spec, it will be automatically
// written out generically, so you probably don't need to add a special case
// here. If you need to special-case the output of a metadata field, you will
// also need to prevent the automatic output by adding the token inside
// Sdf_GetGenericRelationshipMetadataFields().
//
// These special cases below were all kept to prevent reordering in existing
// Pixar files, which would create noise in file diffs.
bool hasComment = !rel.GetComment().empty();
bool hasTargets = rel.HasField(SdfFieldKeys->TargetPaths);
bool hasDefaultValue = rel.HasField(SdfFieldKeys->Default);
bool hasTimeSamples = rel.HasField(SdfFieldKeys->TimeSamples);
bool hasCustom = rel.IsCustom();
// Partition this attribute's fields so that all fields to write in the
// metadata section are in the range [fields.begin(), metadataFieldsEnd).
TfTokenVector fields = rel.ListFields();
TfTokenVector::iterator metadataFieldsEnd = std::partition(
fields.begin(), fields.end(), Sdf_IsRelationshipMetadataField());
bool hasInfo = hasComment || (fields.begin() != metadataFieldsEnd);
bool multiLine = hasInfo;
bool didParens = false;
bool hasExplicitTargets = false;
bool hasTargetListOps = false;
if (hasTargets) {
SdfTargetsProxy targetPathList = rel.GetTargetPathList();
hasExplicitTargets = targetPathList.IsExplicit() &&
targetPathList.HasKeys();
hasTargetListOps = !targetPathList.IsExplicit() &&
targetPathList.HasKeys();
}
// If relationship is a varying relationship, use varying keyword.
bool isVarying = (rel.GetVariability() == SdfVariabilityVarying);
std::string varyingStr = isVarying ? "varying " : ""; // the space in "varying " is required...
// Write the basic line if we have info or a default (i.e. explicit