HDK
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
layer.h
Go to the documentation of this file.
1 //
2 // Copyright 2016 Pixar
3 //
4 // Licensed under the terms set forth in the LICENSE.txt file available at
5 // https://openusd.org/license.
6 //
7 #ifndef PXR_USD_SDF_LAYER_H
8 #define PXR_USD_SDF_LAYER_H
9 
10 /// \file sdf/layer.h
11 
12 #include "pxr/pxr.h"
13 #include "pxr/usd/sdf/api.h"
14 #include "pxr/usd/sdf/data.h"
16 #include "pxr/usd/sdf/identity.h"
17 #include "pxr/usd/sdf/layerHints.h"
20 #include "pxr/usd/sdf/path.h"
21 #include "pxr/usd/sdf/proxyTypes.h"
22 #include "pxr/usd/sdf/spec.h"
23 #include "pxr/usd/sdf/types.h"
24 #include "pxr/usd/ar/ar.h"
25 #include "pxr/usd/ar/assetInfo.h"
28 #include "pxr/base/vt/value.h"
30 
31 #include <atomic>
32 #include <functional>
33 #include <memory>
34 #include <optional>
35 #include <set>
36 #include <string>
37 #include <vector>
38 
40 
43 
44 class SdfChangeList;
45 struct Sdf_AssetInfo;
46 
47 /// \class SdfLayer
48 ///
49 /// A scene description container that can combine with other such containers
50 /// to form simple component assets, and successively larger aggregates. The
51 /// contents of an SdfLayer adhere to the SdfData data model. A layer can be
52 /// ephemeral, or be an asset accessed and serialized through the ArAsset and
53 /// ArResolver interfaces.
54 ///
55 /// The SdfLayer class provides a consistent API for accesing and serializing
56 /// scene description, using any data store provided by Ar plugins. Sdf
57 /// itself provides a UTF-8 text format for layers identified by the ".sdf"
58 /// identifier extension, but via the SdfFileFormat abstraction, allows
59 /// downstream modules and plugins to adapt arbitrary data formats to the
60 /// SdfData/SdfLayer model.
61 ///
62 /// The FindOrOpen() method returns a new SdfLayer object with scene
63 /// description from any supported asset format. Once read, a layer
64 /// remembers which asset it was read from. The Save() method saves the layer
65 /// back out to the original asset. You can use the Export() method to write
66 /// the layer to a different location. You can use the GetIdentifier() method
67 /// to get the layer's Id or GetRealPath() to get the resolved, full URI.
68 ///
69 /// Layer identifiers are UTF-8 encoded strings. A layer's file format is
70 /// determined via the identifier's extension (as resolved by Ar) with [A-Z]
71 /// (and no other characters) explicitly case folded.
72 ///
73 /// Layers can have a timeCode range (startTimeCode and endTimeCode). This range
74 /// represents the suggested playback range, but has no impact on the extent of
75 /// the animation data that may be stored in the layer. The metadatum
76 /// "timeCodesPerSecond" is used to annotate how the time ordinate for samples
77 /// contained in the file scales to seconds. For example, if timeCodesPerSecond
78 /// is 24, then a sample at time ordinate 24 should be viewed exactly one second
79 /// after the sample at time ordinate 0.
80 ///
81 class SdfLayer
82  : public TfRefBase
83  , public TfWeakBase
84 {
85 public:
86  /// Destructor
87  SDF_API
88  virtual ~SdfLayer();
89 
90  /// Noncopyable
91  SdfLayer(const SdfLayer&) = delete;
92  SdfLayer& operator=(const SdfLayer&) = delete;
93 
94  ///
95  /// \name Primary API
96  /// @{
97 
98  /// Returns the schema this layer adheres to. This schema provides details
99  /// about the scene description that may be authored in this layer.
100  SDF_API const SdfSchemaBase& GetSchema() const;
101 
102  /// Returns the file format used by this layer.
103  SDF_API const SdfFileFormatConstPtr& GetFileFormat() const;
104 
105  /// Type for specifying additional file format-specific arguments to
106  /// layer API.
107  typedef std::map<std::string, std::string> FileFormatArguments;
108 
109  /// Returns the file format-specific arguments used during the construction
110  /// of this layer.
112 
113  /// Creates a new empty layer with the given identifier.
114  ///
115  /// Additional arguments may be supplied via the \p args parameter.
116  /// These arguments may control behavior specific to the layer's
117  /// file format.
118  SDF_API
119  static SdfLayerRefPtr CreateNew(const std::string &identifier,
120  const FileFormatArguments &args =
122 
123  /// Creates a new empty layer with the given identifier for a given file
124  /// format class.
125  ///
126  /// This function has the same behavior as the other CreateNew function,
127  /// but uses the explicitly-specified \p fileFormat instead of attempting
128  /// to discern the format from \p identifier.
129  SDF_API
130  static SdfLayerRefPtr CreateNew(const SdfFileFormatConstPtr& fileFormat,
131  const std::string &identifier,
132  const FileFormatArguments &args =
134 
135  /// Creates a new empty layer with the given identifier for a given file
136  /// format class.
137  ///
138  /// The new layer will not be dirty and will not be saved.
139  ///
140  /// Additional arguments may be supplied via the \p args parameter.
141  /// These arguments may control behavior specific to the layer's
142  /// file format.
143  SDF_API
144  static SdfLayerRefPtr New(const SdfFileFormatConstPtr& fileFormat,
145  const std::string &identifier,
146  const FileFormatArguments &args =
148 
149  /// Return an existing layer with the given \p identifier and \p args. If
150  /// the layer can't be found, an error is posted and a null layer is
151  /// returned.
152  ///
153  /// Arguments in \p args will override any arguments specified in
154  /// \p identifier.
155  SDF_API
156  static SdfLayerHandle Find(
157  const std::string &identifier,
159 
160  /// Return an existing layer with the given \p identifier and \p args.
161  /// The given \p identifier will be resolved relative to the \p anchor
162  /// layer. If the layer can't be found, an error is posted and a null
163  /// layer is returned.
164  ///
165  /// If the \p anchor layer is invalid, a coding error is raised, and a null
166  /// handle is returned.
167  ///
168  /// Arguments in \p args will override any arguments specified in
169  /// \p identifier.
170  SDF_API
171  static SdfLayerHandle FindRelativeToLayer(
172  const SdfLayerHandle &anchor,
173  const std::string &identifier,
175 
176  /// Return an existing layer with the given \p identifier and \p args, or
177  /// else load it. If the layer can't be found or loaded, an error is posted
178  /// and a null layer is returned.
179  ///
180  /// Arguments in \p args will override any arguments specified in
181  /// \p identifier.
182  SDF_API
183  static SdfLayerRefPtr FindOrOpen(
184  const std::string &identifier,
186 
187  /// Return an existing layer with the given \p identifier and \p args, or
188  /// else load it. The given \p identifier will be resolved relative to the
189  /// \p anchor layer. If the layer can't be found or loaded, an error is
190  /// posted and a null layer is returned.
191  ///
192  /// If the \p anchor layer is invalid, issues a coding error and returns
193  /// a null handle.
194  ///
195  /// Arguments in \p args will override any arguments specified in
196  /// \p identifier.
197  SDF_API
199  const SdfLayerHandle &anchor,
200  const std::string &identifier,
202 
203  /// Load the given layer from disk as a new anonymous layer. If the
204  /// layer can't be found or loaded, an error is posted and a null
205  /// layer is returned.
206  ///
207  /// The anonymous layer does not retain any knowledge of the backing
208  /// file on the filesystem.
209  ///
210  /// \p metadataOnly is a flag that asks for only the layer metadata
211  /// to be read in, which can be much faster if that is all that is
212  /// required. Note that this is just a hint: some FileFormat readers
213  /// may disregard this flag and still fully populate the layer contents.
214  ///
215  /// An optional \p tag may be specified. See CreateAnonymous for details.
216  SDF_API
218  const std::string &layerPath,
219  bool metadataOnly = false,
220  const std::string& tag = std::string());
221 
222  /// Returns the data from the absolute root path of this layer.
223  SDF_API
224  SdfDataRefPtr GetMetadata() const;
225 
226  /// Return hints about the layer's current contents. Any operation that
227  /// dirties the layer will invalidate all hints.
228  /// \sa SdfLayerHints
229  SDF_API
230  SdfLayerHints GetHints() const;
231 
232  /// Returns handles for all layers currently held by the layer registry.
233  SDF_API
235 
236  /// Returns whether this layer has no significant data.
237  SDF_API
238  bool IsEmpty() const;
239 
240  /// Returns true if this layer streams data from its serialized data
241  /// store on demand, false otherwise.
242  ///
243  /// Layers with streaming data are treated differently to avoid pulling
244  /// in data unnecessarily. For example, reloading a streaming layer
245  /// will not perform fine-grained change notification, since doing
246  /// so would require the full contents of the layer to be loaded.
247  SDF_API
248  bool StreamsData() const;
249 
250  /// Returns true if this layer is detached from its serialized data
251  /// store, false otherwise.
252  ///
253  /// Detached layers are isolated from external changes to their serialized
254  /// data.
255  SDF_API
256  bool IsDetached() const;
257 
258  /// Copies the content of the given layer into this layer.
259  /// Source layer is unmodified.
260  SDF_API
261  void TransferContent(const SdfLayerHandle& layer);
262 
263  /// Creates a new \e anonymous layer with an optional \p tag. An anonymous
264  /// layer is a layer with a system assigned identifier, that cannot be
265  /// saved to disk via Save(). Anonymous layers have an identifier, but no
266  /// real path or other asset information fields.
267  ///
268  /// Anonymous layers may be tagged, which can be done to aid debugging
269  /// subsystems that make use of anonymous layers. The tag becomes the
270  /// display name of an anonymous layer, and is also included in the
271  /// generated identifier. Untagged anonymous layers have an empty display
272  /// name.
273  ///
274  /// Additional arguments may be supplied via the \p args parameter.
275  /// These arguments may control behavior specific to the layer's
276  /// file format.
277  SDF_API
279  const std::string& tag = std::string(),
281 
282  /// Create an anonymous layer with a specific \p format.
283  SDF_API
285  const std::string &tag, const SdfFileFormatConstPtr &format,
287 
288  /// Returns true if this layer is an anonymous layer.
289  SDF_API
290  bool IsAnonymous() const;
291 
292  /// Returns true if the \p identifier is an anonymous layer unique
293  /// identifier.
294  SDF_API
295  static bool IsAnonymousLayerIdentifier(const std::string& identifier);
296 
297  /// Returns the display name for the given \p identifier, using the same
298  /// rules as GetDisplayName.
299  SDF_API
300  static std::string GetDisplayNameFromIdentifier(
301  const std::string& identifier);
302 
303  /// @}
304  /// \name File I/O
305  /// @{
306 
307  /// Returns \c true if successful, \c false if an error occurred.
308  /// Returns \c false if the layer has no remembered file name or the
309  /// layer type cannot be saved. The layer will not be overwritten if the
310  /// file exists and the layer is not dirty unless \p force is true.
311  SDF_API
312  bool Save(bool force = false) const;
313 
314  /// Exports this layer to a file.
315  /// Returns \c true if successful, \c false if an error occurred.
316  ///
317  /// If \p comment is not empty, the layer gets exported with the given
318  /// comment. Additional arguments may be supplied via the \p args parameter.
319  /// These arguments may control behavior specific to the exported layer's
320  /// file format.
321  ///
322  /// Note that the file name or comment of the original layer is not
323  /// updated. This only saves a copy of the layer to the given filename.
324  /// Subsequent calls to Save() will still save the layer to it's
325  /// previously remembered file name.
326  SDF_API
327  bool Export(const std::string& filename,
328  const std::string& comment = std::string(),
329  const FileFormatArguments& args = FileFormatArguments()) const;
330 
331  /// Writes this layer to the given string.
332  ///
333  /// Returns \c true if successful and sets \p result, otherwise
334  /// returns \c false.
335  SDF_API
336  bool ExportToString(std::string* result) const;
337 
338  /// Reads this layer from the given string.
339  ///
340  /// Returns \c true if successful, otherwise returns \c false.
341  SDF_API
342  bool ImportFromString(const std::string &string);
343 
344  /// Clears the layer of all content.
345  ///
346  /// This restores the layer to a state as if it had just been created
347  /// with CreateNew(). This operation is Undo-able.
348  ///
349  /// The fileName and whether journaling is enabled are not affected
350  /// by this method.
351  SDF_API
352  void Clear();
353 
354  /// Reloads the layer from its persistent representation.
355  ///
356  /// This restores the layer to a state as if it had just been created
357  /// with FindOrOpen(). This operation is Undo-able.
358  ///
359  /// The fileName and whether journaling is enabled are not affected
360  /// by this method.
361  ///
362  /// When called with force = false (the default), Reload attempts to
363  /// avoid reloading layers that have not changed on disk. It does so
364  /// by comparing the file's modification time (mtime) to when the
365  /// file was loaded. If the layer has unsaved modifications, this
366  /// mechanism is not used, and the layer is reloaded from disk. If the
367  /// layer has any
368  /// \ref GetExternalAssetDependencies "external asset dependencies"
369  /// their modification state will also be consulted when determining if
370  /// the layer needs to be reloaded.
371  ///
372  /// Passing true to the \p force parameter overrides this behavior,
373  /// forcing the layer to be reloaded from disk regardless of whether
374  /// it has changed.
375  SDF_API
376  bool Reload(bool force = false);
377 
378  /// Reloads the specified layers.
379  ///
380  /// Returns \c false if one or more layers failed to reload.
381  ///
382  /// See \c Reload() for a description of the \p force flag.
383  ///
384  SDF_API
385  static bool ReloadLayers(const std::set<SdfLayerHandle>& layers,
386  bool force = false);
387 
388  /// Imports the content of the given layer path, replacing the content
389  /// of the current layer.
390  /// Note: If the layer path is the same as the current layer's real path,
391  /// no action is taken (and a warning occurs). For this case use
392  /// Reload().
393  SDF_API
394  bool Import(const std::string &layerPath);
395 
396  /// @}
397  /// \name External references
398  /// @{
399 
400  /// \deprecated
401  /// Use GetCompositionAssetDependencies instead.
402  SDF_API
403  std::set<std::string> GetExternalReferences() const;
404 
405  /// \deprecated
406  /// Use UpdateCompositionAssetDependency instead.
407  SDF_API
409  const std::string &oldAssetPath,
410  const std::string &newAssetPath=std::string());
411 
412  /// Return paths of all assets this layer depends on due to composition
413  /// fields.
414  ///
415  /// This includes the paths of all layers referred to by reference,
416  /// payload, and sublayer fields in this layer. This function only returns
417  /// direct composition dependencies of this layer, i.e. it does not recurse
418  /// to find composition dependencies from its dependent layer assets.
419  SDF_API
420  std::set<std::string> GetCompositionAssetDependencies() const;
421 
422  /// Updates the asset path of a composation dependency in this layer.
423  ///
424  /// If \p newAssetPath is supplied, the update works as "rename", updating
425  /// any occurrence of \p oldAssetPath to \p newAssetPath in all reference,
426  /// payload, and sublayer fields.
427  ///
428  /// If \p newAssetPath is not given, this update behaves as a "delete",
429  /// removing all occurrences of \p oldAssetPath from all reference, payload,
430  /// and sublayer fields.
431  SDF_API
433  const std::string &oldAssetPath,
434  const std::string &newAssetPath=std::string());
435 
436  /// Returns a set of resolved paths to all external asset dependencies
437  /// the layer needs to generate its contents. These are additional asset
438  /// dependencies that are determined by the layer's
439  /// \ref SdfFileFormat::GetExternalAssetDependencies "file format" and
440  /// will be consulted during Reload() when determining if the layer needs
441  /// to be reloaded. This specifically does not include dependencies related
442  /// to composition, i.e. this will not include assets from references,
443  /// payloads, and sublayers.
444  SDF_API
445  std::set<std::string> GetExternalAssetDependencies() const;
446 
447  /// @}
448  /// \name Identification
449  ///
450  /// A layer's identifier is a string that uniquely identifies a layer.
451  /// At minimum, it is the string by which the layer was created, either
452  /// via FindOrOpen or CreateNew. If additional arguments were passed
453  /// to those functions, those arguments will be encoded in the identifier.
454  ///
455  /// For example:
456  /// FindOrOpen('foo.sdf', args={'a':'b', 'c':'d'}).identifier
457  /// => "foo.sdf:SDF_FORMAT_ARGS:a=b&c=d"
458  ///
459  /// Note that this means the identifier may in general not be a path.
460  ///
461  /// The identifier format is subject to change; consumers should NOT
462  /// parse layer identifiers themselves, but should use the supplied
463  /// SplitIdentifier and CreateIdentifier helper functions.
464  ///
465  /// @{
466 
467  /// Splits the given layer identifier into its constituent layer path
468  /// and arguments.
469  SDF_API
470  static bool SplitIdentifier(
471  const std::string& identifier,
472  std::string* layerPath,
473  FileFormatArguments* arguments);
474 
475  /// Joins the given layer path and arguments into an identifier.
476  SDF_API
477  static std::string CreateIdentifier(
478  const std::string& layerPath,
479  const FileFormatArguments& arguments);
480 
481  /// Returns the layer identifier.
482  SDF_API
483  const std::string& GetIdentifier() const;
484 
485  /// Sets the layer identifier.
486  /// Note that the new identifier must have the same arguments (if any)
487  /// as the old identifier.
488  SDF_API
489  void SetIdentifier(const std::string& identifier);
490 
491  /// Update layer asset information. Calling this method re-resolves the
492  /// layer identifier, which updates asset information such as the layer's
493  /// resolved path and other asset info. This may be used to update the
494  /// layer after external changes to the underlying asset system.
495  SDF_API
496  void UpdateAssetInfo();
497 
498  /// Returns the layer's display name.
499  ///
500  /// The display name is the base filename of the identifier.
501  SDF_API
502  std::string GetDisplayName() const;
503 
504  /// Returns the resolved path for this layer. This is the path where
505  /// this layer exists or may exist after a call to Save().
506  SDF_API
507  const ArResolvedPath& GetResolvedPath() const;
508 
509  /// Returns the resolved path for this layer. This is equivalent to
510  /// GetResolvedPath().GetPathString().
511  SDF_API
512  const std::string& GetRealPath() const;
513 
514  /// Returns the file extension to use for this layer.
515  /// If this layer was loaded from disk, it should match the extension
516  /// of the file format it was loaded as; if this is an anonymous
517  /// in-memory layer it will be the default extension.
518  SDF_API
519  std::string GetFileExtension() const;
520 
521  /// Returns the asset system version of this layer. If a layer is loaded
522  /// from a location that is not version managed, or a configured asset
523  /// system is not present when the layer is loaded or created, the version
524  /// is empty. By default, asset version tracking is disabled; this method
525  /// returns empty unless asset version tracking is enabled.
526  SDF_API
527  const std::string& GetVersion() const;
528 
529  /// Returns the layer identifier in asset path form. In the presence of a
530  /// properly configured path resolver, the asset path is a double-slash
531  /// prefixed depot path. If the path resolver is not configured, the asset
532  /// path of a layer is empty.
533  SDF_API
534  const std::string& GetRepositoryPath() const;
535 
536  /// Returns the asset name associated with this layer.
537  SDF_API
538  const std::string& GetAssetName() const;
539 
540  /// Returns resolve information from the last time the layer identifier
541  /// was resolved.
542  SDF_API
543  const VtValue& GetAssetInfo() const;
544 
545  /// Returns the path to the asset specified by \p assetPath using this layer
546  /// to anchor the path if necessary. Returns \p assetPath if it's empty or
547  /// an anonymous layer identifier.
548  ///
549  /// This method can be used on asset paths that are authored in this layer
550  /// to create new asset paths that can be copied to other layers. These new
551  /// asset paths should refer to the same assets as the original asset
552  /// paths. For example, if the underlying ArResolver is filesystem-based and
553  /// \p assetPath is a relative filesystem path, this method might return the
554  /// absolute filesystem path using this layer's location as the anchor.
555  ///
556  /// The returned path should in general not be assumed to be an absolute
557  /// filesystem path or any other specific form. It is "absolute" in that it
558  /// should resolve to the same asset regardless of what layer it's authored
559  /// in.
560  SDF_API
561  std::string ComputeAbsolutePath(const std::string& assetPath) const;
562 
563  /// @}
564 
565  /// \name Fields
566  ///
567  /// All scene description for a given object is stored as a set of
568  /// key/value pairs called fields. These methods provide direct access to
569  /// those fields, though most clients should use the Spec API to ensure
570  /// data consistency.
571  ///
572  /// These methods all take SdfPath to identify the queried spec.
573  ///
574  /// @{
575 
576  /// Return the spec type for \a path. This returns SdfSpecTypeUnknown if no
577  /// spec exists at \a path.
578  SDF_API
579  SdfSpecType GetSpecType(const SdfPath& path) const;
580 
581  /// Return whether a spec exists at \a path.
582  SDF_API
583  bool HasSpec(const SdfPath& path) const;
584 
585  /// Return the names of all the fields that are set at \p path.
586  SDF_API
587  std::vector<TfToken> ListFields(const SdfPath& path) const;
588 
589  /// Return whether a value exists for the given \a path and \a fieldName.
590  /// Optionally returns the value if it exists.
591  SDF_API
592  bool HasField(const SdfPath& path, const TfToken& fieldName,
593  VtValue *value=NULL) const;
594  SDF_API
595  bool HasField(const SdfPath& path, const TfToken& fieldName,
596  SdfAbstractDataValue *value) const;
597 
598  /// Returns \c true if the object has a non-empty value with name
599  /// \p name and type \p T. If value ptr is provided, returns the
600  /// value found.
601  template <class T>
602  bool HasField(const SdfPath& path, const TfToken &name,
603  T* value) const
604  {
605  if (!value) {
606  return HasField(path, name, static_cast<VtValue *>(NULL));
607  }
608 
609  SdfAbstractDataTypedValue<T> outValue(value);
610  const bool hasValue = HasField(
611  path, name, static_cast<SdfAbstractDataValue *>(&outValue));
612 
614  return hasValue && outValue.isValueBlock;
615  }
616 
617  return hasValue && (!outValue.isValueBlock);
618  }
619 
620  /// Return the type of the value for \p name on spec \p path. If no such
621  /// field exists, return typeid(void).
622  std::type_info const &GetFieldTypeid(
623  const SdfPath &path, const TfToken &name) const {
624  return _data->GetTypeid(path, name);
625  }
626 
627  /// Return whether a value exists for the given \a path and \a fieldName and
628  /// \a keyPath. The \p keyPath is a ':'-separated path addressing an
629  /// element in sub-dictionaries. Optionally returns the value if it exists.
630  SDF_API
631  bool HasFieldDictKey(const SdfPath& path,
632  const TfToken &fieldName,
633  const TfToken &keyPath,
634  VtValue *value=NULL) const;
635  SDF_API
636  bool HasFieldDictKey(const SdfPath& path,
637  const TfToken &fieldName,
638  const TfToken &keyPath,
639  SdfAbstractDataValue *value) const;
640 
641  /// Returns \c true if the object has a non-empty value with name \p name
642  /// and \p keyPath and type \p T. If value ptr is provided, returns the
643  /// value found. The \p keyPath is a ':'-separated path addressing an
644  /// element in sub-dictionaries.
645  template <class T>
646  bool HasFieldDictKey(const SdfPath& path, const TfToken &name,
647  const TfToken &keyPath, T* value) const
648  {
649  if (!value) {
650  return HasFieldDictKey(path, name, keyPath,
651  static_cast<VtValue *>(NULL));
652  }
653 
654  SdfAbstractDataTypedValue<T> outValue(value);
655  return HasFieldDictKey(path, name, keyPath,
656  static_cast<SdfAbstractDataValue *>(&outValue));
657  }
658 
659 
660  /// Return the value for the given \a path and \a fieldName. Returns an
661  /// empty value if none is set.
662  SDF_API
663  VtValue GetField(const SdfPath& path,
664  const TfToken& fieldName) const;
665 
666  /// Return the value for the given \a path and \a fieldName. Returns the
667  /// provided \a defaultValue value if none is set.
668  template <class T>
669  inline T GetFieldAs(const SdfPath& path,
670  const TfToken& fieldName, const T& defaultValue = T()) const
671  {
672  return _data->GetAs<T>(path, fieldName, defaultValue);
673  }
674 
675  /// Return the value for the given \a path and \a fieldName at \p
676  /// keyPath. Returns an empty value if none is set. The \p keyPath is a
677  /// ':'-separated path addressing an element in sub-dictionaries.
678  SDF_API
680  const TfToken& fieldName,
681  const TfToken& keyPath) const;
682 
683  /// Set the value of the given \a path and \a fieldName.
684  SDF_API
685  void SetField(const SdfPath& path, const TfToken& fieldName,
686  const VtValue& value);
687  SDF_API
688  void SetField(const SdfPath& path, const TfToken& fieldName,
690 
691  /// Set the value of the given \a path and \a fieldName.
692  template <class T>
693  void SetField(const SdfPath& path, const TfToken& fieldName,
694  const T& val)
695  {
696  // Ideally, this would make use of the SdfAbstractDataConstValue
697  // API to avoid unnecessarily copying the value into a VtValue.
698  // However, Sdf needs to create a VtValue for change processing.
699  // If the underlying SdAbstractData implementation also needs a
700  // VtValue, using the SdfAbstractDataConstValue API would cause
701  // another copy to be made. So, it's more efficient to just create
702  // the VtValue once here and push that along.
703  SetField(path, fieldName, VtValue(val));
704  }
705 
706  /// Set the value of the given \a path and \a fieldName. The \p keyPath is a
707  /// ':'-separated path addressing an element in sub-dictionaries.
708  SDF_API
709  void SetFieldDictValueByKey(const SdfPath& path,
710  const TfToken& fieldName,
711  const TfToken& keyPath,
712  const VtValue& value);
713  SDF_API
714  void SetFieldDictValueByKey(const SdfPath& path,
715  const TfToken& fieldName,
716  const TfToken& keyPath,
718 
719  /// Set the value of the given \a path and \a fieldName. The \p keyPath is
720  /// a ':'-separated path addressing an element in sub-dictionaries.
721  template <class T>
722  void SetFieldDictValueByKey(const SdfPath& path,
723  const TfToken& fieldName,
724  const TfToken& keyPath,
725  const T& val)
726  {
727  // Ideally, this would make use of the SdfAbstractDataConstValue
728  // API to avoid unnecessarily copying the value into a VtValue.
729  // However, Sdf needs to create a VtValue for change processing.
730  // If the underlying SdAbstractData implementation also needs
731  // VtValue, using the SdfAbstractDataConstValue API would cause
732  // another copy to be made. So, it's more efficient to just create
733  // the VtValue once here and push that along.
734  SetFieldDictValueByKey(path, fieldName, keyPath, VtValue(val));
735  }
736 
737  /// Remove the field at \p path and \p fieldName, if one exists.
738  SDF_API
739  void EraseField(const SdfPath& path, const TfToken& fieldName);
740 
741  /// Remove the field at \p path and \p fieldName and \p keyPath, if one
742  /// exists. The \p keyPath is a ':'-separated path addressing an
743  /// element in sub-dictionaries.
744  SDF_API
745  void EraseFieldDictValueByKey(const SdfPath& path,
746  const TfToken& fieldName,
747  const TfToken& keyPath);
748 
749  /// \name Traversal
750  /// @{
751 
752  /// Callback function for Traverse. This callback will be invoked with
753  /// the path of each spec that is visited.
754  /// \sa Traverse
755  typedef std::function<void(const SdfPath&)> TraversalFunction;
756 
757  // Traverse will perform a traversal of the scene description hierarchy
758  // rooted at \a path, calling \a func on each spec that it finds.
759  SDF_API
760  void Traverse(const SdfPath& path, const TraversalFunction& func);
761 
762  /// @}
763 
764  /// \name Metadata
765  /// @{
766 
767  /// Returns the color configuration asset-path for this layer.
768  ///
769  /// The default value is an empty asset-path.
770  SDF_API
772 
773  /// Sets the color configuration asset-path for this layer.
774  SDF_API
775  void SetColorConfiguration(const SdfAssetPath &colorConfiguration);
776 
777  /// Returns true if color configuration metadata is set in this layer.
778  /// \sa GetColorConfiguration(), SetColorConfiguration()
779  SDF_API
780  bool HasColorConfiguration() const;
781 
782  /// Clears the color configuration metadata authored in this layer.
783  /// \sa HasColorConfiguration(), SetColorConfiguration()
784  SDF_API
786 
787  /// Returns the color management system used to interpret the color
788  /// configuration asset-path authored in this layer.
789  ///
790  /// The default value is an empty token, which implies that the clients
791  /// will have to determine the color management system from the color
792  /// configuration asset path (i.e. from its file extension), if it's
793  /// specified.
794  SDF_API
796 
797  /// Sets the color management system used to interpret the color
798  /// configuration asset-path authored this layer.
799  SDF_API
800  void SetColorManagementSystem(const TfToken &cms);
801 
802  /// Returns true if colorManagementSystem metadata is set in this layer.
803  /// \sa GetColorManagementSystem(), SetColorManagementSystem()
804  SDF_API
805  bool HasColorManagementSystem() const;
806 
807  /// Clears the 'colorManagementSystem' metadata authored in this layer.
808  /// \sa HascolorManagementSystem(), SetColorManagementSystem()
809  SDF_API
811 
812  /// Returns the comment string for this layer.
813  ///
814  /// The default value for comment is "".
815  SDF_API
816  std::string GetComment() const;
817 
818  /// Sets the comment string for this layer.
819  SDF_API
820  void SetComment(const std::string &comment);
821 
822  /// Return the defaultPrim metadata for this layer. This field
823  /// indicates the name or path of which prim should be targeted by a
824  /// reference or payload to this layer that doesn't specify a prim path.
825  ///
826  /// The default value is the empty token.
827  SDF_API
828  TfToken GetDefaultPrim() const;
829 
830  /// Return this layer's default prim metadata interpreted as an absolute
831  /// prim path regardless of whether it was authored as a root prim name or a
832  /// prim path. For example, if the authored default prim value is
833  /// "rootPrim", return </rootPrim>. If the authored default prim value is
834  /// "/path/to/non/root/prim", return </path/to/non/root/prim>. If the
835  /// authored default prim value cannot be interpreted as a prim path,
836  /// return the empty SdfPath.
837  ///
838  /// The default value is an empty path.
839  SDF_API
841 
842  /// Set the default prim metadata for this layer. The prim at this path
843  /// will be targeted by a reference or a payload to this layer that doesn't
844  /// specify a prim path.
845  /// Note that this can be a name if it refers to a root prim, or a path to
846  /// any prim in this layer. E.g. "rootPrim", "/path/to/non/root/prim" or
847  /// "/rootPrim". See GetDefaultPrim().
848  SDF_API
849  void SetDefaultPrim(const TfToken &name);
850 
851  /// Clear the default prim metadata for this layer. See GetDefaultPrim()
852  /// and SetDefaultPrim().
853  SDF_API
854  void ClearDefaultPrim();
855 
856  /// Return true if the default prim metadata is set in this layer. See
857  /// GetDefaultPrim() and SetDefaultPrim().
858  SDF_API
859  bool HasDefaultPrim();
860 
861  /// Converts the given \p defaultPrim token into a prim path.
862  ///
863  /// If the input token is the string representation of an absolute prim,
864  /// that path is returned. If the token represents a relative prim path, the
865  /// returned path is coverted into a absolute path anchored to the absolute
866  /// root path. If the token does not represent a valid relative or absolute
867  /// prim path, an empty path is returned.
868  SDF_API
869  static SdfPath ConvertDefaultPrimTokenToPath(const TfToken &defaultPrim);
870 
871  /// Converts the path \p primPath into a token value that can be used to
872  /// set the default prim metadata for the layer to refer to the prim at that
873  /// path.
874  ///
875  /// If the given path is a root prim path, the returned token will just be
876  /// the name of the prim. For all other prim paths, this will return the
877  /// absolute path as a string token. If the path is not a prim path, this
878  /// will return an empty token.
879  SDF_API
880  static TfToken ConvertDefaultPrimPathToToken(const SdfPath &primPath);
881 
882  /// Returns the documentation string for this layer.
883  ///
884  /// The default value for documentation is "".
885  SDF_API
886  std::string GetDocumentation() const;
887 
888  /// Sets the documentation string for this layer.
889  SDF_API
890  void SetDocumentation(const std::string &documentation);
891 
892  /// Returns the layer's start timeCode.
893  ///
894  /// The start and end timeCodes of a layer represent the suggested playback
895  /// range. However, time-varying content is not limited to the timeCode range
896  /// of the layer.
897  ///
898  /// The default value for startTimeCode is 0.
899  SDF_API
900  double GetStartTimeCode() const;
901 
902  /// Sets the layer's start timeCode.
903  SDF_API
904  void SetStartTimeCode(double startTimecode);
905 
906  /// Returns true if the layer has a startTimeCode opinion.
907  SDF_API
908  bool HasStartTimeCode() const;
909 
910  /// Clear the startTimeCode opinion.
911  SDF_API
912  void ClearStartTimeCode();
913 
914  /// Returns the layer's end timeCode.
915  /// The start and end timeCode of a layer represent a suggested playback range.
916  /// However, time-varying content is not limited to the timeCode range of the
917  /// layer.
918  ///
919  /// The default value for endTimeCode is 0.
920  SDF_API
921  double GetEndTimeCode() const;
922 
923  /// Sets the layer's end timeCode.
924  SDF_API
925  void SetEndTimeCode(double endTimeCode);
926 
927  /// Returns true if the layer has an endTimeCode opinion.
928  SDF_API
929  bool HasEndTimeCode() const;
930 
931  /// Clear the endTimeCode opinion.
932  SDF_API
933  void ClearEndTimeCode();
934 
935  /// Returns the layer's timeCodes per second.
936  ///
937  /// Scales the time ordinate for samples contained in the file to seconds.
938  /// If timeCodesPerSecond is 24, then a sample at time ordinate 24 should
939  /// be viewed exactly one second after the sample at time ordinate 0.
940  ///
941  /// If this layer doesn't have an authored value for timeCodesPerSecond, but
942  /// it does have an authored value for framesPerSecond, this method will
943  /// return the value of framesPerSecond. This "dynamic fallback" allows
944  /// layers to lock framesPerSecond and timeCodesPerSecond to the same value
945  /// by specifying only framesPerSecond.
946  ///
947  /// The default value of timeCodesPerSecond, used only if there is no
948  /// authored value for either timeCodesPerSecond or framesPerSecond, is 24.
949  SDF_API
950  double GetTimeCodesPerSecond() const;
951 
952  /// Sets the layer's timeCodes per second
953  SDF_API
954  void SetTimeCodesPerSecond(double timeCodesPerSecond);
955 
956  /// Returns true if the layer has a timeCodesPerSecond opinion.
957  SDF_API
958  bool HasTimeCodesPerSecond() const;
959 
960  /// Clear the timeCodesPerSecond opinion.
961  SDF_API
963 
964  /// Returns the layer's frames per second.
965  ///
966  /// This makes an advisory statement about how the contained data can be
967  /// most usefully consumed and presented. It's primarily an indication of
968  /// the expected playback rate for the data, but a timeline editing tool
969  /// might also want to use this to decide how to scale and label its
970  /// timeline.
971  ///
972  /// The default value for framesPerSecond is 24.
973  SDF_API
974  double GetFramesPerSecond() const;
975 
976  /// Sets the layer's frames per second
977  SDF_API
978  void SetFramesPerSecond(double framesPerSecond);
979 
980  /// Returns true if the layer has a frames per second opinion.
981  SDF_API
982  bool HasFramesPerSecond() const;
983 
984  /// Clear the framesPerSecond opinion.
985  SDF_API
986  void ClearFramesPerSecond();
987 
988  /// Returns the layer's frame precision.
989  SDF_API
990  int GetFramePrecision() const;
991 
992  /// Sets the layer's frame precision.
993  SDF_API
994  void SetFramePrecision(int framePrecision);
995 
996  /// Returns true if the layer has a frames precision opinion.
997  SDF_API
998  bool HasFramePrecision() const;
999 
1000  /// Clear the framePrecision opinion.
1001  SDF_API
1002  void ClearFramePrecision();
1003 
1004  /// Returns the layer's owner.
1005  SDF_API
1006  std::string GetOwner() const;
1007 
1008  /// Sets the layer's owner.
1009  SDF_API
1010  void SetOwner(const std::string& owner);
1011 
1012  /// Returns true if the layer has an owner opinion.
1013  SDF_API
1014  bool HasOwner() const;
1015 
1016  /// Clear the owner opinion.
1017  SDF_API
1018  void ClearOwner();
1019 
1020  /// Returns the layer's session owner.
1021  /// Note: This should only be used by session layers.
1022  SDF_API
1023  std::string GetSessionOwner() const;
1024 
1025  /// Sets the layer's session owner.
1026  /// Note: This should only be used by session layers.
1027  SDF_API
1028  void SetSessionOwner(const std::string& owner);
1029 
1030  /// Returns true if the layer has a session owner opinion.
1031  SDF_API
1032  bool HasSessionOwner() const;
1033 
1034  // Clear the session owner opinion.
1035  SDF_API
1036  void ClearSessionOwner();
1037 
1038  /// Returns true if the layer's sublayers are expected to have owners.
1039  SDF_API
1040  bool GetHasOwnedSubLayers() const;
1041 
1042  /// Sets whether the layer's sublayers are expected to have owners.
1043  SDF_API
1044  void SetHasOwnedSubLayers(bool);
1045 
1046  /// Returns the CustomLayerData dictionary associated with this layer.
1047  ///
1048  /// This is a dictionary is custom metadata that is associated with
1049  /// this layer. It allows users to encode any set of information for
1050  /// human or program consumption.
1051  SDF_API
1053 
1054  /// Sets the CustomLayerData dictionary associated with this layer.
1055  SDF_API
1056  void SetCustomLayerData(const VtDictionary& value);
1057 
1058  /// Returns true if CustomLayerData is authored on the layer.
1059  SDF_API
1060  bool HasCustomLayerData() const;
1061 
1062  /// Clears out the CustomLayerData dictionary associated with this layer.
1063  SDF_API
1064  void ClearCustomLayerData();
1065 
1066  /// Returns the expression variables dictionary authored on this layer.
1067  /// See \ref Sdf_Page_VariableExpressions for more details.
1068  SDF_API
1070 
1071  /// Sets the expression variables dictionary for this layer.
1072  SDF_API
1073  void SetExpressionVariables(const VtDictionary& expressionVars);
1074 
1075  /// Returns true if expression variables are authored on this layer.
1076  SDF_API
1077  bool HasExpressionVariables() const;
1078 
1079  /// Clears the expression variables dictionary authored on this layer.
1080  SDF_API
1081  void ClearExpressionVariables();
1082 
1083  /// @}
1084  /// \name Prims
1085  /// @{
1086 
1087  // Type for root prims view.
1089 
1090  /// Returns a vector of the layer's root prims
1091  SDF_API
1092  RootPrimsView GetRootPrims() const;
1093 
1094  /// Sets a new vector of root prims.
1095  /// You can re-order, insert and remove prims but cannot
1096  /// rename them this way. If any of the listed prims have
1097  /// an existing owner, they will be reparented.
1098  SDF_API
1099  void SetRootPrims(const SdfPrimSpecHandleVector &rootPrims);
1100 
1101  /// Adds a new root prim at the given index.
1102  /// If the index is -1, the prim is inserted at the end.
1103  /// The layer will take ownership of the prim, via a TfRefPtr.
1104  /// Returns true if successful, false if failed (for example,
1105  /// due to a duplicate name).
1106  SDF_API
1107  bool InsertRootPrim(const SdfPrimSpecHandle &prim, int index = -1);
1108 
1109  /// Remove a root prim.
1110  SDF_API
1111  void RemoveRootPrim(const SdfPrimSpecHandle &prim);
1112 
1113  /// Cause \p spec to be removed if it no longer affects the scene when the
1114  /// last change block is closed, or now if there are no change blocks.
1115  SDF_API
1116  void ScheduleRemoveIfInert(const SdfSpec& spec);
1117 
1118  /// Removes scene description that does not affect the scene in the
1119  /// layer namespace beginning with \p prim.
1120  ///
1121  /// Calling this method on a prim will only clean up prims with specifier
1122  /// 'over' that are not contributing any opinions. The \p prim will only
1123  /// be removed if all of its nameChildren are also inert. The hierarchy
1124  /// \p prim is defined in will be pruned up to the layer root for each
1125  /// successive inert parent that has specifier 'over'.
1126  ///
1127  /// note: PrimSpecs that contain any PropertySpecs, even PropertySpecs with
1128  /// required fields only (see PropertySpec::HasRequiredFieldsOnly)
1129  /// are not considered inert, and thus the prim won't be removed.
1130  SDF_API
1131  void RemovePrimIfInert(SdfPrimSpecHandle prim);
1132 
1133  /// Removes prop if it has only required fields (i.e. is not
1134  /// contributing any opinions to the scene other than property
1135  /// instantiation).
1136  ///
1137  /// The hierarchy \p prop is defined in will then be pruned up to the
1138  /// layer root for each successive inert parent.
1139  SDF_API
1140  void RemovePropertyIfHasOnlyRequiredFields(SdfPropertySpecHandle prop);
1141 
1142  /// Removes all scene description in this layer that does not affect the
1143  /// scene.
1144  ///
1145  /// This method walks the layer namespace hierarchy and removes any prims
1146  /// and that are not contributing any opinions.
1147  SDF_API
1149 
1150  /// Returns the list of prim names for this layer's reorder rootPrims
1151  /// statement.
1152  ///
1153  /// See SetRootPrimOrder() for more info.
1154  SDF_API
1156 
1157  /// Given a list of (possible sparse) prim names, authors a reorder
1158  /// rootPrims statement for this prim.
1159  ///
1160  /// This reorder statement can modify the order of root prims that have
1161  /// already been explicitly ordered with InsertRootPrim() or SetRootPrims();
1162  /// but only during composition. Therefore, GetRootPrims(),
1163  /// InsertRootPrim(), SetRootPrims(), etc. do not read, author, or pay any
1164  /// attention to this statement.
1165  SDF_API
1166  void SetRootPrimOrder(const std::vector<TfToken>& names);
1167 
1168  /// Adds a new root prim name in the root prim order.
1169  /// If the index is -1, the name is inserted at the end.
1170  SDF_API
1171  void InsertInRootPrimOrder(const TfToken &name, int index = -1);
1172 
1173  /// Removes a root prim name from the root prim order.
1174  SDF_API
1175  void RemoveFromRootPrimOrder(const TfToken & name);
1176 
1177  /// Removes a root prim name from the root prim order by index.
1178  SDF_API
1180 
1181  /// Reorders the given list of prim names according to the reorder rootPrims
1182  /// statement for this layer.
1183  ///
1184  /// This routine employs the standard list editing operations for ordered
1185  /// items in a ListEditor.
1186  SDF_API
1187  void ApplyRootPrimOrder(std::vector<TfToken> *vec) const;
1188 
1189  /// @}
1190  /// \name Sublayers
1191  /// @{
1192 
1193  /// Returns a proxy for this layer's sublayers.
1194  ///
1195  /// Sub-layers are the weaker layers directly included by this layer.
1196  /// They're in order from strongest to weakest and they're all weaker
1197  /// than this layer.
1198  ///
1199  /// Edits through the proxy changes the sublayers. If this layer does
1200  /// not have any sublayers the proxy is empty.
1201  ///
1202  /// Sub-layer paths are asset paths, and thus must contain valid asset path
1203  /// characters (UTF-8 without C0 and C1 controls). See SdfAssetPath for
1204  /// more details.
1205  SDF_API
1207 
1208  /// Sets the paths of the layer's sublayers.
1209  SDF_API
1210  void SetSubLayerPaths(const std::vector<std::string>& newPaths);
1211 
1212  /// Returns the number of sublayer paths (and offsets).
1213  SDF_API
1214  size_t GetNumSubLayerPaths() const;
1215 
1216  /// Inserts new sublayer path at the given index.
1217  ///
1218  /// The default index of -1 means to insert at the end.
1219  SDF_API
1220  void InsertSubLayerPath(const std::string& path, int index = -1);
1221 
1222  /// Removes sublayer path at the given index.
1223  SDF_API
1224  void RemoveSubLayerPath(int index);
1225 
1226  /// Returns the layer offsets for all the subLayer paths.
1227  SDF_API
1229 
1230  /// Returns the layer offset for the subLayer path at the given index.
1231  SDF_API
1233 
1234  /// Sets the layer offset for the subLayer path at the given index.
1235  SDF_API
1236  void SetSubLayerOffset(const SdfLayerOffset& offset, int index);
1237 
1238  /// @}
1239  /// \name Relocates
1240  /// @{
1241 
1242  /// Get the list of relocates specified in this layer's metadata.
1243  ///
1244  /// Each individual relocate in the list is specified as a pair of
1245  /// \c \SdfPath where the first is the source path of the relocate and the
1246  /// second is target path.
1247  ///
1248  /// Note that is NOT a proxy object and cannot be used to edit the field in
1249  /// place.
1250  SDF_API
1251  SdfRelocates GetRelocates() const;
1252 
1253  /// Set the entire list of namespace relocations specified on this layer to
1254  /// \p relocates.
1255  SDF_API
1256  void SetRelocates(const SdfRelocates& relocates);
1257 
1258  /// Returns true if this layer's metadata has any relocates opinion,
1259  /// including that there should be no relocates (i.e. an empty list). An
1260  /// empty list (no relocates) does not mean the same thing as a missing list
1261  /// (no opinion).
1262  SDF_API
1263  bool HasRelocates() const;
1264 
1265  /// Clears the layer relocates opinion in the layer's metadata.
1266  SDF_API
1267  void ClearRelocates();
1268 
1269  /// @}
1270 
1271  /// \name Detached Layers
1272  ///
1273  /// Detached layers are layers that are detached from the serialized
1274  /// data store and isolated from any external changes to that serialized
1275  /// data.
1276  ///
1277  /// File format plugins may produce layers that maintain a persistent
1278  /// connection to their serialized representation to read data on-demand.
1279  /// For example, a file format might set up layers to hold an open file
1280  /// handle and read attribute time samples from it only when requested, to
1281  /// avoid pulling in unnecessary data. However, there may be times when
1282  /// keeping this connection is undesirable. In the previous example, a
1283  /// crash might occur if some other process were to change the file on
1284  /// disk, or users might be prevented from overwriting the file at all
1285  /// which could interfere with workflow.
1286  ///
1287  /// To avoid these problems, the functions below may be used to specify
1288  /// layers that are to be detached from the original serialized data.
1289  ///
1290  /// @{
1291 
1292  /// \class DetachedLayerRules
1293  ///
1294  /// Object used to specify detached layers. Layers may be included or
1295  /// excluded from the detached layer set by specifying simple substring
1296  /// patterns for layer identifiers. For example, the following will
1297  /// include all layers in the detached layer set, except for those whose
1298  /// identifiers contain the substring "sim" or "geom":
1299  ///
1300  /// \code
1301  /// SdfLayer::SetDetachedLayerRules(
1302  /// SdfLayer::DetachedLayerRules()
1303  /// .IncludeAll();
1304  /// .Exclude({"sim", "geom"})
1305  /// );
1306  /// \endcode
1308  {
1309  public:
1310  /// A default constructed rules object Excludes all layers from
1311  /// the detached layer set.
1312  DetachedLayerRules() = default;
1313 
1314  /// Include all layers in the detached layer set.
1316  {
1317  _includeAll = true;
1318  _include.clear();
1319  return *this;
1320  }
1321 
1322  /// Include layers whose identifiers contain any of the strings in
1323  /// \p patterns in the detached layer set.
1324  SDF_API
1325  DetachedLayerRules& Include(const std::vector<std::string>& patterns);
1326 
1327  /// Exclude layers whose identifiers contain any of the strings in
1328  /// \p patterns from the detached layer set.
1329  SDF_API
1330  DetachedLayerRules& Exclude(const std::vector<std::string>& patterns);
1331 
1332  bool IncludedAll() const { return _includeAll; }
1333  const std::vector<std::string>& GetIncluded() const { return _include; }
1334  const std::vector<std::string>& GetExcluded() const { return _exclude; }
1335 
1336  /// Returns true if \p identifier is included in the detached layer set,
1337  /// false otherwise.
1338  ///
1339  /// \p identifier is included if it matches an include pattern (or the
1340  /// mask includes all identifiers) and it does not match any of the
1341  /// exclude patterns. Anonymous layer identifiers are always excluded
1342  /// from the mask.
1343  SDF_API
1344  bool IsIncluded(const std::string& identifier) const;
1345 
1346  private:
1347  friend class SdfLayer;
1348 
1349  std::vector<std::string> _include;
1350  std::vector<std::string> _exclude;
1351  bool _includeAll = false;
1352  };
1353 
1354  /// Sets the rules specifying detached layers.
1355  ///
1356  /// Newly-created or opened layers whose identifiers are included in
1357  /// \p rules will be opened as detached layers. Existing layers that are now
1358  /// included or no longer included will be reloaded. Any unsaved
1359  /// modifications to those layers will be lost.
1360  ///
1361  /// This function is not thread-safe. It may not be run concurrently with
1362  /// any other functions that open, close, or read from any layers.
1363  ///
1364  /// The detached layer rules are initially set to exclude all layers.
1365  /// This may be overridden by setting the environment variables
1366  /// SDF_LAYER_INCLUDE_DETACHED and SDF_LAYER_EXCLUDE_DETACHED to specify
1367  /// the initial set of include and exclude patterns in the rules. These
1368  /// variables can be set to a comma-delimited list of patterns.
1369  /// SDF_LAYER_INCLUDE_DETACHED may also be set to "*" to include
1370  /// all layers. Note that these environment variables only set the initial
1371  /// state of the detached layer rules; these values may be overwritten by
1372  /// subsequent calls to this function.
1373  ///
1374  /// See SdfLayer::DetachedLayerRules::IsIncluded for details on how the
1375  /// rules are applied to layer identifiers.
1376  SDF_API
1377  static void SetDetachedLayerRules(const DetachedLayerRules& mask);
1378 
1379  /// Returns the current rules for the detached layer set.
1380  SDF_API
1381  static const DetachedLayerRules& GetDetachedLayerRules();
1382 
1383  /// Returns whether the given layer identifier is included in the
1384  /// current rules for the detached layer set. This is equivalent to
1385  /// GetDetachedLayerRules().IsIncluded(identifier).
1386  SDF_API
1387  static bool IsIncludedByDetachedLayerRules(const std::string& identifier);
1388 
1389  /// @}
1390 
1391  /// \name Muting
1392  /// @{
1393 
1394  /// Returns the set of muted layer paths.
1395  SDF_API
1396  static std::set<std::string> GetMutedLayers();
1397 
1398  /// Returns \c true if the current layer is muted.
1399  SDF_API
1400  bool IsMuted() const;
1401 
1402  /// Returns \c true if the specified layer path is muted.
1403  SDF_API
1404  static bool IsMuted(const std::string &path);
1405 
1406  /// Mutes the current layer if \p muted is \c true, and unmutes it
1407  /// otherwise.
1408  SDF_API
1409  void SetMuted(bool muted);
1410 
1411  /// Add the specified path to the muted layers set.
1412  SDF_API
1413  static void AddToMutedLayers(const std::string &mutedPath);
1414 
1415  /// Remove the specified path from the muted layers set.
1416  SDF_API
1417  static void RemoveFromMutedLayers(const std::string &mutedPath);
1418 
1419  /// @}
1420  /// \name Lookup
1421  /// @{
1422 
1423  /// Returns the layer's pseudo-root prim.
1424  ///
1425  /// The layer's root prims are namespace children of the pseudo-root.
1426  /// The pseudo-root exists to make the namespace hierarchy a tree
1427  /// instead of a forest. This simplifies the implementation of
1428  /// some algorithms.
1429  ///
1430  /// A layer always has a pseudo-root prim.
1431  SDF_API
1432  SdfPrimSpecHandle GetPseudoRoot() const;
1433 
1434  /// Returns the object at the given \p path.
1435  ///
1436  /// There is no distinction between an absolute and relative path
1437  /// at the SdLayer level.
1438  ///
1439  /// Returns \c NULL if there is no object at \p path.
1440  SDF_API
1441  SdfSpecHandle GetObjectAtPath(const SdfPath &path);
1442 
1443  /// Returns the prim at the given \p path.
1444  ///
1445  /// Returns \c NULL if there is no prim at \p path.
1446  /// This is simply a more specifically typed version of
1447  /// \c GetObjectAtPath().
1448  SDF_API
1449  SdfPrimSpecHandle GetPrimAtPath(const SdfPath &path);
1450 
1451  /// Returns a property at the given \p path.
1452  ///
1453  /// Returns \c NULL if there is no property at \p path.
1454  /// This is simply a more specifically typed version of
1455  /// \c GetObjectAtPath().
1456  SDF_API
1457  SdfPropertySpecHandle GetPropertyAtPath(const SdfPath &path);
1458 
1459  /// Returns an attribute at the given \p path.
1460  ///
1461  /// Returns \c NULL if there is no attribute at \p path.
1462  /// This is simply a more specifically typed version of
1463  /// \c GetObjectAtPath().
1464  SDF_API
1465  SdfAttributeSpecHandle GetAttributeAtPath(const SdfPath &path);
1466 
1467  /// Returns a relationship at the given \p path.
1468  ///
1469  /// Returns \c NULL if there is no relationship at \p path.
1470  /// This is simply a more specifically typed version of
1471  /// \c GetObjectAtPath().
1472  SDF_API
1473  SdfRelationshipSpecHandle GetRelationshipAtPath(const SdfPath &path);
1474 
1475  /// @}
1476  /// \name Permissions
1477  /// @{
1478 
1479  /// Returns true if the caller is allowed to modify the layer and
1480  /// false otherwise. A layer may have to perform some action to acquire
1481  /// permission to be edited.
1482  SDF_API
1483  bool PermissionToEdit() const;
1484 
1485  /// Returns true if the caller is allowed to save the layer to its
1486  /// existing fileName and false otherwise.
1487  SDF_API
1488  bool PermissionToSave() const;
1489 
1490  /// Sets permission to edit.
1491  SDF_API
1492  void SetPermissionToEdit(bool allow);
1493 
1494  /// Sets permission to save.
1495  SDF_API
1496  void SetPermissionToSave(bool allow);
1497 
1498  /// @}
1499  /// \name Batch namespace editing
1500  /// @{
1501 
1502  /// Check if a batch of namespace edits will succeed. This returns
1503  /// \c SdfNamespaceEditDetail::Okay if they will succeed as a batch,
1504  /// \c SdfNamespaceEditDetail::Unbatched if the edits will succeed but
1505  /// will be applied unbatched, and \c SdfNamespaceEditDetail::Error
1506  /// if they will not succeed. No edits will be performed in any case.
1507  ///
1508  /// If \p details is not \c NULL and the method does not return \c Okay
1509  /// then details about the problems will be appended to \p details. A
1510  /// problem may cause the method to return early, so \p details may not
1511  /// list every problem.
1512  ///
1513  /// Note that Sdf does not track backpointers so it's unable to fix up
1514  /// targets/connections to namespace edited objects. Clients must fix
1515  /// those to prevent them from falling off. In addition, this method
1516  /// will report failure if any relational attribute with a target to
1517  /// a namespace edited object is subsequently edited (in the same
1518  /// batch). Clients should perform edits on relational attributes
1519  /// first.
1520  ///
1521  /// Clients may wish to report unbatch details to the user to confirm
1522  /// that the edits should be applied unbatched. This will give the
1523  /// user a chance to correct any problems that cause batching to fail
1524  /// and try again.
1525  SDF_API
1528  SdfNamespaceEditDetailVector* details = NULL) const;
1529 
1530  /// Performs a batch of namespace edits. Returns \c true on success
1531  /// and \c false on failure. On failure, no namespace edits will have
1532  /// occurred.
1533  SDF_API
1534  bool Apply(const SdfBatchNamespaceEdit&);
1535 
1536  /// @}
1537  /// \name Layer state
1538  /// @{
1539 
1540  /// Returns the state delegate used to manage this layer's authoring
1541  /// state.
1542  SDF_API
1543  SdfLayerStateDelegateBasePtr GetStateDelegate() const;
1544 
1545  /// Sets the state delegate used to manage this layer's authoring
1546  /// state. The 'dirty' state of this layer will be transferred to
1547  /// the new delegate.
1548  SDF_API
1549  void SetStateDelegate(const SdfLayerStateDelegateBaseRefPtr& delegate);
1550 
1551  /// Returns \c true if the layer is dirty, i.e. has changed from
1552  /// its persistent representation.
1553  SDF_API
1554  bool IsDirty() const;
1555 
1556  /// @}
1557 
1558  /// \name Time-sample API
1559  /// @{
1560  SDF_API
1561  std::set<double> ListAllTimeSamples() const;
1562 
1563  SDF_API
1564  std::set<double>
1565  ListTimeSamplesForPath(const SdfPath& path) const;
1566 
1567  SDF_API
1568  bool GetBracketingTimeSamples(double time, double* tLower, double* tUpper);
1569 
1570  SDF_API
1571  size_t GetNumTimeSamplesForPath(const SdfPath& path) const;
1572 
1573  SDF_API
1574  bool GetBracketingTimeSamplesForPath(const SdfPath& path,
1575  double time,
1576  double* tLower, double* tUpper) const;
1577 
1578  /// Returns the previous time sample authored just before the querying \p
1579  /// time.
1580  ///
1581  /// If there is no time sample authored just before \p time, this function
1582  /// returns false. Otherwise, it returns true and sets \p tPrevious to the
1583  /// time of the previous sample.
1584  SDF_API
1585  bool GetPreviousTimeSampleForPath(const SdfPath& path, double time,
1586  double* tPrevious) const;
1587 
1588  SDF_API
1589  bool QueryTimeSample(const SdfPath& path, double time,
1590  VtValue *value=NULL) const;
1591 
1592  SDF_API
1593  bool QueryTimeSample(const SdfPath& path, double time,
1594  SdfAbstractDataValue *value) const;
1595 
1596  template <class T>
1597  bool QueryTimeSample(const SdfPath& path, double time,
1598  T* data) const
1599  {
1600  if (!data) {
1601  return QueryTimeSample(path, time);
1602  }
1603 
1604  SdfAbstractDataTypedValue<T> outValue(data);
1605  const bool hasValue = QueryTimeSample(
1606  path, time, static_cast<SdfAbstractDataValue *>(&outValue));
1607 
1609  return hasValue && outValue.isValueBlock;
1610  }
1611 
1612  return hasValue && (!outValue.isValueBlock);
1613  }
1614 
1615  SDF_API
1616  void SetTimeSample(const SdfPath& path, double time,
1617  const VtValue & value);
1618 
1619  SDF_API
1620  void SetTimeSample(const SdfPath& path, double time,
1622 
1623  template <class T>
1624  void SetTimeSample(const SdfPath& path, double time,
1625  const T& value)
1626  {
1627  const SdfAbstractDataConstTypedValue<T> inValue(&value);
1628  const SdfAbstractDataConstValue& untypedInValue = inValue;
1629  return SetTimeSample(path, time, untypedInValue);
1630  }
1631 
1632  SDF_API
1633  void EraseTimeSample(const SdfPath& path, double time);
1634 
1635  /// @}
1636 
1637  // Debugging
1638  // @{
1639 
1640  SDF_API
1641  static void DumpLayerInfo();
1642 
1643  // Write this layer's SdfData to a file in a simple generic format.
1644  SDF_API
1645  bool WriteDataFile(const std::string &filename);
1646 
1647  // @}
1648 
1649  /// Returns a \ref SdfChangeList containing the minimal edits that would be
1650  /// needed to transform this layer to match the contents of the given
1651  /// \p layer parameter. If \p processPropertyFields is false, property
1652  /// fields will be ignored during the diff computation. Any differences in
1653  /// fields between properties with the same path in this layer and \p layer
1654  /// will not be captured in the returned SdfChangeList. This can, however,
1655  /// avoid potentially expensive data retrieval operations.
1656  SDF_API
1658  const SdfLayerHandle& layer,
1659  bool processPropertyFields = true) const;
1660 
1661 protected:
1662  // Private constructor -- use New(), FindOrCreate(), etc.
1663  // Precondition: _layerRegistryMutex must be locked.
1664  SdfLayer(const SdfFileFormatConstPtr& fileFormat,
1665  const std::string &identifier,
1666  const std::string &realPath = std::string(),
1667  const ArAssetInfo& assetInfo = ArAssetInfo(),
1669  bool validateAuthoring = false);
1670 
1671 private:
1672  // Create a new layer.
1673  // Precondition: _layerRegistryMutex must be locked.
1674  static SdfLayerRefPtr _CreateNew(
1675  SdfFileFormatConstPtr fileFormat,
1676  const std::string& identifier,
1677  const FileFormatArguments& args,
1678  bool saveLayer = true);
1679 
1680  static SdfLayerRefPtr _CreateNewWithFormat(
1681  const SdfFileFormatConstPtr &fileFormat,
1682  const std::string& identifier,
1683  const std::string& realPath,
1684  const ArAssetInfo& assetInfo = ArAssetInfo(),
1686 
1687  static SdfLayerRefPtr _CreateAnonymousWithFormat(
1688  const SdfFileFormatConstPtr &fileFormat,
1689  const std::string& tag,
1690  const FileFormatArguments& args);
1691 
1692  // Finish initializing this layer (which may have succeeded or not)
1693  // and publish the results to other threads by unlocking the mutex.
1694  // Sets _initializationWasSuccessful.
1695  void _FinishInitialization(bool success);
1696 
1697  // Layers retrieved from the layer registry may still be in the
1698  // process of having their contents initialized. Other threads
1699  // retrieving layers from the registry must wait until initialization
1700  // is complete, using this method.
1701  // Returns _initializationWasSuccessful.
1702  //
1703  // Callers *must* be holding an SdfLayerRefPtr to this layer to
1704  // ensure that it is not deleted out from under them, in
1705  // case initialization fails. (This method cannot acquire the
1706  // reference itself internally without being susceptible to a race.)
1707  bool _WaitForInitializationAndCheckIfSuccessful();
1708 
1709  // Returns whether or not this layer should post change
1710  // notification. This simply returns (!_GetIsLoading())
1711  bool _ShouldNotify() const;
1712 
1713  // This function keeps track of the last state of IsDirty() before
1714  // updating it. It returns false if the last saved dirty state is the
1715  // same than the current state. It returns true if the state differs and
1716  // will update the 'last dirty state' to the current state. So, after
1717  // returning true, it would return false for subsequent calls until the
1718  // IsDirty() state would change again...
1719  bool _UpdateLastDirtinessState() const;
1720 
1721  // Returns a handle to the spec at the given path if it exists and matches
1722  // type T.
1723  template <class T>
1724  SdfHandle<T> _GetSpecAtPath(const SdfPath& path);
1725 
1726  // Returns true if a spec can be retrieved at the given path, false
1727  // otherwise. This function will return the canonicalized path to the
1728  // spec as well as the spec type.
1729  bool _CanGetSpecAtPath(const SdfPath& path,
1730  SdfPath* canonicalPath, SdfSpecType* specType) const;
1731 
1732  /// Initialize layer internals that are based on it's path.
1733  /// This includes the asset path and show path the layer to be loaded
1734  /// reflects at the point of initialization.
1735  void _InitializeFromIdentifier(
1736  const std::string &identifier,
1737  const std::string &realPath = std::string(),
1738  const std::string &fileVersion = std::string(),
1739  const ArAssetInfo& assetInfo = ArAssetInfo());
1740 
1741  // Helper for computing the necessary information to lookup a layer
1742  // in the registry or open the layer.
1743  struct _FindOrOpenLayerInfo;
1744  static bool _ComputeInfoToFindOrOpenLayer(
1745  const std::string& identifier,
1747  _FindOrOpenLayerInfo* info,
1748  bool computeAssetInfo = false);
1749 
1750  // Open a layer, adding an entry to the registry and releasing
1751  // the registry lock.
1752  // Precondition: _layerRegistryMutex must be locked.
1753  template <class Lock>
1754  static SdfLayerRefPtr _OpenLayerAndUnlockRegistry(
1755  Lock &lock,
1756  const _FindOrOpenLayerInfo& info,
1757  bool metadataOnly);
1758 
1759  // Helper function for finding a layer with \p identifier and \p args.
1760  // \p lock must be unlocked initially and will be locked by this
1761  // function when needed. See docs for \p retryAsWriter argument on
1762  // _TryToFindLayer for details on the final state of the lock when
1763  // this function returns.
1764  template <class ScopedLock>
1765  static SdfLayerRefPtr
1766  _Find(const std::string &identifier,
1767  const FileFormatArguments &args,
1768  ScopedLock &lock, bool retryAsWriter);
1769 
1770  // Helper function to try to find the layer with \p identifier and
1771  // pre-resolved path \p resolvedPath in the registry. Caller must hold
1772  // registry \p lock for reading. If \p retryAsWriter is false, lock is
1773  // released upon return. Otherwise the lock is released upon return if a
1774  // layer is found successfully. If no layer is found then the lock is
1775  // upgraded to a writer lock upon return. Note that this upgrade may not be
1776  // atomic, but this function ensures that if upon return there does not
1777  // exist a matching layer in the registry.
1778  template <class ScopedLock>
1779  static SdfLayerRefPtr
1780  _TryToFindLayer(const std::string &identifier,
1781  const ArResolvedPath &resolvedPath,
1782  ScopedLock &lock, bool retryAsWriter);
1783 
1784  /// Returns true if the spec at the specified path has no effect on the
1785  /// scene.
1786  ///
1787  /// If ignoreChildren is true, this will ignore prim and property
1788  /// children of prim specs. Property specs are always considered to be
1789  /// non-inert unless they have only required fields and
1790  /// requiredFieldOnlyPropertiesareInert is set to false.
1791  bool _IsInert(const SdfPath &path, bool ignoreChildren,
1792  bool requiredFieldOnlyPropertiesAreInert = false) const;
1793 
1794  /// Return true if the entire subtree rooted at \a path does not affect the
1795  /// scene. For this purpose, property specs that have only required fields
1796  /// are considered inert.
1797  bool _IsInertSubtree(const SdfPath &path) const;
1798 
1799  /// Cause \p spec to be removed if it does not affect the scene. This
1800  /// removes any empty descendants before checking if \p spec itself is
1801  /// inert. Property specs are always considered non-inert, so this will
1802  /// remove them if they have only required fields (see
1803  /// PropertySpec::HasOnlyRequiredFields). This also removes inert ancestors.
1804  void _RemoveIfInert(const SdfSpec& spec);
1805 
1806  /// Performs a depth first search of the namespace hierarchy, beginning at
1807  /// \p prim, removing prims that do not affect the scene. The return value
1808  /// indicates whether the prim passed in is now inert as a result of this
1809  /// call, and can itself be removed.
1810  bool _RemoveInertDFS(SdfPrimSpecHandle prim);
1811 
1812  /// If \p prim is inert (has no affect on the scene), removes prim, then
1813  /// prunes inert parent prims back to the root.
1814  void _RemoveInertToRootmost(SdfPrimSpecHandle prim);
1815 
1816  /// Returns whether this layer is validating authoring operations.
1817  bool _ValidateAuthoring() const { return _validateAuthoring; }
1818 
1819  /// Returns the path used in the muted layers set.
1820  std::string _GetMutedPath() const;
1821 
1822  // If old and new asset path is given, rename all external prim
1823  // composition dependency referring to the old path.
1824  void _UpdatePrimCompositionDependencyPaths(
1825  const SdfPrimSpecHandle &parent,
1826  const std::string &oldLayerPath,
1827  const std::string &newLayerPath);
1828 
1829  // Set the clean state to the current state.
1830  void _MarkCurrentStateAsClean() const;
1831 
1832  // Return the field definition for \p fieldName if \p fieldName is a
1833  // required field for the spec type identified by \p path.
1834  inline SdfSchema::FieldDefinition const *
1835  _GetRequiredFieldDef(const SdfPath &path,
1836  const TfToken &fieldName,
1837  SdfSpecType specType = SdfSpecTypeUnknown) const;
1838 
1839  // Return the field definition for \p fieldName if \p fieldName is a
1840  // required field for \p specType subject to \p schema.
1841  static inline SdfSchema::FieldDefinition const *
1842  _GetRequiredFieldDef(const SdfSchemaBase &schema,
1843  const TfToken &fieldName,
1844  SdfSpecType specType);
1845 
1846  // Helper to list all fields on \p data at \p path subject to \p schema.
1847  static std::vector<TfToken>
1848  _ListFields(SdfSchemaBase const &schema,
1849  SdfAbstractData const &data, const SdfPath& path);
1850 
1851  // Helper for HasField for \p path in \p data subject to \p schema.
1852  static inline bool
1853  _HasField(const SdfSchemaBase &schema,
1854  const SdfAbstractData &data,
1855  const SdfPath& path,
1856  const TfToken& fieldName,
1857  VtValue *value);
1858 
1859  // Helper to get a field value for \p path in \p data subject to \p schema.
1860  static inline VtValue
1861  _GetField(const SdfSchemaBase &schema,
1862  const SdfAbstractData &data,
1863  const SdfPath& path,
1864  const TfToken& fieldName);
1865 
1866  // Set a value.
1867  template <class T>
1868  void _SetValue(const TfToken& key, T value);
1869 
1870  // Get a value.
1871  template <class T>
1872  T _GetValue(const TfToken& key) const;
1873 
1874  enum _ReloadResult { _ReloadFailed, _ReloadSucceeded, _ReloadSkipped };
1875  _ReloadResult _Reload(bool force);
1876 
1877  // Reads contents of asset specified by \p identifier with resolved
1878  // path \p resolvedPath into this layer.
1879  bool _Read(const std::string& identifier,
1880  const ArResolvedPath& resolvedPath,
1881  bool metadataOnly);
1882 
1883  // Saves this layer if it is dirty or the layer doesn't already exist
1884  // on disk. If \p force is true, the layer will be written out
1885  // regardless of those conditions.
1886  bool _Save(bool force) const;
1887 
1888  // A helper method used by Save and Export.
1889  // This method allows Save to specify the existing file format and Export
1890  // to use the format provided by the file extension in newFileName. If no
1891  // file format can be discovered from the file name, the existing file
1892  // format associated with the layer will be used in both cases. This allows
1893  // users to export and save to any file name, regardless of extension.
1894  bool _WriteToFile(const std::string& newFileName,
1895  const std::string& comment,
1896  SdfFileFormatConstPtr fileFormat,
1897  const FileFormatArguments& args) const;
1898 
1899  // Swap contents of _data and data. This operation does not register
1900  // inverses or emit change notification.
1901  void _SwapData(SdfAbstractDataRefPtr &data);
1902 
1903  // Set _data to \p newData and send coarse DidReplaceLayerContent
1904  // invalidation notice.
1905  void _AdoptData(const SdfAbstractDataRefPtr &newData);
1906 
1907  // Helper function which will process incoming data to this layer in a
1908  // generic way.
1909  // If \p processPropertyFields is false, this method will not
1910  // consider property spec fields. In some cases, this can avoid expensive
1911  // operations which would pull large amounts of data.
1912  template<typename DeleteSpecFunc, typename CreateSpecFunc,
1913  typename GetFieldValuesFunc, typename SetFieldFunc, typename ErrorFunc>
1914  void _ProcessIncomingData(const SdfAbstractDataPtr &newData,
1915  const SdfSchemaBase *newDataSchema,
1916  bool processPropertyFields,
1917  const DeleteSpecFunc &deleteSpecFunc,
1918  const CreateSpecFunc &createSpecFunc,
1919  const GetFieldValuesFunc &getFieldValuesFunc,
1920  const SetFieldFunc &setFieldFunc,
1921  const ErrorFunc &errorFunc) const;
1922 
1923  // Set _data to match data, calling other primitive setter methods to
1924  // provide fine-grained inverses and notification. If \p data might adhere
1925  // to a different schema than this layer's, pass a pointer to it as \p
1926  // newDataSchema. In this case, check to see if fields from \p data are
1927  // known to this layer's schema, and if not, omit them and issue a TfError
1928  // with SdfAuthoringErrorUnrecognizedFields, but continue to set all other
1929  // known fields.
1930  void _SetData(const SdfAbstractDataPtr &newData,
1931  const SdfSchemaBase *newDataSchema=nullptr);
1932 
1933  // Returns const handle to _data.
1934  SdfAbstractDataConstPtr _GetData() const;
1935 
1936  // Returns a new SdfAbstractData object for this layer.
1937  SdfAbstractDataRefPtr _CreateData() const;
1938 
1939  // Inverse primitive for setting a single field. The previous value for the
1940  // field may be given via \p oldValue. If \p oldValue is non-nullptr, the
1941  // VtValue it points to will be moved-from after the function completes. If
1942  // \p oldValue is nullptr, the old field value will be retrieved
1943  // automatically.
1944  template <class T>
1945  void _PrimSetField(const SdfPath& path,
1946  const TfToken& fieldName,
1947  const T& value,
1948  VtValue *oldValue = nullptr,
1949  bool useDelegate = true);
1950 
1951  // Inverse primitive for setting a single key in a dict-valued field. The
1952  // previous dictionary value for the field (*not* the individual entry) may
1953  // be supplied via \p oldValue. If \p oldValue is non-nullptr, the VtValue
1954  // it points to will be moved-from after the function completes. If \p
1955  // oldValue is nullptr, the old field value will be retrieved automatically.
1956  template <class T>
1957  void _PrimSetFieldDictValueByKey(const SdfPath& path,
1958  const TfToken& fieldName,
1959  const TfToken& keyPath,
1960  const T& value,
1961  VtValue *oldValue = nullptr,
1962  bool useDelegate = true);
1963 
1964  // Primitive for appending a child to the list of children.
1965  template <class T>
1966  void _PrimPushChild(const SdfPath& parentPath,
1967  const TfToken& fieldName,
1968  const T& value,
1969  bool useDelegate = true);
1970  template <class T>
1971  void _PrimPopChild(const SdfPath& parentPath,
1972  const TfToken& fieldName,
1973  bool useDelegate = true);
1974 
1975  // Move all the fields at all paths at or below \a oldPath to be
1976  // at a corresponding location at or below \a newPath. This does
1977  // not update the children fields of the parents of these paths.
1978  bool _MoveSpec(const SdfPath &oldPath, const SdfPath &newPath);
1979 
1980  // Inverse primitive for moving a spec.
1981  void _PrimMoveSpec(const SdfPath &oldPath, const SdfPath &newPath,
1982  bool useDelegate = true);
1983 
1984  // Create a new spec of type \p specType at \p path.
1985  // Returns true if spec was successfully created, false otherwise.
1986  bool _CreateSpec(const SdfPath& path, SdfSpecType specType, bool inert);
1987 
1988  // Delete all the fields at or below the specified path. This does
1989  // not update the children field of the parent of \a path.
1990  bool _DeleteSpec(const SdfPath &path);
1991 
1992  // Inverse primitive for deleting a spec.
1993  void _PrimCreateSpec(const SdfPath &path, SdfSpecType specType, bool inert,
1994  bool useDelegate = true);
1995 
1996  // Inverse primitive for deleting a spec.
1997  void _PrimDeleteSpec(const SdfPath &path, bool inert,
1998  bool useDelegate = true);
1999 
2000  // Inverse primitive for setting time samples.
2001  template <class T>
2002  void _PrimSetTimeSample(const SdfPath& path, double time,
2003  const T& value,
2004  bool useDelegate = true);
2005 
2006  // Helper method for Traverse. Visits the children of \a path using the
2007  // specified \a ChildPolicy.
2008  template <typename ChildPolicy>
2009  void _TraverseChildren(const SdfPath &path, const TraversalFunction &func);
2010 
2011 private:
2012  SdfLayerHandle _self;
2013 
2014  // File format and arguments for this layer.
2015  SdfFileFormatConstPtr _fileFormat;
2016  FileFormatArguments _fileFormatArgs;
2017 
2018  // Cached reference to the _fileFormat's schema -- we need access to this to
2019  // be as fast as possible since we look at it on every SetField(), for
2020  // example.
2021  const SdfSchemaBase &_schema;
2022 
2023  // Registry of Sdf Identities
2024  mutable Sdf_IdentityRegistry _idRegistry;
2025 
2026  // The underlying SdfData which stores all the data in the layer.
2027  SdfAbstractDataRefPtr _data;
2028 
2029  // The state delegate for this layer.
2030  SdfLayerStateDelegateBaseRefPtr _stateDelegate;
2031 
2032  // Dispatcher used in layer initialization, letting waiters participate in
2033  // loading instead of just busy-waiting.
2034  WorkDispatcher _initDispatcher;
2035 
2036  // Atomic variable protecting layer initialization -- the interval between
2037  // adding a layer to the layer registry and finishing the process of
2038  // initializing its contents, at which point we can truly publish the layer
2039  // for consumption by concurrent threads. We add the layer to the registry
2040  // before initialization completes so that other threads can discover and
2041  // wait for it to finish initializing.
2042  std::atomic<bool> _initializationComplete;
2043 
2044  // This is an optional<bool> that is only set once initialization
2045  // is complete, before _initializationComplete is set.
2046  std::optional<bool> _initializationWasSuccessful;
2047 
2048  // remembers the last 'IsDirty' state.
2049  mutable bool _lastDirtyState;
2050 
2051  // Asset information for this layer.
2052  std::unique_ptr<Sdf_AssetInfo> _assetInfo;
2053 
2054  // Modification timestamp of the backing file asset when last read.
2055  mutable VtValue _assetModificationTime;
2056 
2057  // All external asset dependencies, with their modification timestamps, of
2058  // the layer when last read.
2059  mutable VtDictionary _externalAssetModificationTimes;
2060 
2061  // Mutable revision number for cache invalidation.
2062  mutable size_t _mutedLayersRevisionCache;
2063 
2064  // Cache of whether or not this layer is muted. Only valid if
2065  // _mutedLayersRevisionCache is up-to-date with the global revision number.
2066  mutable bool _isMutedCache;
2067 
2068  // Layer permission bits.
2069  bool _permissionToEdit;
2070  bool _permissionToSave;
2071 
2072  // Whether layer edits are validated.
2073  bool _validateAuthoring;
2074 
2075  // Layer hints as of the most recent save operation.
2076  mutable SdfLayerHints _hints;
2077 
2078  // Allow access to _ValidateAuthoring() and _IsInert().
2079  friend class SdfSpec;
2080  friend class SdfPropertySpec;
2081  friend class SdfAttributeSpec;
2082 
2083  friend class Sdf_ChangeManager;
2084 
2085  // Allow access to _CreateSpec and _DeleteSpec and _MoveSpec
2086  template <class ChildPolicy> friend class Sdf_ChildrenUtils;
2087 
2088  // Give the file format access to our data. Limit breaking encapsulation
2089  // to the base SdFileFormat class so we don't have to friend every
2090  // implementation here.
2091  friend class SdfFileFormat;
2092 
2093  // Give layer state delegates access to our data as well as to
2094  // the various _Prim functions.
2096 };
2097 
2099 
2100 #endif // PXR_USD_SDF_LAYER_H
static SDF_API SdfLayerRefPtr FindOrOpen(const std::string &identifier, const FileFormatArguments &args=FileFormatArguments())
SDF_API void ClearColorConfiguration()
std::vector< SdfNamespaceEditDetail > SdfNamespaceEditDetailVector
A sequence of SdfNamespaceEditDetail.
SDF_API bool HasDefaultPrim()
SDF_API void SetFieldDictValueByKey(const SdfPath &path, const TfToken &fieldName, const TfToken &keyPath, const VtValue &value)
Definition: layer.h:81
T GetFieldAs(const SdfPath &path, const TfToken &fieldName, const T &defaultValue=T()) const
Definition: layer.h:669
SDF_API SdfAssetPath GetColorConfiguration() const
SDF_API void EraseTimeSample(const SdfPath &path, double time)
const std::vector< std::string > & GetExcluded() const
Definition: layer.h:1334
DetachedLayerRules & IncludeAll()
Include all layers in the detached layer set.
Definition: layer.h:1315
Result
Validity of an edit.
GT_API const UT_StringHolder filename
SDF_API void SetSubLayerPaths(const std::vector< std::string > &newPaths)
Sets the paths of the layer's sublayers.
SDF_API bool WriteDataFile(const std::string &filename)
SDF_API void RemoveInertSceneDescription()
SDF_API bool InsertRootPrim(const SdfPrimSpecHandle &prim, int index=-1)
SDF_API bool HasEndTimeCode() const
Returns true if the layer has an endTimeCode opinion.
SDF_API void SetComment(const std::string &comment)
Sets the comment string for this layer.
SDF_API VtDictionary GetCustomLayerData() const
SDF_API void SetFramePrecision(int framePrecision)
Sets the layer's frame precision.
SDF_API std::string ComputeAbsolutePath(const std::string &assetPath) const
SDF_API std::set< std::string > GetExternalReferences() const
SDF_API void EraseFieldDictValueByKey(const SdfPath &path, const TfToken &fieldName, const TfToken &keyPath)
bool HasFieldDictKey(const SdfPath &path, const TfToken &name, const TfToken &keyPath, T *value) const
Definition: layer.h:646
SDF_API void RemovePropertyIfHasOnlyRequiredFields(SdfPropertySpecHandle prop)
SDF_API void SetDocumentation(const std::string &documentation)
Sets the documentation string for this layer.
SDF_API void ClearFramesPerSecond()
Clear the framesPerSecond opinion.
PXR_NAMESPACE_OPEN_SCOPE TF_DECLARE_WEAK_PTRS(SdfFileFormat)
static SDF_API SdfLayerRefPtr New(const SdfFileFormatConstPtr &fileFormat, const std::string &identifier, const FileFormatArguments &args=FileFormatArguments())
static SDF_API bool ReloadLayers(const std::set< SdfLayerHandle > &layers, bool force=false)
SDF_API bool HasRelocates() const
SDF_API bool IsMuted() const
Returns true if the current layer is muted.
SDF_API void SetStartTimeCode(double startTimecode)
Sets the layer's start timeCode.
SDF_API bool ExportToString(std::string *result) const
GT_API const UT_StringHolder time
SDF_API const VtValue & GetAssetInfo() const
static SDF_API bool SplitIdentifier(const std::string &identifier, std::string *layerPath, FileFormatArguments *arguments)
GLsizei const GLfloat * value
Definition: glcorearb.h:824
SDF_API bool HasStartTimeCode() const
Returns true if the layer has a startTimeCode opinion.
static SDF_API SdfLayerRefPtr FindOrOpenRelativeToLayer(const SdfLayerHandle &anchor, const std::string &identifier, const FileFormatArguments &args=FileFormatArguments())
SDF_API const std::string & GetAssetName() const
Returns the asset name associated with this layer.
SDF_API void SetDefaultPrim(const TfToken &name)
GLsizei const GLchar *const * path
Definition: glcorearb.h:3341
std::map< std::string, std::string > FileFormatArguments
Definition: layer.h:107
SDF_API bool QueryTimeSample(const SdfPath &path, double time, VtValue *value=NULL) const
SDF_API void ClearSessionOwner()
SDF_API SdfNameOrderProxy GetRootPrimOrder() const
std::type_info const & GetFieldTypeid(const SdfPath &path, const TfToken &name) const
Definition: layer.h:622
SDF_API bool HasSpec(const SdfPath &path) const
Return whether a spec exists at path.
SDF_API SdfAttributeSpecHandle GetAttributeAtPath(const SdfPath &path)
SDF_API void RemoveFromRootPrimOrderByIndex(int index)
Removes a root prim name from the root prim order by index.
SDF_API SdfRelationshipSpecHandle GetRelationshipAtPath(const SdfPath &path)
SDF_API void SetPermissionToEdit(bool allow)
Sets permission to edit.
SDF_API void Traverse(const SdfPath &path, const TraversalFunction &func)
TF_DECLARE_WEAK_AND_REF_PTRS(SdfLayerStateDelegateBase)
SDF_API void ClearRelocates()
Clears the layer relocates opinion in the layer's metadata.
Definition: spec.h:32
SDF_API bool HasSessionOwner() const
Returns true if the layer has a session owner opinion.
friend class Sdf_ChangeManager
Definition: layer.h:2083
SDF_API SdfPrimSpecHandle GetPseudoRoot() const
SDF_API bool PermissionToEdit() const
std::set< SdfHandleTo< SdfLayer >::Handle > SdfLayerHandleSet
static SDF_API SdfLayerRefPtr CreateAnonymous(const std::string &tag=std::string(), const FileFormatArguments &args=FileFormatArguments())
SDF_API void SetSubLayerOffset(const SdfLayerOffset &offset, int index)
Sets the layer offset for the subLayer path at the given index.
SDF_API void ScheduleRemoveIfInert(const SdfSpec &spec)
SDF_API void SetRelocates(const SdfRelocates &relocates)
**But if you need a result
Definition: thread.h:622
std::function< void(const SdfPath &)> TraversalFunction
Definition: layer.h:755
static SDF_API std::string CreateIdentifier(const std::string &layerPath, const FileFormatArguments &arguments)
Joins the given layer path and arguments into an identifier.
SDF_API std::string GetDocumentation() const
SDF_API void SetPermissionToSave(bool allow)
Sets permission to save.
SDF_API bool Apply(const SdfBatchNamespaceEdit &)
SDF_API bool Import(const std::string &layerPath)
SDF_API const std::string & GetRepositoryPath() const
SDF_API SdfPrimSpecHandle GetPrimAtPath(const SdfPath &path)
SDF_API void SetTimeCodesPerSecond(double timeCodesPerSecond)
Sets the layer's timeCodes per second.
static SDF_API std::set< std::string > GetMutedLayers()
Returns the set of muted layer paths.
SDF_API std::set< double > ListTimeSamplesForPath(const SdfPath &path) const
SDF_API SdfLayerOffset GetSubLayerOffset(int index) const
Returns the layer offset for the subLayer path at the given index.
SDF_API double GetTimeCodesPerSecond() const
SDF_API void SetColorConfiguration(const SdfAssetPath &colorConfiguration)
Sets the color configuration asset-path for this layer.
SDF_API std::string GetSessionOwner() const
static SDF_API bool IsIncludedByDetachedLayerRules(const std::string &identifier)
SDF_API SdfSpecType GetSpecType(const SdfPath &path) const
SDF_API void SetEndTimeCode(double endTimeCode)
Sets the layer's end timeCode.
SDF_API bool Reload(bool force=false)
SDF_API double GetStartTimeCode() const
GLenum GLuint GLint GLint layer
Definition: glcorearb.h:1299
SDF_API size_t GetNumSubLayerPaths() const
Returns the number of sublayer paths (and offsets).
SDF_API SdfLayerOffsetVector GetSubLayerOffsets() const
Returns the layer offsets for all the subLayer paths.
SDF_API const SdfFileFormatConstPtr & GetFileFormat() const
Returns the file format used by this layer.
SDF_API void ClearOwner()
Clear the owner opinion.
SDF_API const FileFormatArguments & GetFileFormatArguments() const
SDF_API SdfDataRefPtr GetMetadata() const
Returns the data from the absolute root path of this layer.
SDF_API void RemoveRootPrim(const SdfPrimSpecHandle &prim)
Remove a root prim.
static SDF_API SdfLayerRefPtr OpenAsAnonymous(const std::string &layerPath, bool metadataOnly=false, const std::string &tag=std::string())
SDF_API void ClearFramePrecision()
Clear the framePrecision opinion.
SDF_API void SetStateDelegate(const SdfLayerStateDelegateBaseRefPtr &delegate)
SDF_API void SetColorManagementSystem(const TfToken &cms)
std::vector< SdfLayerOffset > SdfLayerOffsetVector
Definition: layerOffset.h:157
Definition: token.h:70
SDF_API bool HasField(const SdfPath &path, const TfToken &fieldName, VtValue *value=NULL) const
SDF_API void SetSessionOwner(const std::string &owner)
GLintptr offset
Definition: glcorearb.h:665
SDF_API void SetRootPrims(const SdfPrimSpecHandleVector &rootPrims)
SDF_API SdfPath GetDefaultPrimAsPath() const
SDF_API void SetCustomLayerData(const VtDictionary &value)
Sets the CustomLayerData dictionary associated with this layer.
SDF_API void EraseField(const SdfPath &path, const TfToken &fieldName)
Remove the field at path and fieldName, if one exists.
SDF_API std::set< std::string > GetCompositionAssetDependencies() const
SDF_API void ClearEndTimeCode()
Clear the endTimeCode opinion.
SDF_API bool HasCustomLayerData() const
Returns true if CustomLayerData is authored on the layer.
SDF_API bool UpdateExternalReference(const std::string &oldAssetPath, const std::string &newAssetPath=std::string())
SDF_API double GetFramesPerSecond() const
SDF_API void ClearDefaultPrim()
SDF_API void Clear()
static SDF_API std::string GetDisplayNameFromIdentifier(const std::string &identifier)
SDF_API VtValue GetFieldDictValueByKey(const SdfPath &path, const TfToken &fieldName, const TfToken &keyPath) const
SDF_API bool ImportFromString(const std::string &string)
GLint GLint GLsizei GLint GLenum format
Definition: glcorearb.h:108
SDF_API std::set< std::string > GetExternalAssetDependencies() const
const std::vector< std::string > & GetIncluded() const
Definition: layer.h:1333
GLint GLuint mask
Definition: glcorearb.h:124
SDF_API bool HasFramesPerSecond() const
Returns true if the layer has a frames per second opinion.
SdfPrimSpecView RootPrimsView
Returns a vector of the layer's root prims.
Definition: layer.h:1088
SDF_API void SetRootPrimOrder(const std::vector< TfToken > &names)
SDF_API bool Export(const std::string &filename, const std::string &comment=std::string(), const FileFormatArguments &args=FileFormatArguments()) const
SDF_API double GetEndTimeCode() const
SDF_API SdfLayerStateDelegateBasePtr GetStateDelegate() const
SDF_API DetachedLayerRules & Include(const std::vector< std::string > &patterns)
SDF_API void SetHasOwnedSubLayers(bool)
Sets whether the layer's sublayers are expected to have owners.
SDF_API const std::string & GetRealPath() const
SDF_API void ClearTimeCodesPerSecond()
Clear the timeCodesPerSecond opinion.
SDF_API void RemoveFromRootPrimOrder(const TfToken &name)
Removes a root prim name from the root prim order.
SDF_API TfToken GetColorManagementSystem() const
SDF_API bool HasTimeCodesPerSecond() const
Returns true if the layer has a timeCodesPerSecond opinion.
GLuint const GLchar * name
Definition: glcorearb.h:786
SDF_API void ClearExpressionVariables()
Clears the expression variables dictionary authored on this layer.
void SetFieldDictValueByKey(const SdfPath &path, const TfToken &fieldName, const TfToken &keyPath, const T &val)
Definition: layer.h:722
Definition: path.h:273
SdfLayer & operator=(const SdfLayer &)=delete
bool IncludedAll() const
Definition: layer.h:1332
SDF_API bool StreamsData() const
SDF_API DetachedLayerRules & Exclude(const std::vector< std::string > &patterns)
SDF_API bool HasFieldDictKey(const SdfPath &path, const TfToken &fieldName, const TfToken &keyPath, VtValue *value=NULL) const
SDF_API bool HasExpressionVariables() const
Returns true if expression variables are authored on this layer.
SDF_API bool GetBracketingTimeSamples(double time, double *tLower, double *tUpper)
SDF_API void SetFramesPerSecond(double framesPerSecond)
Sets the layer's frames per second.
SDF_API std::string GetDisplayName() const
SDF_API void UpdateAssetInfo()
SDF_API bool IsIncluded(const std::string &identifier) const
SDF_API bool UpdateCompositionAssetDependency(const std::string &oldAssetPath, const std::string &newAssetPath=std::string())
SDF_API const ArResolvedPath & GetResolvedPath() const
SdfLayer(const SdfLayer &)=delete
Noncopyable.
SDF_API SdfNamespaceEditDetail::Result CanApply(const SdfBatchNamespaceEdit &, SdfNamespaceEditDetailVector *details=NULL) const
static SDF_API void SetDetachedLayerRules(const DetachedLayerRules &mask)
SDF_API void InsertSubLayerPath(const std::string &path, int index=-1)
static SDF_API SdfLayerHandle FindRelativeToLayer(const SdfLayerHandle &anchor, const std::string &identifier, const FileFormatArguments &args=FileFormatArguments())
SDF_API SdfSpecHandle GetObjectAtPath(const SdfPath &path)
SDF_API bool GetPreviousTimeSampleForPath(const SdfPath &path, double time, double *tPrevious) const
#define SDF_API
Definition: api.h:23
SDF_API void SetIdentifier(const std::string &identifier)
SDF_API void SetExpressionVariables(const VtDictionary &expressionVars)
Sets the expression variables dictionary for this layer.
SDF_API bool IsAnonymous() const
Returns true if this layer is an anonymous layer.
bool HasField(const SdfPath &path, const TfToken &name, T *value) const
Definition: layer.h:602
GLenum func
Definition: glcorearb.h:783
SDF_API std::string GetFileExtension() const
SDF_API void InsertInRootPrimOrder(const TfToken &name, int index=-1)
SDF_API void RemoveSubLayerPath(int index)
Removes sublayer path at the given index.
SDF_API void SetField(const SdfPath &path, const TfToken &fieldName, const VtValue &value)
Set the value of the given path and fieldName.
PXR_NAMESPACE_CLOSE_SCOPE PXR_NAMESPACE_OPEN_SCOPE
Definition: path.h:1425
SDF_API void TransferContent(const SdfLayerHandle &layer)
SIM_API const UT_StringHolder force
void SetField(const SdfPath &path, const TfToken &fieldName, const T &val)
Set the value of the given path and fieldName.
Definition: layer.h:693
bool QueryTimeSample(const SdfPath &path, double time, T *data) const
Definition: layer.h:1597
SDF_API bool HasColorManagementSystem() const
SDF_API VtDictionary GetExpressionVariables() const
SdfSpecType
Definition: types.h:68
SDF_API std::string GetOwner() const
Returns the layer's owner.
SDF_API void SetMuted(bool muted)
SDF_API void ClearCustomLayerData()
Clears out the CustomLayerData dictionary associated with this layer.
SDF_API bool PermissionToSave() const
static SDF_API TfToken ConvertDefaultPrimPathToToken(const SdfPath &primPath)
virtual SDF_API ~SdfLayer()
Destructor.
SDF_API bool HasColorConfiguration() const
GLuint index
Definition: glcorearb.h:786
SDF_API bool HasOwner() const
Returns true if the layer has an owner opinion.
SDF_API void SetTimeSample(const SdfPath &path, double time, const VtValue &value)
GLuint GLfloat * val
Definition: glcorearb.h:1608
#define PXR_NAMESPACE_CLOSE_SCOPE
Definition: pxr.h:74
SDF_API bool IsDetached() const
SDF_API bool HasFramePrecision() const
Returns true if the layer has a frames precision opinion.
**If you just want to fire and args
Definition: thread.h:618
SDF_API int GetFramePrecision() const
Returns the layer's frame precision.
SDF_API void SetOwner(const std::string &owner)
Sets the layer's owner.
SDF_API const std::string & GetIdentifier() const
Returns the layer identifier.
SDF_API bool GetHasOwnedSubLayers() const
Returns true if the layer's sublayers are expected to have owners.
static SDF_API void RemoveFromMutedLayers(const std::string &mutedPath)
Remove the specified path from the muted layers set.
static SDF_API SdfPath ConvertDefaultPrimTokenToPath(const TfToken &defaultPrim)
SDF_API RootPrimsView GetRootPrims() const
Returns a vector of the layer's root prims.
static SDF_API void AddToMutedLayers(const std::string &mutedPath)
Add the specified path to the muted layers set.
SDF_API TfToken GetDefaultPrim() const
SDF_API SdfChangeList CreateDiff(const SdfLayerHandle &layer, bool processPropertyFields=true) const
SDF_API std::vector< TfToken > ListFields(const SdfPath &path) const
Return the names of all the fields that are set at path.
SDF_API SdfPropertySpecHandle GetPropertyAtPath(const SdfPath &path)
static SDF_API void DumpLayerInfo()
SDF_API size_t GetNumTimeSamplesForPath(const SdfPath &path) const
std::vector< SdfRelocate > SdfRelocates
A vector of relocation source path to target path pairs.
Definition: types.h:274
SDF_API const std::string & GetVersion() const
SDF_API SdfSubLayerProxy GetSubLayerPaths() const
SDF_API bool GetBracketingTimeSamplesForPath(const SdfPath &path, double time, double *tLower, double *tUpper) const
SDF_API void RemovePrimIfInert(SdfPrimSpecHandle prim)
static SDF_API const DetachedLayerRules & GetDetachedLayerRules()
Returns the current rules for the detached layer set.
static SDF_API SdfLayerRefPtr CreateNew(const std::string &identifier, const FileFormatArguments &args=FileFormatArguments())
SDF_API SdfLayerHints GetHints() const
static SDF_API SdfLayerHandleSet GetLoadedLayers()
Returns handles for all layers currently held by the layer registry.
SDF_API const SdfSchemaBase & GetSchema() const
SDF_API bool IsDirty() const
SDF_API void ApplyRootPrimOrder(std::vector< TfToken > *vec) const
SDF_API void ClearStartTimeCode()
Clear the startTimeCode opinion.
SDF_API void ClearColorManagementSystem()
Definition: value.h:146
SDF_API std::string GetComment() const
SDF_API bool Save(bool force=false) const
SDF_API VtValue GetField(const SdfPath &path, const TfToken &fieldName) const
static SDF_API bool IsAnonymousLayerIdentifier(const std::string &identifier)
Definition: format.h:1821
SDF_API std::set< double > ListAllTimeSamples() const
SDF_API bool IsEmpty() const
Returns whether this layer has no significant data.
SDF_API SdfRelocates GetRelocates() const
static SDF_API SdfLayerHandle Find(const std::string &identifier, const FileFormatArguments &args=FileFormatArguments())
void SetTimeSample(const SdfPath &path, double time, const T &value)
Definition: layer.h:1624