forked from PixarAnimationStudios/OpenUSD
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlayer.cpp
4702 lines (4085 loc) · 146 KB
/
layer.cpp
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.
//
///
/// \file Sdf/layer.cpp
#include "pxr/pxr.h"
#include "pxr/usd/sdf/layer.h"
#include "pxr/usd/sdf/assetPathResolver.h"
#include "pxr/usd/sdf/attributeSpec.h"
#include "pxr/usd/sdf/changeBlock.h"
#include "pxr/usd/sdf/changeManager.h"
#include "pxr/usd/sdf/childrenPolicies.h"
#include "pxr/usd/sdf/childrenUtils.h"
#include "pxr/usd/sdf/debugCodes.h"
#include "pxr/usd/sdf/fileFormat.h"
#include "pxr/usd/sdf/layerRegistry.h"
#include "pxr/usd/sdf/layerStateDelegate.h"
#include "pxr/usd/sdf/layerUtils.h"
#include "pxr/usd/sdf/notice.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/specType.h"
#include "pxr/usd/sdf/textFileFormat.h"
#include "pxr/usd/sdf/types.h"
#include "pxr/usd/sdf/subLayerListEditor.h"
#include "pxr/usd/sdf/variantSetSpec.h"
#include "pxr/usd/sdf/variantSpec.h"
#include "pxr/usd/ar/resolver.h"
#include "pxr/usd/ar/resolverContextBinder.h"
#include "pxr/base/arch/fileSystem.h"
#include "pxr/base/arch/errno.h"
#include "pxr/base/trace/trace.h"
#include "pxr/base/tf/debug.h"
#include "pxr/base/tf/envSetting.h"
#include "pxr/base/tf/fileUtils.h"
#include "pxr/base/tf/iterator.h"
#include "pxr/base/tf/mallocTag.h"
#include "pxr/base/tf/ostreamMethods.h"
#include "pxr/base/tf/pathUtils.h"
#include "pxr/base/tf/pyLock.h"
#include "pxr/base/tf/scopeDescription.h"
#include "pxr/base/tf/staticData.h"
#include "pxr/base/tf/stackTrace.h"
#include <tbb/queuing_rw_mutex.h>
#include <atomic>
#include <functional>
#include <fstream>
#include <iostream>
#include <set>
#include <thread>
#include <vector>
using std::map;
using std::set;
using std::string;
using std::vector;
namespace ph = std::placeholders;
PXR_NAMESPACE_OPEN_SCOPE
TF_REGISTRY_FUNCTION(TfType)
{
TfType::Define<SdfLayer>();
}
// Muted Layers stores the paths of layers that should be muted. The stored
// paths should be asset paths, when applicable, or identifiers if no asset
// path exists for the desired layers.
typedef set<string> _MutedLayers;
typedef std::map<std::string, SdfAbstractDataRefPtr> _MutedLayerDataMap;
static TfStaticData<_MutedLayers> _mutedLayers;
static TfStaticData<_MutedLayerDataMap> _mutedLayerData;
// Global mutex protecting _mutedLayers and _mutedLayerData
static TfStaticData<std::mutex> _mutedLayersMutex;
// This is a global revision number that tracks changes to _mutedLayers. Since
// we seldom mute and unmute layers, this lets layers cache their muteness and
// do quick validity checks without taking a lock and looking themselves up in
// _mutedLayers.
static std::atomic_size_t _mutedLayersRevision { 1 };
// A registry for loaded layers.
static TfStaticData<Sdf_LayerRegistry> _layerRegistry;
// Global mutex protecting _layerRegistry.
static tbb::queuing_rw_mutex &
_GetLayerRegistryMutex() {
static tbb::queuing_rw_mutex mutex;
return mutex;
}
TF_DEFINE_ENV_SETTING(
SDF_LAYER_VALIDATE_AUTHORING, false,
"If enabled, layers will validate new fields and specs being authored "
"against their schema. If the field or spec is not defined in the schema "
"a coding error will be issued and the authoring operation will fail.");
SdfLayer::SdfLayer(
const SdfFileFormatConstPtr &fileFormat,
const string &identifier,
const string &realPath,
const ArAssetInfo& assetInfo,
const FileFormatArguments &args,
bool validateAuthoring)
: _self(this)
, _fileFormat(fileFormat)
, _fileFormatArgs(args)
, _idRegistry(SdfLayerHandle(this))
, _data(fileFormat->InitData(args))
, _stateDelegate(SdfSimpleLayerStateDelegate::New())
, _lastDirtyState(false)
, _assetInfo(new Sdf_AssetInfo)
, _mutedLayersRevisionCache(0)
, _isMutedCache(false)
, _permissionToEdit(true)
, _permissionToSave(true)
, _validateAuthoring(
validateAuthoring || TfGetEnvSetting<bool>(SDF_LAYER_VALIDATE_AUTHORING))
, _hints{/*.mightHaveRelocates =*/ false}
{
TF_DEBUG(SDF_LAYER).Msg("SdfLayer::SdfLayer('%s', '%s')\n",
identifier.c_str(), realPath.c_str());
// If the identifier has the anonymous layer identifier prefix, it is a
// template into which the layer address must be inserted. This ensures
// that anonymous layers have unique identifiers, and can be referenced by
// Sd object reprs.
string layerIdentifier = Sdf_IsAnonLayerIdentifier(identifier) ?
Sdf_ComputeAnonLayerIdentifier(identifier, this) : identifier;
// Indicate that this layer's initialization is not yet complete before we
// publish this object (i.e. add it to the registry in
// _InitializeFromIdentifier). This ensures that other threads looking for
// this layer will block until it is fully initialized.
_initializationComplete = false;
// Initialize layer asset information.
_InitializeFromIdentifier(
layerIdentifier, realPath, std::string(), assetInfo);
// A new layer is not dirty.
_MarkCurrentStateAsClean();
}
SdfLayer::~SdfLayer()
{
TF_DEBUG(SDF_LAYER).Msg(
"SdfLayer::~SdfLayer('%s')\n", GetIdentifier().c_str());
if (IsMuted()) {
std::string mutedPath = _GetMutedPath();
SdfAbstractDataRefPtr mutedData;
{
std::lock_guard<std::mutex> lock(*_mutedLayersMutex);
// Drop any in-memory edits we may have been holding for this layer.
// To minimize time holding the lock, swap the data out and
// erase the entry, then release the lock before proceeding
// to drop the refcount.
_MutedLayerDataMap::iterator i = _mutedLayerData->find(mutedPath);
if (i != _mutedLayerData->end()) {
std::swap(mutedData, i->second);
_mutedLayerData->erase(i);
}
}
}
tbb::queuing_rw_mutex::scoped_lock lock(_GetLayerRegistryMutex());
// Note that FindOrOpen may have already removed this layer from
// the registry, so we count on this API not emitting errors in that
// case.
_layerRegistry->Erase(_self);
}
const SdfFileFormatConstPtr&
SdfLayer::GetFileFormat() const
{
return _fileFormat;
}
const SdfLayer::FileFormatArguments&
SdfLayer::GetFileFormatArguments() const
{
return _fileFormatArgs;
}
SdfLayerRefPtr
SdfLayer::_CreateNewWithFormat(
const SdfFileFormatConstPtr &fileFormat,
const string& identifier,
const string& realPath,
const ArAssetInfo& assetInfo,
const FileFormatArguments& args)
{
// This method should be called with the layerRegistryMutex already held.
// Create and return a new layer with _initializationComplete set false.
return fileFormat->NewLayer(
fileFormat, identifier, realPath, assetInfo, args);
}
void
SdfLayer::_FinishInitialization(bool success)
{
_initializationWasSuccessful = success;
_initializationComplete = true; // unblock waiters.
}
bool
SdfLayer::_WaitForInitializationAndCheckIfSuccessful()
{
// Note: the caller is responsible for holding a reference to this
// layer, to keep it from being destroyed out from under us while
// blocked on the mutex.
// Drop the GIL in case we might have it -- if the layer load happening in
// another thread needs the GIL, we'd deadlock here.
TF_PY_ALLOW_THREADS_IN_SCOPE();
// Wait until _initializationComplete is set to true. If the layer is still
// being initialized, this will be false, blocking progress until
// initialization completes.
while (!_initializationComplete) {
std::this_thread::yield();
}
// For various reasons, initialization may have failed.
// For example, the menva parser may have hit a syntax error,
// or transferring content from a source layer may have failed.
// In this case _initializationWasSuccessful will be set to false.
// The callers of this method are responsible for checking the result
// and dropping any references they hold. As a convenience to them,
// we return the value here.
return _initializationWasSuccessful.get();
}
// For the given layer, gets a dictionary of resolved external asset dependency
// paths to the timestamp for each asset.
static VtDictionary
_GetExternalAssetModificationTimes(const SdfLayer& layer)
{
VtDictionary result;
std::set<std::string> externalAssetDependencies =
layer.GetExternalAssetDependencies();
for (const std::string& resolvedPath : externalAssetDependencies) {
// Get the modification timestamp for the path. Note that external
// asset dependencies only returns resolved paths so pass the same
// path for both params.
result[resolvedPath] = ArGetResolver().GetModificationTimestamp(
resolvedPath, ArResolvedPath(resolvedPath));
}
return result;
}
SdfLayerRefPtr
SdfLayer::CreateAnonymous(
const string& tag, const FileFormatArguments& args)
{
SdfFileFormatConstPtr fileFormat;
string suffix = TfStringGetSuffix(tag);
if (!suffix.empty()) {
fileFormat = SdfFileFormat::FindByExtension(suffix, args);
}
if (!fileFormat) {
fileFormat = SdfFileFormat::FindById(SdfTextFileFormatTokens->Id);
}
if (!fileFormat) {
TF_CODING_ERROR("Cannot determine file format for anonymous SdfLayer");
return SdfLayerRefPtr();
}
return _CreateAnonymousWithFormat(fileFormat, tag, args);
}
SdfLayerRefPtr
SdfLayer::CreateAnonymous(
const string &tag, const SdfFileFormatConstPtr &format,
const FileFormatArguments &args)
{
if (!format) {
TF_CODING_ERROR("Invalid file format for anonymous SdfLayer");
return SdfLayerRefPtr();
}
return _CreateAnonymousWithFormat(format, tag, args);
}
SdfLayerRefPtr
SdfLayer::_CreateAnonymousWithFormat(
const SdfFileFormatConstPtr &fileFormat, const std::string& tag,
const FileFormatArguments &args)
{
if (fileFormat->IsPackage()) {
TF_CODING_ERROR("Cannot create anonymous layer: creating package %s "
"layer is not allowed through this API.",
fileFormat->GetFormatId().GetText());
return SdfLayerRefPtr();
}
tbb::queuing_rw_mutex::scoped_lock lock(_GetLayerRegistryMutex());
SdfLayerRefPtr layer =
_CreateNewWithFormat(
fileFormat, Sdf_GetAnonLayerIdentifierTemplate(tag),
string(), ArAssetInfo(), args);
// No layer initialization required, so initialization is complete.
layer->_FinishInitialization(/* success = */ true);
return layer;
}
bool
SdfLayer::IsAnonymous() const
{
return Sdf_IsAnonLayerIdentifier(GetIdentifier());
}
bool
SdfLayer::IsAnonymousLayerIdentifier(const string& identifier)
{
return Sdf_IsAnonLayerIdentifier(identifier);
}
string
SdfLayer::GetDisplayNameFromIdentifier(const string& identifier)
{
return Sdf_GetLayerDisplayName(identifier);
}
SdfLayerRefPtr
SdfLayer::CreateNew(
const string& identifier,
const FileFormatArguments &args)
{
TF_DEBUG(SDF_LAYER).Msg(
"SdfLayer::CreateNew('%s', '%s')\n",
identifier.c_str(), TfStringify(args).c_str());
return _CreateNew(TfNullPtr, identifier, args);
}
SdfLayerRefPtr
SdfLayer::CreateNew(
const SdfFileFormatConstPtr& fileFormat,
const string& identifier,
const FileFormatArguments &args)
{
TF_DEBUG(SDF_LAYER).Msg(
"SdfLayer::CreateNew('%s', '%s', '%s')\n",
fileFormat->GetFormatId().GetText(),
identifier.c_str(), TfStringify(args).c_str());
return _CreateNew(fileFormat, identifier, args);
}
SdfLayerRefPtr
SdfLayer::_CreateNew(
SdfFileFormatConstPtr fileFormat,
const string& identifier,
const FileFormatArguments &args)
{
string whyNot;
if (!Sdf_CanCreateNewLayerWithIdentifier(identifier, &whyNot)) {
TF_CODING_ERROR("Cannot create new layer '%s': %s",
identifier.c_str(),
whyNot.c_str());
return TfNullPtr;
}
ArResolver& resolver = ArGetResolver();
ArAssetInfo assetInfo;
#if AR_VERSION == 1
// When creating a new layer, assume that relative identifiers are
// relative to the current working directory.
const bool isRelativePath = resolver.IsRelativePath(identifier);
const string absIdentifier =
isRelativePath ? TfAbsPath(identifier) : identifier;
// Direct newly created layers to a local path.
const string localPath = resolver.ComputeLocalPath(absIdentifier);
#else
string absIdentifier, localPath;
{
TfErrorMark m;
absIdentifier = resolver.CreateIdentifierForNewAsset(identifier);
// Resolve the identifier to the path where new assets should go.
localPath = resolver.ResolveForNewAsset(absIdentifier);
if (!m.IsClean()) {
std::vector<std::string> errors;
for (const TfError& error : m) {
errors.push_back(error.GetCommentary());
}
whyNot = TfStringJoin(errors, ", ");
m.Clear();
}
}
#endif
if (localPath.empty()) {
TF_CODING_ERROR(
"Cannot create new layer '%s': %s",
absIdentifier.c_str(),
(whyNot.empty() ? "failed to compute path for new layer"
: whyNot.c_str()));
return TfNullPtr;
}
// If not explicitly supplied one, try to determine the fileFormat
// based on the local path suffix,
if (!fileFormat) {
fileFormat = SdfFileFormat::FindByExtension(localPath, args);
// XXX: This should be a coding error, not a failed verify.
if (!TF_VERIFY(fileFormat))
return TfNullPtr;
}
// Restrict creating package layers via the Sdf API. These layers
// are expected to be created via other libraries or external programs.
if (Sdf_IsPackageOrPackagedLayer(fileFormat, identifier)) {
TF_CODING_ERROR("Cannot create new layer '%s': creating %s %s "
"layer is not allowed through this API.",
identifier.c_str(),
fileFormat->IsPackage() ? "package" : "packaged",
fileFormat->GetFormatId().GetText());
return TfNullPtr;
}
// In case of failure below, we want to release the layer
// registry mutex lock before destroying the layer.
SdfLayerRefPtr layer;
{
tbb::queuing_rw_mutex::scoped_lock lock(_GetLayerRegistryMutex());
// Check for existing layer with this identifier.
if (_layerRegistry->Find(absIdentifier)) {
TF_CODING_ERROR("A layer already exists with identifier '%s'",
absIdentifier.c_str());
return TfNullPtr;
}
layer = _CreateNewWithFormat(
fileFormat, absIdentifier, localPath, ArAssetInfo(), args);
if (!TF_VERIFY(layer)) {
return TfNullPtr;
}
// Stash away the existing layer hints. The call to _Save below will
// invalidate them but they should still be good.
SdfLayerHints hints = layer->_hints;
// XXX 2011-08-19 Newly created layers should not be
// saved to disk automatically.
//
// Force the save here to ensure this new layer overwrites any
// existing layer on disk.
if (!layer->_Save(/* force = */ true)) {
// Dropping the layer reference will destroy it, and
// the destructor will remove it from the registry.
return TfNullPtr;
}
layer->_hints = hints;
// Once we have saved the layer, initialization is complete.
layer->_FinishInitialization(/* success = */ true);
}
// Return loaded layer or special-cased in-memory layer.
return layer;
}
SdfLayerRefPtr
SdfLayer::New(
const SdfFileFormatConstPtr& fileFormat,
const string& identifier,
const FileFormatArguments& args)
{
if (!fileFormat) {
TF_CODING_ERROR("Invalid file format");
return TfNullPtr;
}
if (identifier.empty()) {
TF_CODING_ERROR("Cannot construct a layer with an empty identifier.");
return TfNullPtr;
}
if (Sdf_IsPackageOrPackagedLayer(fileFormat, identifier)) {
TF_CODING_ERROR("Cannot construct new %s %s layer",
fileFormat->IsPackage() ? "package" : "packaged",
fileFormat->GetFormatId().GetText());
return TfNullPtr;
}
tbb::queuing_rw_mutex::scoped_lock lock(_GetLayerRegistryMutex());
#if AR_VERSION == 1
// When creating a new layer, assume that relative identifiers are
// relative to the current working directory.
const string absIdentifier = ArGetResolver().IsRelativePath(identifier) ?
TfAbsPath(identifier) : identifier;
#else
const string absIdentifier =
ArGetResolver().CreateIdentifierForNewAsset(identifier);
#endif
SdfLayerRefPtr layer = _CreateNewWithFormat(
fileFormat, absIdentifier, std::string(), ArAssetInfo(), args);
// No further initialization required.
layer->_FinishInitialization(/* success = */ true);
return layer;
}
static SdfLayer::FileFormatArguments&
_CanonicalizeFileFormatArguments(const std::string& filePath,
const SdfFileFormatConstPtr& fileFormat,
SdfLayer::FileFormatArguments& args)
{
// Nothing to do if there isn't an associated file format.
// This is expected by _ComputeInfoToFindOrOpenLayer and isn't an error.
if (!fileFormat) {
// XXX:
// Sdf is unable to determine a file format for layers that are created
// without a file extension (which includes anonymous layers). The keys
// for these layers in the registry will never include a 'target'
// argument -- the API doesn't give you a way to do that.
//
// So, if a 'target' is specified here, we want to strip it out
// so Find and FindOrOpen will search the registry and find these
// layers. If we didn't, we would search the registry for an
// identifier with the 'target' arg embedded, and we'd never find
// it.
//
// This is a hack. I think the right thing is to either:
// a) Ensure that a layer's identifier always encodes its file format
// b) Do this target argument stripping in Find / FindOrOpen, find
// the layer, then verify that the layer's target is the one that
// was specified.
//
// These are larger changes that require updating some clients, so
// I don't want to do this yet.
if (Sdf_GetExtension(filePath).empty()) {
args.erase(SdfFileFormatTokens->TargetArg);
}
return args;
}
SdfLayer::FileFormatArguments::iterator targetIt =
args.find(SdfFileFormatTokens->TargetArg);
if (targetIt != args.end()) {
if (fileFormat->IsPrimaryFormatForExtensions()) {
// If the file format plugin being used to open the indicated layer
// is the primary plugin for layers of that type, it means the
// 'target' argument (if any) had no effect and can be stripped
// from the arguments.
args.erase(targetIt);
}
else {
// The target argument may have been a comma-delimited list of
// targets to use. The canonical arguments should contain just
// the target for the file format for this layer so that subsequent
// lookups using the same target return the same layer. For example,
// a layer opened with target="x" and target="x,y" should return
// the same layer.
targetIt->second = fileFormat->GetTarget().GetString();
}
}
// If there aren't any more args to canonicalize, we can exit early.
if (args.empty()) {
return args;
}
// Strip out any arguments that match the file format's published
// default arguments. A layer opened without any arguments should
// be considered equivalent to a layer opened with only default
// arguments specified.
const SdfLayer::FileFormatArguments defaultArgs =
fileFormat->GetDefaultFileFormatArguments();
TF_FOR_ALL(it, defaultArgs) {
SdfLayer::FileFormatArguments::iterator argIt = args.find(it->first);
if (argIt != args.end() && argIt->second == it->second) {
args.erase(argIt);
}
}
return args;
}
struct SdfLayer::_FindOrOpenLayerInfo
{
// File format plugin for the layer. This may be NULL if
// the file format could not be identified.
SdfFileFormatConstPtr fileFormat;
// Canonical file format arguments.
SdfLayer::FileFormatArguments fileFormatArgs;
// Whether this layer is anonymous.
bool isAnonymous = false;
// Path to the layer.
string layerPath;
// Resolved path for the layer. If the layer is an anonymous layer,
// this will be the same as layerPath.
string resolvedLayerPath;
// Identifier for the layer, combining both the layer path and
// file format arguments.
string identifier;
// Asset info from resolving the layer path.
ArAssetInfo assetInfo;
};
bool
SdfLayer::_ComputeInfoToFindOrOpenLayer(
const string& identifier,
const SdfLayer::FileFormatArguments& args,
_FindOrOpenLayerInfo* info,
bool computeAssetInfo)
{
TRACE_FUNCTION();
if (identifier.empty()) {
return false;
}
string layerPath;
SdfLayer::FileFormatArguments layerArgs;
if (!Sdf_SplitIdentifier(identifier, &layerPath, &layerArgs) ||
layerPath.empty()) {
return false;
}
const bool isAnonymous = IsAnonymousLayerIdentifier(layerPath);
#if AR_VERSION > 1
if (!isAnonymous) {
layerPath = ArGetResolver().CreateIdentifier(layerPath);
}
#endif
// If we're trying to open an anonymous layer, do not try to compute the
// real path for it.
ArAssetInfo assetInfo;
string resolvedLayerPath = isAnonymous ? layerPath :
Sdf_ResolvePath(layerPath, computeAssetInfo ? &assetInfo : nullptr);
// Merge explicitly-specified arguments over any arguments
// embedded in the given identifier.
if (layerArgs.empty()) {
layerArgs = args;
}
else {
TF_FOR_ALL(it, args) {
layerArgs[it->first] = it->second;
}
}
info->fileFormat = SdfFileFormat::FindByExtension(
resolvedLayerPath.empty() ? layerPath : resolvedLayerPath, layerArgs);
info->fileFormatArgs.swap(_CanonicalizeFileFormatArguments(
layerPath, info->fileFormat, layerArgs));
info->isAnonymous = isAnonymous;
info->layerPath.swap(layerPath);
info->resolvedLayerPath.swap(resolvedLayerPath);
info->identifier = Sdf_CreateIdentifier(
info->layerPath, info->fileFormatArgs);
swap(info->assetInfo, assetInfo);
return true;
}
template <class ScopedLock>
SdfLayerRefPtr
SdfLayer::_TryToFindLayer(const string &identifier,
const string &resolvedPath,
ScopedLock &lock,
bool retryAsWriter)
{
SdfLayerRefPtr result;
bool hasWriteLock = false;
retry:
if (SdfLayerHandle layer = _layerRegistry->Find(identifier, resolvedPath)) {
// We found a layer in the registry -- try to acquire a TfRefPtr to this
// layer. Since we have the lock, we guarantee that the layer's
// TfRefBase will not be destroyed until we unlock.
result = TfCreateRefPtrFromProtectedWeakPtr(layer);
if (result) {
// We got an ownership stake in the layer, release the lock and
// return it.
lock.release();
return result;
}
// We found a layer but we could not get an ownership stake in it -- it
// is expiring. Upgrade the lock to a write lock since we will have to
// try to remove this expiring layer from the registry. If our upgrade
// is non-atomic, we must retry the steps above, since everything
// might've changed in the meantime.
if (!hasWriteLock && !lock.upgrade_to_writer()) {
// We have the write lock, but we released it in the interim, so
// repeat our steps above now that we have the write lock.
hasWriteLock = true;
goto retry;
}
if (layer) {
// Layer is expiring and we have the write lock: erase it from the
// registry.
_layerRegistry->Erase(layer);
}
} else if (!hasWriteLock && retryAsWriter && !lock.upgrade_to_writer()) {
// Retry the find since we released the lock in upgrade_to_writer().
hasWriteLock = true;
goto retry;
}
if (!retryAsWriter)
lock.release();
return result;
}
/* static */
SdfLayerRefPtr
SdfLayer::FindOrOpen(const string &identifier,
const FileFormatArguments &args)
{
TRACE_FUNCTION();
TF_DEBUG(SDF_LAYER).Msg(
"SdfLayer::FindOrOpen('%s', '%s')\n",
identifier.c_str(), TfStringify(args).c_str());
// Drop the GIL, since if we hold it and another thread that has the
// _layerRegistryMutex needs it (if its opening code invokes python, for
// instance), we'll deadlock.
TF_PY_ALLOW_THREADS_IN_SCOPE();
_FindOrOpenLayerInfo layerInfo;
if (!_ComputeInfoToFindOrOpenLayer(identifier, args, &layerInfo,
/* computeAssetInfo = */ true)) {
return TfNullPtr;
}
// First see if this layer is already present.
tbb::queuing_rw_mutex::scoped_lock
lock(_GetLayerRegistryMutex(), /*write=*/false);
if (SdfLayerRefPtr layer =
_TryToFindLayer(layerInfo.identifier, layerInfo.resolvedLayerPath,
lock, /*retryAsWriter=*/true)) {
// This could be written as a ternary, but we rely on return values
// being implicitly moved to avoid making an unnecessary copy of
// layer and the associated ref-count bump.
if (layer->_WaitForInitializationAndCheckIfSuccessful()) {
return layer;
}
return TfNullPtr;
}
// At this point _TryToFindLayer has upgraded lock to a writer.
// Some layers, such as anonymous layers, have identifiers but don't have
// resolved paths. They aren't backed by assets on disk. If we don't find
// such a layer by identifier in the registry and the format doesn't specify
// that anonymous layers should still be read, we're done since we don't
// have an asset to open.
if (layerInfo.isAnonymous) {
if (!layerInfo.fileFormat ||
!layerInfo.fileFormat->ShouldReadAnonymousLayers()) {
return TfNullPtr;
}
}
if (layerInfo.resolvedLayerPath.empty()) {
return TfNullPtr;
}
// Otherwise we create the layer and insert it into the registry.
return _OpenLayerAndUnlockRegistry(lock, layerInfo,
/* metadataOnly */ false);
}
/* static */
SdfLayerRefPtr
SdfLayer::FindOrOpenRelativeToLayer(
const SdfLayerHandle &anchor,
const string &identifier,
const FileFormatArguments &args)
{
TRACE_FUNCTION();
if (!anchor) {
TF_CODING_ERROR("Anchor layer is invalid");
return TfNullPtr;
}
// For consistency with FindOrOpen, we silently bail out if identifier
// is empty here to avoid the coding error that is emitted in that case
// in SdfComputeAssetPathRelativeToLayer.
if (identifier.empty()) {
return TfNullPtr;
}
return FindOrOpen(
SdfComputeAssetPathRelativeToLayer(anchor, identifier), args);
}
/* static */
SdfLayerRefPtr
SdfLayer::OpenAsAnonymous(
const std::string &layerPath,
bool metadataOnly,
const std::string &tag)
{
_FindOrOpenLayerInfo layerInfo;
if (!_ComputeInfoToFindOrOpenLayer(layerPath, FileFormatArguments(),
&layerInfo)) {
return TfNullPtr;
}
// XXX: Is this really a coding error? SdfLayer avoids issuing errors if
// given a non-existent file, for instance. Should we be following the
// same policy here?
if (!layerInfo.fileFormat) {
TF_CODING_ERROR("Cannot determine file format for @%s@",
layerInfo.identifier.c_str());
return TfNullPtr;
}
// Create a new anonymous layer.
SdfLayerRefPtr layer;
{
tbb::queuing_rw_mutex::scoped_lock lock(_GetLayerRegistryMutex());
layer = _CreateNewWithFormat(
layerInfo.fileFormat, Sdf_GetAnonLayerIdentifierTemplate(tag),
string());
// From this point, we must call _FinishInitialization() on
// either success or failure in order to unblock other
// threads waiting for initialization to finish.
}
// Run the file parser to read in the file contents.
if (!layer->_Read(layerInfo.identifier, layerInfo.resolvedLayerPath,
metadataOnly)) {
layer->_FinishInitialization(/* success = */ false);
return TfNullPtr;
}
layer->_MarkCurrentStateAsClean();
layer->_FinishInitialization(/* success = */ true);
return layer;
}
const SdfSchemaBase&
SdfLayer::GetSchema() const
{
return GetFileFormat()->GetSchema();
}
SdfLayer::_ReloadResult
SdfLayer::_Reload(bool force)
{
TRACE_FUNCTION();
string identifier = GetIdentifier();
if (identifier.empty()) {
TF_CODING_ERROR("Can't reload a layer with no identifier");
return _ReloadFailed;
}
const bool isAnonymous = IsAnonymous();
SdfChangeBlock block;
if (isAnonymous && GetFileFormat()->ShouldSkipAnonymousReload()) {
// Different file formats have different policies for reloading
// anonymous layers. Some want to treat it as a noop, others want to
// treat it as 'Clear'.
//
// XXX: in the future, I think we want FileFormat plugins to
// have a Reload function. The plugin can manage when it needs to
// reload data appropriately.
return _ReloadSkipped;
}
else if (IsMuted() ||
(isAnonymous && !GetFileFormat()->ShouldReadAnonymousLayers())) {
// Reloading a muted layer leaves it with the initialized contents.
SdfAbstractDataRefPtr initialData =
GetFileFormat()->InitData(GetFileFormatArguments());
if (_data->Equals(initialData)) {
return _ReloadSkipped;
}
_SetData(initialData);
}
else if (isAnonymous) {
// Ask the current external asset dependency state.
VtDictionary externalAssetTimestamps =
_GetExternalAssetModificationTimes(*this);
// See if we can skip reloading.
if (!force && !IsDirty()
&& (externalAssetTimestamps == _externalAssetModificationTimes)) {
return _ReloadSkipped;
}
std::string resolvedPath;
std::string args;
Sdf_SplitIdentifier(GetIdentifier(), &resolvedPath, &args);
if (!_Read(identifier, resolvedPath, /* metadataOnly = */ false)) {
return _ReloadFailed;
}
_externalAssetModificationTimes = std::move(externalAssetTimestamps);
} else {
// The physical location of the file may have changed since
// the last load, so re-resolve the identifier.
const ArResolvedPath oldResolvedPath = GetResolvedPath();
UpdateAssetInfo();
const ArResolvedPath resolvedPath = GetResolvedPath();
// If asset resolution in UpdateAssetInfo failed, we may end
// up with an empty real path, and cannot reload the layer.
if (resolvedPath.empty()) {
TF_RUNTIME_ERROR(
"Cannot determine resolved path for '%s', skipping reload.",
identifier.c_str());
return _ReloadFailed;
}
// If this layer's modification timestamp is empty, this is a
// new layer that has never been serialized. This could happen
// if a layer were created with SdfLayer::New, for instance.
// In such cases we can skip the reload since there's nowhere
// to reload data from.
//
// This ensures we don't ask for the modification timestamp for
// unserialized new layers below, which would result in errors.
//
// XXX 2014-09-02 Reset layer to initial data?
if (_assetModificationTime.IsEmpty()) {
return _ReloadSkipped;
}
// Get the layer's modification timestamp.
VtValue timestamp = ArGetResolver().GetModificationTimestamp(
GetIdentifier(), resolvedPath);
if (timestamp.IsEmpty()) {
TF_CODING_ERROR(
"Unable to get modification time for '%s (%s)'",
GetIdentifier().c_str(), resolvedPath.GetPathString().c_str());
return _ReloadFailed;
}
// Ask the current external asset dependency state.
VtDictionary externalAssetTimestamps =
_GetExternalAssetModificationTimes(*this);
// See if we can skip reloading.
if (!force && !IsDirty()
&& (resolvedPath == oldResolvedPath)
&& (timestamp == _assetModificationTime)