add usd-21-05-win64_py37

This commit is contained in:
Sébastien Albert committed 2021-12-07 17:16:25 +01:00
1 parent 41d23e71ba
commit 66bc054336
15675 files changed
+3061008

No files matched your search

+587
View File
@@ -0,0 +1,587 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_ABSTRACT_DATA_H
#define PXR_USD_SDF_ABSTRACT_DATA_H
#include "pxr/pxr.h"
#include "pxr/usd/sdf/path.h"
#include "pxr/usd/sdf/types.h"
#include "pxr/base/vt/value.h"
#include "pxr/base/tf/staticTokens.h"
#include "pxr/base/tf/token.h"
#include "pxr/base/tf/refBase.h"
#include "pxr/base/tf/weakBase.h"
#include "pxr/base/tf/declarePtrs.h"
#include <vector>
#include <type_traits>
PXR_NAMESPACE_OPEN_SCOPE
TF_DECLARE_WEAK_AND_REF_PTRS(SdfAbstractData);
class SdfAbstractDataSpecVisitor;
class SdfAbstractDataConstValue;
class SdfAbstractDataValue;
#define SDF_DATA_TOKENS \
((TimeSamples, "timeSamples"))
TF_DECLARE_PUBLIC_TOKENS(SdfDataTokens, SDF_API, SDF_DATA_TOKENS);
/// \class SdfAbstractData
///
/// Interface for scene description data storage.
///
/// This is not a layer. SdfAbstractData is an anonymous container holding
/// scene description values. It is like an STL container, but specialized
/// for holding scene description.
///
/// For any given SdfPath, an SdfAbstractData can hold one or more key/value
/// pairs which we call Fields. Most of the API on SdfAbstractData accesses
/// or modifies the value stored in a Field for a particular path and field
/// name.
///
/// SdfAbstractData does not provide undo, change notification, or any strong
/// consistency guarantees about the scene description it contains.
/// Instead, it is a basis for building those things.
///
class SdfAbstractData : public TfRefBase, public TfWeakBase
{
public:
SdfAbstractData() {}
SDF_API
virtual ~SdfAbstractData();
/// Copy the data in \p source into this data object.
///
/// The default implementation does a spec-by-spec, field-by-field
/// copy of \p source into this object.
SDF_API
virtual void CopyFrom(const SdfAbstractDataConstPtr& source);
/// Returns true if this data object streams its data to and from its
/// serialized data store on demand.
///
/// Sdf will treat layers with streaming data differently to avoid pulling
/// in data unnecessarily. For example, reloading a streaming layer
/// will not perform fine-grained change notification, since doing
/// so would require the full contents of the layer to be loaded.
SDF_API
virtual bool StreamsData() const = 0;
/// Returns true if this data object has no specs, false otherwise.
///
/// The default implementation uses a visitor to check if any specs
/// exist.
SDF_API
virtual bool IsEmpty() const;
/// Returns true if this data object contains the same specs and fields
/// as \a lhs, false otherwise.
///
/// The default implementation does a spec-by-spec, field-by-field
/// comparison.
// XXX: What are the right semantics for this?
// Does it matter if the underlying implementation matches?
SDF_API
virtual bool Equals(const SdfAbstractDataRefPtr &rhs) const;
/// Writes the contents of this data object to \p out. This is primarily
/// for debugging purposes.
///
/// The default implementation writes out each field for each spec.
SDF_API
virtual void WriteToStream(std::ostream& out) const;
/// \name Spec API
/// @{
/// Create a new spec at \a path with the given \a specType. If the spec
/// already exists the spec type will be changed.
SDF_API
virtual void CreateSpec(const SdfPath &path,
SdfSpecType specType) = 0;
/// Return true if this data has a spec for \a path.
SDF_API
virtual bool HasSpec(const SdfPath &path) const = 0;
/// Erase the spec at \a path and any fields that are on it.
/// Note that this does not erase child specs.
SDF_API
virtual void EraseSpec(const SdfPath &path) = 0;
/// Move the spec at \a oldPath to \a newPath, including all the
/// fields that are on it. This does not move any child specs.
SDF_API
virtual void MoveSpec(const SdfPath &oldPath,
const SdfPath &newPath) = 0;
/// Return the spec type for the spec at \a path. Returns SdfSpecTypeUnknown
/// if the spec doesn't exist.
virtual SdfSpecType GetSpecType(const SdfPath &path) const = 0;
/// Visits every spec in this SdfAbstractData object with the given
/// \p visitor. The order in which specs are visited is undefined.
/// The visitor may not modify the SdfAbstractData object it is visiting.
/// \sa SdfAbstractDataSpecVisitor
SDF_API
void VisitSpecs(SdfAbstractDataSpecVisitor* visitor) const;
/// @}
/// \name Field API
/// @{
/// Returns whether a value exists for the given \a path and \a fieldName.
/// Optionally returns the value if it exists.
SDF_API
virtual bool Has(const SdfPath& path, const TfToken& fieldName,
SdfAbstractDataValue* value) const = 0;
/// Return whether a value exists for the given \a path and \a fieldName.
/// Optionally returns the value if it exists.
SDF_API
virtual bool Has(const SdfPath& path, const TfToken &fieldName,
VtValue *value = NULL) const = 0;
/// Fill \p specType (which cannot be nullptr) as if by a call to
/// GetSpecType(path). If the resulting specType is not SdfSpecTypeUnknown,
/// then act as if Has(path, fieldName, value) was called and return its
/// result. In other words, the semantics of this function must be
/// identical to this sequence:
///
/// \code
/// *specType = GetSpecType(path);
/// return *specType != SdfSpecTypeUnknown && Has(path, fieldName, value);
/// \endcode
SDF_API
virtual bool
HasSpecAndField(const SdfPath &path, const TfToken &fieldName,
SdfAbstractDataValue *value, SdfSpecType *specType) const;
/// Fill \p specType (which cannot be nullptr) as if by a call to
/// GetSpecType(path). If the resulting specType is not SdfSpecTypeUnknown,
/// then act as if Has(path, fieldName, value) was called and return its
/// result. In other words, the semantics of this function must be
/// identical to this sequence:
///
/// \code
/// *specType = GetSpecType(path);
/// return *specType != SdfSpecTypeUnknown && Has(path, fieldName, value);
/// \endcode
SDF_API
virtual bool
HasSpecAndField(const SdfPath &path, const TfToken &fieldName,
VtValue *value, SdfSpecType *specType) const;
/// Return the value for the given \a path and \a fieldName. Returns an
/// empty value if none is set.
SDF_API
virtual VtValue Get(const SdfPath& path,
const TfToken& fieldName) const = 0;
/// Return the type of the value for \p fieldName on spec \p path. If no
/// such field exists, return typeid(void). Derived classes may optionally
/// override this for performance. The base implementation is equivalent
/// to:
///
/// \code
/// return Get(path, fieldName).GetTypeid();
/// \endcode
SDF_API
virtual std::type_info const &
GetTypeid(const SdfPath &path, const TfToken &fieldName) const;
/// Set the value of the given \a path and \a fieldName.
///
/// It's an error to set a field on a spec that does not exist. Setting a
/// field to an empty VtValue is the same as calling Erase() on it.
SDF_API
virtual void Set(const SdfPath &path, const TfToken &fieldName,
const VtValue &value) = 0;
/// Set the value of the given \a path and \a fieldName.
///
/// It's an error to set a field on a spec that does not exist.
SDF_API
virtual void Set(const SdfPath &path, const TfToken &fieldName,
const SdfAbstractDataConstValue& value) = 0;
/// Remove the field at \p path and \p fieldName, if one exists.
SDF_API
virtual void Erase(const SdfPath& path,
const TfToken& fieldName) = 0;
/// Return the names of all the fields that are set at \p path.
SDF_API
virtual std::vector<TfToken> List(const SdfPath& path) const = 0;
/// Return the value for the given \a path and \a fieldName. Returns the
/// provided \a defaultValue value if none is set.
template <class T>
inline T GetAs(const SdfPath& path, const TfToken& fieldName,
const T& defaultValue = T()) const;
/// @}
/// \name Dict key access API
/// @{
// Return true and set \p value (if non null) if the field identified by
// \p path and \p fieldName is dictionary-valued, and if there is an element
// at \p keyPath in that dictionary. Return false otherwise. If
// \p keyPath names an entire sub-dictionary, set \p value to that entire
// sub-dictionary and return true.
SDF_API
virtual bool HasDictKey(const SdfPath& path,
const TfToken &fieldName,
const TfToken &keyPath,
SdfAbstractDataValue* value) const;
SDF_API
virtual bool HasDictKey(const SdfPath& path,
const TfToken &fieldName,
const TfToken &keyPath,
VtValue *value = NULL) const;
// Same as HasDictKey but return empty VtValue on failure.
SDF_API
virtual VtValue GetDictValueByKey(const SdfPath& path,
const TfToken &fieldName,
const TfToken &keyPath) const;
// Set the element at \p keyPath in the dictionary-valued field identified
// by \p path and \p fieldName. If the field itself is not
// dictionary-valued, replace the field with a new dictionary and set the
// element at \p keyPath in it. If \p value is empty, invoke
// EraseDictValueByKey instead.
SDF_API
virtual void SetDictValueByKey(const SdfPath& path,
const TfToken &fieldName,
const TfToken &keyPath,
const VtValue &value);
SDF_API
virtual void SetDictValueByKey(const SdfPath& path,
const TfToken &fieldName,
const TfToken &keyPath,
const SdfAbstractDataConstValue& value);
// If \p path and \p fieldName identify a dictionary-valued field with an
// element at \p keyPath, remove that element from the dictionary. If this
// leaves the dictionary empty, Erase() the entire field.
SDF_API
virtual void EraseDictValueByKey(const SdfPath& path,
const TfToken &fieldName,
const TfToken &keyPath);
// If \p path, \p fieldName, and \p keyPath identify a (sub) dictionary,
// return a vector of the keys in that dictionary, otherwise return an empty
// vector.
SDF_API
virtual std::vector<TfToken> ListDictKeys(const SdfPath& path,
const TfToken &fieldName,
const TfToken &keyPath) const;
/// @}
/// \name Time-sample API
///
/// This API supports narrowly-targeted queries against the
/// "timeSamples" key of properties. In particular, it enables
/// asking for single time samples without pulling on the entire
/// set of time samples, as well as asking about the set of sample
/// times without pulling on the actual values at those times.
///
/// @{
SDF_API
virtual std::set<double>
ListAllTimeSamples() const = 0;
SDF_API
virtual std::set<double>
ListTimeSamplesForPath(const SdfPath& path) const = 0;
SDF_API
virtual bool
GetBracketingTimeSamples(double time, double* tLower, double* tUpper) const = 0;
SDF_API
virtual size_t
GetNumTimeSamplesForPath(const SdfPath& path) const = 0;
SDF_API
virtual bool
GetBracketingTimeSamplesForPath(const SdfPath& path,
double time,
double* tLower, double* tUpper) const = 0;
SDF_API
virtual bool
QueryTimeSample(const SdfPath& path, double time,
VtValue *optionalValue = NULL) const = 0;
SDF_API
virtual bool
QueryTimeSample(const SdfPath& path, double time,
SdfAbstractDataValue *optionalValue) const = 0;
SDF_API
virtual void
SetTimeSample(const SdfPath& path, double time,
const VtValue & value) = 0;
SDF_API
virtual void
EraseTimeSample(const SdfPath& path, double time) = 0;
/// @}
protected:
/// Visits every spec in this SdfAbstractData object with the given
/// \p visitor. The order in which specs are visited is undefined.
/// The visitor may not modify the SdfAbstractData object it is visiting.
/// This method should \b not call \c Done() on the visitor.
/// \sa SdfAbstractDataSpecVisitor
SDF_API
virtual void _VisitSpecs(SdfAbstractDataSpecVisitor* visitor) const = 0;
};
template <class T>
inline T SdfAbstractData::GetAs(
const SdfPath& path,
const TfToken& field, const T& defaultVal) const
{
VtValue val = Get(path, field);
if (val.IsHolding<T>()) {
return val.UncheckedGet<T>();
}
return defaultVal;
}
/// \class SdfAbstractDataValue
///
/// A type-erased container for a field value in an SdfAbstractData.
///
/// \sa SdfAbstractDataTypedValue
class SdfAbstractDataValue
{
public:
virtual bool StoreValue(const VtValue& value) = 0;
template <class T>
bool StoreValue(const T& v)
{
if (TfSafeTypeCompare(typeid(T), valueType)) {
*static_cast<T*>(value) = v;
return true;
}
typeMismatch = true;
return false;
}
bool StoreValue(const SdfValueBlock& block)
{
isValueBlock = true;
return true;
}
void* value;
const std::type_info& valueType;
bool isValueBlock;
bool typeMismatch;
protected:
SdfAbstractDataValue(void* value_, const std::type_info& valueType_)
: value(value_)
, valueType(valueType_)
, isValueBlock(false)
, typeMismatch(false)
{ }
};
/// \class SdfAbstractDataTypedValue
///
/// The fully-typed container for a field value in an \c SdfAbstractData.
/// An \c SdfAbstractDataTypedValue allows a consumer to pass a pointer to
/// an object through the virtual \c SdfAbstractData interface along with
/// information about that object's type. That information may allow
/// implementations of \c SdfAbstractData to populate the contained object
/// in a more efficient way, avoiding unnecessary boxing/unboxing of data.
///
/// SdfAbstractDataTypedValue objects are intended to be transient; they
/// are solely used to get pointer information into and out of an
/// SdfAbstractData container.
///
template <class T>
class SdfAbstractDataTypedValue : public SdfAbstractDataValue
{
public:
SdfAbstractDataTypedValue(T* value)
: SdfAbstractDataValue(value, typeid(T))
{ }
virtual bool StoreValue(const VtValue& v)
{
if (ARCH_LIKELY(v.IsHolding<T>())) {
*static_cast<T*>(value) = v.UncheckedGet<T>();
if (std::is_same<T, SdfValueBlock>::value) {
isValueBlock = true;
}
return true;
}
if (v.IsHolding<SdfValueBlock>()) {
isValueBlock = true;
return true;
}
typeMismatch = true;
return false;
}
};
/// \class SdfAbstractDataConstValue
///
/// A type-erased container for a const field value in an SdfAbstractData.
///
/// \sa SdfAbstractDataConstTypedValue
class SdfAbstractDataConstValue
{
public:
virtual bool GetValue(VtValue* value) const = 0;
template <class T> bool GetValue(T* v) const
{
if (TfSafeTypeCompare(typeid(T), valueType)) {
*v = *static_cast<const T*>(value);
return true;
}
return false;
}
virtual bool IsEqual(const VtValue& value) const = 0;
const void* value;
const std::type_info& valueType;
protected:
SdfAbstractDataConstValue(const void* value_,
const std::type_info& valueType_)
: value(value_)
, valueType(valueType_)
{
}
};
/// \class SdfAbstractDataConstTypedValue
///
/// The fully-typed container for a field value in an \c SdfAbstractData.
/// An \c SdfAbstractDataConstTypedValue allows a consumer to pass a pointer to
/// an object through the virtual \c SdfAbstractData interface along with
/// information about that object's type. That information may allow
/// implementations of \c SdfAbstractData to store the contained object
/// in a more efficient way, avoiding unnecessary boxing/unboxing of data.
///
/// SdfAbstractDataConstTypedValue objects are intended to be transient; they
/// are solely used to get pointer information into an SdfAbstractData
/// container.
///
template <class T>
class SdfAbstractDataConstTypedValue : public SdfAbstractDataConstValue
{
public:
SdfAbstractDataConstTypedValue(const T* value)
: SdfAbstractDataConstValue(value, typeid(T))
{ }
virtual bool GetValue(VtValue* v) const
{
*v = _GetValue();
return true;
}
virtual bool IsEqual(const VtValue& v) const
{
return (v.IsHolding<T>() && v.UncheckedGet<T>() == _GetValue());
}
private:
const T& _GetValue() const
{
return *static_cast<const T*>(value);
}
};
// Specialization of SdAbstractDataConstTypedValue that converts character
// arrays to std::string.
template <int N>
class SdfAbstractDataConstTypedValue<char[N]>
: public SdfAbstractDataConstTypedValue<std::string>
{
public:
typedef char CharArray[N];
SdfAbstractDataConstTypedValue(const CharArray* value)
: SdfAbstractDataConstTypedValue<std::string>(&_str)
, _str(*value)
{ }
private:
std::string _str;
};
/// \class SdfAbstractDataSpecVisitor
///
/// Base class for objects used to visit specs in an SdfAbstractData object.
///
/// \sa SdfAbstractData::VisitSpecs.
class SdfAbstractDataSpecVisitor
{
public:
SDF_API
virtual ~SdfAbstractDataSpecVisitor();
/// \c SdfAbstractData::VisitSpecs calls this function for every entry it
/// contains, passing itself as \p data and the entry's \p path. Return
/// false to stop iteration early, true to continue.
SDF_API
virtual bool VisitSpec(const SdfAbstractData& data,
const SdfPath& path) = 0;
/// \c SdfAbstractData::VisitSpecs will call this after visitation is
/// complete, even if some \c VisitSpec() returned \c false.
SDF_API
virtual void Done(const SdfAbstractData& data) = 0;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_ABSTRACT_DATA_H
+257
View File
@@ -0,0 +1,257 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_ACCESSOR_HELPERS_H
#define PXR_USD_SDF_ACCESSOR_HELPERS_H
/// \file sdf/accessorHelpers.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/schema.h"
#include "pxr/usd/sdf/spec.h"
#include "pxr/usd/sdf/types.h"
// This file defines macros intended to reduce the amount of boilerplate code
// associated with adding new metadata to SdfSpec subclasses. There's still a
// lot of files to touch, but these at least reduce the copy/paste/edit load.
//
// Prior to using these macros in the SdfSpec implementation file, define the
// following symbols:
//
// #define SDF_ACCESSOR_CLASS SdfSomeSpec
// #define SDF_ACCESSOR_READ_PREDICATE(key_) _CanRead(key_)
// #define SDF_ACCESSOR_WRITE_PREDICATE(key_) _CanWrite(key_)
//
// ...where _CanRead and _CanWrite are member functions of the specified class,
// with the signature 'bool _fn_(const TfToken&)'. If either accessor predicate
// is unnecessary, #define the corresponding symbol to 'SDF_NO_PREDICATE'.
//
// Also, please observe good form and #undef the symbols after instancing the
// accessor macros.
PXR_NAMESPACE_OPEN_SCOPE
// "Helper" macros
#define _GET_KEY_(key_) key_
#define SDF_NO_PREDICATE true
#define _GET_WITH_FALLBACK(key_, heldType_) \
{ \
typedef Sdf_AccessorHelpers<SDF_ACCESSOR_CLASS> _Helper; \
const VtValue& value = _Helper::GetField(this, key_); \
if (value.IsEmpty() || !value.IsHolding<heldType_>()) { \
const SdfSchemaBase& schema = _Helper::GetSchema(this); \
return schema.GetFallback(_GET_KEY_(key_)).Get<heldType_>(); \
} \
else { \
return value.Get<heldType_>(); \
} \
}
// Accessor methods for "simple type" values: Get, Is, Set, Has, Clear
// Usually the client will utilize one of the combination macros (below).
#define SDF_DEFINE_GET(name_, key_, heldType_) \
heldType_ \
SDF_ACCESSOR_CLASS::Get ## name_() const \
{ \
if (SDF_ACCESSOR_READ_PREDICATE(_GET_KEY_(key_))) { \
/* Empty clause needed to prevent compiler complaints */ \
} \
\
_GET_WITH_FALLBACK(key_, heldType_); \
}
#define SDF_DEFINE_IS(name_, key_) \
bool \
SDF_ACCESSOR_CLASS::Is ## name_() const \
{ \
if (!SDF_ACCESSOR_READ_PREDICATE(_GET_KEY_(key_))) { \
return false; \
} \
\
_GET_WITH_FALLBACK(key_, bool); \
}
#define SDF_DEFINE_SET(name_, key_, argType_) \
void \
SDF_ACCESSOR_CLASS::Set ## name_(argType_ value) \
{ \
if (SDF_ACCESSOR_WRITE_PREDICATE(_GET_KEY_(key_))) { \
typedef Sdf_AccessorHelpers<SDF_ACCESSOR_CLASS> _Helper; \
_Helper::SetField(this, _GET_KEY_(key_), value); \
} \
}
#define SDF_DEFINE_HAS(name_, key_) \
bool \
SDF_ACCESSOR_CLASS::Has ## name_() const \
{ \
typedef Sdf_AccessorHelpers<SDF_ACCESSOR_CLASS> _Helper; \
return SDF_ACCESSOR_READ_PREDICATE(_GET_KEY_(key_)) ? \
_Helper::HasField(this, _GET_KEY_(key_)) : false; \
}
#define SDF_DEFINE_CLEAR(name_, key_) \
void \
SDF_ACCESSOR_CLASS::Clear ## name_() \
{ \
typedef Sdf_AccessorHelpers<SDF_ACCESSOR_CLASS> _Helper; \
if (SDF_ACCESSOR_WRITE_PREDICATE(_GET_KEY_(key_))) { \
_Helper::ClearField(this, _GET_KEY_(key_)); \
} \
}
// Accessor methods similar to the above, but intended for private use in
// the SdSpec classes.
#define SDF_DEFINE_GET_PRIVATE(name_, key_, heldType_) \
heldType_ \
SDF_ACCESSOR_CLASS::_Get ## name_() const \
{ \
if (SDF_ACCESSOR_READ_PREDICATE(_GET_KEY_(key_))) { \
/* Empty clause needed to prevent compiler complaints */ \
} \
\
_GET_WITH_FALLBACK(key_, heldType_); \
}
// Accessor methods for VtDictionary types, utilizing SdDictionaryProxy for the
// 'Get' accessors. Due to unusual naming in the original SdSpec API, these
// macros accept/require explicit accessor method names. Dammit.
#define SDF_DEFINE_DICTIONARY_GET(name_, key_) \
SdfDictionaryProxy \
SDF_ACCESSOR_CLASS::name_() const \
{ \
typedef Sdf_AccessorHelpers<SDF_ACCESSOR_CLASS> _Helper; \
return SDF_ACCESSOR_READ_PREDICATE(_GET_KEY_(key_)) ? \
SdfDictionaryProxy(_Helper::GetSpecHandle(this), _GET_KEY_(key_)) : \
SdfDictionaryProxy(); \
}
#define SDF_DEFINE_DICTIONARY_SET(name_, key_) \
void \
SDF_ACCESSOR_CLASS::name_( \
const std::string& name, \
const VtValue& value) \
{ \
typedef Sdf_AccessorHelpers<SDF_ACCESSOR_CLASS> _Helper; \
if (SDF_ACCESSOR_WRITE_PREDICATE(_GET_KEY_(key_))) { \
SdfDictionaryProxy proxy( \
_Helper::GetSpecHandle(this), _GET_KEY_(key_)); \
if (value.IsEmpty()) { \
proxy.erase(name); \
} \
else { \
proxy[name] = value; \
} \
} \
}
// Convenience macros to provide common combinations of value accessors
#define SDF_DEFINE_TYPED_GET_SET(name_, key_, getType_, setType_) \
SDF_DEFINE_GET(name_, key_, getType_) \
SDF_DEFINE_SET(name_, key_, setType_)
#define SDF_DEFINE_TYPED_GET_SET_HAS_CLEAR(name_, key_, getType_, setType_) \
SDF_DEFINE_TYPED_GET_SET(name_, key_, getType_, setType_) \
SDF_DEFINE_HAS(name_, key_) \
SDF_DEFINE_CLEAR(name_, key_)
#define SDF_DEFINE_GET_SET(name_, key_, type_) \
SDF_DEFINE_TYPED_GET_SET(name_, key_, type_, \
boost::call_traits<type_>::param_type)
#define SDF_DEFINE_GET_SET_HAS_CLEAR(name_, key_, type_) \
SDF_DEFINE_TYPED_GET_SET_HAS_CLEAR(name_, key_, type_, \
boost::call_traits<type_>::param_type)
#define SDF_DEFINE_IS_SET(name_, key_) \
SDF_DEFINE_IS(name_, key_) \
SDF_DEFINE_SET(name_, key_, bool)
#define SDF_DEFINE_DICTIONARY_GET_SET(getName_, setName_, key_) \
SDF_DEFINE_DICTIONARY_GET(getName_, key_) \
SDF_DEFINE_DICTIONARY_SET(setName_, key_)
// Implementation details
// The helper macros above can be used in the implementation of a spec
// class or a spec API class (see declareSpec.h for details). Both cases
// access data in a different way -- spec classes can query their data
// members directly, while spec API classes need to query their associated
// spec. These templates capture those differences.
template <class T,
bool IsForSpec = boost::is_base_of<SdfSpec, T>::value>
struct Sdf_AccessorHelpers;
template <class T>
struct Sdf_AccessorHelpers<T, true>
{
static const SdfSchemaBase& GetSchema(const T* spec)
{ return spec->GetSchema(); }
static VtValue GetField(const T* spec, const TfToken& key)
{ return spec->GetField(key); }
template <class V>
static bool SetField(T* spec, const TfToken& key, const V& value)
{ return spec->SetField(key, value); }
static bool HasField(const T* spec, const TfToken& key)
{ return spec->HasField(key); }
static void ClearField(T* spec, const TfToken& key)
{ spec->ClearField(key); }
static SdfSpecHandle GetSpecHandle(const T* spec)
{ return SdfCreateNonConstHandle(spec); }
};
template <class T>
struct Sdf_AccessorHelpers<T, false>
{
static const SdfSchemaBase& GetSchema(const T* spec)
{ return spec->_GetSpec().GetSchema(); }
static VtValue GetField(const T* spec, const TfToken& key)
{ return spec->_GetSpec().GetField(key); }
template <class V>
static bool SetField(T* spec, const TfToken& key, const V& value)
{ return spec->_GetSpec().SetField(key, value); }
static bool HasField(const T* spec, const TfToken& key)
{ return spec->_GetSpec().HasField(key); }
static void ClearField(T* spec, const TfToken& key)
{ spec->_GetSpec().ClearField(key); }
static SdfSpecHandle GetSpecHandle(const T* spec)
{ return SdfCreateNonConstHandle(&(spec->_GetSpec())); }
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // #ifndef PXR_USD_SDF_ACCESSOR_HELPERS_H
+122
View File
@@ -0,0 +1,122 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_ALLOWED_H
#define PXR_USD_SDF_ALLOWED_H
/// \file sdf/allowed.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/base/tf/diagnostic.h"
#include <string>
#include <utility>
#include <boost/operators.hpp>
#include <boost/optional.hpp>
PXR_NAMESPACE_OPEN_SCOPE
/// \class SdfAllowed
///
/// Indicates if an operation is allowed and, if not, why not.
///
/// A \c SdfAllowed either evaluates to \c true in a boolean context
/// or evaluates to \c false and has a string annotation.
///
class SdfAllowed : private boost::equality_comparable<SdfAllowed> {
private:
typedef boost::optional<std::string> _State;
public:
typedef std::pair<bool, std::string> Pair;
/// Construct \c true.
SdfAllowed() { }
/// Construct \c true.
SdfAllowed(bool x) { TF_AXIOM(x); }
/// Construct \c false with annotation \p whyNot.
SdfAllowed(const char* whyNot) : _state(std::string(whyNot)) { }
/// Construct \c false with annotation \p whyNot.
SdfAllowed(const std::string& whyNot) : _state(whyNot) { }
/// Construct in \p condition with annotation \p whyNot if \c false.
SdfAllowed(bool condition, const char* whyNot) :
_state(!condition, std::string(whyNot)) { }
/// Construct in \p condition with annotation \p whyNot if \c false.
SdfAllowed(bool condition, const std::string& whyNot) :
_state(!condition, whyNot) { }
/// Construct from bool,string pair \p x.
SdfAllowed(const Pair& x) : _state(!x.first, x.second) { }
~SdfAllowed() { }
#if !defined(doxygen)
typedef _State SdfAllowed::*UnspecifiedBoolType;
#endif
/// Returns \c true in a boolean context if allowed, \c false otherwise.
operator UnspecifiedBoolType() const
{
return _state ? NULL : &SdfAllowed::_state;
}
/// Returns \c false in a boolean context if allowed, \c true otherwise.
bool operator!() const
{
return static_cast<bool>(_state);
}
/// Returns the reason why the operation is not allowed. If the
/// operation is allowed this returns the empty string.
operator const std::string&() const
{
return GetWhyNot();
}
/// Returns the reason why the operation is not allowed. If the
/// operation is allowed this returns the empty string.
SDF_API const std::string& GetWhyNot() const;
/// Returns \c true if allowed, otherwise fills \p whyNot if not \c NULL
/// and returns \c false.
bool IsAllowed(std::string* whyNot) const
{
if (whyNot && _state) {
*whyNot = *_state;
}
return !_state;
}
/// Compare to \p other. Returns \c true if both are \c true or
/// both are \c false and reasons why not are identical.
bool operator==(const SdfAllowed& other) const
{
return _state == other._state;
}
private:
_State _state;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_ALLOWED_H
+47
View File
@@ -0,0 +1,47 @@
//
// Copyright 2017 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_API_H
#define PXR_USD_SDF_API_H
#include "pxr/base/arch/export.h"
#if defined(PXR_STATIC)
# define SDF_API
# define SDF_API_TEMPLATE_CLASS(...)
# define SDF_API_TEMPLATE_STRUCT(...)
# define SDF_LOCAL
#else
# if defined(SDF_EXPORTS)
# define SDF_API ARCH_EXPORT
# define SDF_API_TEMPLATE_CLASS(...) ARCH_EXPORT_TEMPLATE(class, __VA_ARGS__)
# define SDF_API_TEMPLATE_STRUCT(...) ARCH_EXPORT_TEMPLATE(struct, __VA_ARGS__)
# else
# define SDF_API ARCH_IMPORT
# define SDF_API_TEMPLATE_CLASS(...) ARCH_IMPORT_TEMPLATE(class, __VA_ARGS__)
# define SDF_API_TEMPLATE_STRUCT(...) ARCH_IMPORT_TEMPLATE(struct, __VA_ARGS__)
# endif
# define SDF_LOCAL ARCH_HIDDEN
#endif
#endif
+138
View File
@@ -0,0 +1,138 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_ASSET_PATH_H
#define PXR_USD_SDF_ASSET_PATH_H
/// \file sdf/assetPath.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include <boost/functional/hash.hpp>
#include <boost/operators.hpp>
#include <iosfwd>
#include <string>
PXR_NAMESPACE_OPEN_SCOPE
/// \class SdfAssetPath
///
/// Contains an asset path and an optional resolved path.
///
class SdfAssetPath:
public boost::totally_ordered<SdfAssetPath>
{
public:
/// \name Constructors
/// @{
///
/// Construct an empty asset path.
SDF_API SdfAssetPath();
/// Construct asset path with no associated resolved path.
SDF_API explicit SdfAssetPath(const std::string &path);
/// Construct an asset path with an associated resolved path.
SDF_API SdfAssetPath(const std::string &path, const std::string &resolvedPath);
/// @}
///\name Operators
/// @{
/// Equality, including the resolved path.
bool operator==(const SdfAssetPath &rhs) const {
return _assetPath == rhs._assetPath &&
_resolvedPath == rhs._resolvedPath;
}
/// Ordering first by asset path, then by resolved path.
SDF_API bool operator<(const SdfAssetPath &rhs) const;
/// Hash function
size_t GetHash() const {
size_t hash = 0;
boost::hash_combine(hash, _assetPath);
boost::hash_combine(hash, _resolvedPath);
return hash;
}
/// \class Hash
struct Hash
{
size_t operator()(const SdfAssetPath &ap) const {
return ap.GetHash();
}
};
friend size_t hash_value(const SdfAssetPath &ap) { return ap.GetHash(); }
/// @}
/// \name Accessors
/// @{
/// Return the asset path.
const std::string &GetAssetPath() const {
return _assetPath;
}
/// Return the resolved asset path, if any.
///
/// Note that SdfAssetPath only carries a resolved path if the creator of
/// an instance supplied one to the constructor. SdfAssetPath will never
/// perform any resolution itself.
const std::string &GetResolvedPath() const {
return _resolvedPath;
}
/// @}
private:
friend inline void swap(SdfAssetPath &lhs, SdfAssetPath &rhs) {
lhs._assetPath.swap(rhs._assetPath);
lhs._resolvedPath.swap(rhs._resolvedPath);
}
std::string _assetPath;
std::string _resolvedPath;
};
/// \name Related
/// @{
/// Stream insertion operator for the string representation of this assetPath.
///
/// \note This always encodes only the result of GetAssetPath(). The resolved
/// path is ignored for the purpose of this operator. This means that
/// two SdfAssetPath that do not compare equal may produce
/// indistinguishable ostream output.
SDF_API std::ostream& operator<<(std::ostream& out, const SdfAssetPath& ap);
/// @}
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_ASSET_PATH_H
+191
View File
@@ -0,0 +1,191 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_ATTRIBUTE_SPEC_H
#define PXR_USD_SDF_ATTRIBUTE_SPEC_H
/// \file sdf/attributeSpec.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/usd/sdf/declareSpec.h"
#include "pxr/usd/sdf/path.h"
#include "pxr/usd/sdf/propertySpec.h"
#include "pxr/usd/sdf/types.h"
#include "pxr/base/tf/enum.h"
PXR_NAMESPACE_OPEN_SCOPE
/// \class SdfAttributeSpec
///
/// A subclass of SdfPropertySpec that holds typed data.
///
/// Attributes are typed data containers that can optionally hold any
/// and all of the following:
/// \li A single default value.
/// \li An array of knot values describing how the value varies over time.
/// \li A dictionary of posed values, indexed by name.
///
/// The values contained in an attribute must all be of the same type. In the
/// Python API the \c typeName property holds the attribute type. In the C++
/// API, you can get the attribute type using the GetTypeName() method. In
/// addition, all values, including all knot values, must be the same shape.
/// For information on shapes, see the VtShape class reference in the C++
/// documentation.
///
class SdfAttributeSpec : public SdfPropertySpec
{
SDF_DECLARE_SPEC(SdfAttributeSpec, SdfPropertySpec);
public:
typedef SdfAttributeSpec This;
typedef SdfPropertySpec Parent;
///
/// \name Spec construction
/// @{
/// Constructs a new prim attribute instance.
///
/// Creates and returns a new attribute for the given prim.
/// The \p owner will own the newly created attribute.
SDF_API
static SdfAttributeSpecHandle
New(const SdfPrimSpecHandle& owner,
const std::string& name, const SdfValueTypeName& typeName,
SdfVariability variability = SdfVariabilityVarying,
bool custom = false);
/// @}
/// \name Connections
/// @{
/// Returns a proxy for editing the attribute's connection paths.
///
/// The returned proxy, which is an SdfListEditorProxy, modifies the
/// SdfListOp that represents this attribute's connections.
SDF_API
SdfConnectionsProxy GetConnectionPathList() const;
/// Returns \c true if any connection paths are set on this attribute.
SDF_API
bool HasConnectionPaths() const;
/// Clears the connection paths for this attribute.
SDF_API
void ClearConnectionPaths();
/// @}
/// \name Attribute value API
/// @{
/// Returns the allowed tokens metadata for this attribute.
/// Consumers may use this metadata to define a set of predefined
/// options for this attribute's value. However, this metadata is
/// purely advisory. It is up to the consumer to perform any
/// validation against this set of tokens, if desired.
SDF_API
VtTokenArray GetAllowedTokens() const;
/// Sets the allowed tokens metadata for this attribute.
SDF_API
void SetAllowedTokens(const VtTokenArray& allowedTokens);
/// Returns true if allowed tokens metadata is set for this attribute.
SDF_API
bool HasAllowedTokens() const;
/// Clears the allowed tokens metadata for this attribute.
SDF_API
void ClearAllowedTokens();
/// Returns the display unit of the attribute.
SDF_API
TfEnum GetDisplayUnit() const;
/// Sets the display unit of the attribute.
SDF_API
void SetDisplayUnit(const TfEnum& displayUnit);
/// Returns true if a display unit is set for this attribute.
SDF_API
bool HasDisplayUnit() const;
/// Clears the display unit of the attribute.
SDF_API
void ClearDisplayUnit();
/// Returns the color-space in which a color or texture valued attribute
/// is authored.
SDF_API
TfToken GetColorSpace() const;
/// Sets the color-space in which a color or texture valued attribute is
/// authored.
SDF_API
void SetColorSpace(const TfToken &colorSpace);
/// Returns true if this attribute has a colorSpace value authored.
SDF_API
bool HasColorSpace() const;
/// Clears the colorSpace metadata value set on this attribute.
SDF_API
void ClearColorSpace();
/// @}
/// \name Spec properties
/// @{
/// Returns the roleName for this attribute's typeName.
///
/// If the typeName has no roleName, return empty token.
SDF_API
TfToken GetRoleName() const;
/// @}
};
/// Convenience function to create an attributeSpec on a primSpec at the given
/// path, and any necessary parent primSpecs, in the given layer.
///
/// If an attributeSpec already exists at the given path, just author typeName,
/// variability, and custom according to passed arguments and return true.
///
/// Any newly created prim specs have SdfSpecifierOver and an empty type (as if
/// created by SdfJustCreatePrimInLayer()). attrPath must be a valid prim
/// property path (see SdfPath::IsPrimPropertyPath()). Return false and issue
/// an error if we fail to author the required scene description.
SDF_API
bool
SdfJustCreatePrimAttributeInLayer(
const SdfLayerHandle &layer,
const SdfPath &attrPath,
const SdfValueTypeName &typeName,
SdfVariability variability = SdfVariabilityVarying,
bool isCustom = false);
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_ATTRIBUTE_SPEC_H
+82
View File
@@ -0,0 +1,82 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_CHANGE_BLOCK_H
#define PXR_USD_SDF_CHANGE_BLOCK_H
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
PXR_NAMESPACE_OPEN_SCOPE
/// \class SdfChangeBlock
///
/// <b>DANGER DANGER DANGER</b>
///
/// Please make sure you have read and fully understand the
/// issues below before using a changeblock! They are very
/// easy to use in an unsafe way that could make the system
/// crash or corrupt data. If you have any questions, please
/// contact the USD team, who would be happy to help!
///
/// SdfChangeBlock provides a way to group a round of related changes to
/// scene description in order to process them more efficiently.
///
/// Normally, Sdf sends notification immediately as changes are made so
/// that downstream representations in Csd and Mf can update accordingly.
///
/// However, sometimes it can be advantageous to group a series of Sdf
/// changes into a batch so that they can be processed more efficiently,
/// with a single round of change processing. An example might be when
/// setting many avar values on a model at the same time.
///
/// Opening a changeblock tells Sdf to delay sending notification about
/// changes until the outermost changeblock is exited. Until then,
/// Sdf internally queues up the notification it needs to send.
///
/// \note It is *not* safe to use Csd, Mf, or other downstream API
/// while a changeblock is open!!111 This is because those derived
/// representations will not have had a chance to update while the
/// changeblock is open. Not only will their view of the world be
/// stale, it could be unsafe to even make queries from, since they
/// may be holding onto expired handles to Sdf objects that no longer
/// exist.
///
/// If you need to make a bunch of changes to scene description,
/// the best approach is to build a list of necessary changes that
/// can be performed directly via the Sdf API, then submit those all
/// inside a changeblock without talking to any downstream libraries.
/// For example, this is how Csd performs namespace edits.
///
class SdfChangeBlock {
public:
SDF_API
SdfChangeBlock();
SDF_API
~SdfChangeBlock();
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_CHANGE_BLOCK_H
+266
View File
@@ -0,0 +1,266 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_CHANGE_LIST_H
#define PXR_USD_SDF_CHANGE_LIST_H
/// \file sdf/changeList.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/usd/sdf/path.h"
#include "pxr/usd/sdf/types.h"
#include "pxr/base/tf/smallVector.h"
#include <set>
#include <map>
#include <unordered_map>
#include <iosfwd>
PXR_NAMESPACE_OPEN_SCOPE
class SdfChangeList;
typedef std::vector<
std::pair<SdfLayerHandle, SdfChangeList>
> SdfLayerChangeListVec;
/// \class SdfChangeList
///
/// A list of scene description modifications, organized by the namespace
/// paths where the changes occur.
///
class SdfChangeList
{
public:
SdfChangeList() = default;
SDF_API SdfChangeList(SdfChangeList const &);
SdfChangeList(SdfChangeList &&) = default;
SDF_API SdfChangeList &operator=(SdfChangeList const &);
SdfChangeList &operator=(SdfChangeList &&) = default;
enum SubLayerChangeType {
SubLayerAdded,
SubLayerRemoved,
SubLayerOffset
};
void DidReplaceLayerContent();
void DidReloadLayerContent();
void DidChangeLayerResolvedPath();
void DidChangeLayerIdentifier(const std::string &oldIdentifier);
void DidChangeSublayerPaths(const std::string &subLayerPath,
SubLayerChangeType changeType);
void DidAddPrim(const SdfPath &primPath, bool inert);
void DidRemovePrim(const SdfPath &primPath, bool inert);
void DidReorderPrims(const SdfPath &parentPath);
void DidChangePrimName(const SdfPath &oldPath, const SdfPath &newPath);
void DidChangePrimVariantSets(const SdfPath &primPath);
void DidChangePrimInheritPaths(const SdfPath &primPath);
void DidChangePrimReferences(const SdfPath &primPath);
void DidChangePrimSpecializes(const SdfPath &primPath);
void DidAddProperty(const SdfPath &propPath, bool hasOnlyRequiredFields);
void DidRemoveProperty(const SdfPath &propPath, bool hasOnlyRequiredFields);
void DidReorderProperties(const SdfPath &propPath);
void DidChangePropertyName(const SdfPath &oldPath, const SdfPath &newPath);
void DidChangeAttributeTimeSamples(const SdfPath &attrPath);
void DidChangeAttributeConnection(const SdfPath &attrPath);
void DidChangeRelationshipTargets(const SdfPath &relPath);
void DidAddTarget(const SdfPath &targetPath);
void DidRemoveTarget(const SdfPath &targetPath);
void DidChangeInfo(const SdfPath &path, const TfToken &key,
const VtValue &oldValue, const VtValue &newValue);
/// \struct Entry
///
/// Entry of changes at a single path in namespace.
///
/// If the path is SdfPath::AbsoluteRootPath(), that indicates a change
/// to the root of namespace (that is, a layer or stage).
///
/// Note: Our language for invalidation used to be more precise
/// about items added, removed, or reordered. It might seem that
/// this would afford more opportunities for efficient updates,
/// but in practice it does not. Because our derived data typically
/// must recompose or reinstantiate based on the underlying data,
/// the particular delta might be ignored, overridden, or invalid.
/// It is simpler to treat all changes identically, and focus on
/// making the common base case fast, rather than have complicated
/// differential update logic. It also vastly simplifies the
/// language of invalidation.
///
struct Entry {
// Map of info keys that have changed to (old, new) value pairs.
typedef std::pair<VtValue, VtValue> InfoChange;
// We usually change just a few fields on a spec in one go, so we store
// up to three locally (e.g. typeName, variability, default).
typedef TfSmallVector<std::pair<TfToken, InfoChange>, 3> InfoChangeVec;
InfoChangeVec infoChanged;
/// Return the iterator in infoChanged whose first element is \p key, or
/// infoChanged.end() if there is no such element.
InfoChangeVec::const_iterator
FindInfoChange(TfToken const &key) const {
InfoChangeVec::const_iterator iter = infoChanged.begin();
for (InfoChangeVec::const_iterator end = infoChanged.end();
iter != end; ++iter) {
if (iter->first == key) {
break;
}
}
return iter;
}
/// Return true if this entry has an info change for \p key, false
/// otherwise.
bool HasInfoChange(TfToken const &key) const {
return FindInfoChange(key) != infoChanged.end();
}
typedef std::pair<std::string, SubLayerChangeType> SubLayerChange;
std::vector<SubLayerChange> subLayerChanges;
// Empty if didRename is not set
SdfPath oldPath;
// Empty if didChangeIdentifier is not set
std::string oldIdentifier;
// Most changes are stored as simple bits.
struct _Flags {
_Flags() {
memset(this, 0, sizeof(*this));
}
// SdfLayer
bool didChangeIdentifier:1;
bool didChangeResolvedPath:1;
bool didReplaceContent:1;
bool didReloadContent:1;
// SdfLayer, SdfPrimSpec, SdfRelationshipTarget.
bool didReorderChildren:1;
bool didReorderProperties:1;
// SdfPrimSpec, SdfPropertySpec
bool didRename:1;
// SdfPrimSpec
bool didChangePrimVariantSets:1;
bool didChangePrimInheritPaths:1;
bool didChangePrimSpecializes:1;
bool didChangePrimReferences:1;
// SdfPropertySpec
bool didChangeAttributeTimeSamples:1;
bool didChangeAttributeConnection:1;
bool didChangeRelationshipTargets:1;
bool didAddTarget:1;
bool didRemoveTarget:1;
// SdfPrimSpec add/remove
bool didAddInertPrim:1;
bool didAddNonInertPrim:1;
bool didRemoveInertPrim:1;
bool didRemoveNonInertPrim:1;
// Property add/remove
bool didAddPropertyWithOnlyRequiredFields:1;
bool didAddProperty:1;
bool didRemovePropertyWithOnlyRequiredFields:1;
bool didRemoveProperty:1;
};
_Flags flags;
};
/// Map of change entries at various paths in a layer. We store one entry
/// in local space, since it's very common to edit just a single spec in a
/// single round of changes.
using EntryList = TfSmallVector<std::pair<SdfPath, Entry>, 1>;
public:
const EntryList & GetEntryList() const { return _entries; }
// Change accessors/mutators
SDF_API
Entry const &GetEntry( const SdfPath & ) const;
using const_iterator = EntryList::const_iterator;
SDF_API
const_iterator FindEntry(SdfPath const &) const;
const_iterator begin() const {
return _entries.begin();
}
const_iterator cbegin() const {
return _entries.cbegin();
}
const_iterator end() const {
return _entries.end();
}
const_iterator cend() const {
return _entries.cend();
}
private:
friend void swap(SdfChangeList &a, SdfChangeList &b) {
a._entries.swap(b._entries);
a._entriesAccel.swap(b._entriesAccel);
}
Entry &_GetEntry(SdfPath const &);
// If no entry with `newPath` exists, create one. If an entry with
// `oldPath` exists, move its contents over `newPath`'s and erase it.
// Return a reference to `newPath`'s entry.
Entry &_MoveEntry(SdfPath const &oldPath, SdfPath const &newPath);
EntryList::iterator _MakeNonConstIterator(EntryList::const_iterator i);
Entry &_AddNewEntry(SdfPath const &path);
void _EraseEntry(SdfPath const &);
void _RebuildAccel();
EntryList _entries;
using _AccelTable = std::unordered_map<SdfPath, size_t, SdfPath::Hash>;
std::unique_ptr<_AccelTable> _entriesAccel;
static constexpr size_t _AccelThreshold = 64;
};
// Stream-output operator
SDF_API std::ostream& operator<<(std::ostream&, const SdfChangeList &);
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_CHANGE_LIST_H
+123
View File
@@ -0,0 +1,123 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_CHILDREN_H
#define PXR_USD_SDF_CHILDREN_H
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/usd/sdf/declareHandles.h"
#include "pxr/usd/sdf/path.h"
#include <boost/iterator/iterator_facade.hpp>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
SDF_DECLARE_HANDLES(SdfLayer);
class SdfSpec;
/// \class Sdf_Children
///
/// Sdf_Children generically represents the children of an object. For
/// instance, it might be used for the name children of a prim or the
/// relationship targets of a relationship.
///
/// The provided ChildPolicy class determines how this object behaves.
/// It primarily specifies how to map between keys (such as the name of
/// an object) and values (such as SpecHandles for those objects).
///
template<class ChildPolicy>
class Sdf_Children
{
public:
typedef typename ChildPolicy::KeyPolicy KeyPolicy;
typedef typename ChildPolicy::KeyType KeyType;
typedef typename ChildPolicy::ValueType ValueType;
typedef typename ChildPolicy::FieldType FieldType;
typedef Sdf_Children<ChildPolicy> This;
SDF_API
Sdf_Children();
SDF_API
Sdf_Children(const Sdf_Children<ChildPolicy> &other);
SDF_API
Sdf_Children(const SdfLayerHandle &layer,
const SdfPath &parentPath, const TfToken &childrenKey,
const KeyPolicy& keyPolicy = KeyPolicy());
/// Return whether this object is valid.
SDF_API
bool IsValid() const;
/// Return the number of children that this object contains.
SDF_API
size_t GetSize() const;
/// Return the child at the specified index.
SDF_API
ValueType GetChild(size_t index) const;
/// Find the index of the specified key, or return the size if it's not found.
SDF_API
size_t Find(const KeyType &key) const;
/// Find the key that corresponds to \a value, or return a default
/// constructed key if it's not found.
SDF_API
KeyType FindKey(const ValueType &value) const;
/// Return true if this object and \a other are equivalent.
SDF_API
bool IsEqualTo(const This &other) const;
/// Replace this object's children with the ones in \a values.
SDF_API
bool Copy(const std::vector<ValueType> & values, const std::string &type);
/// Insert a new child at the specified \a index.
SDF_API
bool Insert(const ValueType& value, size_t index, const std::string &type);
/// Erase the child with the specified key.
SDF_API
bool Erase(const KeyType& key, const std::string &type);
private:
void _UpdateChildNames() const;
private:
SdfLayerHandle _layer;
SdfPath _parentPath;
TfToken _childrenKey;
KeyPolicy _keyPolicy;
mutable std::vector<FieldType> _childNames;
mutable bool _childNamesValid;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_CHILDREN_H
+293
View File
@@ -0,0 +1,293 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_CHILDREN_POLICIES_H
#define PXR_USD_SDF_CHILDREN_POLICIES_H
// These policies are used as template arguments to SdfChildrenView to
// determine how the view maps between keys (the child's name or path) and
// values (the child's SpecHandle).
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/usd/sdf/path.h"
#include "pxr/usd/sdf/types.h"
#include "pxr/usd/sdf/declareHandles.h"
#include "pxr/usd/sdf/proxyPolicies.h"
#include "pxr/usd/sdf/schema.h"
PXR_NAMESPACE_OPEN_SCOPE
SDF_DECLARE_HANDLES(SdfAttributeSpec);
SDF_DECLARE_HANDLES(SdfPrimSpec);
SDF_DECLARE_HANDLES(SdfPropertySpec);
SDF_DECLARE_HANDLES(SdfRelationshipSpec);
SDF_DECLARE_HANDLES(SdfVariantSpec);
SDF_DECLARE_HANDLES(SdfVariantSetSpec);
//
// Token Child Policies
//
template <class SpecType>
class Sdf_TokenChildPolicy {
public:
typedef SdfNameKeyPolicy KeyPolicy;
typedef KeyPolicy::value_type KeyType;
typedef TfToken FieldType;
typedef SpecType ValueType;
static KeyType GetKey(const ValueType &spec) {
return spec->GetPath().GetName();
}
static SdfPath GetParentPath(const SdfPath &childPath) {
return childPath.GetParentPath();
}
static FieldType GetFieldValue(const SdfPath &childPath) {
return childPath.GetNameToken();
}
static bool IsValidIdentifier(const std::string &name) {
return SdfSchema::IsValidIdentifier(name);
}
};
class Sdf_PrimChildPolicy :
public Sdf_TokenChildPolicy<SdfPrimSpecHandle>
{
public:
static SdfPath GetChildPath(const SdfPath &parentPath, const FieldType &key) {
return parentPath.AppendChild(key);
}
static TfToken GetChildrenToken(const SdfPath& parentPath) {
return SdfChildrenKeys->PrimChildren;
}
};
class Sdf_PropertyChildPolicy :
public Sdf_TokenChildPolicy<SdfPropertySpecHandle>
{
public:
static SdfPath GetChildPath(const SdfPath &parentPath, const FieldType &key) {
if (parentPath.IsTargetPath()) {
return parentPath.AppendRelationalAttribute(key);
}
else {
return parentPath.AppendProperty(key);
}
}
static TfToken GetChildrenToken(const SdfPath& parentPath) {
return SdfChildrenKeys->PropertyChildren;
}
static bool IsValidIdentifier(const std::string &name) {
return SdfSchema::IsValidNamespacedIdentifier(name);
}
};
class Sdf_AttributeChildPolicy :
public Sdf_TokenChildPolicy<SdfAttributeSpecHandle>
{
public:
static SdfPath GetChildPath(const SdfPath &parentPath, const FieldType &key) {
if (parentPath.IsTargetPath()) {
return parentPath.AppendRelationalAttribute(key);
}
else {
return parentPath.AppendProperty(key);
}
}
static TfToken GetChildrenToken(const SdfPath& parentPath) {
return SdfChildrenKeys->PropertyChildren;
}
static bool IsValidIdentifier(const std::string &name) {
return SdfSchema::IsValidNamespacedIdentifier(name);
}
};
class Sdf_RelationshipChildPolicy :
public Sdf_TokenChildPolicy<SdfRelationshipSpecHandle>
{
public:
static SdfPath GetChildPath(const SdfPath &parentPath, const FieldType &key) {
return parentPath.AppendProperty(key);
}
static TfToken GetChildrenToken(const SdfPath& parentPath) {
return SdfChildrenKeys->PropertyChildren;
}
static bool IsValidIdentifier(const std::string &name) {
return SdfSchema::IsValidNamespacedIdentifier(name);
}
};
class Sdf_MapperArgChildPolicy :
public Sdf_TokenChildPolicy<SdfSpecHandle>
{
public:
static SdfPath GetChildPath(const SdfPath &parentPath, const FieldType &key) {
return parentPath.AppendMapperArg(key);
}
static TfToken GetChildrenToken(const SdfPath& parentPath) {
return SdfChildrenKeys->MapperArgChildren;
}
};
class Sdf_ExpressionChildPolicy :
public Sdf_TokenChildPolicy<SdfSpecHandle>
{
public:
static SdfPath GetChildPath(const SdfPath &parentPath, const FieldType &key) {
return parentPath.AppendExpression();
}
static TfToken GetChildrenToken(const SdfPath& parentPath) {
return SdfChildrenKeys->ExpressionChildren;
}
};
class Sdf_VariantChildPolicy :
public Sdf_TokenChildPolicy<SdfVariantSpecHandle>
{
public:
static SdfPath GetChildPath(const SdfPath &parentPath, const FieldType &key) {
std::string variantSet = parentPath.GetVariantSelection().first;
return parentPath.GetParentPath().AppendVariantSelection(
TfToken(variantSet), key);
}
static SdfPath GetParentPath(const SdfPath &childPath) {
// Construct a path with the same variant set but an empty variant
std::string variantSet = childPath.GetVariantSelection().first;
return childPath.GetParentPath().AppendVariantSelection(variantSet, "");
}
static TfToken GetChildrenToken(const SdfPath& parentPath) {
return SdfChildrenKeys->VariantChildren;
}
};
class Sdf_VariantSetChildPolicy :
public Sdf_TokenChildPolicy<SdfVariantSetSpecHandle>
{
public:
static SdfPath GetChildPath(const SdfPath &parentPath, const FieldType &key) {
return parentPath.AppendVariantSelection(key, "");
}
static TfToken GetChildrenToken(const SdfPath& parentPath) {
return SdfChildrenKeys->VariantSetChildren;
}
};
//
// Path Child Policies
//
template <class SpecType>
class Sdf_PathChildPolicy
{
public:
typedef SdfPathKeyPolicy KeyPolicy;
typedef KeyPolicy::value_type KeyType;
typedef SpecType ValueType;
typedef SdfPath FieldType;
static SdfPath GetParentPath(const SdfPath &childPath) {
return childPath.GetParentPath();
}
static KeyType GetKey(const ValueType &value) {
return value->GetPath().GetTargetPath();
}
static SdfPath GetChildPath(const SdfPath &parentPath, const FieldType &key) {
return parentPath.AppendTarget(key);
}
static FieldType GetFieldValue(const SdfPath &childPath) {
return childPath.GetTargetPath();
}
static bool IsValidIdentifier(const FieldType &path) {
return true;
}
static bool IsValidIdentifier(const std::string &path) {
return SdfPath::IsValidPathString(path);
}
};
class Sdf_MapperChildPolicy :
public Sdf_PathChildPolicy<SdfSpecHandle>
{
public:
static SdfPath GetChildPath(const SdfPath &parentPath, const FieldType &key) {
SdfPath targetPath = key.MakeAbsolutePath(parentPath.GetPrimPath());
return parentPath.AppendMapper(targetPath);
}
static FieldType GetFieldValue(const SdfPath &childPath) {
SdfPath targetPath = childPath.GetTargetPath();
return targetPath.MakeAbsolutePath(childPath.GetPrimPath());
}
static TfToken GetChildrenToken(const SdfPath& parentPath) {
return SdfChildrenKeys->MapperChildren;
}
};
class Sdf_AttributeConnectionChildPolicy :
public Sdf_PathChildPolicy<SdfSpecHandle> {
public:
static TfToken GetChildrenToken(const SdfPath& parentPath) {
return SdfChildrenKeys->ConnectionChildren;
}
};
class Sdf_RelationshipTargetChildPolicy :
public Sdf_PathChildPolicy<SdfSpecHandle> {
public:
static TfToken GetChildrenToken(const SdfPath& parentPath) {
return SdfChildrenKeys->RelationshipTargetChildren;
}
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_CHILDREN_POLICIES_H
+478
View File
@@ -0,0 +1,478 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_CHILDREN_PROXY_H
#define PXR_USD_SDF_CHILDREN_PROXY_H
/// \file sdf/childrenProxy.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/usd/sdf/changeBlock.h"
#include "pxr/base/vt/value.h"
#include "pxr/base/tf/diagnostic.h"
#include "pxr/base/tf/iterator.h"
#include <boost/iterator/iterator_facade.hpp>
#include <boost/iterator/reverse_iterator.hpp>
#include <boost/operators.hpp>
#include <iterator>
#include <map>
#include <utility>
PXR_NAMESPACE_OPEN_SCOPE
template <class _View>
class SdfChildrenProxy : boost::equality_comparable<SdfChildrenProxy<_View> > {
public:
typedef _View View;
typedef typename View::Adapter Adapter;
typedef typename View::ChildPolicy ChildPolicy;
typedef typename View::key_type key_type;
typedef typename View::value_type mapped_type;
typedef std::vector<mapped_type> mapped_vector_type;
typedef std::pair<const key_type, mapped_type> value_type;
typedef std::map<key_type, mapped_type> map_type;
typedef typename View::size_type size_type;
typedef SdfChildrenProxy<View> This;
private:
typedef typename View::const_iterator _inner_iterator;
class _ValueProxy {
public:
_ValueProxy() : _owner(NULL) { }
_ValueProxy(This* owner, _inner_iterator i) : _owner(owner), _pos(i)
{
// Do nothing
}
operator mapped_type() const
{
return *_pos;
}
template <class U>
_ValueProxy& operator=(const U& x)
{
_owner->_Set(*_pos, x);
return *this;
}
bool operator==(const mapped_type& other) const
{
return *_pos == other;
}
private:
This* _owner;
_inner_iterator _pos;
};
class _PairProxy {
public:
explicit _PairProxy(This* owner, _inner_iterator i) :
first(owner->_view.key(i)), second(owner, i) { }
const key_type first;
_ValueProxy second;
operator value_type() const
{
return value_type(first, second);
}
};
friend class _PairProxy;
class _Traits {
public:
static value_type Dereference(const This* owner, _inner_iterator i)
{
return value_type(owner->_view.key(i), *i);
}
static _PairProxy Dereference(This* owner, _inner_iterator i)
{
return _PairProxy(owner, i);
}
};
template <class _Owner, class _Iter, class _Value>
class _Iterator :
public boost::iterator_facade<
_Iterator<_Owner, _Iter, _Value>,
_Value,
std::bidirectional_iterator_tag,
_Value> {
public:
_Iterator() { }
_Iterator(_Owner owner, _inner_iterator i) : _owner(owner), _pos(i) { }
template <class O2, class I2, class V2>
_Iterator(const _Iterator<O2, I2, V2>& other) :
_owner(other._owner), _pos(other._pos) { }
private:
friend class boost::iterator_core_access;
_Value dereference() const
{
return _Traits::Dereference(_owner, _pos);
}
template <class O2, class I2, class V2>
bool equal(const _Iterator<O2, I2, V2>& other) const
{
return _pos == other._pos;
}
void increment() {
++_pos;
}
void decrement() {
--_pos;
}
private:
_Owner _owner;
_inner_iterator _pos;
template <class O2, class I2, class V2>
friend class _Iterator;
};
public:
typedef _ValueProxy reference;
typedef _Iterator<This*, _inner_iterator, _PairProxy> iterator;
typedef boost::reverse_iterator<iterator> reverse_iterator;
typedef _Iterator<const This*, _inner_iterator, value_type> const_iterator;
typedef boost::reverse_iterator<const_iterator> const_reverse_iterator;
static const int CanSet = 1;
static const int CanInsert = 2;
static const int CanErase = 4;
SdfChildrenProxy(const View& view, const std::string& type,
int permission = CanSet | CanInsert | CanErase) :
_view(view), _type(type), _permission(permission)
{
// Do nothing
}
template <class U>
SdfChildrenProxy(const SdfChildrenProxy<U>& other) :
_view(other._view), _type(other._type), _permission(other._permission)
{
// Do nothing
}
This& operator=(const This& other)
{
if (other._Validate()) {
_Copy(other._view.values());
}
return *this;
}
template <class U>
This& operator=(const SdfChildrenProxy<U>& other)
{
if (other._Validate()) {
_Copy(other._view.values());
}
return *this;
}
This& operator=(const mapped_vector_type& values)
{
_Copy(values);
return *this;
}
operator mapped_vector_type() const
{
return _Validate() ? _view.values() : mapped_vector_type();
}
map_type items() const
{
return _Validate() ? _view.template items_as<map_type>() :map_type();
}
iterator begin()
{
return iterator(_GetThis(), _view.begin());
}
iterator end()
{
return iterator(_GetThis(), _view.end());
}
const_iterator begin() const
{
return const_iterator(_GetThis(), _view.begin());
}
const_iterator end() const
{
return const_iterator(_GetThis(), _view.end());
}
reverse_iterator rbegin()
{
return reverse_iterator(end());
}
reverse_iterator rend()
{
return reverse_iterator(begin());
}
const_reverse_iterator rbegin() const
{
return reverse_iterator(end());
}
const_reverse_iterator rend() const
{
return reverse_iterator(begin());
}
size_type size() const
{
return _Validate() ? _view.size() : 0;
}
size_type max_size() const
{
return _view.max_size();
}
bool empty() const
{
return _Validate() ? _view.empty() : true;
}
std::pair<iterator, bool> insert(const mapped_type& value)
{
if (_Validate(CanInsert)) {
iterator i = find(_view.key(value));
if (i == end()) {
if (_PrimInsert(value, size())) {
return std::make_pair(find(_view.key(value)), true);
}
else {
return std::make_pair(end(), false);
}
}
else {
return std::make_pair(i, false);
}
}
else {
return std::make_pair(iterator(), false);
}
}
iterator insert(iterator pos, const mapped_type& value)
{
return insert(value).first;
}
template <class InputIterator>
void insert(InputIterator first, InputIterator last)
{
if (_Validate(CanInsert)) {
SdfChangeBlock block;
for (; first != last; ++first) {
_PrimInsert(*first, size());
}
}
}
void erase(iterator pos)
{
_Erase(pos->first);
}
size_type erase(const key_type& key)
{
return _Erase(key) ? 1 : 0;
}
void erase(iterator first, iterator last)
{
if (_Validate(CanErase)) {
SdfChangeBlock block;
while (first != last) {
const key_type& key = first->first;
++first;
_PrimErase(key);
}
}
}
void clear()
{
_Copy(mapped_vector_type());
}
iterator find(const key_type& key)
{
return _Validate() ? iterator(this, _view.find(key)) : iterator();
}
const_iterator find(const key_type& key) const
{
return _Validate() ? const_iterator(this, _view.find(key)) :
const_iterator();
}
size_type count(const key_type& key) const
{
return _Validate() ? _view.count(key) : 0;
}
bool operator==(const This& other) const
{
return _view == other._view;
}
/// Explicit bool conversion operator. The proxy object converts to
/// \c true if it is valid, \c false otherwise.
explicit operator bool() const
{
return _view.IsValid();
}
private:
const std::string& _GetType() const
{
return _type;
}
int _GetPermission() const
{
return _permission;
}
This* _GetThis()
{
return _Validate() ? this : NULL;
}
const This* _GetThis() const
{
return _Validate() ? this : NULL;
}
bool _Validate() const
{
if (_view.IsValid()) {
return true;
}
else {
TF_CODING_ERROR("Accessing expired %s", _type.c_str());
return false;
}
}
bool _Validate(int permission)
{
if (!_Validate()) {
return false;
}
if ((_permission & permission) == permission) {
return true;
}
const char* op = "edit";
if (~_permission & permission & CanSet) {
op = "replace";
}
else if (~_permission & permission & CanInsert) {
op = "insert";
}
else if (~_permission & permission & CanErase) {
op = "remove";
}
TF_CODING_ERROR("Cannot %s %s", op, _type.c_str());
return false;
}
bool _Copy(const mapped_vector_type& values)
{
return _Validate(CanSet) ? _PrimCopy(values) : false;
}
bool _Insert(const mapped_type& value, size_t index)
{
return _Validate(CanInsert) ? _PrimInsert(value, index) : false;
}
bool _Erase(const key_type& key)
{
return _Validate(CanErase) ? _PrimErase(key) : false;
}
bool _PrimCopy(const mapped_vector_type& values)
{
typedef std::vector<typename ChildPolicy::ValueType>
ChildrenValueVector;
ChildrenValueVector v;
for (size_t i = 0; i < values.size(); ++i)
v.push_back(Adapter::Convert(values[i]));
return _view.GetChildren().Copy(v, _type);
}
bool _PrimInsert(const mapped_type& value, size_t index)
{
return _view.GetChildren().Insert(
Adapter::Convert(value), index, _type);
}
bool _PrimErase(const key_type& key)
{
return _view.GetChildren().Erase(key, _type);
}
private:
View _view;
std::string _type;
int _permission;
template <class V> friend class SdfChildrenProxy;
template <class V> friend class SdfPyChildrenProxy;
};
// Allow TfIteration over children proxies.
template <typename _View>
struct Tf_ShouldIterateOverCopy<SdfChildrenProxy<_View> > : boost::true_type
{
};
// Cannot get from a VtValue except as the correct type.
template <class _View>
struct Vt_DefaultValueFactory<SdfChildrenProxy<_View> > {
static Vt_DefaultValueHolder Invoke() = delete;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_CHILDREN_PROXY_H
+177
View File
@@ -0,0 +1,177 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_CHILDREN_UTILS_H
#define PXR_USD_SDF_CHILDREN_UTILS_H
/// \file sdf/childrenUtils.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/usd/sdf/allowed.h"
#include "pxr/usd/sdf/types.h"
PXR_NAMESPACE_OPEN_SCOPE
/// \class Sdf_ChildrenUtils
///
/// Helper functions for creating and manipulating the children
/// of a spec. A ChildPolicy must be provided that specifies which type
/// of children to edit. (See childrenPolicies.h for details).
///
template<class ChildPolicy>
class Sdf_ChildrenUtils
{
public:
/// The type of the key that identifies a child. This is usually
/// a std::string or an SdfPath.
typedef typename ChildPolicy::KeyType KeyType;
/// The type of the child identifier as it's stored in the layer's data.
/// This is usually a TfToken.
typedef typename ChildPolicy::FieldType FieldType;
/// Create a new spec in \a layer at \childPath and add it to its parent's
/// field named \childrenKey. Emit an error and return false if the new spec
/// couldn't be created.
static bool CreateSpec(
const SdfLayerHandle &layer,
const SdfPath &childPath,
SdfSpecType specType,
bool inert=true) {
return CreateSpec(get_pointer(layer), childPath, specType, inert);
}
// This overload is intended primarily for internal use.
SDF_API
static bool CreateSpec(
SdfLayer *layer,
const SdfPath &childPath,
SdfSpecType specType,
bool inert=true);
/// \name Rename API
/// @{
/// Return whether \a newName is a valid name for a child.
SDF_API
static bool IsValidName(const FieldType &newName);
/// Return whether \a newName is a valid name for a child.
SDF_API
static bool IsValidName(const std::string &newName);
/// Return whether \a spec can be renamed to \a newName.
static SdfAllowed CanRename(
const SdfSpec &spec,
const FieldType &newName);
/// Rename \a spec to \a newName. If \a fixPrimListEdits is true,
/// then also fix up the name children order. It's an error for
/// \a fixPrimListEdits to be true if spec is not a PrimSpec.
SDF_API
static bool Rename(
const SdfSpec &spec,
const FieldType &newName);
/// @}
/// \name Children List API
/// @{
/// Replace the children of the spec at \a path with the specs in \a
/// values. This will delete existing children that aren't in \a values and
/// reparent children from other locations in the layer.
SDF_API
static bool SetChildren(
const SdfLayerHandle &layer,
const SdfPath &path,
const std::vector<typename ChildPolicy::ValueType> &values);
/// Insert \a value as a child of \a path at the specified index.
SDF_API
static bool InsertChild(
const SdfLayerHandle &layer,
const SdfPath &path,
const typename ChildPolicy::ValueType& value,
int index);
/// Remove the child identified by \a key.
SDF_API
static bool RemoveChild(
const SdfLayerHandle &layer,
const SdfPath &path,
const typename ChildPolicy::KeyType& key);
/// @}
/// \name Batch editing API
/// @{
/// Insert \a value as a child of \a path at the specified index with
/// the new name \p newName.
SDF_API
static bool MoveChildForBatchNamespaceEdit(
const SdfLayerHandle &layer,
const SdfPath &path,
const typename ChildPolicy::ValueType& value,
const typename ChildPolicy::FieldType& newName,
int index);
/// Remove the child identified by \a key.
SDF_API
static bool RemoveChildForBatchNamespaceEdit(
const SdfLayerHandle &layer,
const SdfPath &path,
const typename ChildPolicy::KeyType& key)
{
return RemoveChild(layer, path, key);
}
/// Returns \c true if \p value can be inserted as a child of \p path
/// with the new name \p newName at the index \p index, otherwise
/// returns \c false and sets \p whyNot.
SDF_API
static bool CanMoveChildForBatchNamespaceEdit(
const SdfLayerHandle &layer,
const SdfPath &path,
const typename ChildPolicy::ValueType& value,
const typename ChildPolicy::FieldType& newName,
int index,
std::string* whyNot);
/// Returns \c true if the child of \p path identified by \p key can
/// be removed, otherwise returns \c false and sets \p whyNot.
SDF_API
static bool CanRemoveChildForBatchNamespaceEdit(
const SdfLayerHandle &layer,
const SdfPath &path,
const typename ChildPolicy::FieldType& key,
std::string* whyNot);
/// @}
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_CHILDREN_UTILS_H
+537
View File
@@ -0,0 +1,537 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_CHILDREN_VIEW_H
#define PXR_USD_SDF_CHILDREN_VIEW_H
/// \file sdf/childrenView.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/usd/sdf/children.h"
#include "pxr/base/tf/iterator.h"
#include <boost/compressed_pair.hpp>
#include <boost/iterator/filter_iterator.hpp>
#include <boost/iterator/iterator_facade.hpp>
#include <boost/iterator/reverse_iterator.hpp>
#include <algorithm>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
/// \class SdfChildrenViewTrivialPredicate
///
/// Special case predicate that always passes.
///
/// \c T is the type exposed by the value traits.
///
/// This predicate is compiled out.
///
template <class T>
class SdfChildrenViewTrivialPredicate {
public:
bool operator()(const T& x) const { return true; }
};
/// \class SdfChildrenViewTrivialAdapter
///
/// Special case adapter that does no conversions.
///
template <class T>
class SdfChildrenViewTrivialAdapter {
public:
typedef T PrivateType;
typedef T PublicType;
static const PublicType& Convert(const PrivateType& t) { return t; }
};
/// \class Sdf_ChildrenViewTraits
/// This traits class defines the iterator for a particular ChildrenView
/// along with conversions to and from the view's internal un-filtered iterator.
///
/// A specialization of the traits for trivial predicates allows the
/// internal iterator to be used directly.
///
template <typename _Owner, typename _InnerIterator, typename _DummyPredicate>
class Sdf_ChildrenViewTraits {
private:
// Internal predicate object which will be passed to the filter
// iterator. This just calls through to the owner's predicate.
class _Predicate {
public:
typedef typename _Owner::value_type value_type;
_Predicate() : _owner(NULL) { }
_Predicate(const _Owner* owner) : _owner(owner) { }
bool operator()(const value_type& x) const
{
return _owner->GetPredicate()(
_Owner::Adapter::Convert(x));
}
private:
const _Owner* _owner;
};
public:
typedef boost::filter_iterator<_Predicate, _InnerIterator> const_iterator;
// Convert from a private _InnerIterator to a public const_iterator.
// filter_iterator requires an end iterator, which is constructed using
// size.
static const_iterator GetIterator(const _Owner* owner,
const _InnerIterator& i,
size_t size)
{
_InnerIterator end(owner,size);
return const_iterator(_Predicate(owner), i, end);
}
// Convert from a public const_iterator to a private _InnerIterator.
static const _InnerIterator& GetBase(const const_iterator& i)
{
return i.base();
}
};
// Children view traits specialization for trivial predicates. This
// eliminates the predicate altogether and defines the public iterator type
// to be the same as the inner iterator type.
template <typename _Owner, typename _InnerIterator>
class Sdf_ChildrenViewTraits<_Owner, _InnerIterator,
SdfChildrenViewTrivialPredicate<typename _Owner::ChildPolicy::ValueType> > {
private:
public:
typedef _InnerIterator const_iterator;
static const const_iterator& GetIterator(const _Owner*,
const _InnerIterator& i, size_t size)
{
return i;
}
static const _InnerIterator& GetBase(const const_iterator& i)
{
return i;
}
};
/// \class SdfChildrenView
///
/// Provides a view onto an object's children.
///
/// The \c _ChildPolicy dictates the type of children being viewed by this
/// object. This policy defines the key type by which children are referenced
/// (e.g. a TfToken, or an SdfPath) and the value type of the children objects.
///
/// The \c _Predicate takes a value type argument and returns \c true if the
/// object should be included in the view and \c false otherwise.
///
/// The \c _Adapter allows the view to present the children objects as a
/// different type. The _Adapter class must provide functions to convert the
/// children object type defined by \c _ChildPolicy to the desired public
/// type and vice-versa. See SdfChildrenViewTrivialAdapter for an example.
/// By default, the view presents children objects as the value type defined
/// in \c _ChildPolicy.
///
/// Note that all methods are const, i.e. the children cannot be changed
/// through a view.
///
template <typename _ChildPolicy,
typename _Predicate =
SdfChildrenViewTrivialPredicate<
typename _ChildPolicy::ValueType>,
typename _Adapter =
SdfChildrenViewTrivialAdapter<
typename _ChildPolicy::ValueType> >
class SdfChildrenView {
public:
typedef SdfChildrenView<_ChildPolicy, _Predicate, _Adapter> This;
typedef _Adapter Adapter;
typedef _Predicate Predicate;
typedef _ChildPolicy ChildPolicy;
typedef typename ChildPolicy::KeyPolicy KeyPolicy;
typedef Sdf_Children<ChildPolicy> ChildrenType;
typedef typename ChildPolicy::KeyType key_type;
typedef typename Adapter::PublicType value_type;
private:
// An iterator type for the internal unfiltered data storage. This
// iterator holds a pointer to its owning object and an index into
// the owner's storage. That allows the iterator to operate without
// knowing anything about the specific data storage that's used,
// which is important for providing both Gd and Lsd backed storage.
class _InnerIterator :
public boost::iterator_facade<_InnerIterator,
value_type,
std::random_access_iterator_tag,
value_type> {
public:
typedef value_type reference;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
_InnerIterator() :
_owner(NULL), _pos(0) { }
_InnerIterator(const This* owner, const size_t& pos) :
_owner(owner), _pos(pos) { }
private:
friend class boost::iterator_core_access;
reference dereference() const
{
return _owner->_Get(_pos);
}
bool equal(const _InnerIterator& other) const
{
return _pos == other._pos;
}
void increment() {
++_pos;
}
void decrement() {
--_pos;
}
void advance(difference_type n) {
_pos += n;
}
difference_type distance_to(const _InnerIterator& other) const {
return other._pos-_pos;
}
private:
const This* _owner;
size_t _pos;
};
public:
typedef Sdf_ChildrenViewTraits<This, _InnerIterator, Predicate> _Traits;
typedef typename _Traits::const_iterator const_iterator;
typedef boost::reverse_iterator<const_iterator> const_reverse_iterator;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
SdfChildrenView()
{
}
SdfChildrenView(const SdfLayerHandle &layer, const SdfPath &path,
const TfToken &childrenKey,
const KeyPolicy& keyPolicy = KeyPolicy()) :
_children(layer, path, childrenKey, keyPolicy)
{
}
SdfChildrenView(const SdfLayerHandle &layer, const SdfPath &path,
const TfToken &childrenKey,
const Predicate& predicate,
const KeyPolicy& keyPolicy = KeyPolicy()) :
_children(layer, path, childrenKey, keyPolicy),
_predicate(predicate)
{
}
SdfChildrenView(const SdfChildrenView &other) :
_children(other._children),
_predicate(other._predicate)
{
}
template <class OtherAdapter>
SdfChildrenView(const SdfChildrenView<ChildPolicy, Predicate,
OtherAdapter> &other) :
_children(other._children),
_predicate(other._predicate)
{
}
~SdfChildrenView()
{
}
SdfChildrenView& operator=(const SdfChildrenView &other)
{
_children= other._children;
_predicate = other._predicate;
return *this;
}
/// Returns an const_iterator pointing to the beginning of the vector.
const_iterator begin() const {
_InnerIterator i(this,0);
return _Traits::GetIterator(this, i, _GetSize());
}
/// Returns an const_iterator pointing to the end of the vector.
const_iterator end() const {
_InnerIterator i(this,_GetSize());
return _Traits::GetIterator(this, i, _GetSize());
}
/// Returns an const_reverse_iterator pointing to the beginning of the
/// reversed vector.
const_reverse_iterator rbegin() const {
return const_reverse_iterator(end());
}
/// Returns an const_reverse_iterator pointing to the end of the
/// reversed vector.
const_reverse_iterator rend() const {
return const_reverse_iterator(begin());
}
/// Returns the size of the vector.
size_type size() const {
return std::distance(begin(), end());
}
/// Returns \c true if the vector is empty.
bool empty() const {
return begin() == end();
}
/// Returns the \p n'th element.
value_type operator[](size_type n) const {
const_iterator i = begin();
std::advance(i, n);
return *i;
}
/// Returns the first element.
value_type front() const {
return *begin();
}
/// Returns the last element.
value_type back() const {
return *rbegin();
}
/// Finds the element with key \p x.
const_iterator find(const key_type& x) const {
_InnerIterator inner(this, _children.Find(x));
const_iterator iter = _Traits::GetIterator(this, inner, _GetSize());
// _Traits::GetIterator may return a filtered iterator. We need to
// check that that iterator actually corresponds to the desired item.
// This ensures that we return end() in the case where the element being
// searched for is present in the children but filtered out by the
// view's predicate.
return _Traits::GetBase(iter) == inner ? iter : end();
}
/// Finds element \p x, if present in this view.
const_iterator find(const value_type& x) const {
const_iterator i = find(key(x));
return (i != end() && *i == x) ? i : end();
}
/// Returns the key for an element.
key_type key(const const_iterator& x) const {
return key(*x);
}
/// Returns the key for a value.
key_type key(const value_type& x) const {
return _children.FindKey(Adapter::Convert(x));
}
/// Returns the elements, in order.
std::vector<value_type> values() const {
return std::vector<value_type>(begin(), end());
}
/// Returns the elements, in order.
template <typename V>
V values_as() const {
V x;
std::copy(begin(), end(), std::inserter(x, x.begin()));
return x;
}
/// Returns the keys for all elements, in order.
std::vector<key_type> keys() const {
std::vector<key_type> result;
result.reserve(size());
for (const_iterator i = begin(), n = end(); i != n; ++i) {
result.push_back(key(i));
}
return result;
}
/// Returns the keys for all elements, in order.
template <typename V>
V keys_as() const {
std::vector<key_type> k = keys();
return V(k.begin(), k.end());
}
/// Returns the elements as a dictionary.
template <typename Dict>
Dict items_as() const {
Dict result;
for (const_iterator i = begin(), n = end(); i != n; ++i) {
result.insert(std::make_pair(key(i), *i));
}
return result;
}
/// Returns true if an element with key \p x is in the container.
bool has(const key_type& x) const {
return (_children.Find(x) != _GetSize());
}
/// Returns true if an element with the same key as \p x is in
/// the container.
bool has(const value_type& x) const {
return has(key(Adapter::Convert(x)));
}
/// Returns the number of elements with key \p x in the container.
size_type count(const key_type& x) const {
return has(x);
}
/// Returns the element with key \p x or a default constructed value
/// if no such element exists.
value_type get(const key_type& x) const {
size_t index = _children.Find(x);
if (index == _GetSize()) {
return value_type();
}
return _Get(index);
}
/// Returns the element with key \p x or the fallback if no such
/// element exists.
value_type get(const key_type& x, const value_type& fallback) const {
size_t index = _children.Find(x);
if (index == _GetSize()) {
return fallback;
}
return _Get(index);
}
/// Returns the element with key \p x or a default constructed value
/// if no such element exists.
value_type operator[](const key_type& x) const {
return get(x);
}
/// Compares children for equality. Children are equal if the
/// list edits are identical and the keys contain the same elements.
bool operator==(const This& other) const {
return _children.IsEqualTo(other._children);
}
/// Compares children for inequality. Children are not equal if
/// list edits are not identical or the keys don't contain the same
/// elements.
bool operator!=(const This& other) const {
return !_children.IsEqualTo(other._children);
}
// Return true if this object is valid
bool IsValid() const {
return _children.IsValid();
}
// Return the Sd_Children object that this view is holding.
ChildrenType &GetChildren() {
return _children;
}
// Return this view's predicate.
const Predicate& GetPredicate() const {
return _predicate;
}
private:
// Return the value that corresponds to the provided index.
value_type _Get(size_type index) const {
return Adapter::Convert(_children.GetChild(index));
}
// Return the number of elements
size_t _GetSize() const {
return _children.GetSize();
}
private:
template <class V, class P, class A> friend class SdfChildrenView;
ChildrenType _children;
Predicate _predicate;
};
/// Helper class to convert a given view of type \c _View to an
/// adapted view using \c _Adapter as the adapter class.
template <class _View, class _Adapter>
struct SdfAdaptedChildrenViewCreator
{
typedef _View OriginalView;
typedef SdfChildrenView<typename _View::ChildPolicy,
typename _View::Predicate,
_Adapter> AdaptedView;
static AdaptedView Create(const OriginalView& view)
{
return AdaptedView(view);
}
};
// Allow TfIteration over children views.
template <typename C, typename P, typename A>
struct Tf_ShouldIterateOverCopy<SdfChildrenView<C, P, A> > : boost::true_type
{
};
template <typename C, typename P, typename A>
struct Tf_IteratorInterface<SdfChildrenView<C, P, A>, false> {
typedef SdfChildrenView<C, P, A> Type;
typedef typename Type::const_iterator IteratorType;
static IteratorType Begin(Type const &c) { return c.begin(); }
static IteratorType End(Type const &c) { return c.end(); }
};
template <typename C, typename P, typename A>
struct Tf_IteratorInterface<SdfChildrenView<C, P, A>, true> {
typedef SdfChildrenView<C, P, A> Type;
typedef typename Type::const_reverse_iterator IteratorType;
static IteratorType Begin(Type const &c) { return c.rbegin(); }
static IteratorType End(Type const &c) { return c.rend(); }
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_CHILDREN_VIEW_H
+83
View File
@@ -0,0 +1,83 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_CLEANUP_ENABLER_H
#define PXR_USD_SDF_CLEANUP_ENABLER_H
/// \file sdf/cleanupEnabler.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/base/tf/stacked.h"
PXR_NAMESPACE_OPEN_SCOPE
/// \class SdfCleanupEnabler
///
/// An RAII class which, when an instance is alive, enables scheduling of
/// automatic cleanup of SdfLayers.
///
/// Any affected specs which no longer contribute to the scene will be removed
/// when the last SdfCleanupEnabler instance goes out of scope. Note that for
/// this purpose, SdfPropertySpecs are removed if they have only required fields
/// (see SdfPropertySpecs::HasOnlyRequiredFields), but only if the property spec
/// itself was affected by an edit that left it with only required fields. This
/// will have the effect of uninstantiating on-demand attributes. For example,
/// if its parent prim was affected by an edit that left it otherwise inert, it
/// will not be removed if it contains an SdfPropertySpec with only required
/// fields, but if the property spec itself is edited leaving it with only
/// required fields, it will be removed, potentially uninstantiating it if it's
/// an on-demand property.
///
/// SdfCleanupEnablers are accessible in both C++ and Python.
///
/// /// SdfCleanupEnabler can be used in the following manner:
/// \code
/// {
/// SdfCleanupEnabler enabler;
///
/// // Perform any action that might otherwise leave inert specs around,
/// // such as removing info from properties or prims, or removing name
/// // children. i.e:
/// primSpec->ClearInfo(SdfFieldKeys->Default);
///
/// // When enabler goes out of scope on the next line, primSpec will
/// // be removed if it has been left as an empty over.
/// }
/// \endcode
///
TF_DEFINE_STACKED(SdfCleanupEnabler, false, SDF_API)
{
public:
SDF_API SdfCleanupEnabler();
SDF_API ~SdfCleanupEnabler();
/// Returns whether cleanup is currently being scheduled.
SDF_API static bool IsCleanupEnabled();
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // #ifndef PXR_USD_SDF_CLEANUP_ENABLER_H
+228
View File
@@ -0,0 +1,228 @@
//
// Copyright 2017 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_COPY_UTILS_H
#define PXR_USD_SDF_COPY_UTILS_H
/// \file sdf/copyUtils.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/usd/sdf/declareHandles.h"
#include "pxr/usd/sdf/types.h"
#include <boost/optional.hpp>
#include <functional>
PXR_NAMESPACE_OPEN_SCOPE
class SdfPath;
class TfToken;
class VtValue;
SDF_DECLARE_HANDLES(SdfLayer);
/// \name Simple Spec Copying API
/// @{
/// Utility function for copying spec data at \p srcPath in \p srcLayer to
/// \p destPath in \p destLayer.
///
/// Copying is performed recursively: all child specs are copied as well.
/// Any destination specs that already exist will be overwritten.
///
/// Parent specs of the destination are not created, and must exist before
/// SdfCopySpec is called, or a coding error will result. For prim parents,
/// clients may find it convenient to call SdfCreatePrimInLayer before
/// SdfCopySpec.
///
/// As a special case, if the top-level object to be copied is a relationship
/// target or a connection, the destination spec must already exist. That is
/// because we don't want SdfCopySpec to impose any policy on how list edits are
/// made; client code should arrange for relationship targets and connections to
/// be specified as prepended, appended, deleted, and/or ordered, as needed.
///
/// Variant specs may be copied to prim paths and vice versa. When copying a
/// variant to a prim, the specifier and typename from the variant's parent
/// prim will be used.
///
/// Attribute connections, relationship targets, inherit and specializes paths,
/// and internal sub-root references that target an object beneath \p srcPath
/// will be remapped to target objects beneath \p dstPath.
///
SDF_API
bool
SdfCopySpec(
const SdfLayerHandle& srcLayer, const SdfPath& srcPath,
const SdfLayerHandle& dstLayer, const SdfPath& dstPath);
/// @}
/// \name Advanced Spec Copying API
/// @{
/// Return true if \p field should be copied from the spec at \p srcPath in
/// \p srcLayer to the spec at \p dstPath in \p dstLayer. \p fieldInSrc and
/// \p fieldInDst indicates whether the field has values at the source and
/// destination specs. Return false otherwise.
///
/// This function may modify the value that is copied by filling in
/// \p valueToCopy with the desired value. \p valueToCopy may also be a
/// SdfCopySpecsValueEdit that specifies an editing operation for this field.
/// If \p valueToCopy is not set, the field value from the source spec will be
/// used as-is. Setting \p valueToCopy to an empty VtValue indicates that the
/// field should be removed from the destination spec, if it already exists.
///
/// Note that if this function returns true and the source spec has no value
/// for \p field (e.g., fieldInSrc == false), the field in the destination
/// spec will also be set to no value.
using SdfShouldCopyValueFn = std::function<
bool(SdfSpecType specType, const TfToken& field,
const SdfLayerHandle& srcLayer, const SdfPath& srcPath, bool fieldInSrc,
const SdfLayerHandle& dstLayer, const SdfPath& dstPath, bool fieldInDst,
boost::optional<VtValue>* valueToCopy)>;
/// \class SdfCopySpecsValueEdit
/// Value containing an editing operation for SdfCopySpecs.
///
/// The SdfShouldCopyValueFn callback allows users to return a value to copy
/// into the destination spec via the \p valueToCopy parameter. However, there
/// may be cases where it would be more efficient to perform incremental edits
/// using specific SdfLayer API instead.
///
/// To accommodate this, consumers may provide a callback that applies a
/// scene description edit in \p valueToCopy via an SdfCopySpecsValueEdit
/// object.
class SdfCopySpecsValueEdit
{
public:
/// Callback to apply a scene description edit to the specified layer and
/// spec path.
using EditFunction =
std::function<void(const SdfLayerHandle&, const SdfPath&)>;
explicit SdfCopySpecsValueEdit(const EditFunction& edit) : _edit(edit) { }
const EditFunction& GetEditFunction() const { return _edit; }
/// SdfCopySpecsValueEdit objects are not comparable, but must provide
/// operator== to be stored in a VtValue.
bool operator==(const SdfCopySpecsValueEdit& rhs) const { return false; }
bool operator!=(const SdfCopySpecsValueEdit& rhs) const { return true; }
private:
EditFunction _edit;
};
/// Return true if \p childrenField and the child objects the field represents
/// should be copied from the spec at \p srcPath in \p srcLayer to the spec at
/// \p dstPath in \p dstLayer. \p fieldInSrc and \p fieldInDst indicates
/// whether that field has values at the source and destination specs.
/// Return false otherwise.
///
/// This function may modify which children are copied by filling in
/// \p srcChildren and \p dstChildren will the children to copy and their
/// destination. Both of these values must be set, and must contain the same
/// number of children.
///
/// Note that if this function returns true and the source spec has no value
/// for \p childrenField (e.g., fieldInSrc == false), the field in the
/// destination spec will also be set to no value, causing any existing children
/// to be removed.
using SdfShouldCopyChildrenFn = std::function<
bool(const TfToken& childrenField,
const SdfLayerHandle& srcLayer, const SdfPath& srcPath, bool fieldInSrc,
const SdfLayerHandle& dstLayer, const SdfPath& dstPath, bool fieldInDst,
boost::optional<VtValue>* srcChildren,
boost::optional<VtValue>* dstChildren)>;
/// SdfShouldCopyValueFn used by the simple version of SdfCopySpec.
///
/// Copies all values from the source, transforming path-valued fields prefixed
/// with \p srcRootPath to have the prefix \p dstRootPath.
///
/// Existing values in the destination will be overwritten by values in the
/// source. Any fields in the destination that aren't in the source will be
/// cleared.
SDF_API
bool
SdfShouldCopyValue(
const SdfPath& srcRootPath, const SdfPath& dstRootPath,
SdfSpecType specType, const TfToken& field,
const SdfLayerHandle& srcLayer, const SdfPath& srcPath, bool fieldInSrc,
const SdfLayerHandle& dstLayer, const SdfPath& dstPath, bool fieldInDst,
boost::optional<VtValue>* valueToCopy);
/// SdfShouldCopyChildrenFn used by the simple version of SdfCopySpec.
///
/// Copies all child values from the source, transforming path-valued fields
/// prefixed with \p srcRootPath to have the prefix \p dstRootPath.
///
/// Existing values in the destination will be overwritten by values in the
/// source. Any fields in the destination that aren't in the source will be
/// cleared.
SDF_API
bool
SdfShouldCopyChildren(
const SdfPath& srcRootPath, const SdfPath& dstRootPath,
const TfToken& childrenField,
const SdfLayerHandle& srcLayer, const SdfPath& srcPath, bool fieldInSrc,
const SdfLayerHandle& dstLayer, const SdfPath& dstPath, bool fieldInDst,
boost::optional<VtValue>* srcChildren,
boost::optional<VtValue>* dstChildren);
/// Utility function for copying spec data at \p srcPath in \p srcLayer to
/// \p destPath in \p destLayer. Various behaviors (such as which parts of the
/// spec to copy) are controlled by the supplied \p shouldCopyValueFn and
/// \p shouldCopyChildrenFn.
///
/// Copying is performed recursively: all child specs are copied as well, except
/// where prevented by \p shouldCopyChildrenFn.
///
/// Parent specs of the destination are not created, and must exist before
/// SdfCopySpec is called, or a coding error will result. For prim parents,
/// clients may find it convenient to call SdfCreatePrimInLayer before
/// SdfCopySpec.
///
/// Variant specs may be copied to prim paths and vice versa. When copying a
/// variant to a prim, the specifier and typename from the variant's parent
/// prim will be used.
///
/// As a special case, if the top-level object to be copied is a relationship
/// target or a connection, the destination spec must already exist. That is
/// because we don't want SdfCopySpec to impose any policy on how list edits are
/// made; client code should arrange for relationship targets and connections to
/// be specified as prepended, appended, deleted, and/or ordered, as needed.
///
SDF_API
bool
SdfCopySpec(
const SdfLayerHandle& srcLayer, const SdfPath& srcPath,
const SdfLayerHandle& dstLayer, const SdfPath& dstPath,
const SdfShouldCopyValueFn& shouldCopyValueFn,
const SdfShouldCopyChildrenFn& shouldCopyChildrenFn);
/// @}
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_COPY_UTILS_H
+184
View File
@@ -0,0 +1,184 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_DATA_H
#define PXR_USD_SDF_DATA_H
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/usd/sdf/abstractData.h"
#include "pxr/usd/sdf/path.h"
#include "pxr/base/tf/declarePtrs.h"
#include "pxr/base/tf/hashmap.h"
#include "pxr/base/tf/token.h"
#include "pxr/base/vt/value.h"
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
TF_DECLARE_WEAK_AND_REF_PTRS(SdfData);
/// \class SdfData
///
/// SdfData provides concrete scene description data storage.
///
/// An SdfData is an implementation of SdfAbstractData that simply
/// stores specs and fields in a map keyed by path.
///
class SdfData : public SdfAbstractData
{
public:
SdfData() {}
SDF_API
virtual ~SdfData();
/// SdfAbstractData overrides
SDF_API
virtual bool StreamsData() const;
SDF_API
virtual void CreateSpec(const SdfPath& path,
SdfSpecType specType);
SDF_API
virtual bool HasSpec(const SdfPath& path) const;
SDF_API
virtual void EraseSpec(const SdfPath& path);
SDF_API
virtual void MoveSpec(const SdfPath& oldPath,
const SdfPath& newPath);
SDF_API
virtual SdfSpecType GetSpecType(const SdfPath& path) const;
SDF_API
virtual bool Has(const SdfPath& path, const TfToken &fieldName,
SdfAbstractDataValue* value) const;
SDF_API
virtual bool Has(const SdfPath& path, const TfToken& fieldName,
VtValue *value = NULL) const;
SDF_API
virtual bool
HasSpecAndField(const SdfPath &path, const TfToken &fieldName,
SdfAbstractDataValue *value, SdfSpecType *specType) const;
SDF_API
virtual bool
HasSpecAndField(const SdfPath &path, const TfToken &fieldName,
VtValue *value, SdfSpecType *specType) const;
SDF_API
virtual VtValue Get(const SdfPath& path,
const TfToken& fieldName) const;
SDF_API
virtual void Set(const SdfPath& path, const TfToken& fieldName,
const VtValue & value);
SDF_API
virtual void Set(const SdfPath& path, const TfToken& fieldName,
const SdfAbstractDataConstValue& value);
SDF_API
virtual void Erase(const SdfPath& path,
const TfToken& fieldName);
SDF_API
virtual std::vector<TfToken> List(const SdfPath& path) const;
SDF_API
virtual std::set<double>
ListAllTimeSamples() const;
SDF_API
virtual std::set<double>
ListTimeSamplesForPath(const SdfPath& path) const;
SDF_API
virtual bool
GetBracketingTimeSamples(double time, double* tLower, double* tUpper) const;
SDF_API
virtual size_t
GetNumTimeSamplesForPath(const SdfPath& path) const;
SDF_API
virtual bool
GetBracketingTimeSamplesForPath(const SdfPath& path,
double time,
double* tLower, double* tUpper) const;
SDF_API
virtual bool
QueryTimeSample(const SdfPath& path, double time,
SdfAbstractDataValue *optionalValue) const;
SDF_API
virtual bool
QueryTimeSample(const SdfPath& path, double time,
VtValue *value) const;
SDF_API
virtual void
SetTimeSample(const SdfPath& path, double time,
const VtValue & value);
SDF_API
virtual void
EraseTimeSample(const SdfPath& path, double time);
protected:
// SdfAbstractData overrides
SDF_API
virtual void _VisitSpecs(SdfAbstractDataSpecVisitor* visitor) const;
private:
const VtValue* _GetSpecTypeAndFieldValue(const SdfPath& path,
const TfToken& field,
SdfSpecType* specType) const;
const VtValue* _GetFieldValue(const SdfPath& path,
const TfToken& field) const;
VtValue* _GetMutableFieldValue(const SdfPath& path,
const TfToken& field);
VtValue* _GetOrCreateFieldValue(const SdfPath& path,
const TfToken& field);
private:
// Backing storage for a single "spec" -- prim, property, etc.
typedef std::pair<TfToken, VtValue> _FieldValuePair;
struct _SpecData {
_SpecData() : specType(SdfSpecTypeUnknown) {}
SdfSpecType specType;
std::vector<_FieldValuePair> fields;
};
// Hashtable storing _SpecData.
typedef SdfPath _Key;
typedef SdfPath::Hash _KeyHash;
typedef TfHashMap<_Key, _SpecData, _KeyHash> _HashTable;
_HashTable _data;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_DATA_H
+340
View File
@@ -0,0 +1,340 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_DECLARE_HANDLES_H
#define PXR_USD_SDF_DECLARE_HANDLES_H
/// \file sdf/declareHandles.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/base/arch/demangle.h"
#include "pxr/base/arch/hints.h"
#include "pxr/base/tf/diagnostic.h"
#include "pxr/base/tf/weakPtrFacade.h"
#include "pxr/base/tf/declarePtrs.h"
#include <set>
#include <typeinfo>
#include <type_traits>
#include <vector>
#include <boost/intrusive_ptr.hpp>
#include <boost/operators.hpp>
PXR_NAMESPACE_OPEN_SCOPE
class SdfLayer;
class SdfSpec;
template <class T> class TfRefPtr;
class Sdf_Identity;
// Sdf_Identities are held via intrusive_ptr so that we can carefully
// manage the ref-count to avoid race conditions -- see
// Sdf_IdentityRegistry::Identify().
typedef boost::intrusive_ptr<Sdf_Identity> Sdf_IdentityRefPtr;
/// \class SdfHandle
///
/// SdfHandle is a smart ptr that calls IsDormant() on the pointed-to
/// object as an extra expiration check so that dormant objects appear to
/// be expired.
///
template <class T>
class SdfHandle : private boost::totally_ordered<SdfHandle<T> > {
public:
typedef SdfHandle<T> This;
typedef T SpecType;
typedef typename std::remove_const<SpecType>::type NonConstSpecType;
typedef SdfHandle<NonConstSpecType> NonConstThis;
SdfHandle() { }
SdfHandle(TfNullPtrType) { }
explicit SdfHandle(const Sdf_IdentityRefPtr& id) : _spec(id) { }
SdfHandle(const SpecType& spec) : _spec(spec) { }
template <class U>
SdfHandle(const SdfHandle<U>& x) : _spec(x._spec) { }
This& operator=(const This& x)
{
const_cast<NonConstSpecType&>(_spec) = x._spec;
return *this;
}
template <class U>
This& operator=(const SdfHandle<U>& x)
{
const_cast<NonConstSpecType&>(_spec) = x._spec;
return *this;
}
/// Dereference. Raises a fatal error if the object is invalid or
/// dormant.
SpecType* operator->() const
{
if (ARCH_UNLIKELY(_spec.IsDormant())) {
TF_FATAL_ERROR("Dereferenced an invalid %s",
ArchGetDemangled(typeid(SpecType)).c_str());
return 0;
}
return const_cast<SpecType*>(&_spec);
}
const SpecType & GetSpec() const
{
return _spec;
}
void Reset()
{
const_cast<SpecType&>(_spec) = SpecType();
}
#if !defined(doxygen)
typedef SpecType This::*UnspecifiedBoolType;
#endif
/// Returns \c true in a boolean context if the object is valid,
/// \c false otherwise.
operator UnspecifiedBoolType() const
{
return _spec.IsDormant() ? 0 : &This::_spec;
}
/// Returns \c false in a boolean context if the object is valid,
/// \c true otherwise.
bool operator!() const
{
return _spec.IsDormant();
}
/// Compares handles for equality.
template <class U>
bool operator==(const SdfHandle<U>& other) const
{
return _spec == other._spec;
}
/// Arranges handles in an arbitrary strict weak ordering. Note that
/// this ordering is stable across path changes.
template <class U>
bool operator<(const SdfHandle<U>& other) const
{
return _spec < other._spec;
}
/// Hash.
friend size_t hash_value(const This &x) {
return hash_value(x._spec);
}
private:
friend
inline SpecType *get_pointer(const SdfHandle &x) {
return ARCH_UNLIKELY(x._spec.IsDormant()) ?
nullptr : const_cast<SpecType*>(&x._spec);
}
SpecType _spec;
template <class U> friend class SdfHandle;
};
PXR_NAMESPACE_CLOSE_SCOPE
namespace boost {
using PXR_NS::get_pointer;
}
PXR_NAMESPACE_OPEN_SCOPE
template <class T>
struct SdfHandleTo {
typedef SdfHandle<T> Handle;
typedef SdfHandle<const T> ConstHandle;
typedef std::vector<Handle> Vector;
typedef std::vector<ConstHandle> ConstVector;
};
template <>
struct SdfHandleTo<SdfLayer> {
typedef TfWeakPtr<SdfLayer> Handle;
typedef TfWeakPtr<const SdfLayer> ConstHandle;
typedef std::vector<Handle> Vector;
typedef std::vector<ConstHandle> ConstVector;
};
template <typename T>
typename SdfHandleTo<T>::Handle
SdfCreateHandle(T *p)
{
return typename SdfHandleTo<T>::Handle(p ? *p : T());
}
template <>
SDF_API SdfHandleTo<SdfLayer>::Handle
SdfCreateHandle(SdfLayer *p);
template <typename T>
typename SdfHandleTo<T>::Handle
SdfCreateNonConstHandle(T const *p)
{
return SdfCreateHandle(const_cast<T *>(p));
}
struct Sdf_CastAccess {
template<class DST, class SRC>
static DST CastSpec(const SRC& spec) {
return DST(spec);
}
};
SDF_API bool
Sdf_CanCastToType(
const SdfSpec& srcSpec, const std::type_info& destType);
SDF_API bool
Sdf_CanCastToTypeCheckSchema(
const SdfSpec& srcSpec, const std::type_info& destType);
template <class DST, class SRC>
struct Sdf_SpecTypesAreDirectlyRelated
: std::integral_constant<bool,
std::is_base_of<DST, SRC>::value ||
std::is_base_of<SRC, DST>::value>
{ };
/// Convert SdfHandle<SRC> \p x to an SdfHandle<DST>. This function
/// behaves similar to a dynamic_cast. If class DST cannot represent
/// the spec pointed to be \p x, or if the classes DST and SRC are
/// not directly related to each other in the C++ type hierarchy,
/// the conversion fails and an invalid handle is returned.
///
/// XXX: The second condition in the above statement is currently untrue.
/// This function will allow casting between spec classes even if
/// they are not directly related. Doing so could lead to schema
/// mismatches and other buggy behavior.
template <typename DST, typename SRC>
inline
SdfHandle<typename DST::SpecType>
TfDynamic_cast(const SdfHandle<SRC>& x)
{
typedef typename DST::SpecType Spec;
typedef SdfHandle<Spec> Handle;
if (Sdf_CanCastToType(x.GetSpec(), typeid(Spec))) {
return Handle(Sdf_CastAccess::CastSpec<Spec,SRC>(x.GetSpec()));
}
return Handle();
}
template <typename DST, typename SRC>
inline
SdfHandle<typename DST::SpecType>
TfSafeDynamic_cast(const SdfHandle<SRC>& x)
{
return TfDynamic_cast(x);
}
/// Convert SdfHandle<SRC> \p x to an SdfHandle<DST>. This function
/// behaves similar to a static_cast. No runtime checks are performed
/// to ensure the conversion is valid; it is up to the consumer to
/// ensure this.
template <typename DST, typename SRC>
inline
SdfHandle<typename DST::SpecType>
TfStatic_cast(const SdfHandle<SRC>& x)
{
typedef typename DST::SpecType Spec;
typedef SdfHandle<Spec> Handle;
static_assert(Sdf_SpecTypesAreDirectlyRelated<Spec, SRC>::value,
"Spec and SRC must be directly related.");
return Handle(Sdf_CastAccess::CastSpec<Spec,SRC>(x.GetSpec()));
}
template <typename T>
inline
SdfHandle<typename T::SpecType>
TfConst_cast(const SdfHandle<const typename T::SpecType>& x)
{
return TfStatic_cast<T>(x);
}
/// Convert SdfHandle<SRC> \p x to an SdfHandle<DST>. This function is
/// similar to TfDynamic_cast, but it allows the SRC and DST spec to be
/// indirectly related, so long as the schema associated with the DST
/// spec type is a subclass of the schema associated with \p x.
template <typename DST, typename SRC>
inline
SdfHandle<typename DST::SpecType>
SdfSpecDynamic_cast(const SdfHandle<SRC>& x)
{
typedef typename DST::SpecType Spec;
typedef SdfHandle<Spec> Handle;
if (Sdf_CanCastToTypeCheckSchema(x.GetSpec(), typeid(Spec))) {
return Handle(Sdf_CastAccess::CastSpec<Spec,SRC>(x.GetSpec()));
}
return Handle();
}
/// Convert SdfHandle<SRC> \p x to an SdfHandle<DST>. This function is
/// similar to TfStatic_cast, but it allows the SRC and DST spec to be
/// indirectly related.
template <typename DST, typename SRC>
inline
SdfHandle<typename DST::SpecType>
SdfSpecStatic_cast(const SdfHandle<SRC>& x)
{
typedef typename DST::SpecType Spec;
typedef SdfHandle<Spec> Handle;
return Handle(Sdf_CastAccess::CastSpec<Spec,SRC>(x.GetSpec()));
}
/// Convert SRC_SPEC to a DST_SPEC.
template <typename DST_SPEC, typename SRC_SPEC>
inline
DST_SPEC
SdfSpecStatic_cast(const SRC_SPEC& x)
{
return Sdf_CastAccess::CastSpec<DST_SPEC,SRC_SPEC>(x);
}
typedef TfRefPtr<SdfLayer> SdfLayerRefPtr;
typedef std::vector<TfRefPtr<SdfLayer> > SdfLayerRefPtrVector;
typedef std::set<SdfHandleTo<SdfLayer>::Handle> SdfLayerHandleSet;
#define SDF_DECLARE_HANDLES(cls) \
typedef SdfHandleTo<class cls>::Handle cls##Handle; \
typedef SdfHandleTo<class cls>::ConstHandle cls##ConstHandle; \
typedef SdfHandleTo<class cls>::Vector cls##HandleVector; \
typedef SdfHandleTo<class cls>::ConstVector cls##ConstHandleVector
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_DECLARE_HANDLES_H
+118
View File
@@ -0,0 +1,118 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_DECLARE_SPEC_H
#define PXR_USD_SDF_DECLARE_SPEC_H
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/usd/sdf/declareHandles.h"
#include "pxr/usd/sdf/specType.h"
#include "pxr/base/tf/registryManager.h"
#include "pxr/base/tf/type.h"
PXR_NAMESPACE_OPEN_SCOPE
class SdfSpec;
/// Helper macros for implementing C++ spec classes corresponding to
/// the various scene description spec types defined by Sdf. There are
/// two macros that each C++ spec class must invoke, one in the class
/// definition and one in the implementation .cpp file. For example:
///
/// <in MySpecType.h>
/// class MySpecType : public MyBaseSpecType {
/// SDF_DECLARE_SPEC(MySpecType, MyBaseSpecType);
/// ...
/// };
///
/// <in MySpecType.cpp>
/// SDF_DEFINE_SPEC(MySchemaType, <SdfSpecType enum value>, MySpecType,
/// MyBaseSpecType);
///
/// There are two sets of these macros, one for concrete spec types
/// and one for 'abstract' spec types that only serve as a base class
/// for concrete specs.
///
#define SDF_DECLARE_ABSTRACT_SPEC(SpecType, BaseSpecType) \
public: \
SpecType() { } \
SpecType(const SpecType& spec) \
: BaseSpecType(spec) { } \
explicit SpecType(const Sdf_IdentityRefPtr& identity) \
: BaseSpecType(identity) { } \
protected: \
friend struct Sdf_CastAccess; \
explicit SpecType(const SdfSpec& spec) \
: BaseSpecType(spec) { } \
#define SDF_DEFINE_ABSTRACT_SPEC(SchemaType, SpecType, BaseSpecType) \
TF_REGISTRY_FUNCTION_WITH_TAG(TfType, Type) \
{ \
TfType::Define<SpecType, TfType::Bases<BaseSpecType> >(); \
} \
TF_REGISTRY_FUNCTION_WITH_TAG(SdfSpecTypeRegistration, Registration) \
{ \
SdfSpecTypeRegistration::RegisterAbstractSpecType< \
SchemaType, SpecType>(); \
}
// ------------------------------------------------------------
#define SDF_DECLARE_SPEC(SpecType, BaseSpecType) \
SDF_DECLARE_ABSTRACT_SPEC(SpecType, BaseSpecType) \
#define SDF_DEFINE_SPEC(SchemaType, SpecTypeEnum, SpecType, BaseSpecType) \
TF_REGISTRY_FUNCTION_WITH_TAG(TfType, Type) \
{ \
TfType::Define<SpecType, TfType::Bases<BaseSpecType> >(); \
} \
TF_REGISTRY_FUNCTION_WITH_TAG(SdfSpecTypeRegistration, Registration) \
{ \
SdfSpecTypeRegistration::RegisterSpecType<SchemaType, SpecType> \
(SpecTypeEnum); \
}
// ------------------------------------------------------------
// Special set of macros for SdfSpec only.
#define SDF_DECLARE_BASE_SPEC(SpecType) \
public: \
SpecType() { } \
SpecType(const SpecType& spec) : _id(spec._id) { } \
explicit SpecType(const Sdf_IdentityRefPtr& id) : _id(id) { } \
#define SDF_DEFINE_BASE_SPEC(SchemaType, SpecType) \
TF_REGISTRY_FUNCTION_WITH_TAG(TfType, Type) \
{ \
TfType::Define<SpecType>(); \
} \
TF_REGISTRY_FUNCTION_WITH_TAG(SdfSpecTypeRegistration, Registration) \
{ \
SdfSpecTypeRegistration::RegisterAbstractSpecType< \
SchemaType, SpecType>(); \
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_DECLARE_SPEC_H
+492
View File
@@ -0,0 +1,492 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_FILE_FORMAT_H
#define PXR_USD_SDF_FILE_FORMAT_H
/// \file sdf/fileFormat.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/usd/sdf/declareHandles.h"
#include "pxr/base/tf/declarePtrs.h"
#include "pxr/base/tf/refBase.h"
#include "pxr/base/tf/staticTokens.h"
#include "pxr/base/tf/token.h"
#include "pxr/base/tf/type.h"
#include "pxr/base/tf/weakBase.h"
#include <map>
#include <string>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
class ArAssetInfo;
class SdfSchemaBase;
class SdfLayerHints;
SDF_DECLARE_HANDLES(SdfLayer);
SDF_DECLARE_HANDLES(SdfSpec);
TF_DECLARE_WEAK_AND_REF_PTRS(SdfAbstractData);
TF_DECLARE_WEAK_AND_REF_PTRS(SdfFileFormat);
#define SDF_FILE_FORMAT_TOKENS \
((TargetArg, "target"))
TF_DECLARE_PUBLIC_TOKENS(SdfFileFormatTokens, SDF_API, SDF_FILE_FORMAT_TOKENS);
/// \class SdfFileFormat
///
/// Base class for file format implementations.
///
class SdfFileFormat
: public TfRefBase
, public TfWeakBase
{
public:
SdfFileFormat(const SdfFileFormat&) = delete;
SdfFileFormat& operator=(const SdfFileFormat&) = delete;
/// Returns the schema for this format.
SDF_API const SdfSchemaBase& GetSchema() const;
/// Returns the format identifier.
SDF_API const TfToken& GetFormatId() const;
/// Returns the target for this file format.
SDF_API const TfToken& GetTarget() const;
/// Returns the cookie to be used when writing files with this format.
SDF_API const std::string& GetFileCookie() const;
/// Returns the current version of this file format.
SDF_API const TfToken& GetVersionString() const;
/// Returns true if this file format is the primary format for the
/// extensions it handles.
SDF_API bool IsPrimaryFormatForExtensions() const;
/// Returns a list of extensions that this format supports.
SDF_API const std::vector<std::string>& GetFileExtensions() const;
/// Returns the primary file extension for this format. This is the
/// extension that is reported for layers using this file format.
SDF_API const std::string& GetPrimaryFileExtension() const;
/// Returns true if \p extension matches one of the extensions returned by
/// GetFileExtensions.
SDF_API bool IsSupportedExtension(const std::string& extension) const;
/// Returns true if this file format is a package containing other
/// assets.
SDF_API
virtual bool IsPackage() const;
/// Returns the path of the "root" layer contained in the package
/// layer at \p resolvedPath produced by this file format. If this
/// file format is not a package, returns the empty string.
///
/// The package root layer is the layer in the package layer that
/// is used when that package is opened via SdfLayer.
SDF_API
virtual std::string GetPackageRootLayerPath(
const std::string& resolvedPath) const;
/// Type for specifying additional file format-specific arguments
/// to the various API below.
typedef std::map<std::string, std::string> FileFormatArguments;
/// Returns the FileFormatArguments that correspond to the default behavior
/// of this file format when no FileFormatArguments are passed to NewLayer
/// or InitData.
SDF_API
virtual FileFormatArguments GetDefaultFileFormatArguments() const;
/// This method allows the file format to bind to whatever data container is
/// appropriate.
///
/// Returns a shared pointer to an SdfAbstractData implementation.
SDF_API
virtual SdfAbstractDataRefPtr
InitData(const FileFormatArguments& args) const;
/// Instantiate a layer.
SDF_API
SdfLayerRefPtr NewLayer(const SdfFileFormatConstPtr &fileFormat,
const std::string &identifier,
const std::string &realPath,
const ArAssetInfo& assetInfo,
const FileFormatArguments &args) const;
/// Return true if this file format prefers to skip reloading anonymous
/// layers.
SDF_API bool ShouldSkipAnonymousReload() const;
/// Return true if layers produced by this file format are based
/// on physical files on disk. If so, this file format requires
/// layers to be serialized to and read from files on disk.
///
/// For file formats where this function returns true, when
/// opening a layer Sdf will fetch layers to the filesystem
/// via calls to ArResolver::FetchToLocalResolvedPath prior
/// to calling ReadFromFile.
///
/// This allows asset systems that do not store layers as individual
/// files to operate with file formats that require these files.
///
/// \sa ArResolver::Resolve
/// \sa ArResolver::FetchToLocalResolvedPath
SDF_API bool LayersAreFileBased() const;
/// Returns true if \p file can be read by this format.
SDF_API
virtual bool CanRead(
const std::string& file) const = 0;
/// Reads scene description from the asset specified by \p resolvedPath
/// into the layer \p layer.
///
/// \p metadataOnly is a flag that asks for only the layer metadata
/// to be read in, which can be much faster if that is all that is
/// required. Note that this is just a hint: some FileFormat readers
/// may disregard this flag and still fully populate the layer contents.
///
/// Returns true if the asset is successfully read into \p layer,
/// false otherwise.
SDF_API
virtual bool Read(
SdfLayer* layer,
const std::string& resolvedPath,
bool metadataOnly) const = 0;
/// Writes the content in \p layer into the file at \p filePath. If the
/// content is successfully written, this method returns true. Otherwise,
/// false is returned and errors are posted. The default implementation
/// returns false.
SDF_API
virtual bool WriteToFile(
const SdfLayer& layer,
const std::string& filePath,
const std::string& comment = std::string(),
const FileFormatArguments& args = FileFormatArguments()) const;
/// Reads data in the string \p str into the layer \p layer. If
/// the file is successfully read, this method returns true. Otherwise,
/// false is returned and errors are posted.
SDF_API
virtual bool ReadFromString(
SdfLayer* layer,
const std::string& str) const;
/// Write the provided \p spec to \p out indented \p indent levels.
SDF_API
virtual bool WriteToStream(
const SdfSpecHandle &spec,
std::ostream& out,
size_t indent) const;
/// Writes the content in \p layer to the string \p str. This function
/// should write a textual representation of \p layer to the stream
/// that can be read back in via ReadFromString.
SDF_API
virtual bool WriteToString(
const SdfLayer& layer,
std::string* str,
const std::string& comment = std::string()) const;
/// Returns the set of resolved paths to external asset file dependencies
/// for the given \p layer. These are additional dependencies, specific to
/// the file format, that are needed when generating the layer's contents
/// and would not otherwise be discoverable through composition dependencies
/// (i.e. sublayers, references, and payloads).
///
/// The default implementation returns an empty set. Derived file formats
/// that depend on external assets to read and generate layer content
/// should implement this function to return the external asset paths.
///
/// \sa SdfLayer::GetExternalAssetDependencies
/// \sa SdfLayer::Reload
SDF_API
virtual std::set<std::string> GetExternalAssetDependencies(
const SdfLayer& layer) const;
/// Returns the file extension for path or file name \p s, without the
/// leading dot character.
SDF_API static std::string GetFileExtension(const std::string& s);
/// Returns a set containing the extension(s) corresponding to
/// all registered file formats.
SDF_API static std::set<std::string> FindAllFileFormatExtensions();
/// Returns the file format instance with the specified \p formatId
/// identifier. If a format with a matching identifier is not found, this
/// returns a null file format pointer.
SDF_API
static SdfFileFormatConstPtr FindById(
const TfToken& formatId);
/// Returns the file format instance that supports the extension for
/// \p path. If a format with a matching extension is not found, this
/// returns a null file format pointer.
///
/// An extension may be handled by multiple file formats, but each
/// with a different target. In such cases, if no \p target is specified,
/// the file format that is registered as the primary plugin will be
/// returned. Otherwise, the file format whose target matches \p target
/// will be returned.
SDF_API
static SdfFileFormatConstPtr FindByExtension(
const std::string& path,
const std::string& target = std::string());
/// Returns a file format instance that supports the extension for \p
/// path and whose target matches one of those specified by the given
/// \p args. If the \p args specify no target, then the file format that is
/// registered as the primary plugin will be returned. If a format with a
/// matching extension is not found, this returns a null file format
/// pointer.
SDF_API
static SdfFileFormatConstPtr FindByExtension(
const std::string& path,
const FileFormatArguments& args);
protected:
/// Constructor.
SDF_API SdfFileFormat(
const TfToken& formatId,
const TfToken& versionString,
const TfToken& target,
const std::string& extension);
/// Constructor.
/// \p schema must remain valid for the lifetime of this file format.
SDF_API SdfFileFormat(
const TfToken& formatId,
const TfToken& versionString,
const TfToken& target,
const std::string& extension,
const SdfSchemaBase& schema);
/// Disallow temporary SdfSchemaBase objects being passed to the c'tor.
SdfFileFormat(
const TfToken& formatId,
const TfToken& versionString,
const TfToken& target,
const std::string& extension,
const SdfSchemaBase&& schema) = delete;
/// Constructor.
SDF_API SdfFileFormat(
const TfToken& formatId,
const TfToken& versionString,
const TfToken& target,
const std::vector<std::string> &extensions);
/// Constructor.
/// \p schema must remain valid for the lifetime of this file format.
SDF_API SdfFileFormat(
const TfToken& formatId,
const TfToken& versionString,
const TfToken& target,
const std::vector<std::string> &extensions,
const SdfSchemaBase& schema);
/// Disallow temporary SdfSchemaBase objects being passed to the c'tor.
SdfFileFormat(
const TfToken& formatId,
const TfToken& versionString,
const TfToken& target,
const std::vector<std::string> &extensions,
const SdfSchemaBase&& schema) = delete;
/// Destructor.
SDF_API virtual ~SdfFileFormat();
//
// Minimally break layer encapsulation with the following methods. These
// methods are also intended to limit the need for SdfLayer friendship with
// SdfFileFormat child classes.
//
/// Set the internal data for \p layer to \p data, possibly transferring
/// ownership of \p data.
///
/// Existing layer hints are reset to the default hints.
SDF_API
static void _SetLayerData(
SdfLayer* layer, SdfAbstractDataRefPtr& data);
/// Set the internal data for \p layer to \p data, possibly transferring
/// ownership of \p data.
///
/// Existing layer hints are replaced with \p hints.
SDF_API
static void _SetLayerData(
SdfLayer* layer, SdfAbstractDataRefPtr& data,
SdfLayerHints hints);
/// Get the internal data for \p layer.
SDF_API
static SdfAbstractDataConstPtr _GetLayerData(const SdfLayer& layer);
private:
SDF_API
virtual SdfLayer *_InstantiateNewLayer(
const SdfFileFormatConstPtr &fileFormat,
const std::string &identifier,
const std::string &realPath,
const ArAssetInfo& assetInfo,
const FileFormatArguments &args) const;
// File format subclasses may override this if they prefer not to skip
// reloading anonymous layers. Default implementation returns true.
SDF_API
virtual bool _ShouldSkipAnonymousReload() const;
/// File format subclasses may override this to specify whether
/// their layers are backed by physical files on disk.
/// Default implementation returns true.
SDF_API
virtual bool _LayersAreFileBased() const;
const SdfSchemaBase& _schema;
const TfToken _formatId;
const TfToken _target;
const std::string _cookie;
const TfToken _versionString;
const std::vector<std::string> _extensions;
const bool _isPrimaryFormat;
};
// Base file format factory.
class Sdf_FileFormatFactoryBase : public TfType::FactoryBase {
public:
virtual SdfFileFormatRefPtr New() const = 0;
};
// Default file format factory.
template <typename T>
class Sdf_FileFormatFactory : public Sdf_FileFormatFactoryBase {
public:
virtual SdfFileFormatRefPtr New() const
{
return TfCreateRefPtr(new T);
}
};
/// \def SDF_DEFINE_FILE_FORMAT
///
/// Performs registrations needed for the specified file format class to be
/// discovered by Sdf. This typically would be invoked in a TF_REGISTRY_FUNCTION
/// in the source file defining the file format.
///
/// The first argument is the name of the file format class being registered.
/// Subsequent arguments list the base classes of the file format. Since all
/// file formats must ultimately derive from SdfFileFormat, there should be
/// at least one base class specified.
///
/// For example:
///
/// \code
/// // in MyFileFormat.cpp
/// TF_REGISTRY_FUNCTION(TfType)
/// {
/// SDF_DEFINE_FILE_FORMAT(MyFileFormat, SdfFileFormat);
/// }
/// \endcode
///
#ifdef doxygen
#define SDF_DEFINE_FILE_FORMAT(FileFormatClass, BaseClass1, ...)
#else
#define SDF_DEFINE_FILE_FORMAT(...) SdfDefineFileFormat<__VA_ARGS__>()
template <class FileFormat, class ...BaseFormats>
void SdfDefineFileFormat()
{
TfType::Define<FileFormat, TfType::Bases<BaseFormats...>>()
.template SetFactory<Sdf_FileFormatFactory<FileFormat>>();
}
#endif // doxygen
/// \def SDF_DEFINE_ABSTRACT_FILE_FORMAT
///
/// Performs registrations needed for the specified abstract file format
/// class. This is used to register types that serve as base classes
/// for other concrete file format classes used by Sdf.
///
/// The first argument is the name of the file format class being registered.
/// Subsequent arguments list the base classes of the file format. Since all
/// file formats must ultimately derive from SdfFileFormat, there should be
/// at least one base class specified.
///
/// For example:
///
/// \code
/// // in MyFileFormat.cpp
/// TF_REGISTRY_FUNCTION(TfType)
/// {
/// SDF_DEFINE_ABSTRACT_FILE_FORMAT(MyFileFormat, SdfFileFormat);
/// }
/// \endcode
///
#ifdef doxygen
#define SDF_DEFINE_ABSTRACT_FILE_FORMAT(FileFormatClass, BaseClass1, ...)
#else
#define SDF_DEFINE_ABSTRACT_FILE_FORMAT(...) \
SdfDefineAbstractFileFormat<__VA_ARGS__>()
template <class FileFormat, class ...BaseFormats>
void SdfDefineAbstractFileFormat()
{
TfType::Define<FileFormat, TfType::Bases<BaseFormats...>>();
}
#endif //doxygen
/// \def SDF_FILE_FORMAT_FACTORY_ACCESS
///
/// Provides access to allow file format classes to be instantiated
/// from Sdf. This should be specified in the class definition for
/// concrete file format classes.
///
/// For example:
///
/// \code
/// // in MyFileFormat.h
/// class MyFileFormat : public SdfFileFormat
/// {
/// SDF_FILE_FORMAT_FACTORY_ACCESS;
/// // ...
/// };
/// \endcode
///
#ifdef doxygen
#define SDF_FILE_FORMAT_FACTORY_ACCESS
#else
#define SDF_FILE_FORMAT_FACTORY_ACCESS \
template<typename T> friend class Sdf_FileFormatFactory
#endif //doxygen
PXR_NAMESPACE_CLOSE_SCOPE
#endif
+132
View File
@@ -0,0 +1,132 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_IDENTITY_H
#define PXR_USD_SDF_IDENTITY_H
#include "pxr/pxr.h"
#include "pxr/base/tf/hashmap.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/usd/sdf/declareHandles.h"
#include "pxr/usd/sdf/path.h"
#include <boost/intrusive_ptr.hpp>
#include <boost/noncopyable.hpp>
#include <tbb/spin_mutex.h>
PXR_NAMESPACE_OPEN_SCOPE
class Sdf_IdentityRegistry;
SDF_DECLARE_HANDLES(SdfLayer);
/// \class Sdf_Identity
///
/// Identifies the logical object behind an SdfSpec.
///
/// This is simply the layer the spec belongs to and the path to the spec.
///
class Sdf_Identity : public boost::noncopyable {
public:
/// Returns the layer that this identity refers to.
SDF_API
const SdfLayerHandle &GetLayer() const;
/// Returns the path that this identity refers to.
const SdfPath &GetPath() const {
return _path;
}
private:
// Ref-counting ops manage _refCount.
friend void intrusive_ptr_add_ref(Sdf_Identity*);
friend void intrusive_ptr_release(Sdf_Identity*);
friend class Sdf_IdentityRegistry;
SDF_API
Sdf_Identity(Sdf_IdentityRegistry *registry, const SdfPath &path);
SDF_API
~Sdf_Identity();
void _Forget();
mutable std::atomic_int _refCount;
Sdf_IdentityRegistry *_registry;
SdfPath _path;
};
// Specialize boost::intrusive_ptr operations.
inline void intrusive_ptr_add_ref(PXR_NS::Sdf_Identity* p) {
++p->_refCount;
}
inline void intrusive_ptr_release(PXR_NS::Sdf_Identity* p) {
if (--p->_refCount == 0) {
delete p;
}
}
class Sdf_IdentityRegistry : public boost::noncopyable {
public:
Sdf_IdentityRegistry(const SdfLayerHandle &layer);
~Sdf_IdentityRegistry();
/// Returns the layer that owns this registry.
const SdfLayerHandle &GetLayer() const {
return _layer;
}
/// Return the identity associated with \a path, issuing a new
/// one if necessary. The registry will track the identity
/// and update it if the logical object it represents moves
/// in namespace.
Sdf_IdentityRefPtr Identify(const SdfPath &path);
/// Update identity in response to a namespace edit.
void MoveIdentity(const SdfPath &oldPath, const SdfPath &newPath);
private:
// When an identity expires, it will remove itself from the registry.
friend class Sdf_Identity;
// Remove the identity mapping for \a path to \a id from the registry.
// This is only called by Sdf_Identity's destructor.
void _Remove(const SdfPath &path, Sdf_Identity *id);
/// The layer that owns this registry, and on behalf of which
/// this registry tracks identities.
const SdfLayerHandle _layer;
/// The identities being managed by this registry
typedef TfHashMap<SdfPath, Sdf_Identity*, SdfPath::Hash> _IdMap;
_IdMap _ids;
/// Cache the last fetched identity, it's commonly re-fetched.
Sdf_IdentityRefPtr _lastId;
// This mutex synchronizes access to _ids.
tbb::spin_mutex _idsMutex;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_IDENTITY_H
File diff suppressed because it is too large. Load diff
+53
View File
@@ -0,0 +1,53 @@
//
// Copyright 2020 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_LAYER_HINTS_H
#define PXR_USD_SDF_LAYER_HINTS_H
#include "pxr/pxr.h"
PXR_NAMESPACE_OPEN_SCOPE
/// Contains hints about layer contents that may be used to accelerate certain
/// composition operations.
class SdfLayerHints
{
public:
/// Default constructed hints provide the most conservative set of values
/// such that consumers of the hints will act correctly if not optimally.
SdfLayerHints() = default;
/// Construct hints with specific values. Using this constructor requires
/// that all hint fields be specified.
explicit SdfLayerHints(bool mightHaveRelocates)
: mightHaveRelocates(mightHaveRelocates)
{}
/// If this field is false, the layer does not contain relocates. If
/// true, relocates may be present but are not guaranteed to exist.
bool mightHaveRelocates = true;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif
+165
View File
@@ -0,0 +1,165 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_LAYER_OFFSET_H
#define PXR_USD_SDF_LAYER_OFFSET_H
/// \file sdf/layerOffset.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include <boost/operators.hpp>
#include <iosfwd>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
class SdfTimeCode;
/// \class SdfLayerOffset
///
/// Represents a time offset and scale between layers.
///
/// The SdfLayerOffset class is an affine transform, providing both a scale and
/// a translate. It supports vector algebra semantics for composing
/// SdfLayerOffsets together via multiplication. The SdfLayerOffset class is
/// unitless: it does not refer to seconds or frames.
///
/// For example, suppose layer A uses layer B, with an offset of X:
/// when bringing animation from B into A, you first apply the scale of X, and
/// then the offset. Suppose you have a scale of 2 and an offset of 24:
/// first multiply B's frame numbers by 2, and then add 24. The animation from
/// B as seen in A will take twice as long and start 24 frames later.
///
/// Offsets are typically used in either sublayers or prim references. For more
/// information, see the SetSubLayerOffset() method of the SdfLayer class (the
/// subLayerOffsets property in Python), as well as the SetReference() and
/// GetReferenceLayerOffset() methods (the latter is the referenceLayerOffset
/// property in Python) of the SdfPrimSpec class.
///
class SdfLayerOffset : public boost::totally_ordered<SdfLayerOffset>
{
public:
/// \name Constructors
/// @{
/// Constructs a new SdfLayerOffset instance.
SDF_API
explicit SdfLayerOffset(double offset = 0.0, double scale = 1.0);
/// @}
/// \name Accessors
/// @{
/// Returns the time offset.
double GetOffset() const { return _offset; }
/// Returns the time scale factor.
double GetScale() const { return _scale; }
/// Sets the time offset.
void SetOffset(double newOffset) { _offset = newOffset; }
/// Sets the time scale factor.
void SetScale(double newScale) { _scale = newScale; }
/// Returns \c true if this is an identity transformation, with
/// an offset of 0.0 and a scale of 1.0.
SDF_API
bool IsIdentity() const;
/// Returns \c true if this offset is valid, i.e. both the offset and
/// scale are finite (not infinite or NaN). Note that a valid layer
/// offset's inverse may be invalid.
SDF_API
bool IsValid() const;
/// Gets the inverse offset, which performs the opposite transformation.
SDF_API
SdfLayerOffset GetInverse() const;
/// \name Hashing
/// @{
/// Returns hash for this offset.
SDF_API
size_t GetHash() const;
/// Hash functor for hash maps and sets.
struct Hash {
size_t operator()(const SdfLayerOffset &offset) const {
return offset.GetHash();
}
};
friend inline size_t hash_value(const SdfLayerOffset &offset) {
return offset.GetHash();
}
/// @}
/// \name Operators
/// @{
/// Returns whether the offsets are equal.
SDF_API
bool operator==(const SdfLayerOffset &rhs) const;
/// Returns whether this offset is less than another. The meaning
/// of less than is somewhat arbitrary.
SDF_API
bool operator<(const SdfLayerOffset &rhs) const;
/// Composes this with the offset \e rhs, such that the resulting
/// offset is equivalent to first applying \e rhs and then \e *this.
SDF_API
SdfLayerOffset operator*(const SdfLayerOffset &rhs) const;
/// Applies the offset to the given value.
SDF_API
double operator*(double rhs) const;
/// Applies the offset to the given value.
SDF_API
SdfTimeCode operator*(const SdfTimeCode &rhs) const;
/// @}
private:
double _offset;
double _scale;
};
typedef std::vector<SdfLayerOffset> SdfLayerOffsetVector;
///
/// Writes the string representation of \a SdfLayerOffset to \a out.
SDF_API
std::ostream & operator<<( std::ostream &out,
const SdfLayerOffset &layerOffset );
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_LAYER_OFFSET_H
+347
View File
@@ -0,0 +1,347 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_LAYER_STATE_DELEGATE_H
#define PXR_USD_SDF_LAYER_STATE_DELEGATE_H
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/usd/sdf/declareHandles.h"
#include "pxr/usd/sdf/types.h"
#include "pxr/base/tf/declarePtrs.h"
#include "pxr/base/tf/refBase.h"
#include "pxr/base/tf/weakBase.h"
PXR_NAMESPACE_OPEN_SCOPE
SDF_DECLARE_HANDLES(SdfLayer);
TF_DECLARE_WEAK_AND_REF_PTRS(SdfLayerStateDelegateBase);
TF_DECLARE_WEAK_AND_REF_PTRS(SdfSimpleLayerStateDelegate);
TF_DECLARE_WEAK_PTRS(SdfAbstractData);
class SdfAbstractDataConstValue;
class SdfPath;
class TfToken;
/// \class SdfLayerStateDelegateBase
///
/// Maintains authoring state information for an associated layer.
///
/// For example, layers rely on a state delegate to determine whether or
/// not they have been dirtied by authoring operations.
///
/// A layer's state delegate is invoked on every authoring operation on
/// that layer. The delegate may keep track of these operations for various
/// purposes.
///
class SdfLayerStateDelegateBase
: public TfRefBase
, public TfWeakBase
{
public:
SDF_API
virtual ~SdfLayerStateDelegateBase();
SDF_API
bool IsDirty();
SDF_API
void SetField(
const SdfPath& path,
const TfToken& field,
const VtValue& value,
const VtValue *oldValue=NULL);
SDF_API
void SetField(
const SdfPath& path,
const TfToken& field,
const SdfAbstractDataConstValue& value,
const VtValue *oldValue=NULL);
SDF_API
void SetFieldDictValueByKey(
const SdfPath& path,
const TfToken& field,
const TfToken& keyPath,
const VtValue& value,
const VtValue *oldValue=NULL);
SDF_API
void SetFieldDictValueByKey(
const SdfPath& path,
const TfToken& field,
const TfToken& keyPath,
const SdfAbstractDataConstValue& value,
const VtValue *oldValue=NULL);
SDF_API
void SetTimeSample(
const SdfPath& path,
double time,
const VtValue& value);
SDF_API
void SetTimeSample(
const SdfPath& path,
double time,
const SdfAbstractDataConstValue& value);
SDF_API
void CreateSpec(
const SdfPath& path,
SdfSpecType specType,
bool inert);
SDF_API
void DeleteSpec(
const SdfPath& path,
bool inert);
SDF_API
void MoveSpec(
const SdfPath& oldPath,
const SdfPath& newPath);
SDF_API
void PushChild(
const SdfPath& parentPath,
const TfToken& field,
const TfToken& value);
SDF_API
void PushChild(
const SdfPath& parentPath,
const TfToken& field,
const SdfPath& value);
SDF_API
void PopChild(
const SdfPath& parentPath,
const TfToken& field,
const TfToken& oldValue);
SDF_API
void PopChild(
const SdfPath& parentPath,
const TfToken& field,
const SdfPath& oldValue);
protected:
SDF_API
SdfLayerStateDelegateBase();
/// Returns the layer associated with this state delegate.
/// May be NULL if no layer is associated.
SDF_API
SdfLayerHandle _GetLayer() const;
/// Returns the underlying data object for the layer associated with
/// this state delegate. May be NULL if no layer is associated.
SDF_API
SdfAbstractDataPtr _GetLayerData() const;
/// Returns true if the associated layer has been authored to since
/// the last time the layer was marked clean, false otherwise.
virtual bool _IsDirty() = 0;
/// Mark the current state of the layer as clean, i.e. unchanged from its
/// persistent representation.
virtual void _MarkCurrentStateAsClean() = 0;
/// Mark the current state of the layer as dirty, i.e. modified from its
/// persistent representation.
virtual void _MarkCurrentStateAsDirty() = 0;
/// Invoked when the state delegate is associated with layer \p layer.
/// \p layer may be NULL if the state delegate is being removed.
virtual void _OnSetLayer(
const SdfLayerHandle& layer) = 0;
/// Invoked when a field is being changed on the associated layer.
virtual void _OnSetField(
const SdfPath& path,
const TfToken& fieldName,
const VtValue& value) = 0;
virtual void _OnSetField(
const SdfPath& path,
const TfToken& fieldName,
const SdfAbstractDataConstValue& value) = 0;
/// Invoked when a field dict key is being changed on the associated layer.
virtual void _OnSetFieldDictValueByKey(
const SdfPath& path,
const TfToken& fieldName,
const TfToken& keyPath,
const VtValue& value) = 0;
virtual void _OnSetFieldDictValueByKey(
const SdfPath& path,
const TfToken& fieldName,
const TfToken& keyPath,
const SdfAbstractDataConstValue& value) = 0;
/// Invoked when a time sample is being changed on the associated layer.
virtual void _OnSetTimeSample(
const SdfPath& path,
double time,
const VtValue& value) = 0;
virtual void _OnSetTimeSample(
const SdfPath& path,
double time,
const SdfAbstractDataConstValue& value) = 0;
/// Invoked when a new spec is created on the associated layer.
virtual void _OnCreateSpec(
const SdfPath& path,
SdfSpecType specType,
bool inert) = 0;
/// Invoked when a spec and its children are deleted from the associated
/// layer.
virtual void _OnDeleteSpec(
const SdfPath& path,
bool inert) = 0;
/// Invoked when a spec and its children are moved.
virtual void _OnMoveSpec(
const SdfPath& oldPath,
const SdfPath& newPath) = 0;
/// Invoked when a child spec is pushed onto a parent's list of children.
virtual void _OnPushChild(
const SdfPath& parentPath,
const TfToken& fieldName,
const TfToken& value) = 0;
/// Invoked when a child spec is pushed onto a parent's list of children.
virtual void _OnPushChild(
const SdfPath& parentPath,
const TfToken& fieldName,
const SdfPath& value) = 0;
/// Invoked when a child spec is popped off a parent's list of children.
virtual void _OnPopChild(
const SdfPath& parentPath,
const TfToken& fieldName,
const TfToken& oldValue) = 0;
/// Invoked when a child spec is popped off a parent's list of children.
virtual void _OnPopChild(
const SdfPath& parentPath,
const TfToken& fieldName,
const SdfPath& oldValue) = 0;
private:
friend class SdfLayer;
SDF_API void _SetLayer(const SdfLayerHandle& layer);
private:
SdfLayerHandle _layer;
};
/// \class SdfSimpleLayerStateDelegate
/// A layer state delegate that simply records whether any changes have
/// been made to a layer.
class SdfSimpleLayerStateDelegate
: public SdfLayerStateDelegateBase
{
public:
static SdfSimpleLayerStateDelegateRefPtr New();
protected:
SdfSimpleLayerStateDelegate();
// SdfLayerStateDelegateBase overrides
virtual bool _IsDirty() override;
virtual void _MarkCurrentStateAsClean() override;
virtual void _MarkCurrentStateAsDirty() override;
virtual void _OnSetLayer(
const SdfLayerHandle& layer) override;
virtual void _OnSetField(
const SdfPath& path,
const TfToken& fieldName,
const VtValue& value) override;
virtual void _OnSetField(
const SdfPath& path,
const TfToken& fieldName,
const SdfAbstractDataConstValue& value) override;
virtual void _OnSetFieldDictValueByKey(
const SdfPath& path,
const TfToken& fieldName,
const TfToken& keyPath,
const VtValue& value) override;
virtual void _OnSetFieldDictValueByKey(
const SdfPath& path,
const TfToken& fieldName,
const TfToken& keyPath,
const SdfAbstractDataConstValue& value) override;
virtual void _OnSetTimeSample(
const SdfPath& path,
double time,
const VtValue& value) override;
virtual void _OnSetTimeSample(
const SdfPath& path,
double time,
const SdfAbstractDataConstValue& value) override;
virtual void _OnCreateSpec(
const SdfPath& path,
SdfSpecType specType,
bool inert) override;
virtual void _OnDeleteSpec(
const SdfPath& path,
bool inert) override;
virtual void _OnMoveSpec(
const SdfPath& oldPath,
const SdfPath& newPath) override;
virtual void _OnPushChild(
const SdfPath& path,
const TfToken& fieldName,
const TfToken& value) override;
virtual void _OnPushChild(
const SdfPath& path,
const TfToken& fieldName,
const SdfPath& value) override;
virtual void _OnPopChild(
const SdfPath& path,
const TfToken& fieldName,
const TfToken& oldValue) override;
virtual void _OnPopChild(
const SdfPath& path,
const TfToken& fieldName,
const SdfPath& oldValue) override;
private:
bool _dirty;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_LAYER_STATE_DELEGATE_H
+89
View File
@@ -0,0 +1,89 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_LAYER_TREE_H
#define PXR_USD_SDF_LAYER_TREE_H
/// \file sdf/layerTree.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/usd/sdf/declareHandles.h"
#include "pxr/usd/sdf/layerOffset.h"
#include <boost/noncopyable.hpp>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
// Layer tree forward declarations.
class SdfLayerTree;
typedef TfRefPtr<SdfLayerTree> SdfLayerTreeHandle;
typedef std::vector<SdfLayerTreeHandle> SdfLayerTreeHandleVector;
SDF_DECLARE_HANDLES(SdfLayer);
/// \class SdfLayerTree
///
/// A SdfLayerTree is an immutable tree structure representing a sublayer
/// stack and its recursive structure.
///
/// Layers can have sublayers, which can in turn have sublayers of their
/// own. Clients that want to represent that hierarchical structure in
/// memory can build a SdfLayerTree for that purpose.
///
/// We use TfRefPtr<SdfLayerTree> as handles to LayerTrees, as a simple way
/// to pass them around as immutable trees without worrying about lifetime.
///
class SdfLayerTree : public TfRefBase, public TfWeakBase, boost::noncopyable {
public:
/// Create a new layer tree node.
SDF_API
static SdfLayerTreeHandle
New( const SdfLayerHandle & layer,
const SdfLayerTreeHandleVector & childTrees,
const SdfLayerOffset & cumulativeOffset = SdfLayerOffset() );
/// Returns the layer handle this tree node represents.
SDF_API const SdfLayerHandle & GetLayer() const;
/// Returns the cumulative layer offset from the root of the tree.
SDF_API const SdfLayerOffset & GetOffset() const;
/// Returns the children of this tree node.
SDF_API const SdfLayerTreeHandleVector & GetChildTrees() const;
private:
SdfLayerTree( const SdfLayerHandle & layer,
const SdfLayerTreeHandleVector & childTrees,
const SdfLayerOffset & cumulativeOffset );
private:
const SdfLayerHandle _layer;
const SdfLayerOffset _offset;
const SdfLayerTreeHandleVector _childTrees;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_LAYER_TREE_H
+56
View File
@@ -0,0 +1,56 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_LAYER_UTILS_H
#define PXR_USD_SDF_LAYER_UTILS_H
/// \file sdf/layerUtils.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/usd/sdf/declareHandles.h"
#include "pxr/usd/sdf/layer.h"
#include <string>
PXR_NAMESPACE_OPEN_SCOPE
SDF_DECLARE_HANDLES(SdfLayer);
/// Returns the path to the asset specified by \p assetPath, using the
/// \p anchor layer to anchor the path if it is relative. If the result of
/// anchoring \p assetPath to \p anchor's path cannot be resolved and
/// \p assetPath is a search path, \p assetPath will be returned. If
/// \p assetPath is not relative, \p assetPath will be returned. Otherwise,
/// the anchored path will be returned.
///
/// Note that if \p anchor is an anonymous layer, we will always return
/// the untouched \p assetPath.
SDF_API std::string
SdfComputeAssetPathRelativeToLayer(
const SdfLayerHandle& anchor,
const std::string& assetPath);
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_LAYER_UTILS_H
+351
View File
@@ -0,0 +1,351 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_LIST_EDITOR_H
#define PXR_USD_SDF_LIST_EDITOR_H
#include "pxr/pxr.h"
#include "pxr/base/tf/token.h"
#include "pxr/usd/sdf/allowed.h"
#include "pxr/usd/sdf/declareHandles.h"
#include "pxr/usd/sdf/listOp.h"
#include "pxr/usd/sdf/path.h"
#include "pxr/usd/sdf/schema.h"
#include "pxr/usd/sdf/spec.h"
#include <boost/noncopyable.hpp>
#include <boost/optional.hpp>
#include <functional>
PXR_NAMESPACE_OPEN_SCOPE
SDF_DECLARE_HANDLES(SdfLayer);
SDF_DECLARE_HANDLES(SdfSpec);
/// \class Sdf_ListEditor
///
/// Base class for list editor implementations in which list editing operations
/// are stored in data field(s) associated with an owning spec.
///
template <class TypePolicy>
class Sdf_ListEditor
: public boost::noncopyable
{
private:
typedef Sdf_ListEditor<TypePolicy> This;
public:
typedef typename TypePolicy::value_type value_type;
typedef std::vector<value_type> value_vector_type;
SdfLayerHandle GetLayer() const
{
return _owner ? _owner->GetLayer() : SdfLayerHandle();
}
SdfPath GetPath() const
{
return _owner ? _owner->GetPath() : SdfPath();
}
bool IsValid() const
{
return !IsExpired();
}
bool IsExpired() const
{
return !_owner;
}
bool HasKeys() const
{
if (IsExplicit()) {
return true;
}
else if (IsOrderedOnly()) {
return !_GetOperations(SdfListOpTypeOrdered).empty();
}
else {
return (!_GetOperations(SdfListOpTypeAdded).empty() ||
!_GetOperations(SdfListOpTypePrepended).empty() ||
!_GetOperations(SdfListOpTypeAppended).empty() ||
!_GetOperations(SdfListOpTypeDeleted).empty() ||
!_GetOperations(SdfListOpTypeOrdered).empty());
}
}
virtual bool IsExplicit() const = 0;
virtual bool IsOrderedOnly() const = 0;
virtual SdfAllowed PermissionToEdit(SdfListOpType op) const
{
if (!_owner) {
return SdfAllowed("List editor is expired");
}
if (!_owner->PermissionToEdit()) {
return SdfAllowed("Permission denied");
}
return true;
}
virtual bool CopyEdits(const Sdf_ListEditor& rhs) = 0;
virtual bool ClearEdits() = 0;
virtual bool ClearEditsAndMakeExplicit() = 0;
typedef std::function<
boost::optional<value_type>(const value_type&)
>
ModifyCallback;
/// Modifies the operations stored in all operation lists.
/// \p callback is called for every key. If the returned key is
/// invalid then the key is removed, otherwise it's replaced with the
/// returned key.
virtual void ModifyItemEdits(const ModifyCallback& cb) = 0;
typedef std::function<
boost::optional<value_type>(SdfListOpType, const value_type&)
>
ApplyCallback;
/// Apply the list operations represented by this interface to the given
/// vector of values \p vec. If \p callback is valid then it's called
/// for every key in the editor before applying it to \p vec. If the
/// returned key is empty then the key will not be applied. Otherwise
/// the returned key is applied, allowing callbacks to perform key
/// translation. Note that this means list editors can't meaningfully
/// hold the empty key.
virtual void ApplyEditsToList(
value_vector_type* vec,
const ApplyCallback& cb = ApplyCallback()) = 0;
/// Returns the number of elements in the specified list of operations.
size_t GetSize(SdfListOpType op) const
{
return _GetOperations(op).size();
}
/// Returns the \p i'th value in the specified list of operations.
value_type Get(SdfListOpType op, size_t i) const
{
return _GetOperations(op)[i];
}
/// Returns the specified list of operations.
value_vector_type GetVector(SdfListOpType op) const
{
return _GetOperations(op);
}
/// Returns the number of occurrences of \p val in the specified list of
/// operations.
size_t Count(SdfListOpType op, const value_type& val) const
{
const value_vector_type& ops = _GetOperations(op);
return std::count(ops.begin(), ops.end(), _typePolicy.Canonicalize(val));
}
/// Returns the index of \p val in the specified list of operations, -1
/// if \p val is not found.
size_t Find(SdfListOpType op, const value_type& val) const
{
const value_vector_type& vec = _GetOperations(op);
typename value_vector_type::const_iterator findIt =
std::find(vec.begin(), vec.end(), _typePolicy.Canonicalize(val));
if (findIt != vec.end()) {
return std::distance(vec.begin(), findIt);
}
return size_t(-1);
}
/// Replaces the operations in the specified list of operations in range
/// [index, index + n) with the given \p elems.
virtual bool ReplaceEdits(
SdfListOpType op, size_t index, size_t n,
const value_vector_type& elems) = 0;
/// Applies a \p rhs opinions about a given operation list to this one.
virtual void ApplyList(SdfListOpType op, const Sdf_ListEditor& rhs) = 0;
protected:
Sdf_ListEditor()
{
}
Sdf_ListEditor(const SdfSpecHandle& owner, const TfToken& field,
const TypePolicy& typePolicy)
: _owner(owner),
_field(field),
_typePolicy(typePolicy)
{
}
virtual ~Sdf_ListEditor() = default;
const SdfSpecHandle& _GetOwner() const
{
return _owner;
}
const TfToken& _GetField() const
{
return _field;
}
const TypePolicy& _GetTypePolicy() const
{
return _typePolicy;
}
virtual bool _ValidateEdit(SdfListOpType op,
const value_vector_type& oldValues,
const value_vector_type& newValues) const
{
// Disallow duplicate items from being stored in the new list
// editor values. This is O(n^2), but we expect the number of elements
// stored to be small enough that this won't matter.
//
// XXX:
// We assume that duplicate data items are never allowed to be
// authored. For full generality, this information ought to come from
// the layer schema.
// We also assume that the `oldValues` are already valid and do not
// contain duplicates. With this assumption, we can accelerate the
// common case of appending new items at the end and skip over a common
// prefix of oldValues and newValues. Then we can only check for dupes
// in the tail of newValues.
typename value_vector_type::const_iterator
oldValuesTail = oldValues.begin(),
newValuesTail = newValues.begin();
auto oldEnd = oldValues.end(), newEnd = newValues.end();
while (oldValuesTail != oldEnd && newValuesTail != newEnd &&
*oldValuesTail == *newValuesTail) {
++oldValuesTail, ++newValuesTail;
}
for (auto i = newValuesTail; i != newEnd; ++i) {
// Have to check unmatched new items for dupes.
for (auto j = newValues.begin(); j != i; ++j) {
if (*i == *j) {
TF_CODING_ERROR("Duplicate item '%s' not allowed for "
"field '%s' on <%s>",
TfStringify(*i).c_str(),
_field.GetText(),
this->GetPath().GetText());
return false;
}
}
}
// Ensure that all new values are valid for this field.
const SdfSchema::FieldDefinition* fieldDef =
_owner->GetSchema().GetFieldDefinition(_field);
if (!fieldDef) {
TF_CODING_ERROR("No field definition for field '%s'",
_field.GetText());
}
else {
for (auto i = newValuesTail; i != newEnd; ++i) {
if (SdfAllowed isValid = fieldDef->IsValidListValue(*i)) { }
else {
TF_CODING_ERROR("%s", isValid.GetWhyNot().c_str());
return false;
}
}
}
return true;
}
virtual void _OnEdit(SdfListOpType op,
const value_vector_type& oldValues,
const value_vector_type& newValues) const
{
}
virtual const value_vector_type& _GetOperations(SdfListOpType op) const = 0;
private:
SdfSpecHandle _owner;
TfToken _field;
TypePolicy _typePolicy;
};
template <class TypePolicy>
std::ostream&
operator<<(std::ostream& s, const Sdf_ListEditor<TypePolicy>& x)
{
struct Util {
typedef typename Sdf_ListEditor<TypePolicy>::value_vector_type
value_vector_type;
static void _Write(std::ostream& s, const value_vector_type& v)
{
s << '[';
for (size_t i = 0, n = v.size(); i < n; ++i) {
if (i != 0) {
s << ", ";
}
s << v[i];
}
s << ']';
}
};
if (!x.IsValid()) {
return s;
}
else if (x.IsExplicit()) {
Util::_Write(s, x.GetVector(SdfListOpTypeExplicit));
return s;
}
else {
s << "{ ";
if (!x.IsOrderedOnly()) {
s << "'added': ";
Util::_Write(s, x.GetVector(SdfListOpTypeAdded));
s << "'prepended': ";
Util::_Write(s, x.GetVector(SdfListOpTypePrepended));
s << "'appended': ";
Util::_Write(s, x.GetVector(SdfListOpTypeAppended));
s << ", 'deleted': ";
Util::_Write(s, x.GetVector(SdfListOpTypeDeleted));
s << ", ";
}
s << "'ordered': ";
Util::_Write(s, x.GetVector(SdfListOpTypeOrdered));
return s << " }";
}
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_LIST_EDITOR_H
+478
View File
@@ -0,0 +1,478 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_LIST_EDITOR_PROXY_H
#define PXR_USD_SDF_LIST_EDITOR_PROXY_H
/// \file sdf/listEditorProxy.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/listEditor.h"
#include "pxr/usd/sdf/listProxy.h"
#include "pxr/usd/sdf/changeBlock.h"
#include "pxr/base/vt/value.h" // for Vt_DefaultValueFactory
#include <boost/optional.hpp>
#include <boost/shared_ptr.hpp>
#include <functional>
PXR_NAMESPACE_OPEN_SCOPE
/// \class SdfListEditorProxy
///
/// Represents a set of list editing operations.
///
/// An SdfListEditorProxy allows consumers to specify a transformation to be
/// applied to a list via a set of list editing operations. Given a starting
/// ordered list, it can either replace the result with another ordered list
/// or apply a sequence of three operations: deleting keys, then adding keys
/// to the end (if they aren't already in the starting list), then reordering
/// keys.
///
/// The type policy defines the value type that a particular proxy can operate
/// on.
template <class _TypePolicy>
class SdfListEditorProxy {
public:
typedef _TypePolicy TypePolicy;
typedef SdfListEditorProxy<TypePolicy> This;
typedef SdfListProxy<TypePolicy> ListProxy;
typedef typename TypePolicy::value_type value_type;
typedef std::vector<value_type> value_vector_type;
// ApplyEdits types.
typedef std::function<boost::optional<value_type>
(SdfListOpType, const value_type&)> ApplyCallback;
// ModifyEdits types.
typedef std::function<boost::optional<value_type>
(const value_type&)> ModifyCallback;
/// Creates a default proxy object. The object evaluates to \c false in a
/// boolean context and all operations on this object have no effect.
SdfListEditorProxy()
{
}
/// Creates a new proxy object backed by the supplied list editor.
explicit SdfListEditorProxy(
const boost::shared_ptr<Sdf_ListEditor<TypePolicy> >& listEditor)
: _listEditor(listEditor)
{
}
/// Returns true if the list editor is expired.
bool IsExpired() const
{
if (!_listEditor) {
return false;
}
return _listEditor->IsExpired();
}
/// Returns \c true if the editor has an explicit list, \c false if
/// it has list operations.
bool IsExplicit() const
{
return _Validate() ? _listEditor->IsExplicit() : true;
}
/// Returns \c true if the editor is not explicit and allows ordering
/// only.
bool IsOrderedOnly() const
{
return _Validate() ? _listEditor->IsOrderedOnly() : false;
}
/// Returns \c true if the editor has an explicit list (even if it's
/// empty) or it has any added, prepended, appended, deleted,
/// or ordered keys.
bool HasKeys() const
{
return _Validate() ? _listEditor->HasKeys() : true;
}
/// Apply the edits to \p vec.
void ApplyEditsToList(value_vector_type* vec) const
{
if (_Validate()) {
_listEditor->ApplyEditsToList(vec, ApplyCallback());
}
}
/// Apply the edits to \p vec. If \p callback is valid then it's called
/// for every key in the editor before applying it to \p vec. If the
/// returned key is invalid then the key will not be applied. Otherwise
/// the returned key is applied, allowing callbacks to perform key
/// translation.
template <class CB>
void ApplyEditsToList(value_vector_type* vec, CB callback) const
{
if (_Validate()) {
_listEditor->ApplyEditsToList(vec, ApplyCallback(callback));
}
}
/// Copies the keys from \p other. This differs from assignment
/// because assignment just makes two list editors refer to the
/// same lists.
///
/// Not all list editors support changing their mode. If the mode
/// can't be changed to the mode of \p other then this does nothing
/// and returns \c false, otherwise it returns \c true.
bool CopyItems(const This& other)
{
return _Validate() && other._Validate() ?
_listEditor->CopyEdits(*other._listEditor) : false;
}
/// Removes all keys and changes the editor to have list operations.
///
/// Not all list editors support changing their mode. If the mode
/// can't be changed to the mode of \p other then this does nothing
/// and returns \c false, otherwise it returns \c true.
bool ClearEdits()
{
return _Validate() ? _listEditor->ClearEdits() : false;
}
/// Removes all keys and changes the editor to be explicit.
///
/// Not all list editors support changing their mode. If the mode
/// can't be changed to the mode of \p other then this does nothing
/// and returns \c false, otherwise it returns \c true.
bool ClearEditsAndMakeExplicit()
{
return _Validate() ? _listEditor->ClearEditsAndMakeExplicit() : false;
}
/// \p callback is called for every key. If the returned key is
/// invalid then the key is removed, otherwise it's replaced with the
/// returned key.
template <class CB>
void ModifyItemEdits(CB callback)
{
if (_Validate()) {
_listEditor->ModifyItemEdits(ModifyCallback(callback));
}
}
/// Check if the given item is explicit, added, prepended, appended,
/// deleted, or ordered by this editor. If \p onlyAddOrExplicit is
/// \c true we only check the added or explicit items.
bool ContainsItemEdit(const value_type& item,
bool onlyAddOrExplicit = false) const
{
if (_Validate()) {
size_t i;
i = GetExplicitItems().Find(item);
if (i != size_t(-1)) {
return true;
}
i = GetAddedItems().Find(item);
if (i != size_t(-1)) {
return true;
}
i = GetPrependedItems().Find(item);
if (i != size_t(-1)) {
return true;
}
i = GetAppendedItems().Find(item);
if (i != size_t(-1)) {
return true;
}
if (!onlyAddOrExplicit) {
i = GetDeletedItems().Find(item);
if (i != size_t(-1)) {
return true;
}
i = GetOrderedItems().Find(item);
if (i != size_t(-1)) {
return true;
}
}
}
return false;
}
/// Remove all occurrences of the given item, regardless of whether
/// the item is explicit, added, prepended, appended, deleted, or ordered.
void RemoveItemEdits(const value_type& item)
{
if (_Validate()) {
SdfChangeBlock block;
GetExplicitItems().Remove(item);
GetAddedItems().Remove(item);
GetPrependedItems().Remove(item);
GetAppendedItems().Remove(item);
GetDeletedItems().Remove(item);
GetOrderedItems().Remove(item);
}
}
/// Replace all occurrences of the given item, regardless of
/// whether the item is explicit, added, prepended, appended,
/// deleted or ordered.
void ReplaceItemEdits(const value_type& oldItem, const value_type& newItem)
{
if (_Validate()) {
SdfChangeBlock block;
GetExplicitItems().Replace(oldItem, newItem);
GetAddedItems().Replace(oldItem, newItem);
GetPrependedItems().Replace(oldItem, newItem);
GetAppendedItems().Replace(oldItem, newItem);
GetDeletedItems().Replace(oldItem, newItem);
GetOrderedItems().Replace(oldItem, newItem);
}
}
/// Returns the explicitly set items.
ListProxy GetExplicitItems() const
{
return ListProxy(_listEditor, SdfListOpTypeExplicit);
}
/// Returns the items added by this list editor
ListProxy GetAddedItems() const
{
return ListProxy(_listEditor, SdfListOpTypeAdded);
}
/// Returns the items prepended by this list editor
ListProxy GetPrependedItems() const
{
return ListProxy(_listEditor, SdfListOpTypePrepended);
}
/// Returns the items appended by this list editor
ListProxy GetAppendedItems() const
{
return ListProxy(_listEditor, SdfListOpTypeAppended);
}
/// Returns the items deleted by this list editor
ListProxy GetDeletedItems() const
{
return ListProxy(_listEditor, SdfListOpTypeDeleted);
}
/// Returns the items reordered by this list editor
ListProxy GetOrderedItems() const
{
return ListProxy(_listEditor, SdfListOpTypeOrdered);
}
/// Returns the added or explicitly set items.
value_vector_type GetAddedOrExplicitItems() const
{
value_vector_type result;
if (_Validate()) {
_listEditor->ApplyEditsToList(&result);
}
return result;
}
void Add(const value_type& value)
{
if (_Validate()) {
if (!_listEditor->IsOrderedOnly()) {
if (_listEditor->IsExplicit()) {
_AddOrReplace(SdfListOpTypeExplicit, value);
}
else {
GetDeletedItems().Remove(value);
_AddOrReplace(SdfListOpTypeAdded, value);
}
}
}
}
void Prepend(const value_type& value)
{
if (_Validate()) {
if (!_listEditor->IsOrderedOnly()) {
if (_listEditor->IsExplicit()) {
_Prepend(SdfListOpTypeExplicit, value);
}
else {
GetDeletedItems().Remove(value);
_Prepend(SdfListOpTypePrepended, value);
}
}
}
}
void Append(const value_type& value)
{
if (_Validate()) {
if (!_listEditor->IsOrderedOnly()) {
if (_listEditor->IsExplicit()) {
_Append(SdfListOpTypeExplicit, value);
}
else {
GetDeletedItems().Remove(value);
_Append(SdfListOpTypeAppended, value);
}
}
}
}
void Remove(const value_type& value)
{
if (_Validate()) {
if (_listEditor->IsExplicit()) {
GetExplicitItems().Remove(value);
}
else if (!_listEditor->IsOrderedOnly()) {
GetAddedItems().Remove(value);
GetPrependedItems().Remove(value);
GetAppendedItems().Remove(value);
_AddIfMissing(SdfListOpTypeDeleted, value);
}
}
}
void Erase(const value_type& value)
{
if (_Validate()) {
if (!_listEditor->IsOrderedOnly()) {
if (_listEditor->IsExplicit()) {
GetExplicitItems().Remove(value);
}
else {
GetAddedItems().Remove(value);
GetPrependedItems().Remove(value);
GetAppendedItems().Remove(value);
}
}
}
}
/// Explicit bool conversion operator. A ListEditorProxy object
/// converts to \c true iff the list editor is valid, converts to \c false
/// otherwise.
explicit operator bool() const
{
return _listEditor && _listEditor->IsValid();
}
private:
bool _Validate()
{
if (!_listEditor) {
return false;
}
if (IsExpired()) {
TF_CODING_ERROR("Accessing expired list editor");
return false;
}
return true;
}
bool _Validate() const
{
if (!_listEditor) {
return false;
}
if (IsExpired()) {
TF_CODING_ERROR("Accessing expired list editor");
return false;
}
return true;
}
void _AddIfMissing(SdfListOpType op, const value_type& value)
{
ListProxy proxy(_listEditor, op);
size_t index = proxy.Find(value);
if (index == size_t(-1)) {
proxy.push_back(value);
}
}
void _AddOrReplace(SdfListOpType op, const value_type& value)
{
ListProxy proxy(_listEditor, op);
size_t index = proxy.Find(value);
if (index == size_t(-1)) {
proxy.push_back(value);
}
else if (value != static_cast<value_type>(proxy[index])) {
proxy[index] = value;
}
}
void _Prepend(SdfListOpType op, const value_type& value)
{
ListProxy proxy(_listEditor, op);
size_t index = proxy.Find(value);
if (index != 0) {
if (index != size_t(-1)) {
proxy.Erase(index);
}
proxy.insert(proxy.begin(), value);
}
}
void _Append(SdfListOpType op, const value_type& value)
{
ListProxy proxy(_listEditor, op);
size_t index = proxy.Find(value);
if (proxy.empty() || (index != proxy.size()-1)) {
if (index != size_t(-1)) {
proxy.Erase(index);
}
proxy.push_back(value);
}
}
private:
boost::shared_ptr<Sdf_ListEditor<TypePolicy> > _listEditor;
friend class Sdf_ListEditorProxyAccess;
template <class T> friend class SdfPyWrapListEditorProxy;
};
// Cannot get from a VtValue except as the correct type.
template <class TP>
struct Vt_DefaultValueFactory<SdfListEditorProxy<TP> > {
static Vt_DefaultValueHolder Invoke() = delete;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_LIST_EDITOR_PROXY_H
+323
View File
@@ -0,0 +1,323 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_LIST_OP_H
#define PXR_USD_SDF_LIST_OP_H
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/base/tf/token.h"
#include <boost/functional/hash.hpp>
#include <boost/optional/optional_fwd.hpp>
#include <functional>
#include <iosfwd>
#include <list>
#include <map>
#include <string>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
/// \enum SdfListOpType
///
/// Enum for specifying one of the list editing operation types.
///
enum SdfListOpType {
SdfListOpTypeExplicit,
SdfListOpTypeAdded,
SdfListOpTypeDeleted,
SdfListOpTypeOrdered,
SdfListOpTypePrepended,
SdfListOpTypeAppended
};
/// \struct Sdf_ListOpTraits
///
/// Trait classes for specializing behaviors of SdfListOp for a given item
/// type.
///
template <class T>
struct Sdf_ListOpTraits
{
typedef std::less<T> ItemComparator;
};
/// \class SdfListOp
///
/// Value type representing a list-edit operation.
///
/// SdfListOp is a value type representing an operation that edits a list.
/// It may add or remove items, reorder them, or replace the list entirely.
///
template <typename T>
class SdfListOp {
public:
typedef T ItemType;
typedef std::vector<ItemType> ItemVector;
typedef ItemType value_type;
typedef ItemVector value_vector_type;
/// Create a ListOp in explicit mode with the given \p explicitItems.
SDF_API
static SdfListOp CreateExplicit(
const ItemVector& explicitItems = ItemVector());
/// Create a ListOp in non-explicit mode with the given
/// \p prependedItems, \p appendedItems, and \p deletedItems
SDF_API
static SdfListOp Create(
const ItemVector& prependedItems = ItemVector(),
const ItemVector& appendedItems = ItemVector(),
const ItemVector& deletedItems = ItemVector());
/// Create an empty ListOp in non-explicit mode.
SDF_API SdfListOp();
SDF_API void Swap(SdfListOp<T>& rhs);
/// Returns \c true if the editor has an explicit list (even if it's
/// empty) or it has any added, prepended, appended, deleted,
/// or ordered keys.
bool HasKeys() const
{
if (IsExplicit()) {
return true;
}
if (_addedItems.size() != 0 ||
_prependedItems.size() != 0 ||
_appendedItems.size() != 0 ||
_deletedItems.size() != 0) {
return true;
}
return _orderedItems.size() != 0;
}
/// Returns \c true if the given item is in any of the item lists.
SDF_API bool HasItem(const T& item) const;
/// Returns \c true if the list is explicit.
bool IsExplicit() const
{
return _isExplicit;
}
/// Returns the explicit items.
const ItemVector& GetExplicitItems() const
{
return _explicitItems;
}
/// Returns the explicit items.
const ItemVector& GetAddedItems() const
{
return _addedItems;
}
/// Returns the explicit items.
const ItemVector& GetPrependedItems() const
{
return _prependedItems;
}
/// Returns the explicit items.
const ItemVector& GetAppendedItems() const
{
return _appendedItems;
}
/// Returns the deleted items.
const ItemVector& GetDeletedItems() const
{
return _deletedItems;
}
/// Returns the ordered items.
const ItemVector& GetOrderedItems() const
{
return _orderedItems;
}
/// Return the item vector identified by \p type.
SDF_API const ItemVector& GetItems(SdfListOpType type) const;
SDF_API void SetExplicitItems(const ItemVector &items);
SDF_API void SetAddedItems(const ItemVector &items);
SDF_API void SetPrependedItems(const ItemVector &items);
SDF_API void SetAppendedItems(const ItemVector &items);
SDF_API void SetDeletedItems(const ItemVector &items);
SDF_API void SetOrderedItems(const ItemVector &items);
/// Sets the item vector for the given operation \p type.
SDF_API void SetItems(const ItemVector &items, SdfListOpType type);
/// Removes all items and changes the list to be non-explicit.
SDF_API void Clear();
/// Removes all items and changes the list to be explicit.
SDF_API void ClearAndMakeExplicit();
/// Callback type for ApplyOperations.
typedef std::function<
boost::optional<ItemType>(SdfListOpType, const ItemType&)
> ApplyCallback;
/// Applies edit operations to the given ItemVector.
/// If supplied, \p cb will be called on each item in the operation vectors
/// before they are applied to \p vec. Consumers can use this to transform
/// the items stored in the operation vectors to match what's stored in
/// \p vec.
SDF_API
void ApplyOperations(ItemVector* vec,
const ApplyCallback& cb = ApplyCallback()) const;
/// Applies edit operations to the given ListOp.
///
/// The result is a ListOp that, when applied to a list, has the same
/// effect as applying \p inner and then \p this in sequence.
///
/// The result will be empty if the result is not well defined.
/// The result is well-defined when \p inner and \p this do not
/// use the 'ordered' or 'added' item lists. In other words, only
/// the explicit, prepended, appended, and deleted portions of
/// SdfListOp are closed under composition with ApplyOperations().
SDF_API
boost::optional<SdfListOp<T>>
ApplyOperations(const SdfListOp<T> &inner) const;
/// Callback type for ModifyOperations.
typedef std::function<
boost::optional<ItemType>(const ItemType&)
> ModifyCallback;
/// Modifies operations specified in this object.
/// \p callback is called for every item in all operation vectors. If the
/// returned key is empty then the key is removed, otherwise it's replaced
/// with the returned key.
///
/// Returns true if a change was made, false otherwise.
SDF_API bool ModifyOperations(const ModifyCallback& callback);
/// Replaces the items in the specified operation vector in the range
/// (index, index + n] with the given \p newItems. If \p newItems is empty
/// the items in the range will simply be removed.
SDF_API
bool ReplaceOperations(const SdfListOpType op, size_t index, size_t n,
const ItemVector& newItems);
/// Composes a stronger SdfListOp's opinions for a given operation list
/// over this one.
SDF_API
void ComposeOperations(const SdfListOp<T>& stronger, SdfListOpType op);
friend inline size_t hash_value(const SdfListOp &op) {
size_t h = 0;
boost::hash_combine(h, op._isExplicit);
boost::hash_combine(h, op._explicitItems);
boost::hash_combine(h, op._addedItems);
boost::hash_combine(h, op._prependedItems);
boost::hash_combine(h, op._appendedItems);
boost::hash_combine(h, op._deletedItems);
boost::hash_combine(h, op._orderedItems);
return h;
}
bool operator==(const SdfListOp<T> &rhs) const {
return _isExplicit == rhs._isExplicit &&
_explicitItems == rhs._explicitItems &&
_addedItems == rhs._addedItems &&
_prependedItems == rhs._prependedItems &&
_appendedItems == rhs._appendedItems &&
_deletedItems == rhs._deletedItems &&
_orderedItems == rhs._orderedItems;
};
bool operator!=(const SdfListOp<T> &rhs) const {
return !(*this == rhs);
};
private:
void _SetExplicit(bool isExplicit);
typedef typename Sdf_ListOpTraits<T>::ItemComparator _ItemComparator;
typedef std::list<ItemType> _ApplyList;
typedef std::map<ItemType, typename _ApplyList::iterator, _ItemComparator>
_ApplyMap;
void _AddKeys(SdfListOpType, const ApplyCallback& cb,
_ApplyList* result, _ApplyMap* search) const;
void _PrependKeys(SdfListOpType, const ApplyCallback& cb,
_ApplyList* result, _ApplyMap* search) const;
void _AppendKeys(SdfListOpType, const ApplyCallback& cb,
_ApplyList* result, _ApplyMap* search) const;
void _DeleteKeys(SdfListOpType, const ApplyCallback& cb,
_ApplyList* result, _ApplyMap* search) const;
void _ReorderKeys(SdfListOpType, const ApplyCallback& cb,
_ApplyList* result, _ApplyMap* search) const;
private:
bool _isExplicit;
ItemVector _explicitItems;
ItemVector _addedItems;
ItemVector _prependedItems;
ItemVector _appendedItems;
ItemVector _deletedItems;
ItemVector _orderedItems;
};
// ADL swap.
template <class T>
void swap(SdfListOp<T> &x, SdfListOp<T> &y)
{
x.Swap(y);
}
// Helper function for applying an ordering operation described by \p orderVector
// to vector \p v.
template <class ItemType>
SDF_API
void SdfApplyListOrdering(std::vector<ItemType>* v,
const std::vector<ItemType>& order);
// Ostream output methods for list values (useful for debugging and required
// for storing a list value in a VtValue).
template <typename T>
SDF_API
std::ostream & operator<<( std::ostream &, const SdfListOp<T> & );
// Concrete, instantiated listop types.
typedef class SdfListOp<int> SdfIntListOp;
typedef class SdfListOp<unsigned int> SdfUIntListOp;
typedef class SdfListOp<int64_t> SdfInt64ListOp;
typedef class SdfListOp<uint64_t> SdfUInt64ListOp;
typedef class SdfListOp<TfToken> SdfTokenListOp;
typedef class SdfListOp<std::string> SdfStringListOp;
typedef class SdfListOp<class SdfPath> SdfPathListOp;
typedef class SdfListOp<class SdfReference> SdfReferenceListOp;
typedef class SdfListOp<class SdfPayload> SdfPayloadListOp;
typedef class SdfListOp<class SdfUnregisteredValue> SdfUnregisteredValueListOp;
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_LIST_OP_H
+616
View File
@@ -0,0 +1,616 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_LIST_PROXY_H
#define PXR_USD_SDF_LIST_PROXY_H
/// \file sdf/listProxy.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/allowed.h"
#include "pxr/usd/sdf/listEditor.h"
#include "pxr/usd/sdf/listOp.h"
#include "pxr/usd/sdf/path.h"
#include "pxr/base/tf/diagnostic.h"
#include "pxr/base/tf/errorMark.h"
#include "pxr/base/tf/iterator.h"
#include <boost/iterator/iterator_facade.hpp>
#include <boost/iterator/reverse_iterator.hpp>
#include <boost/operators.hpp>
#include <boost/optional.hpp>
#include <boost/type_traits/is_base_of.hpp>
#include <boost/type_traits/remove_cv.hpp>
#include <boost/type_traits/remove_reference.hpp>
PXR_NAMESPACE_OPEN_SCOPE
/// \class SdfListProxy
///
/// Represents a single list of list editing operations.
///
/// An SdfListProxy represents a single list of list editing operations, making
/// it look like an STL vector (modeling a random access container and back
/// insertion sequence).
///
template <class _TypePolicy>
class SdfListProxy :
boost::totally_ordered<SdfListProxy<_TypePolicy>,
std::vector<typename _TypePolicy::value_type> > {
public:
typedef _TypePolicy TypePolicy;
typedef SdfListProxy<TypePolicy> This;
typedef typename TypePolicy::value_type value_type;
typedef std::vector<value_type> value_vector_type;
private:
// Proxies an item in a list editor list.
class _ItemProxy : boost::totally_ordered<_ItemProxy> {
public:
explicit _ItemProxy(This* owner, size_t index) :
_owner(owner), _index(index)
{
// Do nothing
}
_ItemProxy& operator=(const _ItemProxy& x) {
_owner->_Edit(_index, 1, value_vector_type(1, x));
return *this;
}
_ItemProxy& operator=(const value_type& x) {
_owner->_Edit(_index, 1, value_vector_type(1, x));
return *this;
}
operator value_type() const {
return _owner->_Get(_index);
}
bool operator==(const value_type& x) const {
return _owner->_Get(_index) == x;
}
bool operator<(const value_type& x) const {
return _owner->_Get(_index) < x;
}
private:
This* _owner;
size_t _index;
};
friend class _ItemProxy;
class _GetHelper {
public:
typedef _ItemProxy result_type;
result_type operator()(This* owner, size_t index) const {
return _ItemProxy(owner, index);
}
};
class _ConstGetHelper {
public:
typedef value_type result_type;
result_type operator()(const This* owner, size_t index) const {
return owner->_Get(index);
}
};
friend class _GetHelper;
friend class _ConstGetHelper;
template <class Owner, class GetItem>
class _Iterator :
public boost::iterator_facade<
_Iterator<Owner, GetItem>,
typename boost::remove_cv<
typename boost::remove_reference<
typename GetItem::result_type
>::type
>::type,
std::random_access_iterator_tag,
typename GetItem::result_type> {
public:
typedef _Iterator<Owner, GetItem> This;
typedef
boost::iterator_facade<
_Iterator<Owner, GetItem>,
typename boost::remove_cv<
typename boost::remove_reference<
typename GetItem::result_type
>::type
>::type,
std::random_access_iterator_tag,
typename GetItem::result_type> Parent;
typedef typename Parent::reference reference;
typedef typename Parent::difference_type difference_type;
_Iterator() : _owner(NULL), _index(0)
{
// Do nothing
}
_Iterator(Owner owner, size_t index) : _owner(owner), _index(index)
{
// Do nothing
}
private:
friend class boost::iterator_core_access;
reference dereference() const {
return _getItem(_owner, _index);
}
bool equal(const This& other) const {
if (_owner != other._owner) {
TF_CODING_ERROR("Comparing SdfListProxy iterators from "
"different proxies!");
return false;
}
return _index == other._index;
}
void increment() {
++_index;
}
void decrement() {
--_index;
}
void advance(difference_type n) {
_index += n;
}
difference_type distance_to(const This& other) const {
return other._index - _index;
}
private:
GetItem _getItem;
Owner _owner;
size_t _index;
};
public:
typedef _ItemProxy reference;
typedef _Iterator<This*, _GetHelper> iterator;
typedef _Iterator<const This*, _ConstGetHelper> const_iterator;
typedef boost::reverse_iterator<iterator> reverse_iterator;
typedef boost::reverse_iterator<const_iterator> const_reverse_iterator;
/// Creates a default list proxy object for list operation vector specified
/// \p op. This object evaluates to false in a boolean context and all
/// operations on this object have no effect.
SdfListProxy(SdfListOpType op) :
_op(op)
{
}
/// Create a new proxy wrapping the list operation vector specified by
/// \p op in the underlying \p listEditor.
SdfListProxy(const boost::shared_ptr<Sdf_ListEditor<TypePolicy> >& editor,
SdfListOpType op) :
_listEditor(editor),
_op(op)
{
}
/// Return an iterator to the start of the sequence.
iterator begin() {
return iterator(_GetThis(), 0);
}
/// Return an iterator to the end of the sequence.
iterator end() {
return iterator(_GetThis(), _GetSize());
}
/// Return a reverse iterator to the last item of the sequence.
reverse_iterator rbegin() {
return reverse_iterator(end());
}
/// Return a reverse iterator past the start item of the sequence.
reverse_iterator rend() {
return reverse_iterator(begin());
}
/// Return a const iterator to the start of the sequence.
const_iterator begin() const {
return const_iterator(_GetThis(), 0);
}
/// Return a const iterator to the end of the sequence.
const_iterator end() const {
return const_iterator(_GetThis(), _GetSize());
}
/// Return a const reverse iterator to the last item of the sequence.
const_reverse_iterator rbegin() const {
return const_reverse_iterator(end());
}
/// Return a const reverse iterator past the start item of the
/// sequence.
const_reverse_iterator rend() const {
return const_reverse_iterator(begin());
}
/// Return the size of the sequence.
size_t size() const {
return _Validate() ? _GetSize() : 0;
}
/// Return true if size() == 0.
bool empty() const {
return size() == 0;
}
/// Return a \p reference to the item at index \p n.
reference operator[](size_t n) {
return reference(_GetThis(), n);
}
/// Return a copy of the item at index \p n.
value_type operator[](size_t n) const {
return _Get(n);
}
/// Return a \p reference to the item at the front of the sequence.
reference front() {
return reference(_GetThis(), 0);
}
/// Return a \p reference to the item at the back of the sequence.
reference back() {
return reference(_GetThis(), _GetSize() - 1);
}
/// Return a copy of the item at the front of the sequence.
value_type front() const {
return _Get(0);
}
/// Return a copy of the item at the back of the sequence.
value_type back() const {
return _Get(_GetSize() - 1);
}
/// Append \p elem to this sequence.
void push_back(const value_type& elem) {
_Edit(_GetSize(), 0, value_vector_type(1, elem));
}
/// Remove the last element from this sequence.
void pop_back() {
_Edit(_GetSize() - 1, 1, value_vector_type());
}
/// Insert \p x into this sequence at position \p pos.
iterator insert(iterator pos, const value_type& x) {
_Edit(pos - iterator(this, 0), 0, value_vector_type(1, x));
return pos;
}
/// Insert copies of the elements in [\p f, \p l) into this sequence
/// starting at position \p pos.
template <class InputIterator>
void insert(iterator pos, InputIterator f, InputIterator l) {
_Edit(pos - iterator(this, 0), 0, value_vector_type(f, l));
}
/// Erase the element at \p pos.
void erase(iterator pos) {
_Edit(pos - iterator(this, 0), 1, value_vector_type());
}
/// Erase all the elements in the range [\p f, \p l).
void erase(iterator f, iterator l) {
_Edit(f - iterator(this, 0), l - f, value_vector_type());
}
/// Clear the contents of the sequence.
void clear() {
_Edit(0, _GetSize(), value_vector_type());
}
/// Resize the contents of the sequence.
///
/// Inserts or erases copies of \p t at the end
/// such that the size becomes \p n.
void resize(size_t n, const value_type& t = value_type()) {
size_t s = _GetSize();
if (n > s) {
_Edit(s, 0, value_vector_type(n - s, t));
}
else if (n < s) {
_Edit(n, s - n, value_vector_type());
}
}
/// Produce a copy of the contents of this sequence into a vector.
operator value_vector_type() const {
return _listEditor ? _listEditor->GetVector(_op) : value_vector_type();
}
/// Replace all elements in this sequence with the elements in
/// the \p other sequence.
template <class T2>
This& operator=(const SdfListProxy<T2>& other) {
_Edit(0, _GetSize(), static_cast<value_vector_type>(other));
return *this;
}
/// Replace all elements in this sequence with the given vector.
This& operator=(const value_vector_type& other) {
_Edit(0, _GetSize(), other);
return *this;
}
/// Replace all elements in this sequence with the given vector.
template <class Y>
This& operator=(const std::vector<Y>& v) {
_Edit(0, _GetSize(), value_vector_type(v.begin(), v.end()));
return *this;
}
/// Equality comparison.
template <class T2>
bool operator==(const SdfListProxy<T2>& y) const {
return value_vector_type(*this) == value_vector_type(y);
}
/// Inequality comparison.
template <class T2>
bool operator!=(const SdfListProxy<T2>& y) const {
return !(*this == y);
}
/// Less-than comparison.
template <class T2>
bool operator<(const SdfListProxy<T2>& y) const {
return value_vector_type(*this) < value_vector_type(y);
}
/// Less-than-or-equal comparison.
template <class T2>
bool operator<=(const SdfListProxy<T2>& y) const {
return value_vector_type(*this) <= value_vector_type(y);
}
/// Greater-than comparison.
template <class T2>
bool operator>(const SdfListProxy<T2>& y) const {
return !(*this <= y);
}
/// Greater-than-or-equal comparison.
template <class T2>
bool operator>=(const SdfListProxy<T2>& y) const {
return !(*this < y);
}
/// Equality comparison.
bool operator==(const value_vector_type& y) const {
return value_vector_type(*this) == y;
}
/// Less-than comparison.
bool operator<(const value_vector_type& y) const {
return value_vector_type(*this) < y;
}
/// Greater-than comparison.
bool operator>(const value_vector_type& y) const {
return value_vector_type(*this) > y;
}
/// Explicit bool conversion operator. The list proxy object converts to
/// \c true if the list editor is valid, \c false otherwise.
explicit operator bool() const
{
return _listEditor && _listEditor->IsValid() && _IsRelevant();
}
// Extensions
/// Returns the layer that this list editor belongs to.
SdfLayerHandle GetLayer() const
{
return _listEditor ? _listEditor->GetLayer() : SdfLayerHandle();
}
/// Returns the path to this list editor's value.
SdfPath GetPath() const
{
return _listEditor ? _listEditor->GetPath() : SdfPath();
}
/// Returns true if the list editor is expired.
bool IsExpired() const
{
return _listEditor && _listEditor->IsExpired();
}
size_t Count(const value_type& value) const
{
return (_Validate() ? _listEditor->Count(_op, value) : 0);
}
size_t Find(const value_type& value) const
{
return (_Validate() ? _listEditor->Find(_op, value) : size_t(-1));
}
void Insert(int index, const value_type& value)
{
if (index == -1) {
index = static_cast<int>(_GetSize());
}
_Edit(index, 0, value_vector_type(1, value));
}
void Remove(const value_type& value)
{
size_t index = Find(value);
if (index != size_t(-1)) {
Erase(index);
}
else {
// Allow policy to raise an error even though we're not
// doing anything.
_Edit(_GetSize(), 0, value_vector_type());
}
}
void Replace(const value_type& oldValue, const value_type& newValue)
{
size_t index = Find(oldValue);
if (index != size_t(-1)) {
_Edit(index, 1, value_vector_type(1, newValue));
}
else {
// Allow policy to raise an error even though we're not
// doing anything.
_Edit(_GetSize(), 0, value_vector_type());
}
}
void Erase(size_t index)
{
_Edit(index, 1, value_vector_type());
}
/// Applies the edits in the given list to this one.
void ApplyList(const SdfListProxy &list)
{
if (_Validate() && list._Validate()) {
_listEditor->ApplyList(_op, *list._listEditor);
}
}
/// Apply the edits in this list to the given \p vec.
void ApplyEditsToList(value_vector_type* vec)
{
if (_Validate()) {
_listEditor->ApplyEditsToList(vec);
}
}
private:
bool _Validate()
{
if (!_listEditor) {
return false;
}
if (IsExpired()) {
TF_CODING_ERROR("Accessing expired list editor");
return false;
}
return true;
}
bool _Validate() const
{
if (!_listEditor) {
return false;
}
if (IsExpired()) {
TF_CODING_ERROR("Accessing expired list editor");
return false;
}
return true;
}
This* _GetThis()
{
return _Validate() ? this : NULL;
}
const This* _GetThis() const
{
return _Validate() ? this : NULL;
}
bool _IsRelevant() const
{
if (_listEditor->IsExplicit()) {
return _op == SdfListOpTypeExplicit;
}
else if (_listEditor->IsOrderedOnly()) {
return _op == SdfListOpTypeOrdered;
}
else {
return _op != SdfListOpTypeExplicit;
}
}
size_t _GetSize() const
{
return _listEditor ? _listEditor->GetSize(_op) : 0;
}
value_type _Get(size_t n) const
{
return _Validate() ? _listEditor->Get(_op, n) : value_type();
}
void _Edit(size_t index, size_t n, const value_vector_type& elems)
{
if (_Validate()) {
// Allow policy to raise an error even if we're not
// doing anything.
if (n == 0 && elems.empty()) {
SdfAllowed canEdit = _listEditor->PermissionToEdit(_op);
if (!canEdit) {
TF_CODING_ERROR("Editing list: %s",
canEdit.GetWhyNot().c_str());
}
return;
}
bool valid =
_listEditor->ReplaceEdits(_op, index, n, elems);
if (!valid) {
TF_CODING_ERROR("Inserting invalid value into list editor");
}
}
}
private:
boost::shared_ptr<Sdf_ListEditor<TypePolicy> > _listEditor;
SdfListOpType _op;
template <class> friend class SdfPyWrapListProxy;
};
// Allow TfIteration over list proxies.
template <typename T>
struct Tf_ShouldIterateOverCopy<SdfListProxy<T> > : boost::true_type
{
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_LIST_PROXY_H
+930
View File
@@ -0,0 +1,930 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_MAP_EDIT_PROXY_H
#define PXR_USD_SDF_MAP_EDIT_PROXY_H
/// \file sdf/mapEditProxy.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/allowed.h"
#include "pxr/usd/sdf/changeBlock.h"
#include "pxr/usd/sdf/declareHandles.h"
#include "pxr/usd/sdf/mapEditor.h"
#include "pxr/usd/sdf/spec.h"
#include "pxr/base/vt/value.h" // for Vt_DefaultValueFactory
#include "pxr/base/tf/diagnostic.h"
#include "pxr/base/tf/mallocTag.h"
#include <boost/iterator/iterator_facade.hpp>
#include <boost/iterator/reverse_iterator.hpp>
#include <boost/operators.hpp>
#include <iterator>
#include <utility>
PXR_NAMESPACE_OPEN_SCOPE
class TfToken;
SDF_DECLARE_HANDLES(SdfSpec);
/// \class SdfIdentityMapEditProxyValuePolicy
///
/// A value policy for \c SdfMapEditProxy that does nothing.
///
/// A \c SdfMapEditProxy value policy converts incoming keys and values
/// into a canonical form used for storage. This is useful if you have
/// a key where multiple values are equivalent for the purposes of the
/// map but don't compare equal and you can store any one of the
/// equivalent values. Note that the policy is only used on inputs to
/// the map proxy; it's never used when returning keys or values from
/// the proxy.
///
template <class T>
class SdfIdentityMapEditProxyValuePolicy {
public:
typedef T Type;
typedef typename Type::key_type key_type;
typedef typename Type::mapped_type mapped_type;
typedef typename Type::value_type value_type;
/// Canonicalize an entire \c Type object. \c Type must be convertible
/// to the type of \p x. The return value must be convertible to a
/// \c Type.
static const Type& CanonicalizeType(const SdfSpecHandle&, const Type& x)
{
return x;
}
/// Canonicalize a key. \c key_type must be convertible to the type of
/// \p x. The return value must be convertible to a \c key_type.
static const key_type& CanonicalizeKey(const SdfSpecHandle&,
const key_type& x)
{
return x;
}
/// Canonicalize a value. \c mapped_type must be convertible to the type
/// of \p x. The return value must be convertible to a \c mapped_type.
static const mapped_type& CanonicalizeValue(const SdfSpecHandle&,
const mapped_type& x)
{
return x;
}
/// Canonicalize a key/value pair. \c value_type must be convertible
/// to the type of \p x. The return value must be convertible to a
/// \c value_type.
static const value_type& CanonicalizePair(const SdfSpecHandle&,
const value_type& x)
{
return x;
}
};
/// \class SdfMapEditProxy
///
/// A proxy for editing map-like values.
///
/// A \c SdfMapEditProxy provides an interface for editing fields
/// containing map-like values. The proxy allows consumers to
/// interact with these values like a typical std::map while
/// taking into account additional editing and validation policies.
///
/// The \c _ValuePolicy is used to canonicalize keys and values before
/// storage or comparison.
///
/// \sa SdfIdentityMapEditProxyValuePolicy
///
template <class T, class _ValuePolicy = SdfIdentityMapEditProxyValuePolicy<T> >
class SdfMapEditProxy :
boost::totally_ordered<SdfMapEditProxy<T, _ValuePolicy>, T> {
public:
typedef T Type;
typedef _ValuePolicy ValuePolicy;
typedef SdfMapEditProxy<Type, ValuePolicy> This;
typedef typename Type::key_type key_type;
typedef typename Type::mapped_type mapped_type;
typedef typename Type::value_type value_type;
private:
// Note: We're playing a dangerous game with copy-on-write and
// iterators. Our iterators wrap iterators on the proxied
// Type. When and if we copy-on-write then all of our
// existing iterators use the old proxied object's iterators
// and any new iterators will use the new proxied object's
// iterators. Therefore old and new iterators are no longer
// compatible and an old and new iterator that refer to the
// same key will not compare equal.
//
// It turns out that this is okay because we don't promise
// to keep iterators valid across an edit. However, we'd
// like dereferencing an old iterator to either report an
// error or yield the current state. We can do that by
// storing the Type* in use when the iterator was created
// and comparing it to the current Type*. If they're
// different we need to report an error or use the key from
// the old iterator and lookup that key in the new Type*.
// We currently choose to return the current state.
typedef typename Type::iterator inner_iterator;
typedef typename Type::const_iterator const_inner_iterator;
class _ValueProxy {
public:
_ValueProxy(This* owner, const Type* data, inner_iterator i) :
_owner(owner), _data(data), _pos(i)
{
// Do nothing
}
template <class U>
_ValueProxy& operator=(const U& other)
{
if (!_owner) {
TF_CODING_ERROR("Assignment to invalid map proxy");
} else {
_owner->_Set(_data, _pos, other);
}
return *this;
}
operator mapped_type() const
{
return Get();
}
// Required for _PairProxy::operator value_type().
mapped_type Get() const
{
if (!_owner) {
TF_CODING_ERROR("Read from invalid map proxy");
return mapped_type();
}
return _owner->_Get(_data, _pos);
}
private:
This* _owner;
const Type* _data;
inner_iterator _pos;
};
class _PairProxy {
public:
explicit _PairProxy(This* owner, const Type* data, inner_iterator i) :
first(i->first), second(_ValueProxy(owner, data, i)) { }
const key_type first;
_ValueProxy second;
operator value_type() const
{
// Note that we cannot simply use 'second' or we'll use the
// mapped_type c'tor instead of the _ValueProxy implicit
// conversion if one is available. If mapped_type is VtValue
// then we'll type erase _ValueProxy instead of just getting
// the VtValue out of the _ValueProxy.
return value_type(first, second.Get());
}
};
class Traits {
public:
static _PairProxy Dereference(This* owner,
const Type* data, inner_iterator i)
{
if (!owner) {
TF_FATAL_ERROR("Dereferenced an invalid map proxy iterator");
}
return _PairProxy(owner, data, i);
}
static const value_type& Dereference(const This* owner,
const Type* data,
const_inner_iterator i)
{
if (!owner) {
TF_FATAL_ERROR("Dereferenced an invalid map proxy iterator");
}
return owner->_Get(data, i);
}
};
template <class Owner, class I, class R>
class _Iterator :
public boost::iterator_facade<_Iterator<Owner, I, R>, R,
std::bidirectional_iterator_tag, R> {
public:
_Iterator() :
_owner(NULL), _data(NULL) { }
_Iterator(Owner owner, const Type* data, I i) :
_owner(owner), _data(data), _pos(i)
{
// Do nothing
}
template <class Owner2, class I2, class R2>
_Iterator(const _Iterator<Owner2, I2, R2>& other) :
_owner(other._owner), _data(other._data), _pos(other._pos)
{
// Do nothing
}
const I& base() const
{
return _pos;
}
private:
R dereference() const
{
return Traits::Dereference(_owner, _data, _pos);
}
template <class Owner2, class I2, class R2>
bool equal(const _Iterator<Owner2, I2, R2>& other) const
{
if (_owner == other._owner && _pos == other._pos) {
return true;
}
else {
// All iterators at the end compare equal.
return atEnd() && other.atEnd();
}
}
void increment() {
++_pos;
}
void decrement() {
--_pos;
}
bool atEnd() const {
// We consider an iterator with no owner to be at the end.
return !_owner || _pos == _owner->_ConstData()->end();
}
private:
Owner _owner;
const Type* _data;
I _pos;
friend class boost::iterator_core_access;
template <class Owner2, class I2, class R2> friend class _Iterator;
};
public:
typedef _ValueProxy reference;
typedef const value_type& const_reference;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef _Iterator<This*, inner_iterator, _PairProxy> iterator;
typedef _Iterator<const This*, const_inner_iterator,
const value_type&> const_iterator;
typedef boost::reverse_iterator<iterator> reverse_iterator;
typedef boost::reverse_iterator<const_iterator> const_reverse_iterator;
explicit SdfMapEditProxy(const SdfSpecHandle& owner, const TfToken& field) :
_editor(Sdf_CreateMapEditor<T>(owner, field))
{
// Do nothing
}
SdfMapEditProxy()
{
// Do nothing
}
This& operator=(const This& other)
{
if (other._Validate()) {
_Copy(*other._ConstData());
}
return *this;
}
template <class U, class UVP>
This& operator=(const SdfMapEditProxy<U, UVP>& other)
{
if (other._Validate()) {
_Copy(Type(other._ConstData()->begin(), other._ConstData()->end()));
}
return *this;
}
This& operator=(const Type& data)
{
_Copy(data);
return *this;
}
/// Returns a copy of the value.
operator Type() const
{
return _Validate() ? *_ConstData() : Type();
}
iterator begin()
{
return _Validate() ? iterator(this, _Data(), _Data()->begin()) :
iterator();
}
iterator end()
{
return _Validate() ? iterator(this, _Data(), _Data()->end()) :
iterator();
}
const_iterator begin() const
{
return _Validate() ?
const_iterator(this, _ConstData(), _ConstData()->begin()) :
const_iterator();
}
const_iterator end() const
{
return _Validate() ?
const_iterator(this, _ConstData(), _ConstData()->end()) :
const_iterator();
}
reverse_iterator rbegin()
{
return reverse_iterator(end());
}
reverse_iterator rend()
{
return reverse_iterator(begin());
}
const_reverse_iterator rbegin() const
{
return const_reverse_iterator(end());
}
const_reverse_iterator rend() const
{
return const_reverse_iterator(begin());
}
size_type size() const
{
return _Validate() ? _ConstData()->size() : 0;
}
size_type max_size() const
{
return _Validate() ? _ConstData()->max_size() : 0;
}
bool empty() const
{
return _Validate() ? _ConstData()->empty() : true;
}
std::pair<iterator, bool> insert(const value_type& value)
{
return _Insert(value);
}
iterator insert(iterator pos, const value_type& value)
{
return _Insert(value).first;
}
template <class InputIterator>
void insert(InputIterator first, InputIterator last)
{
if (_Validate()) {
SdfChangeBlock block;
for (; first != last; ++first) {
const value_type& v =
ValuePolicy::CanonicalizePair(_Owner(), *first);
if (_ValidateInsert(v)) {
_editor->Insert(v);
}
}
}
}
void erase(iterator pos)
{
if (_Validate() && _ValidateErase(pos->first)) {
_Erase(pos->first);
}
}
size_type erase(const key_type& key)
{
if (_Validate()) {
const key_type& k = ValuePolicy::CanonicalizeKey(_Owner(), key);
if (_ValidateErase(k)) {
return _editor->Erase(k) ? 1 : 0;
}
}
return 0;
}
void erase(iterator first, iterator last)
{
if (_Validate()) {
SdfChangeBlock block;
while (first != last) {
const key_type& key = first->first;
++first;
if (_ValidateErase(key)) {
_editor->Erase(key);
}
}
}
}
void clear()
{
_Copy(Type());
}
iterator find(const key_type& key)
{
return
_Validate() ?
iterator(this, _Data(),
_Data()->find(ValuePolicy::CanonicalizeKey(_Owner(), key))) :
iterator();
}
const_iterator find(const key_type& key) const
{
return
_Validate() ?
const_iterator(this, _ConstData(),
_ConstData()->find(
ValuePolicy::CanonicalizeKey(_Owner(), key))) :
const_iterator();
}
size_type count(const key_type& key) const
{
return
_Validate() ?
_ConstData()->count(
ValuePolicy::CanonicalizeKey(_Owner(), key)) :
0;
}
iterator lower_bound(const key_type& key)
{
return
_Validate() ?
iterator(this, _Data(),
_Data()->lower_bound(
ValuePolicy::CanonicalizeKey(_Owner(), key))) :
iterator();
}
const_iterator lower_bound(const key_type& key) const
{
return
_Validate() ?
const_iterator(this, _ConstData(),
_ConstData()->lower_bound(
ValuePolicy::CanonicalizeKey(_Owner(), key))) :
const_iterator();
}
iterator upper_bound(const key_type& key)
{
return
_Validate() ?
iterator(this, _Data(),
_Data()->upper_bound(
ValuePolicy::CanonicalizeKey(_Owner(), key))) :
iterator();
}
const_iterator upper_bound(const key_type& key) const
{
return
_Validate() ?
const_iterator(this, _ConstData(),
_ConstData()->upper_bound(
ValuePolicy::CanonicalizeKey(_Owner(), key))) :
const_iterator();
}
std::pair<iterator, iterator> equal_range(const key_type& key)
{
if (_Validate()) {
std::pair<inner_iterator, inner_iterator> result =
_Data()->equal_range(
ValuePolicy::CanonicalizeKey(_Owner(), key));
return std::make_pair(iterator(this, _Data(), result.first),
iterator(this, _Data(), result.second));
}
else {
return std::make_pair(iterator(), iterator());
}
}
std::pair<const_iterator,const_iterator>
equal_range(const key_type& key) const
{
if (_Validate()) {
std::pair<const_inner_iterator, const_inner_iterator> result =
_ConstData()->equal_range(
ValuePolicy::CanonicalizeKey(_Owner(), key));
return std::make_pair(
const_iterator(this, _ConstData(), result.first),
const_iterator(this, _ConstData(), result.second));
}
else {
return std::make_pair(const_iterator(), const_iterator());
}
}
reference operator[](const key_type& key)
{
auto iter = _Insert(value_type(key, mapped_type())).first;
bool failed = iter == iterator();
return reference(failed ? nullptr : this,
failed ? nullptr : _Data(),
iter.base());
}
bool operator==(const Type& other) const
{
return _Validate() ? _CompareEqual(other) : false;
}
bool operator<(const Type& other) const
{
return _Validate() ? _Compare(other) < 0 : false;
}
bool operator>(const Type& other) const
{
return _Validate() ? _Compare(other) > 0 : false;
}
template <class U, class UVP>
bool operator==(const SdfMapEditProxy<U, UVP>& other) const
{
return _Validate() && other._Validate() ?
_CompareEqual(*other._ConstData()) : false;
}
template <class U, class UVP>
bool operator!=(const SdfMapEditProxy<U, UVP>& other) const
{
return !(*this == other);
}
template <class U, class UVP>
bool operator<(const SdfMapEditProxy<U, UVP>& other) const
{
return _Validate() && other._Validate() ?
_Compare(*other._ConstData()) < 0 : false;
}
template <class U, class UVP>
bool operator<=(const SdfMapEditProxy<U, UVP>& other) const
{
return _Validate() && other._Validate() ?
_Compare(*other._ConstData()) <= 0 : false;
}
template <class U, class UVP>
bool operator>(const SdfMapEditProxy<U, UVP>& other) const
{
return !(*this <= other);
}
template <class U, class UVP>
bool operator>=(const SdfMapEditProxy<U, UVP>& other) const
{
return !(*this < other);
}
/// Returns true if the value is expired. Note this a default-constructed
/// MapEditProxy is considered to be invalid but *not* expired.
bool IsExpired() const
{
return _editor && _editor->IsExpired();
}
/// Explicit bool conversion operator. Returns \c true if the value is
/// valid, \c false otherwise.
explicit operator bool() const
{
return _ConstData() && !IsExpired();
}
private:
bool _Validate()
{
if (_ConstData() && !IsExpired()) {
return true;
}
else {
TF_CODING_ERROR("Editing an invalid map proxy");
return false;
}
}
bool _Validate() const
{
if (_ConstData() && !IsExpired()) {
return true;
}
else {
TF_CODING_ERROR("Accessing an invalid map proxy");
return false;
}
}
Type* _Data()
{
return _editor ? _editor->GetData() : NULL;
}
const Type* _ConstData() const
{
return _editor ? _editor->GetData() : NULL;
}
SdfSpecHandle _Owner() const
{
return _editor ? _editor->GetOwner() : SdfSpecHandle();
}
std::string _Location() const
{
return _editor ? _editor->GetLocation() : std::string();
}
bool _CompareEqual(const Type& other) const
{
if (_ConstData()->size() < other.size()) {
return false;
}
if (_ConstData()->size() > other.size()) {
return false;
}
// Same size -- find the first mismatch.
const Type& x = ValuePolicy::CanonicalizeType(_Owner(), other);
std::pair<const_inner_iterator, const_inner_iterator> result =
std::mismatch(_ConstData()->begin(), _ConstData()->end(),
x.begin());
return result.first == _ConstData()->end();
}
int _Compare(const Type& other) const
{
if (_ConstData()->size() < other.size()) {
return -1;
}
if (_ConstData()->size() > other.size()) {
return 1;
}
// Same size -- find the first mismatch.
const Type& x = ValuePolicy::CanonicalizeType(_Owner(), other);
std::pair<const_inner_iterator, const_inner_iterator> result =
std::mismatch(_ConstData()->begin(), _ConstData()->end(),
x.begin());
if (*result.first < *result.second) {
return -1;
}
else if (*result.first > *result.second) {
return 1;
}
else {
return 0;
}
}
template <class D>
bool _CompareEqual(const D& other) const
{
// This is expensive but yields reliable results.
return _CompareEqual(Type(other.begin(), other.end()));
}
template <class D>
int _Compare(const D& other) const
{
// This is expensive but yields reliable ordering.
return _Compare(Type(other.begin(), other.end()));
}
mapped_type _Get(const Type* data, const inner_iterator& i)
{
if (_Validate()) {
if (data == _ConstData()) {
return i->second;
}
else {
// Data has changed since we created the iterator.
// Look up same key in new data.
return _ConstData()->find(i->first)->second;
}
}
return mapped_type();
}
const value_type& _Get(const Type* data,
const const_inner_iterator& i) const
{
// If data has changed since we created the iterator then look up
// the same key in the new data.
return (data == _ConstData()) ? *i : *_ConstData()->find(i->first);
}
void _Copy(const Type& other)
{
if (_Validate()) {
// Canonicalize the given map before copying it into ourselves.
// If multiple keys in the given map would conflict with each
// other in the canonicalized map, we consider this an error.
// This is primarily to avoid confusing the consumer, who would
// otherwise observe a key/value pair to be missing entirely.
Type canonicalOther;
TF_FOR_ALL(it, other) {
const value_type canonicalValue =
ValuePolicy::CanonicalizePair(_Owner(), *it);
if (!canonicalOther.insert(canonicalValue).second) {
TF_CODING_ERROR("Can't copy to %s: Duplicate key '%s' "
"exists in map.",
_Location().c_str(),
TfStringify(canonicalValue.first).c_str());
return;
}
}
if (_ValidateCopy(canonicalOther)) {
_editor->Copy(canonicalOther);
}
}
}
bool _ValidateCopy(const Type& other)
{
SdfSpecHandle owner = _Owner();
if (owner && !owner->PermissionToEdit()) {
TF_CODING_ERROR("Can't copy to %s: Permission denied.",
_Location().c_str());
return false;
}
if (other.empty()) {
return true;
}
TF_FOR_ALL(it, other) {
if (!_ValidateInsert(*it)) {
return false;
}
}
return true;
}
template <class U>
void _Set(const Type* data, const inner_iterator& i, const U& value)
{
if (_Validate()) {
const mapped_type& x =
ValuePolicy::CanonicalizeValue(_Owner(), value);
if (_ValidateSet(i->first, x)) {
_editor->Set(i->first, x);
}
}
}
bool _ValidateSet(const key_type& key, const mapped_type& value)
{
SdfSpecHandle owner = _Owner();
if (owner && !owner->PermissionToEdit()) {
TF_CODING_ERROR("Can't set value in %s: Permission denied.",
_Location().c_str());
return false;
}
if (SdfAllowed allowed = _editor->IsValidValue(value)) {
// Do nothing
}
else {
TF_CODING_ERROR("Can't set value in %s: %s",
_Location().c_str(),
allowed.GetWhyNot().c_str());
return false;
}
return true;
}
std::pair<iterator, bool> _Insert(const value_type& value)
{
if (_Validate()) {
const value_type& v = ValuePolicy::CanonicalizePair(_Owner(), value);
if (_ValidateInsert(v)) {
std::pair<inner_iterator, bool> status = _editor->Insert(v);
return std::make_pair(iterator(this, _Data(), status.first),
status.second);
}
else {
return std::make_pair(iterator(), false);
}
}
return std::make_pair(iterator(), false);
}
bool _ValidateInsert(const value_type& value)
{
SdfSpecHandle owner = _Owner();
if (owner && !owner->PermissionToEdit()) {
TF_CODING_ERROR("Can't insert value in %s: Permission denied.",
_Location().c_str());
return false;
}
if (SdfAllowed allowed = _editor->IsValidKey(value.first)) {
// Do nothing
}
else {
TF_CODING_ERROR("Can't insert key in %s: %s",
_Location().c_str(),
allowed.GetWhyNot().c_str());
return false;
}
if (SdfAllowed allowed = _editor->IsValidValue(value.second)) {
// Do nothing
}
else {
TF_CODING_ERROR("Can't insert value in %s: %s",
_Location().c_str(),
allowed.GetWhyNot().c_str());
return false;
}
return true;
}
void _Erase(const key_type& key)
{
if (_Validate() && _ValidateErase(key)) {
_editor->Erase(key);
}
}
bool _ValidateErase(const key_type& key)
{
SdfSpecHandle owner = _Owner();
if (owner && !owner->PermissionToEdit()) {
TF_CODING_ERROR("Can't erase value from %s: Permission denied.",
_Location().c_str());
return false;
}
return true;
}
private:
template <class ProxyT> friend class SdfPyWrapMapEditProxy;
boost::shared_ptr<Sdf_MapEditor<T> > _editor;
};
// Cannot get from a VtValue except as the correct type.
template <class T, class _ValuePolicy>
struct Vt_DefaultValueFactory<SdfMapEditProxy<T, _ValuePolicy> > {
static Vt_DefaultValueHolder Invoke() = delete;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_MAP_EDIT_PROXY_H
+97
View File
@@ -0,0 +1,97 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_MAP_EDITOR_H
#define PXR_USD_SDF_MAP_EDITOR_H
#include "pxr/pxr.h"
#include "pxr/usd/sdf/allowed.h"
#include "pxr/usd/sdf/spec.h"
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <string>
#include <utility>
PXR_NAMESPACE_OPEN_SCOPE
class TfToken;
/// \class Sdf_MapEditor
///
/// Interface for private implementations used by SdfMapEditProxy.
///
template <class MapType>
class Sdf_MapEditor {
public:
typedef typename MapType::key_type key_type;
typedef typename MapType::mapped_type mapped_type;
typedef typename MapType::value_type value_type;
typedef typename MapType::iterator iterator;
virtual ~Sdf_MapEditor();
/// Returns a string describing the location of the map being edited.
/// This is used for debugging and error messages.
virtual std::string GetLocation() const = 0;
/// Returns owner of the map being edited.
virtual SdfSpecHandle GetOwner() const = 0;
/// Returns true if the map being edited is expired, false otherwise.
virtual bool IsExpired() const = 0;
/// Returns const pointer to map being edited.
virtual const MapType* GetData() const = 0;
/// Returns non-const pointer to map being edited.
/// All edits to the map should be done using the editing functions below.
/// This function is primarily here for convenience. Ideally, only the
/// const version of this function would exist.
virtual MapType* GetData() = 0;
/// \name Editing Operations
/// @{
virtual void Copy(const MapType& other) = 0;
virtual void Set(const key_type& key, const mapped_type& other) = 0;
virtual std::pair<iterator, bool> Insert(const value_type& value) = 0;
virtual bool Erase(const key_type& key) = 0;
virtual SdfAllowed IsValidKey(const key_type& key) const = 0;
virtual SdfAllowed IsValidValue(const mapped_type& value) const = 0;
/// @}
protected:
Sdf_MapEditor();
};
template <class T>
boost::shared_ptr<Sdf_MapEditor<T> >
Sdf_CreateMapEditor(const SdfSpecHandle& owner, const TfToken& field);
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_MAP_EDITOR_H
+301
View File
@@ -0,0 +1,301 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_NAMESPACE_EDIT_H
#define PXR_USD_SDF_NAMESPACE_EDIT_H
/// \file sdf/namespaceEdit.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/usd/sdf/path.h"
#include <boost/operators.hpp>
#include <functional>
#include <iosfwd>
#include <string>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
/// \class SdfNamespaceEdit
///
/// A single namespace edit. It supports renaming, reparenting, reparenting
/// with a rename, reordering, and removal.
///
struct SdfNamespaceEdit :
boost::equality_comparable<SdfNamespaceEdit> {
public:
typedef SdfNamespaceEdit This;
typedef SdfPath Path;
typedef int Index;
/// Special index that means at the end.
static const Index AtEnd = -1;
/// Special index that means don't move. It's only meaningful when
/// renaming. In other cases implementations may assume \c AtEnd.
static const Index Same = -2;
/// The default edit maps the empty path to the empty path.
SdfNamespaceEdit() : index(AtEnd) { }
/// The fully general edit.
SdfNamespaceEdit(const Path& currentPath_, const Path& newPath_,
Index index_ = AtEnd) :
currentPath(currentPath_), newPath(newPath_), index(index_) { }
/// Returns a namespace edit that removes the object at \p currentPath.
static This Remove(const Path& currentPath)
{
return This(currentPath, Path::EmptyPath());
}
/// Returns a namespace edit that renames the prim or property at
/// \p currentPath to \p name
static This Rename(const Path& currentPath, const TfToken& name)
{
return This(currentPath, currentPath.ReplaceName(name), Same);
}
/// Returns a namespace edit to reorder the prim or property at
/// \p currentPath to index \p index.
static This Reorder(const Path& currentPath, Index index)
{
return This(currentPath, currentPath, index);
}
/// Returns a namespace edit to reparent the prim or property at
/// \p currentPath to be under \p newParentPath at index \p index.
static This Reparent(const Path& currentPath,
const Path& newParentPath,
Index index)
{
return This(currentPath,
currentPath.ReplacePrefix(currentPath.GetParentPath(),
newParentPath),
index);
}
/// Returns a namespace edit to reparent the prim or property at
/// \p currentPath to be under \p newParentPath at index \p index
/// with the name \p name.
static This ReparentAndRename(const Path& currentPath,
const Path& newParentPath,
const TfToken& name,
Index index)
{
return This(currentPath,
currentPath.ReplacePrefix(currentPath.GetParentPath(),
newParentPath).
ReplaceName(name),
index);
}
SDF_API bool operator==(const This& rhs) const;
public:
Path currentPath; ///< Path of the object when this edit starts.
Path newPath; ///< Path of the object when this edit ends.
Index index; ///< Index for prim insertion.
};
/// A sequence of \c SdfNamespaceEdit.
typedef std::vector<SdfNamespaceEdit> SdfNamespaceEditVector;
SDF_API std::ostream& operator<<(std::ostream&, const SdfNamespaceEdit&);
SDF_API std::ostream& operator<<(std::ostream&, const SdfNamespaceEditVector&);
/// \struct SdfNamespaceEditDetail
///
/// Detailed information about a namespace edit.
///
struct SdfNamespaceEditDetail :
boost::equality_comparable<SdfNamespaceEditDetail> {
public:
/// Validity of an edit.
enum Result {
Error, ///< Edit will fail.
Unbatched, ///< Edit will succeed but not batched.
Okay, ///< Edit will succeed as a batch.
};
SDF_API SdfNamespaceEditDetail();
SDF_API SdfNamespaceEditDetail(Result, const SdfNamespaceEdit& edit,
const std::string& reason);
SDF_API bool operator==(const SdfNamespaceEditDetail& rhs) const;
public:
Result result; ///< Validity.
SdfNamespaceEdit edit; ///< The edit.
std::string reason; ///< The reason the edit will not succeed cleanly.
};
/// A sequence of \c SdfNamespaceEditDetail.
typedef std::vector<SdfNamespaceEditDetail> SdfNamespaceEditDetailVector;
SDF_API std::ostream& operator<<(std::ostream&, const SdfNamespaceEditDetail&);
SDF_API std::ostream& operator<<(std::ostream&, const SdfNamespaceEditDetailVector&);
/// Combine two results, yielding Error over Unbatched over Okay.
inline
SdfNamespaceEditDetail::Result
CombineResult(
SdfNamespaceEditDetail::Result lhs,
SdfNamespaceEditDetail::Result rhs)
{
return lhs < rhs ? lhs : rhs;
}
/// Combine a result with Error, yielding Error over Unbatched over Okay.
inline
SdfNamespaceEditDetail::Result
CombineError(SdfNamespaceEditDetail::Result)
{
return SdfNamespaceEditDetail::Error;
}
/// Combine a result with Unbatched, yielding Error over Unbatched over Okay.
inline
SdfNamespaceEditDetail::Result
CombineUnbatched(SdfNamespaceEditDetail::Result other)
{
return CombineResult(other, SdfNamespaceEditDetail::Unbatched);
}
/// \class SdfBatchNamespaceEdit
///
/// A description of an arbitrarily complex namespace edit.
///
/// A \c SdfBatchNamespaceEdit object describes zero or more namespace edits.
/// Various types providing a namespace will allow the edits to be applied
/// in a single operation and also allow testing if this will work.
///
/// Clients are encouraged to group several edits into one object because
/// that may allow more efficient processing of the edits. If, for example,
/// you need to reparent several prims it may be faster to add all of the
/// reparents to a single \c SdfBatchNamespaceEdit and apply them at once
/// than to apply each separately.
///
/// Objects that allow applying edits are free to apply the edits in any way
/// and any order they see fit but they should guarantee that the resulting
/// namespace will be as if each edit was applied one at a time in the order
/// they were added.
///
/// Note that the above rule permits skipping edits that have no effect or
/// generate a non-final state. For example, if renaming A to B then to C
/// we could just rename A to C. This means notices may be elided. However,
/// implementations must not elide notices that contain information about any
/// edit that clients must be able to know but otherwise cannot determine.
///
class SdfBatchNamespaceEdit {
public:
/// Create an empty sequence of edits.
SDF_API SdfBatchNamespaceEdit();
SDF_API SdfBatchNamespaceEdit(const SdfBatchNamespaceEdit&);
SDF_API SdfBatchNamespaceEdit(const SdfNamespaceEditVector&);
SDF_API ~SdfBatchNamespaceEdit();
SDF_API SdfBatchNamespaceEdit& operator=(const SdfBatchNamespaceEdit&);
/// Add a namespace edit.
void Add(const SdfNamespaceEdit& edit)
{
_edits.push_back(edit);
}
/// Add a namespace edit.
void Add(const SdfNamespaceEdit::Path& currentPath,
const SdfNamespaceEdit::Path& newPath,
SdfNamespaceEdit::Index index = SdfNamespaceEdit::AtEnd)
{
Add(SdfNamespaceEdit(currentPath, newPath, index));
}
/// Returns the edits.
const SdfNamespaceEditVector& GetEdits() const
{
return _edits;
}
/// Functor that returns \c true iff an object exists at the given path.
typedef std::function<bool(const SdfPath&)> HasObjectAtPath;
/// Functor that returns \c true iff the namespace edit will succeed.
/// If not it returns \c false and sets the string argument.
typedef std::function<bool(const SdfNamespaceEdit&,std::string*)> CanEdit;
/// Validate the edits and generate a possibly more efficient edit
/// sequence. Edits are treated as if they were performed one at time
/// in sequence, therefore each edit occurs in the namespace resulting
/// from all previous edits.
///
/// Editing the descendants of the object in each edit is implied. If
/// an object is removed then the new path will be empty. If an object
/// is removed after being otherwise edited, the other edits will be
/// processed and included in \p processedEdits followed by the removal.
/// This allows clients to fixup references to point to the object's
/// final location prior to removal.
///
/// This function needs help to determine if edits are allowed. The
/// callbacks provide that help. \p hasObjectAtPath returns \c true
/// iff there's an object at the given path. This path will be in the
/// original namespace not any intermediate or final namespace.
/// \p canEdit returns \c true iff the object at the current path can
/// be namespace edited to the new path, ignoring whether an object
/// already exists at the new path. Both paths are in the original
/// namespace. If it returns \c false it should set the string to the
/// reason why the edit isn't allowed. It should not write either path
/// to the string.
///
/// If \p hasObjectAtPath is invalid then this assumes objects exist
/// where they should and don't exist where they shouldn't. Use this
/// with care. If \p canEdit in invalid then it's assumed all edits
/// are valid.
///
/// If \p fixBackpointers is \c true then target/connection paths are
/// expected to be in the intermediate namespace resulting from all
/// previous edits. If \c false and any current or new path contains a
/// target or connection path that has been edited then this will
/// generate an error.
///
/// This method returns \c true if the edits are allowed and sets
/// \p processedEdits to a new edit sequence at least as efficient as
/// the input sequence. If not allowed it returns \c false and appends
/// reasons why not to \p details.
SDF_API
bool Process(SdfNamespaceEditVector* processedEdits,
const HasObjectAtPath& hasObjectAtPath,
const CanEdit& canEdit,
SdfNamespaceEditDetailVector* details = NULL,
bool fixBackpointers = true) const;
private:
SdfNamespaceEditVector _edits;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_NAMESPACE_EDIT_H
+237
View File
@@ -0,0 +1,237 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_NOTICE_H
#define PXR_USD_SDF_NOTICE_H
/// \file sdf/notice.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/usd/sdf/changeList.h"
#include "pxr/usd/sdf/declareHandles.h"
#include "pxr/usd/sdf/path.h"
#include "pxr/base/tf/notice.h"
PXR_NAMESPACE_OPEN_SCOPE
SDF_DECLARE_HANDLES(SdfLayer);
/// \class SdfNotice
///
/// Wrapper class for Sdf notices.
///
class SdfNotice {
public:
/// \class Base
///
/// Base notification class for scene. Only useful for type hierarchy
/// purposes.
///
class Base : public TfNotice {
public:
SDF_API ~Base();
};
/// \class BaseLayersDidChange
///
/// Base class for LayersDidChange and LayersDidChangeSentPerLayer.
///
class BaseLayersDidChange {
public:
BaseLayersDidChange(const SdfLayerChangeListVec &changeVec,
size_t serialNumber)
: _vec(&changeVec)
, _serialNumber(serialNumber)
{}
using const_iterator = SdfLayerChangeListVec::const_iterator;
using iterator = const_iterator;
/// A list of layers changed.
SDF_API
SdfLayerHandleVector GetLayers() const;
/// A list of layers and the changes that occurred to them.
const SdfLayerChangeListVec &GetChangeListVec() const { return *_vec; }
const_iterator begin() const { return _vec->begin(); }
const_iterator cbegin() const { return _vec->cbegin(); }
const_iterator end() const { return _vec->end(); }
const_iterator cend() const { return _vec->cend(); }
const_iterator find(SdfLayerHandle const &layer) const {
return std::find_if(
begin(), end(),
[&layer](SdfLayerChangeListVec::value_type const &p) {
return p.first == layer;
});
}
bool count(SdfLayerHandle const &layer) const {
return find(layer) != end();
}
/// The serial number for this round of change processing.
size_t GetSerialNumber() const { return _serialNumber; }
private:
const SdfLayerChangeListVec *_vec;
const size_t _serialNumber;
};
/// \class LayersDidChangeSentPerLayer
///
/// Notice sent per-layer indicating all layers whose contents have changed
/// within a single round of change processing. If more than one layer
/// changes in a single round of change processing, we send this notice once
/// per layer with the same changeVec and serialNumber. This is so clients
/// can listen to notices from only the set of layers they care about rather
/// than listening to the global LayersDidChange notice.
///
class LayersDidChangeSentPerLayer
: public Base, public BaseLayersDidChange {
public:
LayersDidChangeSentPerLayer(const SdfLayerChangeListVec &changeVec,
size_t serialNumber)
: BaseLayersDidChange(changeVec, serialNumber) {}
SDF_API virtual ~LayersDidChangeSentPerLayer();
};
/// \class LayersDidChange
///
/// Global notice sent to indicate that layer contents have changed.
///
class LayersDidChange
: public Base, public BaseLayersDidChange {
public:
LayersDidChange(const SdfLayerChangeListVec &changeVec,
size_t serialNumber)
: BaseLayersDidChange(changeVec, serialNumber) {}
SDF_API virtual ~LayersDidChange();
};
/// \class LayerInfoDidChange
///
/// Sent when the (scene spec) info of a layer have changed.
///
class LayerInfoDidChange : public Base {
public:
LayerInfoDidChange( const TfToken &key ) :
_key(key) {}
SDF_API ~LayerInfoDidChange();
/// Return the key affected.
const TfToken & key() const { return _key; }
private:
TfToken _key;
};
/// \class LayerIdentifierDidChange
///
/// Sent when the identifier of a layer has changed.
///
class LayerIdentifierDidChange : public Base {
public:
SDF_API
LayerIdentifierDidChange(const std::string& oldIdentifier,
const std::string& newIdentifier);
SDF_API
~LayerIdentifierDidChange();
/// Returns the old identifier for the layer.
const std::string& GetOldIdentifier() const { return _oldId; }
/// Returns the new identifier for the layer.
const std::string& GetNewIdentifier() const { return _newId; }
private:
std::string _oldId;
std::string _newId;
};
/// \class LayerDidReplaceContent
///
/// Sent after a menv layer has been loaded from a file.
///
class LayerDidReplaceContent : public Base {
public:
SDF_API ~LayerDidReplaceContent();
};
/// \class LayerDidReloadContent
/// Sent after a layer is reloaded.
class LayerDidReloadContent : public LayerDidReplaceContent {
public:
SDF_API virtual ~LayerDidReloadContent();
};
/// \class LayerDidSaveLayerToFile
///
/// Sent after a layer is saved to file.
///
class LayerDidSaveLayerToFile : public Base {
public:
SDF_API ~LayerDidSaveLayerToFile();
};
/// \class LayerDirtinessChanged
///
/// Similar behavior to LayersDidChange, but only gets sent if a change
/// in the dirty status of a layer occurs.
///
class LayerDirtinessChanged : public Base {
public:
SDF_API ~LayerDirtinessChanged();
};
/// \class LayerMutenessChanged
///
/// Sent after a layer has been added or removed from the set of
/// muted layers. Note this does not necessarily mean the specified
/// layer is currently loaded.
///
class LayerMutenessChanged : public Base {
public:
LayerMutenessChanged(const std::string& layerPath, bool wasMuted)
: _layerPath(layerPath)
, _wasMuted(wasMuted)
{ }
SDF_API ~LayerMutenessChanged();
/// Returns the path of the layer that was muted or unmuted.
const std::string& GetLayerPath() const { return _layerPath; }
/// Returns true if the layer was muted, false if unmuted.
bool WasMuted() const { return _wasMuted; }
private:
std::string _layerPath;
bool _wasMuted;
};
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_NOTICE_H
File diff suppressed because it is too large. Load diff
+87
View File
@@ -0,0 +1,87 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
/* A Bison parser, made by GNU Bison 2.4.1. */
/* Skeleton interface for Bison's Yacc-like parsers in C
Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006
Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* As a special exception, you may create a larger work that contains
part or all of the Bison parser skeleton and distribute that work
under terms of your choice, so long as that work isn't itself a
parser generator using the skeleton or a modified version thereof
as a parser skeleton. Alternatively, if you modify or redistribute
the parser skeleton itself, you may (at your option) remove this
special exception, which will cause the skeleton and the resulting
Bison output files to be licensed under the GNU General Public
License without this special exception.
This special exception was added by the Free Software Foundation in
version 2.2 of Bison. */
/* Tokens. */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
/* Put the tokens into the symbol table, so that GDB and other debuggers
know about them. */
enum yytokentype {
TOK_MAPPER = 258,
TOK_EXPRESSION = 259,
TOK_IDENTIFIER = 260,
TOK_NAMESPACED_IDENTIFIER = 261,
TOK_PRIM_NAME = 262,
TOK_VARIANT_NAME = 263,
TOK_DOTDOT = 264,
TOK_WHITESPACE = 265
};
#endif
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
typedef int YYSTYPE;
# define YYSTYPE_IS_TRIVIAL 1
# define yystype YYSTYPE /* obsolescent; will be withdrawn */
# define YYSTYPE_IS_DECLARED 1
#endif
+732
View File
@@ -0,0 +1,732 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_PATH_NODE_H
#define PXR_USD_SDF_PATH_NODE_H
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/base/tf/token.h"
#include "pxr/base/tf/mallocTag.h"
#include <boost/noncopyable.hpp>
#include <boost/intrusive_ptr.hpp>
#include <tbb/atomic.h>
PXR_NAMESPACE_OPEN_SCOPE
// Sdf_PathNode
//
// This class is the root of the path node hierarchy. It used to use ordinary
// C++ polymorphism, but it no longer does. This is primarily a space
// optimization: the set of node types is fixed, we already have an enum 'type'
// field, and we typically have lots (e.g. ~1e8) of these objects. Dropping the
// C++ polymorphism saves us the vtable pointer, and we can pack the '_nodeType'
// field in a much smaller space with other flags.
//
// We currently store PathNode objects in two prefix trees. The "prim like"
// path nodes (the root nodes '/' and '.', prim path nodes, and prim variant
// selection nodes are in one prefix tree, and the "property like" nodes are in
// another prefix tree (prim property nodes, target nodes, expression nodes,
// mapper arg nodes). We do this because there are far fewer unique property
// nodes (generally) than there are prim nodes. We allocate these in Sdf_Pools,
// so that the SdfPath class can store a handle to an element in each tree in 64
// bits total. (Sdf_Pool is designed so that we can refer to objects in memory
// using 32-bit indexes instead of 64-bit pointers). An SdfPath joins together
// these two elements to form a whole path. For example, the path
// '/Foo/Bar.attr' would store a prim-part handle to the '/Foo/Bar' node, and a
// property-part handle to 'attr'.
//
class Sdf_PathNode {
Sdf_PathNode(Sdf_PathNode const &) = delete;
Sdf_PathNode &operator=(Sdf_PathNode const &) = delete;
public:
// Node types identify what kind of path node a given instance is.
// There are restrictions on what type of children each node type
// can have,
enum NodeType {
/********************************************************/
/******************************* Prim portion nodes *****/
RootNode,
// Allowable child node types:
// PrimNode
// PrimPropertyNode (only for relative root)
// PrimVariantSelectionNode (only for relative root)
PrimNode,
// Allowable child node types:
// PrimNode
// PrimPropertyNode
// PrimVariantSelectionNode
PrimVariantSelectionNode,
// Allowable child node types:
// PrimNode
// PrimPropertyNode
// PrimVariantSelectionNode
// (for variants that contain variant sets)
/********************************************************/
/******************************* Property portion nodes */
PrimPropertyNode,
// Allowable child node types:
// TargetNode
// MapperNode
// ExpressionNode
TargetNode,
// Allowable child node types:
// RelationalAttributeNode (only if parent is PrimPropertyNode)
MapperNode,
// Allowable child node types:
// MapperArgNode
RelationalAttributeNode,
// Allowable child node types:
// TargetNode
// MapperNode
// ExpressionNode
MapperArgNode,
// Allowable child node types:
// <none>
ExpressionNode,
// Allowable child node types:
// <none>
NumNodeTypes ///< Internal sentinel value
};
static Sdf_PathPrimNodeHandle
FindOrCreatePrim(Sdf_PathNode const *parent, const TfToken &name);
static Sdf_PathPropNodeHandle
FindOrCreatePrimProperty(Sdf_PathNode const *parent, const TfToken &name);
static Sdf_PathPrimNodeHandle
FindOrCreatePrimVariantSelection(Sdf_PathNode const *parent,
const TfToken &variantSet,
const TfToken &variant);
static Sdf_PathPropNodeHandle
FindOrCreateTarget(Sdf_PathNode const *parent,
SdfPath const &targetPath);
static Sdf_PathPropNodeHandle
FindOrCreateRelationalAttribute(Sdf_PathNode const *parent,
const TfToken &name);
static Sdf_PathPropNodeHandle
FindOrCreateMapper(Sdf_PathNode const *parent, SdfPath const &targetPath);
static Sdf_PathPropNodeHandle
FindOrCreateMapperArg(Sdf_PathNode const *parent, const TfToken &name);
static Sdf_PathPropNodeHandle
FindOrCreateExpression(Sdf_PathNode const *parent);
static Sdf_PathNode const *GetAbsoluteRootNode();
static Sdf_PathNode const *GetRelativeRootNode();
NodeType GetNodeType() const { return NodeType(_nodeType); }
static std::pair<Sdf_PathNode const *, Sdf_PathNode const *>
RemoveCommonSuffix(Sdf_PathNode const *a,
Sdf_PathNode const *b,
bool stopAtRootPrim);
// This method returns a node pointer
Sdf_PathNode const *GetParentNode() const { return _parent.get(); }
size_t GetElementCount() const { return size_t(_elementCount); }
bool IsAbsolutePath() const { return _isAbsolute; }
bool IsAbsoluteRoot() const { return (_isAbsolute) & (!_elementCount); }
bool ContainsTargetPath() const { return _containsTargetPath; }
bool IsNamespaced() const {
return (_nodeType == PrimPropertyNode ||
_nodeType == RelationalAttributeNode) && _IsNamespacedImpl();
}
bool ContainsPrimVariantSelection() const {
return _containsPrimVariantSelection;
}
// For PrimNode, PrimPropertyNode, RelationalAttributeNode, and
// MapperArgNode this is the name (with no "dot" for
// properties/relational attributes/mapper args). For others, it
// is EmptyToken.
inline const TfToken &GetName() const;
// For TargetNode and MapperNode this is the target path.
// For others, it is InvalidPath.
inline const SdfPath &GetTargetPath() const;
typedef std::pair<TfToken, TfToken> VariantSelectionType;
inline const VariantSelectionType& GetVariantSelection() const;
// Returns the path element string (".name" for properties, "[path]" for
// targets, etc...)
inline TfToken GetElement() const;
// Append this element's text (same as GetElement()) to \p str.
void AppendText(std::string *str) const;
// Return the stringified path to this node as a TfToken lvalue.
SDF_API static const TfToken &
GetPathToken(Sdf_PathNode const *primPart, Sdf_PathNode const *propPart);
// Return the stringified path to this node as a TfToken rvalue.
SDF_API static TfToken
GetPathAsToken(Sdf_PathNode const *primPart, Sdf_PathNode const *propPart);
// Lexicographic ordering for Compare().
struct LessThan {
template <class T>
inline bool operator()(T const &a, T const &b) const {
return a < b;
}
};
// This operator only works properly when the rhs has the same parent
// as this node.
template <class Less>
inline bool Compare(const Sdf_PathNode &rhs) const;
// Return the current ref-count.
// Meant for diagnostic use.
unsigned int GetCurrentRefCount() const { return _refCount; }
protected:
Sdf_PathNode(Sdf_PathNode const *parent, NodeType nodeType)
: _parent(parent)
, _refCount(1)
, _elementCount(parent ? parent->_elementCount + 1 : 1)
, _nodeType(nodeType)
, _isAbsolute(parent && parent->IsAbsolutePath())
, _containsPrimVariantSelection(
nodeType == PrimVariantSelectionNode ||
(parent && parent->_containsPrimVariantSelection))
, _containsTargetPath(nodeType == TargetNode ||
nodeType == MapperNode ||
(parent && parent->_containsTargetPath))
, _hasToken(false)
{}
// This constructor is used only to create the two special root nodes.
explicit Sdf_PathNode(bool isAbsolute);
~Sdf_PathNode() {
if (_hasToken)
_RemovePathTokenFromTable();
}
// Helper to downcast and destroy the dynamic type of this object -- this is
// required since this class hierarchy doesn't use normal C++ polymorphism
// for space reasons.
inline void _Destroy() const;
// // Helper function for GetPathToken, which lazily creates its token
static TfToken _CreatePathToken(Sdf_PathNode const *primPart,
Sdf_PathNode const *propPart);
// Helper for dtor, removes this path node's token from the token table.
SDF_API void _RemovePathTokenFromTable() const;
struct _EqualElement {
template <class T>
inline bool operator()(T const &a, T const &b) const {
return a == b;
}
};
friend struct Sdf_PathNodePrivateAccess;
// Ref-counting ops manage _refCount.
friend void intrusive_ptr_add_ref(const Sdf_PathNode*);
friend void intrusive_ptr_release(const Sdf_PathNode*);
private:
// Downcast helper, just sugar to static_cast this to Derived const *.
template <class Derived>
Derived const *_Downcast() const {
return static_cast<Derived const *>(this);
}
// Helper to scan this node's name for the property namespace delimiter.
bool _IsNamespacedImpl() const;
// Helper to return a const lvalue variant selection.
VariantSelectionType const &_GetEmptyVariantSelection() const;
// Instance variables. PathNode's size is important to keep small. Please
// be mindful of that when making any changes here.
const Sdf_PathNodeConstRefPtr _parent;
mutable tbb::atomic<unsigned int> _refCount;
const short _elementCount;
const unsigned char _nodeType;
const bool _isAbsolute:1;
const bool _containsPrimVariantSelection:1;
const bool _containsTargetPath:1;
// This is racy -- we ensure that the token creation code carefully
// synchronizes so that if we read 'true' from this flag, it guarantees that
// there's a token for this path node in the token table. If we read
// 'false' it means there may or may not be, unless we're in the destructor,
// which must run exclusively, then reading 'false' guarantees there is no
// token in the table. We use this flag to do that optimization in the
// destructor so we can avoid looking in the table in the case where we
// haven't created a token.
mutable bool _hasToken:1;
};
class Sdf_PrimPartPathNode : public Sdf_PathNode {
public:
using Sdf_PathNode::Sdf_PathNode;
SDF_API void operator delete (void *p);
};
class Sdf_PropPartPathNode : public Sdf_PathNode {
public:
using Sdf_PathNode::Sdf_PathNode;
SDF_API void operator delete (void *p);
};
class Sdf_RootPathNode : public Sdf_PrimPartPathNode {
public:
typedef bool ComparisonType;
static const NodeType nodeType = Sdf_PathNode::RootNode;
static SDF_API Sdf_PathNode const *New(bool isAbsolute);
private:
// This constructor is used only to create the two special root nodes.
Sdf_RootPathNode(bool isAbsolute) : Sdf_PrimPartPathNode(isAbsolute) {}
ComparisonType _GetComparisonValue() const {
// Root nodes, there are only two, one absolute and one relative.
// (absolute < relative...)
return !IsAbsolutePath();
}
friend class Sdf_PathNode;
template <int nodeType, class Comp> friend struct Sdf_PathNodeCompare;
};
class Sdf_PrimPathNode : public Sdf_PrimPartPathNode {
public:
typedef TfToken ComparisonType;
static const NodeType nodeType = Sdf_PathNode::PrimNode;
private:
Sdf_PrimPathNode(Sdf_PathNode const *parent,
const TfToken &name)
: Sdf_PrimPartPathNode(parent, nodeType)
, _name(name) {}
SDF_API ~Sdf_PrimPathNode();
const ComparisonType &_GetComparisonValue() const { return _name; }
friend class Sdf_PathNode;
friend struct Sdf_PathNodePrivateAccess;
template <int nodeType, class Comp> friend struct Sdf_PathNodeCompare;
// Instance variables
TfToken _name;
};
class Sdf_PrimPropertyPathNode : public Sdf_PropPartPathNode {
public:
typedef TfToken ComparisonType;
static const NodeType nodeType = Sdf_PathNode::PrimPropertyNode;
private:
Sdf_PrimPropertyPathNode(Sdf_PathNode const *parent,
const TfToken &name)
: Sdf_PropPartPathNode(parent, nodeType)
, _name(name) {}
SDF_API ~Sdf_PrimPropertyPathNode();
friend class Sdf_PathNode;
friend struct Sdf_PathNodePrivateAccess;
template <int nodeType, class Comp> friend struct Sdf_PathNodeCompare;
const ComparisonType &_GetComparisonValue() const { return _name; }
// Instance variables
TfToken _name;
};
class Sdf_PrimVariantSelectionNode : public Sdf_PrimPartPathNode {
public:
typedef VariantSelectionType ComparisonType;
static const NodeType nodeType = Sdf_PathNode::PrimVariantSelectionNode;
const TfToken &_GetNameImpl() const;
void _AppendText(std::string *str) const;
private:
Sdf_PrimVariantSelectionNode(Sdf_PathNode const *parent,
const VariantSelectionType &variantSelection)
: Sdf_PrimPartPathNode(parent, nodeType)
, _variantSelection(new VariantSelectionType(variantSelection)) {}
SDF_API ~Sdf_PrimVariantSelectionNode();
const ComparisonType &_GetComparisonValue() const {
return *_variantSelection;
}
friend class Sdf_PathNode;
friend struct Sdf_PathNodePrivateAccess;
template <int nodeType, class Comp> friend struct Sdf_PathNodeCompare;
// Instance variables
std::unique_ptr<VariantSelectionType> _variantSelection;
};
class Sdf_TargetPathNode : public Sdf_PropPartPathNode {
public:
typedef SdfPath ComparisonType;
static const NodeType nodeType = Sdf_PathNode::TargetNode;
void _AppendText(std::string *str) const;
private:
Sdf_TargetPathNode(Sdf_PathNode const *parent,
const SdfPath &targetPath)
: Sdf_PropPartPathNode(parent, nodeType)
, _targetPath(targetPath) {}
SDF_API ~Sdf_TargetPathNode();
const ComparisonType& _GetComparisonValue() const { return _targetPath; }
friend class Sdf_PathNode;
friend struct Sdf_PathNodePrivateAccess;
template <int nodeType, class Comp> friend struct Sdf_PathNodeCompare;
// Instance variables
SdfPath _targetPath;
};
class Sdf_RelationalAttributePathNode : public Sdf_PropPartPathNode {
public:
typedef TfToken ComparisonType;
static const NodeType nodeType = Sdf_PathNode::RelationalAttributeNode;
private:
Sdf_RelationalAttributePathNode(Sdf_PathNode const *parent,
const TfToken &name)
: Sdf_PropPartPathNode(parent, nodeType)
, _name(name) {}
SDF_API ~Sdf_RelationalAttributePathNode();
const ComparisonType& _GetComparisonValue() const { return _name; }
friend class Sdf_PathNode;
friend struct Sdf_PathNodePrivateAccess;
template <int nodeType, class Comp> friend struct Sdf_PathNodeCompare;
// Instance variables
TfToken _name;
};
class Sdf_MapperPathNode : public Sdf_PropPartPathNode {
public:
typedef SdfPath ComparisonType;
static const NodeType nodeType = Sdf_PathNode::MapperNode;
void _AppendText(std::string *str) const;
private:
Sdf_MapperPathNode(Sdf_PathNode const *parent,
const SdfPath &targetPath)
: Sdf_PropPartPathNode(parent, nodeType)
, _targetPath(targetPath) {}
SDF_API ~Sdf_MapperPathNode();
const ComparisonType& _GetComparisonValue() const { return _targetPath; }
friend class Sdf_PathNode;
friend struct Sdf_PathNodePrivateAccess;
template <int nodeType, class Comp> friend struct Sdf_PathNodeCompare;
// Instance variables
SdfPath _targetPath;
};
class Sdf_MapperArgPathNode : public Sdf_PropPartPathNode {
public:
typedef TfToken ComparisonType;
static const NodeType nodeType = Sdf_PathNode::MapperArgNode;
void _AppendText(std::string *str) const;
private:
Sdf_MapperArgPathNode(Sdf_PathNode const *parent,
const TfToken &name)
: Sdf_PropPartPathNode(parent, nodeType)
, _name(name) {}
SDF_API ~Sdf_MapperArgPathNode();
const ComparisonType& _GetComparisonValue() const { return _name; }
friend class Sdf_PathNode;
friend struct Sdf_PathNodePrivateAccess;
template <int nodeType, class Comp> friend struct Sdf_PathNodeCompare;
// Instance variables
TfToken _name;
};
class Sdf_ExpressionPathNode : public Sdf_PropPartPathNode {
public:
typedef void *ComparisonType;
static const NodeType nodeType = Sdf_PathNode::ExpressionNode;
void _AppendText(std::string *str) const;
private:
Sdf_ExpressionPathNode(Sdf_PathNode const *parent)
: Sdf_PropPartPathNode(parent, nodeType) {}
SDF_API ~Sdf_ExpressionPathNode();
ComparisonType _GetComparisonValue() const { return nullptr; }
friend class Sdf_PathNode;
friend struct Sdf_PathNodePrivateAccess;
template <int nodeType, class Comp> friend struct Sdf_PathNodeCompare;
// Instance variables
// <none>
};
template <int nodeType>
struct Sdf_PathNodeTypeToType {
};
template <> struct Sdf_PathNodeTypeToType<Sdf_PathNode::PrimNode> {
typedef Sdf_PrimPathNode Type;
};
template <> struct Sdf_PathNodeTypeToType<Sdf_PathNode::PrimPropertyNode> {
typedef Sdf_PrimPropertyPathNode Type;
};
template <> struct Sdf_PathNodeTypeToType<Sdf_PathNode::RelationalAttributeNode> {
typedef Sdf_RelationalAttributePathNode Type;
};
template <> struct Sdf_PathNodeTypeToType<Sdf_PathNode::MapperArgNode> {
typedef Sdf_MapperArgPathNode Type;
};
template <> struct Sdf_PathNodeTypeToType<Sdf_PathNode::TargetNode> {
typedef Sdf_TargetPathNode Type;
};
template <> struct Sdf_PathNodeTypeToType<Sdf_PathNode::MapperNode> {
typedef Sdf_MapperPathNode Type;
};
template <> struct Sdf_PathNodeTypeToType<Sdf_PathNode::PrimVariantSelectionNode> {
typedef Sdf_PrimVariantSelectionNode Type;
};
template <> struct Sdf_PathNodeTypeToType<Sdf_PathNode::ExpressionNode> {
typedef Sdf_ExpressionPathNode Type;
};
template <> struct Sdf_PathNodeTypeToType<Sdf_PathNode::RootNode> {
typedef Sdf_RootPathNode Type;
};
template <int nodeType, class Comp>
struct Sdf_PathNodeCompare {
inline bool operator()(const Sdf_PathNode &lhs,
const Sdf_PathNode &rhs) const {
typedef typename Sdf_PathNodeTypeToType<nodeType>::Type Type;
return Comp()(static_cast<const Type&>(lhs)._GetComparisonValue(),
static_cast<const Type&>(rhs)._GetComparisonValue());
}
};
template <class Comp>
inline bool
Sdf_PathNode::Compare(const Sdf_PathNode &rhs) const
{
// Compare two nodes.
// We first compare types, then, if types match, we compare
// based on the type-specific content.
// Names are compared lexicographically.
// Compare types. If node types are different use Comp() on them, otherwise
// continue to node-specific comparisons.
NodeType nodeType = GetNodeType(), rhsNodeType = rhs.GetNodeType();
if (nodeType != rhsNodeType) {
return Comp()(nodeType, rhsNodeType);
}
// Types are the same. Avoid virtual function calls for performance.
switch (nodeType) {
case Sdf_PathNode::PrimNode:
return Sdf_PathNodeCompare<Sdf_PathNode::PrimNode,
Comp>()(*this, rhs);
case Sdf_PathNode::PrimPropertyNode:
return Sdf_PathNodeCompare<Sdf_PathNode::PrimPropertyNode,
Comp>()(*this, rhs);
case Sdf_PathNode::RelationalAttributeNode:
return Sdf_PathNodeCompare<Sdf_PathNode::RelationalAttributeNode,
Comp>()(*this, rhs);
case Sdf_PathNode::MapperArgNode:
return Sdf_PathNodeCompare<Sdf_PathNode::MapperArgNode,
Comp>()(*this, rhs);
case Sdf_PathNode::TargetNode:
return Sdf_PathNodeCompare<Sdf_PathNode::TargetNode,
Comp>()(*this, rhs);
case Sdf_PathNode::MapperNode:
return Sdf_PathNodeCompare<Sdf_PathNode::MapperNode,
Comp>()(*this, rhs);
case Sdf_PathNode::PrimVariantSelectionNode:
return Sdf_PathNodeCompare<Sdf_PathNode::PrimVariantSelectionNode,
Comp>()(*this, rhs);
case Sdf_PathNode::ExpressionNode:
return Sdf_PathNodeCompare<Sdf_PathNode::ExpressionNode,
Comp>()(*this, rhs);
case Sdf_PathNode::RootNode:
return Sdf_PathNodeCompare<Sdf_PathNode::RootNode,
Comp>()(*this, rhs);
default:
TF_CODING_ERROR("Unhandled Sdf_PathNode::NodeType enumerant");
return false;
}
}
inline void
Sdf_PathNode::_Destroy() const
{
// Note: This function deletes this object!
switch (_nodeType) {
case RootNode:
return delete _Downcast<Sdf_RootPathNode>();
case PrimNode:
return delete _Downcast<Sdf_PrimPathNode>();
case PrimPropertyNode:
return delete _Downcast<Sdf_PrimPropertyPathNode>();
case PrimVariantSelectionNode:
return delete _Downcast<Sdf_PrimVariantSelectionNode>();
case TargetNode:
return delete _Downcast<Sdf_TargetPathNode>();
case RelationalAttributeNode:
return delete _Downcast<Sdf_RelationalAttributePathNode>();
case MapperNode:
return delete _Downcast<Sdf_MapperPathNode>();
case MapperArgNode:
return delete _Downcast<Sdf_MapperArgPathNode>();
case ExpressionNode:
return delete _Downcast<Sdf_ExpressionPathNode>();
default:
return;
};
}
inline const TfToken &
Sdf_PathNode::GetName() const
{
switch (_nodeType) {
default:
return SdfPathTokens->empty;
case RootNode:
return IsAbsolutePath() ?
SdfPathTokens->absoluteIndicator : SdfPathTokens->relativeRoot;
case PrimNode:
return _Downcast<Sdf_PrimPathNode>()->_name;
case PrimPropertyNode:
return _Downcast<Sdf_PrimPropertyPathNode>()->_name;
case PrimVariantSelectionNode:
return _Downcast<Sdf_PrimVariantSelectionNode>()->_GetNameImpl();
case RelationalAttributeNode:
return _Downcast<Sdf_RelationalAttributePathNode>()->_name;
case MapperArgNode:
return _Downcast<Sdf_MapperArgPathNode>()->_name;
case ExpressionNode:
return SdfPathTokens->expressionIndicator;
}
}
inline const SdfPath &
Sdf_PathNode::GetTargetPath() const
{
switch (_nodeType) {
default:
return SdfPath::EmptyPath();
case TargetNode:
return _Downcast<Sdf_TargetPathNode>()->_targetPath;
case MapperNode:
return _Downcast<Sdf_MapperPathNode>()->_targetPath;
};
}
inline const Sdf_PathNode::VariantSelectionType &
Sdf_PathNode::GetVariantSelection() const
{
if (ARCH_LIKELY(_nodeType == PrimVariantSelectionNode)) {
return *_Downcast<Sdf_PrimVariantSelectionNode>()->_variantSelection;
}
return _GetEmptyVariantSelection();
}
inline TfToken
Sdf_PathNode::GetElement() const
{
switch (_nodeType) {
case RootNode:
return TfToken();
case PrimNode:
return _Downcast<Sdf_PrimPathNode>()->_name;
default:
std::string str;
AppendText(&str);
return TfToken(str);
};
}
/// Diagnostic output.
SDF_API void Sdf_DumpPathStats();
inline void intrusive_ptr_add_ref(const PXR_NS::Sdf_PathNode* p) {
++p->_refCount;
}
inline void intrusive_ptr_release(const PXR_NS::Sdf_PathNode* p) {
if (p->_refCount.fetch_and_decrement() == 1)
p->_Destroy();
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_PATH_NODE_H
+711
View File
@@ -0,0 +1,711 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_PATH_TABLE_H
#define PXR_USD_SDF_PATH_TABLE_H
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/usd/sdf/path.h"
#include "pxr/base/tf/pointerAndBits.h"
#include <boost/iterator/iterator_facade.hpp>
#include <boost/noncopyable.hpp>
#include <algorithm>
#include <utility>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
// Helper function for clearing path tables.
SDF_API
void Sdf_ClearPathTableInParallel(void **, size_t, void (*)(void *));
/// \class SdfPathTable
///
/// A mapping from SdfPath to \a MappedType, somewhat similar to map<SdfPath,
/// MappedType> and TfHashMap<SdfPath, MappedType>, but with key
/// differences. Notably:
///
/// Works exclusively with absolute paths.
///
/// Inserting a path \a p also implicitly inserts all of \a p's ancestors.
///
/// Erasing a path \a p also implicitly erases all of \a p's descendants.
///
/// The table has an order: it's a preordering of the paths in the table, but
/// with arbitrary sibling order. Given a path \a p in the table, all other
/// paths in the table with \a p as a prefix appear contiguously, immediately
/// following \a p. For example, suppose a table contains the paths:
///
/// {'/a/b/c', '/a', '/a/d', '/', '/a/b'}
///
/// Then there are two possible valid orderings:
///
/// ['/', '/a', '/a/d', '/a/b', '/a/b/c']
/// ['/', '/a', '/a/b', '/a/b/c', '/a/d']
///
/// In addition to the ordinary map and TfHashMap methods, this class
/// provides a method \a FindSubtreeRange, which, given a path \a p, returns
/// a pair of iterators [\a b, \a e) defining a range such that for every
/// iterator \a i in [\a b, \a e), i->first is either equal to \a p or is
/// prefixed by \a p.
///
/// Iterator Invalidation
///
/// Like most other node-based containers, iterators are only invalidated when
/// the element they refer to is removed from the table. Note however, that
/// since removing the element with path \a p also implicitly removes all
/// elements with paths prefixed by \a p, a call to erase(\a i) may invalidate
/// many iterators.
///
template <class MappedType>
class SdfPathTable
{
public:
typedef SdfPath key_type;
typedef MappedType mapped_type;
typedef std::pair<key_type, mapped_type> value_type;
private:
// An _Entry represents an item in the table. It holds the item's value, a
// pointer (\a next) to the next item in the hash bucket's linked list, and
// two pointers (\a firstChild and \a nextSibling) that describe the tree
// structure.
struct _Entry : boost::noncopyable {
_Entry(value_type const &value, _Entry *n)
: value(value)
, next(n)
, firstChild(0)
, nextSiblingOrParent(0, false) {}
// If this entry's nextSiblingOrParent field points to a sibling, return
// a pointer to it, otherwise return null.
_Entry *GetNextSibling() {
return nextSiblingOrParent.template BitsAs<bool>() ?
nextSiblingOrParent.Get() : 0;
}
// If this entry's nextSiblingOrParent field points to a sibling, return
// a pointer to it, otherwise return null.
_Entry const *GetNextSibling() const {
return nextSiblingOrParent.template BitsAs<bool>() ?
nextSiblingOrParent.Get() : 0;
}
// If this entry's nextSiblingOrParent field points to a parent, return
// a pointer to it, otherwise return null.
_Entry *GetParentLink() {
return nextSiblingOrParent.template BitsAs<bool>() ? 0 :
nextSiblingOrParent.Get();
}
// If this entry's nextSiblingOrParent field points to a parent, return
// a pointer to it, otherwise return null.
_Entry const *GetParentLink() const {
return nextSiblingOrParent.template BitsAs<bool>() ? 0 :
nextSiblingOrParent.Get();
}
// Set this entry's nextSiblingOrParent field to point to the passed
// sibling.
void SetSibling(_Entry *sibling) {
nextSiblingOrParent.Set(sibling, /* isSibling */ true);
}
// Set this entry's nextSiblingOrParent field to point to the passed
// parent.
void SetParentLink(_Entry *parent) {
nextSiblingOrParent.Set(parent, /* isSibling */ false);
}
// Add \a child as a child of this entry.
void AddChild(_Entry *child) {
// If there are already one or more children, make \a child be our
// new first child. Otherwise, add \a child as the first child.
if (firstChild)
child->SetSibling(firstChild);
else
child->SetParentLink(this);
firstChild = child;
}
void RemoveChild(_Entry *child) {
// Remove child from this _Entry's children.
if (child == firstChild) {
firstChild = child->GetNextSibling();
} else {
// Search the list to find the preceding child, then unlink the
// child to remove.
_Entry *prev, *cur = firstChild;
do {
prev = cur;
cur = prev->GetNextSibling();
} while (cur != child);
prev->nextSiblingOrParent = cur->nextSiblingOrParent;
}
}
// The value object mapped by this entry.
value_type value;
// The next field links together entries in chained hash table buckets.
_Entry *next;
// The firstChild and nextSiblingOrParent fields describe the tree
// structure of paths. An entry has one or more children when
// firstChild is non null. Its chlidren are stored in a singly linked
// list, where nextSiblingOrParent points to the next entry in the list.
//
// The end of the list is reached when the bit stored in
// nextSiblingOrParent is set false, indicating a pointer to the parent
// rather than another sibling.
_Entry *firstChild;
TfPointerAndBits<_Entry> nextSiblingOrParent;
};
// Hash table's list of buckets is a vector of _Entry ptrs.
typedef std::vector<_Entry *> _BucketVec;
public:
// The iterator class, used to make both const and non-const
// iterators. Currently only forward traversal is supported.
template <class, class> friend class Iterator;
template <class ValType, class EntryPtr>
class Iterator :
public boost::iterator_facade<Iterator<ValType, EntryPtr>,
ValType, boost::forward_traversal_tag>
{
public:
/// The standard requires default construction but places practically no
/// requirements on the semantics of default-constructed iterators.
Iterator() {}
/// Copy constructor (also allows for converting non-const to const).
template <class OtherVal, class OtherEntryPtr>
Iterator(Iterator<OtherVal, OtherEntryPtr> const &other)
: _entry(other._entry)
{}
/// Return an iterator \a e, defining a maximal range [\a *this, \a e)
/// such that for all \a i in the range, \a i->first is \a
/// (*this)->first or is prefixed by \a (*this)->first.
Iterator GetNextSubtree() const {
Iterator result(0);
if (_entry) {
if (EntryPtr sibling = _entry->GetNextSibling()) {
// Next subtree is next sibling, if present.
result._entry = sibling;
} else {
// Otherwise, walk up parents until we either find one with
// a next sibling or run out.
for (EntryPtr p = _entry->GetParentLink(); p;
p = p->GetParentLink()) {
if (EntryPtr sibling = p->GetNextSibling()) {
result._entry = sibling;
break;
}
}
}
}
return result;
}
protected:
friend class boost::iterator_core_access;
friend class SdfPathTable;
template <class, class> friend class Iterator;
explicit Iterator(EntryPtr entry)
: _entry(entry) {}
// Fundamental functionality to implement the iterator.
// boost::iterator_facade will invoke these as necessary to implement
// the full iterator public interface.
// Iterator increment.
inline void increment() {
// Move to first child, if present. Otherwise move to next subtree.
_entry = _entry->firstChild ? _entry->firstChild :
GetNextSubtree()._entry;
}
// Equality comparison. A template, to allow comparison between const
// and non-const iterators.
template <class OtherVal, class OtherEntryPtr>
bool equal(Iterator<OtherVal, OtherEntryPtr> const &other) const {
return _entry == other._entry;
}
// Dereference.
ValType &dereference() const {
return _entry->value;
}
// Store pointer to current entry.
EntryPtr _entry;
};
typedef Iterator<value_type, _Entry *> iterator;
typedef Iterator<const value_type, const _Entry *> const_iterator;
/// Result type for insert().
typedef std::pair<iterator, bool> _IterBoolPair;
/// Default constructor.
SdfPathTable() : _size(0), _mask(0) {}
/// Copy constructor.
SdfPathTable(SdfPathTable const &other)
: _buckets(other._buckets.size())
, _size(0) // size starts at 0, since we insert elements.
, _mask(other._mask)
{
// Walk all elements in the other container, inserting into this one,
// and creating the right child/sibling links along the way.
for (const_iterator i = other.begin(), end = other.end();
i != end; ++i) {
iterator j = _InsertInTable(*i).first;
// Ensure first child and next sibling links are created.
if (i._entry->firstChild && !j._entry->firstChild) {
j._entry->firstChild =
_InsertInTable(i._entry->firstChild->value).first._entry;
}
// Ensure the nextSibling/parentLink is created.
if (i._entry->nextSiblingOrParent.Get() &&
!j._entry->nextSiblingOrParent.Get()) {
j._entry->nextSiblingOrParent.Set(
_InsertInTable(i._entry->nextSiblingOrParent.
Get()->value).first._entry,
i._entry->nextSiblingOrParent.template BitsAs<bool>());
}
}
}
/// Move constructor.
SdfPathTable(SdfPathTable &&other)
: _buckets(std::move(other._buckets))
, _size(other._size)
, _mask(other._mask)
{
other._size = 0;
other._mask = 0;
}
/// Destructor.
~SdfPathTable() {
// Call clear to free all nodes.
clear();
}
/// Copy assignment.
SdfPathTable &operator=(SdfPathTable const &other) {
if (this != &other)
SdfPathTable(other).swap(*this);
return *this;
}
/// Move assignment.
SdfPathTable &operator=(SdfPathTable &&other) {
if (this != &other)
SdfPathTable(std::move(other)).swap(*this);
return *this;
}
/// Return an iterator to the start of the table.
iterator begin() {
// Return an iterator pointing to the root if this table isn't empty.
if (empty())
return end();
return find(SdfPath::AbsoluteRootPath());
}
/// Return a const_iterator to the start of the table.
const_iterator begin() const {
// Return an iterator pointing to the root if this table isn't empty.
if (empty())
return end();
return find(SdfPath::AbsoluteRootPath());
}
/// Return an iterator denoting the end of the table.
iterator end() {
return iterator(0);
}
/// Return a const_iterator denoting the end of the table.
const_iterator end() const {
return const_iterator(0);
}
/// Remove the element with path \a path from the table as well as all
/// elements whose paths are prefixed by \a path. Return true if any
/// elements were removed, false otherwise.
///
/// Note that since descendant paths are also erased, size() may be
/// decreased by more than one after calling this function.
bool erase(SdfPath const &path) {
iterator i = find(path);
if (i == end())
return false;
erase(i);
return true;
}
/// Remove the element pointed to by \p i from the table as well as all
/// elements whose paths are prefixed by \a i->first. \a i must be a valid
/// iterator for this table.
///
/// Note that since descendant paths are also erased, size() may be
/// decreased by more than one after calling this function.
void erase(iterator const &i) {
// Delete descendant nodes, if any. Then remove from parent, finally
// erase from hash table.
_Entry * const entry = i._entry;
_EraseSubtree(entry);
_RemoveFromParent(entry);
_EraseFromTable(entry);
}
/// Return an iterator to the element corresponding to \a path, or \a end()
/// if there is none.
iterator find(SdfPath const &path) {
if (!empty()) {
// Find the item in the list.
for (_Entry *e = _buckets[_Hash(path)]; e; e = e->next) {
if (e->value.first == path)
return iterator(e);
}
}
return end();
}
/// Return a const_iterator to the element corresponding to \a path, or
/// \a end() if there is none.
const_iterator find(SdfPath const &path) const {
if (!empty()) {
// Find the item in the list.
for (_Entry const *e = _buckets[_Hash(path)]; e; e = e->next) {
if (e->value.first == path)
return const_iterator(e);
}
}
return end();
}
/// Return a pair of iterators [\a b, \a e), describing the maximal range
/// such that for all \a i in the range, \a i->first is \a b->first or
/// is prefixed by \a b->first.
std::pair<iterator, iterator>
FindSubtreeRange(SdfPath const &path) {
std::pair<iterator, iterator> result;
result.first = find(path);
result.second = result.first.GetNextSubtree();
return result;
}
/// Return a pair of const_iterators [\a b, \a e), describing the maximal
/// range such that for all \a i in the range, \a i->first is \a b->first or
/// is prefixed by \a b->first.
std::pair<const_iterator, const_iterator>
FindSubtreeRange(SdfPath const &path) const {
std::pair<const_iterator, const_iterator> result;
result.first = find(path);
result.second = result.first.GetNextSubtree();
return result;
}
/// Return 1 if there is an element for \a path in the table, otherwise 0.
size_t count(SdfPath const &path) const {
return find(path) != end();
}
/// Return the number of elements in the table.
inline size_t size() const { return _size; }
/// Return true if this table is empty.
inline bool empty() const { return !size(); }
/// Insert \a value into the table, and additionally insert default entries
/// for all ancestral paths of \a value.first that do not already exist in
/// the table.
///
/// Return a pair of iterator and bool. The iterator points to the inserted
/// element, the bool indicates whether insertion was successful. The bool
/// is true if \a value was successfully inserted and false if an element
/// with path \a value.first was already present in the map.
///
/// Note that since ancestral paths are also inserted, size() may be
/// increased by more than one after calling this function.
_IterBoolPair insert(value_type const &value) {
// Insert in table.
_IterBoolPair result = _InsertInTable(value);
if (result.second) {
// New element -- make sure the parent is inserted.
_Entry * const newEntry = result.first._entry;
SdfPath const &parentPath = _GetParentPath(value.first);
if (!parentPath.IsEmpty()) {
iterator parIter =
insert(value_type(parentPath, mapped_type())).first;
// Add the new entry to the parent's children.
parIter._entry->AddChild(newEntry);
}
}
return result;
}
/// Shorthand for the following, where \a t is an SdfPathTable<T>.
/// \code
/// t.insert(value_type(path, mapped_type())).first->second
/// \endcode
mapped_type &operator[](SdfPath const &path) {
return insert(value_type(path, mapped_type())).first->second;
}
/// Remove all elements from the table, leaving size() == 0. Note that this
/// function will not shrink the number of buckets used for the hash table.
/// To do that, swap this instance with a default constructed instance.
/// See also \a TfReset.
void clear() {
// Note this leaves the size of _buckets unchanged.
for (size_t i = 0, n = _buckets.size(); i != n; ++i) {
_Entry *entry = _buckets[i];
while (entry) {
_Entry *next = entry->next;
delete entry;
entry = next;
}
_buckets[i] = 0;
}
_size = 0;
}
/// Equivalent to clear(), but destroy contained objects in parallel. This
/// requires that running the contained objects' destructors is thread-safe.
void ClearInParallel() {
Sdf_ClearPathTableInParallel(reinterpret_cast<void **>(_buckets.data()),
_buckets.size(), _DeleteEntryChain);
_size = 0;
}
/// Swap this table's contents with \a other.
void swap(SdfPathTable &other) {
_buckets.swap(other._buckets);
std::swap(_size, other._size);
std::swap(_mask, other._mask);
}
/// Return a vector of the count of elements in each bucket.
std::vector<size_t> GetBucketSizes() const {
std::vector<size_t> sizes(_buckets.size(), 0u);;
for (size_t i = 0, n = _buckets.size(); i != n; ++i) {
for (_Entry *entry = _buckets[i]; entry; entry = entry->next) {
sizes[i]++;
}
}
return sizes;
}
/// Replaces all prefixes from \p oldName to \p newName.
/// Note that \p oldName and \p newName need to be silbing paths (ie.
/// their parent paths must be the same).
void UpdateForRename(const SdfPath &oldName, const SdfPath &newName) {
if (oldName.GetParentPath() != newName.GetParentPath()) {
TF_CODING_ERROR("Unexpected arguments.");
return;
}
std::pair<iterator, iterator> range = FindSubtreeRange(oldName);
for (iterator i=range.first; i!=range.second; ++i) {
insert(value_type(
i->first.ReplacePrefix(oldName, newName),
i->second));
}
if (range.first != range.second)
erase(oldName);
}
/// @}
private:
// Helper to delete entries.
static void _DeleteEntryChain(void *voidEntry) {
_Entry *entry = static_cast<_Entry *>(voidEntry);
while (entry) {
_Entry *next = entry->next;
delete entry;
entry = next;
}
}
// Helper to get parent paths.
static SdfPath _GetParentPath(SdfPath const &path) {
return path.GetParentPath();
}
// Helper to insert \a value in the hash table. Is responsible for growing
// storage space when necessary. Does not consider the tree structure.
_IterBoolPair _InsertInTable(value_type const &value) {
// If we have no storage at all so far, grow.
if (_mask == 0)
_Grow();
// Find the item, if present.
_Entry **bucketHead = &(_buckets[_Hash(value.first)]);
for (_Entry *e = *bucketHead; e; e = e->next)
if (e->value.first == value.first)
return _IterBoolPair(iterator(e), false);
// Not present. If the table is getting full then grow and re-find the
// bucket.
if (_IsTooFull()) {
_Grow();
bucketHead = &(_buckets[_Hash(value.first)]);
}
TfAutoMallocTag2 tag2("Sdf", "SdfPathTable::_FindOrCreate");
TfAutoMallocTag tag(__ARCH_PRETTY_FUNCTION__);
// Create a new item and insert it in the list
*bucketHead = new _Entry(value, *bucketHead);
// One more element
++_size;
// Return the new item
return _IterBoolPair(iterator(*bucketHead), true);
}
// Erase \a entry from the hash table. Does not consider tree structure.
void _EraseFromTable(_Entry *entry) {
// Remove from table.
_Entry **cur = &_buckets[_Hash(entry->value.first)];
while (*cur != entry)
cur = &((*cur)->next);
// Unlink item and destroy it
--_size;
_Entry *tmp = *cur;
*cur = tmp->next;
delete tmp;
}
// Erase all the tree structure descendants of \a entry from the table.
void _EraseSubtree(_Entry *entry) {
// Delete descendant nodes, if any.
if (_Entry * const firstChild = entry->firstChild) {
_EraseSubtreeAndSiblings(firstChild);
_EraseFromTable(firstChild);
}
}
// Erase all the tree structure descendants and siblings of \a entry from
// the table.
void _EraseSubtreeAndSiblings(_Entry *entry) {
// Remove subtree.
_EraseSubtree(entry);
// And siblings.
_Entry *sibling = entry->GetNextSibling();
_Entry *nextSibling = sibling ? sibling->GetNextSibling() : nullptr;
while (sibling) {
_EraseSubtree(sibling);
_EraseFromTable(sibling);
sibling = nextSibling;
nextSibling = sibling ? sibling->GetNextSibling() : nullptr;
}
}
// Remove \a entry from its parent's list of children in the tree structure
// alone. Does not consider the table.
void _RemoveFromParent(_Entry *entry) {
if (entry->value.first == SdfPath::AbsoluteRootPath())
return;
// Find parent in table.
iterator parIter = find(_GetParentPath(entry->value.first));
// Remove this entry from the parent's children.
parIter._entry->RemoveChild(entry);
}
// Grow the table's number of buckets to the next larger size. Rehashes the
// elements into the new table, but leaves tree structure untouched. (The
// tree structure need not be modified).
void _Grow() {
TfAutoMallocTag2 tag2("Sdf", "SdfPathTable::_Grow");
TfAutoMallocTag tag(__ARCH_PRETTY_FUNCTION__);
// Allocate a new bucket list of twice the size. Minimum nonzero number
// of buckets is 8.
_mask = std::max(size_t(7), (_mask << 1) + 1);
_BucketVec newBuckets(_mask + 1);
// Move items to a new bucket list
for (size_t i = 0, n = _buckets.size(); i != n; ++i) {
_Entry *elem = _buckets[i];
while (elem) {
// Save pointer to next item
_Entry *next = elem->next;
// Get the bucket in the new list
_Entry *&m = newBuckets[_Hash(elem->value.first)];
// Insert the item at the head
elem->next = m;
m = elem;
// Next item
elem = next;
}
}
// Use the new buckets
_buckets.swap(newBuckets);
}
// Return true if the table should be made bigger.
bool _IsTooFull() const {
return _size > _buckets.size();
}
// Return the bucket index for \a path.
inline size_t _Hash(SdfPath const &path) const {
return path.GetHash() & _mask;
}
private:
_BucketVec _buckets;
size_t _size;
size_t _mask;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_PATH_TABLE_H
+131
View File
@@ -0,0 +1,131 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_PAYLOAD_H
#define PXR_USD_SDF_PAYLOAD_H
/// \file sdf/payload.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/usd/sdf/layerOffset.h"
#include "pxr/usd/sdf/path.h"
#include <boost/functional/hash.hpp>
#include <boost/operators.hpp>
#include <iosfwd>
#include <string>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
class SdfPayload;
typedef std::vector<SdfPayload> SdfPayloadVector;
/// \class SdfPayload
///
/// Represents a payload and all its meta data.
///
/// A payload represents a prim reference to an external layer. A payload
/// is similar to a prim reference (see SdfReference) with the major
/// difference that payloads are explicitly loaded by the user.
///
/// Unloaded payloads represent a boundary that lazy composition and
/// system behaviors will not traverse across, providing a user-visible
/// way to manage the working set of the scene.
///
class SdfPayload : boost::totally_ordered<SdfPayload> {
public:
/// Creates a payload.
///
SDF_API
SdfPayload(
const std::string &assetPath = std::string(),
const SdfPath &primPath = SdfPath(),
const SdfLayerOffset &layerOffset = SdfLayerOffset());
/// Returns the asset path of the layer that the payload uses.
const std::string &GetAssetPath() const {
return _assetPath;
}
/// Sets a new asset path for the layer the payload uses.
void SetAssetPath(const std::string &assetPath) {
_assetPath = assetPath;
}
/// Returns the scene path of the prim for the payload.
const SdfPath &GetPrimPath() const {
return _primPath;
}
/// Sets a new prim path for the prim that the payload uses.
void SetPrimPath(const SdfPath &primPath) {
_primPath = primPath;
}
/// Returns the layer offset associated with the payload.
const SdfLayerOffset &GetLayerOffset() const {
return _layerOffset;
}
/// Sets a new layer offset.
void SetLayerOffset(const SdfLayerOffset &layerOffset) {
_layerOffset = layerOffset;
}
/// Returns whether this payload equals \a rhs.
SDF_API bool operator==(const SdfPayload &rhs) const;
/// Returns whether this payload is less than \a rhs.
/// The meaning of less than is arbitrary but stable.
SDF_API bool operator<(const SdfPayload &rhs) const;
private:
friend inline size_t hash_value(const SdfPayload &p) {
size_t h = 0;
boost::hash_combine(h, p._assetPath);
boost::hash_combine(h, p._primPath);
boost::hash_combine(h, p._layerOffset);
return h;
}
// The asset path to the external layer.
std::string _assetPath;
// The root prim path to the referenced prim in the external layer.
SdfPath _primPath;
// The layer offset to transform time.
SdfLayerOffset _layerOffset;
};
/// Writes the string representation of \a SdfPayload to \a out.
SDF_API
std::ostream & operator<<(std::ostream &out, const SdfPayload &payload);
PXR_NAMESPACE_CLOSE_SCOPE
#endif
+280
View File
@@ -0,0 +1,280 @@
//
// Copyright 2019 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_POOL_H
#define PXR_USD_SDF_POOL_H
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/base/arch/demangle.h"
#include "pxr/base/arch/hints.h"
#include "pxr/base/arch/pragmas.h"
#include "pxr/base/tf/diagnostic.h"
#include "pxr/base/tf/staticData.h"
#include <tbb/concurrent_queue.h>
#include <atomic>
#include <thread>
PXR_NAMESPACE_OPEN_SCOPE
// A helper struct for thread_local that uses nullptr initialization as a
// sentinel to prevent guard variable use from being invoked after first
// initialization.
template <class T>
struct Sdf_FastThreadLocalBase
{
static T &Get() {
static thread_local T *theTPtr = nullptr;
if (ARCH_LIKELY(theTPtr)) {
return *theTPtr;
}
static thread_local T theT;
T *p = &theT;
theTPtr = p;
return *p;
}
};
// Fixed-size scalable pool allocator with 32-bit "handles" returned. Reserves
// virtual memory in big regions. It's optimized for per-thread allocations,
// and intended to be used for SdfPath. The Tag template argument just serves
// as to distinguish one pool instantiation from another with otherwise
// equivalent template arguments. The ElemSize argument is the size of an
// allocated element in bytes. It must be at least 4 bytes. The RegionBits
// argument determines how many contiguous "chunks" of virtual memory the pool
// will use. A good number for this is 8, meaning we'll have at most 256
// "regions" or "chunks" of contiguous virtual memory, each 2^24 times ElemSize
// bytes in size. To allocate from reserved chunks, each thread acquires a span
// to hold ElemsPerSpan elements from the range, then uses that to dole out
// individual allocations. When freed, allocations are placed on a thread-local
// free list, and eventually shared back for use by other threads when the free
// list gets large.
template <class Tag,
unsigned ElemSize,
unsigned RegionBits,
unsigned ElemsPerSpan=16384>
class Sdf_Pool
{
static_assert(ElemSize >= sizeof(uint32_t),
"ElemSize must be at least sizeof(uint32_t)");
public:
// Number of pool elements per region.
static constexpr uint64_t ElemsPerRegion = 1ull << (32-RegionBits);
// Maximum index of an element in a region.
static constexpr uint32_t MaxIndex = ElemsPerRegion - 1;
// Mask to extract region number from a handle value.
static constexpr uint32_t RegionMask = ((1 << RegionBits)-1);
friend struct Handle;
// A Handle refers to an item in the pool. It just wraps around a uint32_t
// that represents the item's index and the item's region.
struct Handle {
constexpr Handle() noexcept = default;
constexpr Handle(std::nullptr_t) noexcept : value(0) {}
Handle(unsigned region, uint32_t index)
: value((index << RegionBits) | region) {}
Handle &operator=(Handle const &) = default;
Handle &operator=(std::nullptr_t) { return *this = Handle(); }
inline char *GetPtr() const noexcept {
ARCH_PRAGMA_PUSH
ARCH_PRAGMA_MAYBE_UNINITIALIZED
return Sdf_Pool::_GetPtr(value & RegionMask, value >> RegionBits);
ARCH_PRAGMA_POP
}
static inline Handle GetHandle(char const *ptr) noexcept {
return Sdf_Pool::_GetHandle(ptr);
}
explicit operator bool() const {
return value != 0;
}
inline bool operator ==(Handle const &r) const noexcept {
return value == r.value;
}
inline bool operator !=(Handle const &r) const noexcept {
return value != r.value;
}
inline bool operator <(Handle const &r) const noexcept {
return value < r.value;
}
inline void swap(Handle &r) noexcept {
std::swap(value, r.value);
}
uint32_t value = 0;
};
private:
// We maintain per-thread free lists of pool items.
struct _FreeList {
inline void Pop() {
char *p = head.GetPtr();
Handle *hp = reinterpret_cast<Handle *>(p);
head = *hp;
--size;
}
inline void Push(Handle h) {
++size;
char *p = h.GetPtr();
Handle *hp = reinterpret_cast<Handle *>(p);
*hp = head;
head = h;
}
Handle head;
size_t size = 0;
};
// A pool span represents a "chunk" of new pool space that threads allocate
// from when their free lists are empty. When both the free list and the
// pool span are exhausted, a thread will look for a shared free list, or
// will obtain a new chunk of pool space to use.
struct _PoolSpan {
size_t size() const { return endIndex - beginIndex; }
inline Handle Alloc() {
return Handle(region, beginIndex++);
}
inline bool empty() const {
return beginIndex == endIndex;
}
unsigned region;
uint32_t beginIndex;
uint32_t endIndex;
};
struct _PerThreadData {
// Local free-list of elems returned to the pool.
_FreeList freeList;
// Contiguous range of reserved but as-yet-unalloc'd space.
_PoolSpan span;
};
// The region state structure represents the global state of the pool. This
// is a pool-global structure that is used to reserve new spans of pool data
// by threads when needed. See the Reserve() member, and the _ReserveSpan()
// function that does most of the state manipulation.
struct _RegionState {
static constexpr uint32_t LockedState = ~0;
_RegionState() = default;
constexpr _RegionState(unsigned region, uint32_t index)
: _state((index << RegionBits) | region) {}
// Make a new state that reserves up to \p num elements. There must be
// space left remaining.
inline _RegionState Reserve(unsigned num) const;
static constexpr _RegionState GetInitState() {
return _RegionState(0, 0);
}
static constexpr _RegionState GetLockedState() {
return _RegionState(LockedState, LockedState);
}
constexpr bool operator==(_RegionState other) const {
return _state == other._state;
}
uint32_t GetIndex() const {
return _state >> RegionBits;
}
unsigned GetRegion() const {
return _state & RegionMask;
}
bool IsLocked() const {
return _state == LockedState;
}
// low RegionBits bits are region id, rest are index.
uint32_t _state;
};
public:
static inline Handle Allocate();
static inline void Free(Handle h);
private:
// Given a region id and index, form the pointer into the pool.
static inline char *_GetPtr(unsigned region, uint32_t index) {
// Suppress undefined-var-template warnings from clang; _regionStarts
// is expected to be instantiated in another translation unit via
// the SDF_INSTANTIATE_POOL macro.
ARCH_PRAGMA_PUSH
ARCH_PRAGMA_UNDEFINED_VAR_TEMPLATE
return _regionStarts[region] + (index * ElemSize);
ARCH_PRAGMA_POP
}
// Given a pointer into the pool, produce its corresponding Handle. Don't
// do this unless you really have to, it has to do a bit of a search.
static inline Handle _GetHandle(char const *ptr) {
if (ptr) {
for (unsigned region = 1; region != NumRegions+1; ++region) {
char const *start = _regionStarts[region];
ptrdiff_t diff = ptr - start;
// Indexes start at 1 to avoid hash collisions when combining
// multiple pool indexes in a single hash, so strictly greater
// than 0 rather than greater-equal is appropriate here.
if (ARCH_LIKELY(start && (diff > 0) &&
(diff < static_cast<ptrdiff_t>(ElemsPerRegion*ElemSize)))){
return Handle(region,
static_cast<uint32_t>(diff / ElemSize));
}
}
}
return nullptr;
}
// Try to take a shared free list.
static bool _TakeSharedFreeList(_FreeList &out) {
return _sharedFreeLists->try_pop(out);
}
// Give a free list to be shared by other threads.
static void _ShareFreeList(_FreeList &in) {
_sharedFreeLists->push(in);
in = {};
}
// Reserve a new span of pool space.
static inline void _ReserveSpan(_PoolSpan &out);
static constexpr int NumRegions = 1 << RegionBits;
using _ThreadData = Sdf_FastThreadLocalBase<_PerThreadData>;
SDF_API static _ThreadData _threadData;
SDF_API static char *_regionStarts[NumRegions+1];
SDF_API static std::atomic<_RegionState> _regionState;
SDF_API static TfStaticData<tbb::concurrent_queue<_FreeList>> _sharedFreeLists;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_POOL_H
+787
View File
@@ -0,0 +1,787 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_PRIM_SPEC_H
#define PXR_USD_SDF_PRIM_SPEC_H
/// \file sdf/primSpec.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/declareSpec.h"
#include "pxr/usd/sdf/spec.h"
#include "pxr/usd/sdf/path.h"
#include "pxr/usd/sdf/payload.h"
#include "pxr/usd/sdf/proxyTypes.h"
#include "pxr/usd/sdf/types.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/base/tf/declarePtrs.h"
#include <iosfwd>
#include <map>
#include <string>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
/// \class SdfPrimSpec
///
/// Represents a prim description in an SdfLayer object.
///
/// Every SdfPrimSpec object is defined in a layer. It is identified by its
/// path (SdfPath class) in the namespace hierarchy of its layer. SdfPrimSpecs
/// can be created using the New() method as children of either the containing
/// SdfLayer itself (for "root level" prims), or as children of other
/// SdfPrimSpec objects to extend a hierarchy. The helper function
/// SdfCreatePrimInLayer() can be used to quickly create a hierarchy of
/// primSpecs.
///
/// SdfPrimSpec objects have properties of two general types: attributes
/// (containing values) and relationships (different types of connections to
/// other prims and attributes). Attributes are represented by the
/// SdfAttributeSpec class and relationships by the SdfRelationshipSpec class.
/// Each prim has its own namespace of properties. Properties are stored and
/// accessed by their name.
///
/// SdfPrimSpec objects have a typeName, permission restriction, and they
/// reference and inherit prim paths. Permission restrictions control which
/// other layers may refer to, or express opinions about a prim. See the
/// SdfPermission class for more information.
///
/// \todo
/// \li Insert doc about references and inherits here.
/// \li Should have validate... methods for name, children, properties
///
class SdfPrimSpec : public SdfSpec
{
SDF_DECLARE_SPEC(SdfPrimSpec, SdfSpec);
public:
typedef SdfPrimSpecView NameChildrenView;
typedef SdfPropertySpecView PropertySpecView;
typedef SdfAttributeSpecView AttributeSpecView;
typedef SdfRelationshipSpecView RelationshipSpecView;
///
/// \name Spec creation
/// @{
/// Create a root prim spec.
///
/// Creates a prim spec with a \p name, \p specifier and \p typeName as a
/// root prim in the given layer.
SDF_API
static SdfPrimSpecHandle
New(const SdfLayerHandle& parentLayer,
const std::string& name, SdfSpecifier spec,
const std::string& typeName = std::string());
/// Create a prim spec.
///
/// Creates a prim spec with a \p name, \p specifier and \p typeName as
/// a namespace child of the given prim.
///
/// \sa SdfCreatePrimInLayer() to create a PrimSpec with all required
/// ancestor specs as SdfSpecifierOver.
SDF_API
static SdfPrimSpecHandle
New(const SdfPrimSpecHandle& parentPrim,
const std::string& name, SdfSpecifier spec,
const std::string& typeName = std::string());
/// \name Name
/// @{
/// Returns the prim's name.
SDF_API
const std::string& GetName() const;
/// Returns the prim's name, as a token.
SDF_API
TfToken GetNameToken() const;
/// Returns true if setting the prim spec's name to \p newName will
/// succeed.
///
/// Returns false if it won't, and sets \p whyNot with a string
/// describing why not.
SDF_API
bool CanSetName(const std::string& newName, std::string* whyNot) const;
/// Sets the prim's name.
///
/// Children prims must be unique by name. It is an error to
/// set the name to the same name as an existing child of this
/// prim's parent.
///
/// Setting validate to false, will skip validation of the \p newName
/// (that is, CanSetName will not be called).
///
/// Returns true if successful, false otherwise.
SDF_API
bool SetName(const std::string& newName, bool validate = true);
/// Returns true if the given string is a valid prim name.
SDF_API
static bool IsValidName(const std::string& name);
/// @}
/// \name Namespace hierarchy
/// @{
/// Returns the prim's namespace pseudo-root prim.
SDF_API
SdfPrimSpecHandle GetNameRoot() const;
/// Returns the prim's namespace parent.
///
/// This does not return the pseudo-root for root prims. Most
/// algorithms that scan the namespace hierarchy upwards don't
/// want to process the pseudo-root the same way as actual prims.
/// Algorithms that do can always call \c GetRealNameParent().
SDF_API
SdfPrimSpecHandle GetNameParent() const;
/// Returns the prim's namespace parent.
SDF_API
SdfPrimSpecHandle GetRealNameParent() const;
/// Returns a keyed vector view of the prim's namespace children.
SDF_API
NameChildrenView GetNameChildren() const;
/// Updates nameChildren to match the given vector of prims.
SDF_API
void SetNameChildren(const SdfPrimSpecHandleVector&);
/// Inserts a child.
///
/// \p index is ignored except for range checking; -1 is permitted.
///
/// Returns true if successful, false if failed.
SDF_API
bool InsertNameChild(const SdfPrimSpecHandle& child, int index = -1);
/// Removes the child. Returns true if successful, false if failed.
SDF_API
bool RemoveNameChild(const SdfPrimSpecHandle& child);
/// Returns the list of child names for this prim's reorder.
/// nameChildren statement.
///
/// See SetNameChildrenOrder() for more info.
SDF_API
SdfNameChildrenOrderProxy GetNameChildrenOrder() const;
/// Returns true if this prim has name children order specified
SDF_API
bool HasNameChildrenOrder() const;
/// Given a list of (possibly sparse) child names, authors a reorder
/// nameChildren statement for this prim.
///
/// The reorder statement can modify the order of name children
/// during composition. This order doesn't affect GetNameChildren(),
/// InsertNameChild(), SetNameChildren(), et al.
SDF_API
void SetNameChildrenOrder(const std::vector<TfToken>& names);
/// Adds a new name child \p name in the name children order.
/// If \p index is -1, the name is inserted at the end.
SDF_API
void InsertInNameChildrenOrder(const TfToken& name, int index = -1);
/// Removes a name child name from the name children order.
SDF_API
void RemoveFromNameChildrenOrder(const TfToken& name);
/// Removes a name child name from the name children order by index.
SDF_API
void RemoveFromNameChildrenOrderByIndex(int index);
/// Reorders the given list of child names according to the reorder
/// nameChildren statement for this prim.
///
/// This routine employs the standard list editing operation for ordered
/// items in a ListEditor.
SDF_API
void ApplyNameChildrenOrder(std::vector<TfToken>* vec) const;
/// @}
/// \name Properties
/// @{
/// Returns the prim's properties.
SDF_API
PropertySpecView GetProperties() const;
/// Updates properties to match the given vector of properties.
SDF_API
void SetProperties(const SdfPropertySpecHandleVector&);
/// Inserts a property.
///
/// \p index is ignored except for range checking; -1 is permitted.
///
/// Returns true if successful, false if failed.
SDF_API
bool InsertProperty(const SdfPropertySpecHandle& property, int index = -1);
/// Removes the property.
SDF_API
void RemoveProperty(const SdfPropertySpecHandle& property);
/// Returns a view of the attributes of this prim.
SDF_API
AttributeSpecView GetAttributes() const;
/// Returns a view of the relationships of this prim.
SDF_API
RelationshipSpecView GetRelationships() const;
/// Returns the list of property names for this prim's reorder
/// properties statement.
///
/// See SetPropertyOrder() for more info.
SDF_API
SdfPropertyOrderProxy GetPropertyOrder() const;
/// Returns true if this prim has a property ordering specified.
SDF_API
bool HasPropertyOrder() const;
/// Given a list of (possibly sparse) property names, authors a
/// reorder properties statement for this prim.
///
/// The reorder statement can modify the order of properties during
/// composition. This order doesn't affect GetProperties(),
/// InsertProperty(), SetProperties(), et al.
SDF_API
void SetPropertyOrder(const std::vector<TfToken>& names);
/// Add a new property \p name in the property order.
/// If \p index is -1, the name is inserted at the end.
SDF_API
void InsertInPropertyOrder(const TfToken& name, int index = -1);
/// Remove a property name from the property order.
SDF_API
void RemoveFromPropertyOrder(const TfToken& name);
/// Remove a property name from the property order by index.
SDF_API
void RemoveFromPropertyOrderByIndex(int index);
/// Reorders the given list of property names according to the
/// reorder properties statement for this prim.
///
/// This routine employs the standard list editing operation for ordered
/// items in a ListEditor.
SDF_API
void ApplyPropertyOrder(std::vector<TfToken>* vec) const;
/// @}
/// \name Lookup
/// @{
/// Returns the object for the given \p path.
///
/// If \p path is relative then it will be interpreted as
/// relative to this prim. If it is absolute then it will be
/// interpreted as absolute in this prim's layer.
///
/// Returns invalid handle if there is no object at \p path.
SDF_API
SdfSpecHandle GetObjectAtPath(const SdfPath& path) const;
/// Returns a prim given its \p path.
///
/// Returns invalid handle if there is no prim at \p path.
/// This is simply a more specifically typed version of GetObjectAtPath.
SDF_API
SdfPrimSpecHandle GetPrimAtPath(const SdfPath& path) const;
/// Returns a property given its \p path.
///
/// Returns invalid handle if there is no property at \p path.
/// This is simply a more specifically typed version of GetObjectAtPath.
SDF_API
SdfPropertySpecHandle GetPropertyAtPath(const SdfPath& path) const;
/// Returns an attribute given its \p path.
///
/// Returns invalid handle if there is no attribute at \p path.
/// This is simply a more specifically typed version of GetObjectAtPath.
SDF_API
SdfAttributeSpecHandle GetAttributeAtPath(const SdfPath& path) const;
/// Returns a relationship given its \p path.
///
/// Returns invalid handle if there is no relationship at \p path.
/// This is simply a more specifically typed version of GetObjectAtPath.
SDF_API
SdfRelationshipSpecHandle GetRelationshipAtPath(const SdfPath& path) const;
/// @}
/// \name Metadata
/// @{
/// Returns the typeName of the model prim.
///
/// For prims this specifies the sub-class of MfPrim that
/// this prim describes.
///
/// The default value for typeName is the empty token.
SDF_API
TfToken GetTypeName() const;
/// Sets the typeName of the model prim.
SDF_API
void SetTypeName(const std::string& value);
/// Returns the comment string for this prim spec.
///
/// The default value for comment is @"".
SDF_API
std::string GetComment() const;
/// Sets the comment string for this prim spec.
SDF_API
void SetComment(const std::string& value);
/// Returns the documentation string for this prim spec.
///
/// The default value for documentation is @"".
SDF_API
std::string GetDocumentation() const;
/// Sets the documentation string for this prim spec.
SDF_API
void SetDocumentation(const std::string& value);
/// Returns whether this prim spec is active.
///
/// The default value for active is true.
SDF_API
bool GetActive() const;
/// Sets whether this prim spec is active.
SDF_API
void SetActive(bool value);
/// Returns true if this prim spec has an opinion about active.
SDF_API
bool HasActive() const;
/// Removes the active opinion in this prim spec if there is one.
SDF_API
void ClearActive();
/// Returns whether this prim spec will be hidden in browsers.
///
/// The default value for hidden is false.
SDF_API
bool GetHidden() const;
/// Sets whether this prim spec will be hidden in browsers.
SDF_API
void SetHidden( bool value );
/// Returns this prim spec's kind.
///
/// The default value for kind is an empty \c TfToken.
SDF_API
TfToken GetKind() const;
/// Sets this prim spec's kind.
SDF_API
void SetKind(const TfToken& value);
/// Returns true if this prim spec has an opinion about kind.
SDF_API
bool HasKind() const;
/// Remove the kind opinion from this prim spec if there is one.
SDF_API
void ClearKind();
/// Returns the symmetry function for this prim.
///
/// The default value for symmetry function is an empty token.
SDF_API
TfToken GetSymmetryFunction() const;
/// Sets the symmetry function for this prim.
///
/// If \p functionName is an empty token, then this removes any symmetry
/// function for the given prim.
SDF_API
void SetSymmetryFunction(const TfToken& functionName);
/// Returns the symmetry arguments for this prim.
///
/// The default value for symmetry arguments is an empty dictionary.
SDF_API
SdfDictionaryProxy GetSymmetryArguments() const;
/// Sets a symmetry argument for this prim.
///
/// If \p value is empty, then this removes the setting
/// for the given symmetry argument \p name.
SDF_API
void SetSymmetryArgument(const std::string& name, const VtValue& value);
/// Returns the symmetric peer for this prim.
///
/// The default value for symmetric peer is an empty string.
SDF_API
std::string GetSymmetricPeer() const;
/// Sets a symmetric peer for this prim.
///
/// If \p peerName is empty, then this removes the symmetric peer
/// for this prim.
SDF_API
void SetSymmetricPeer(const std::string& peerName);
/// Returns the prefix string for this prim spec.
///
/// The default value for prefix is "".
SDF_API
std::string GetPrefix() const;
/// Sets the prefix string for this prim spec.
SDF_API
void SetPrefix(const std::string& value);
/// Returns the suffix string for this prim spec.
///
/// The default value for suffix is "".
SDF_API
std::string GetSuffix() const;
/// Sets the suffix string for this prim spec.
SDF_API
void SetSuffix(const std::string& value);
/// Returns the custom data for this prim.
///
/// The default value for custom data is an empty dictionary.
///
/// Custom data is for use by plugins or other non-tools supplied
/// extensions that need to be able to store data attached to arbitrary
/// scene objects. Note that if the only objects you want to store data
/// on are prims, using custom attributes is probably a better choice.
/// But if you need to possibly store this data on attributes or
/// relationships or as annotations on reference arcs, then custom data
/// is an appropriate choice.
SDF_API
SdfDictionaryProxy GetCustomData() const;
/// Returns the asset info dictionary for this prim.
///
/// The default value is an empty dictionary.
///
/// The asset info dictionary is used to annotate prims representing the
/// root-prims of assets (generally organized as models) with various
/// data related to asset management. For example, asset name, root layer
/// identifier, asset version etc.
///
SDF_API
SdfDictionaryProxy GetAssetInfo() const;
/// Sets a custom data entry for this prim.
///
/// If \p value is empty, then this removes the given custom data entry.
SDF_API
void SetCustomData(const std::string& name, const VtValue& value);
/// Sets a asset info entry for this prim.
///
/// If \p value is empty, then this removes the given asset info entry.
///
/// \sa GetAssetInfo()
///
SDF_API
void SetAssetInfo(const std::string& name, const VtValue& value);
/// Returns the spec specifier (def, over or class).
SDF_API
SdfSpecifier GetSpecifier() const;
/// Sets the spec specifier (def or over).
SDF_API
void SetSpecifier(SdfSpecifier value);
/// Returns the prim's permission restriction.
///
/// The default value for permission is SdfPermissionPublic.
SDF_API
SdfPermission GetPermission() const;
/// Sets the prim's permission restriction.
SDF_API
void SetPermission(SdfPermission value);
/// Returns the prefixSubstitutions dictionary for this prim spec.
///
/// The default value for prefixSubstitutions is an empty VtDictionary.
SDF_API
VtDictionary GetPrefixSubstitutions() const;
/// Sets the \p prefixSubstitutions dictionary for this prim spec.
SDF_API
void SetPrefixSubstitutions(const VtDictionary& prefixSubstitutions);
/// Returns the suffixSubstitutions dictionary for this prim spec.
///
/// The default value for suffixSubstitutions is an empty VtDictionary.
SDF_API
VtDictionary GetSuffixSubstitutions() const;
/// Sets the \p suffixSubstitutions dictionary for this prim spec.
SDF_API
void SetSuffixSubstitutions(const VtDictionary& suffixSubstitutions);
/// Sets the value for the prim's instanceable flag.
SDF_API
void SetInstanceable(bool instanceable);
/// Returns the value for the prim's instanceable flag.
SDF_API
bool GetInstanceable() const;
/// Returns true if this prim spec has a value authored for its
/// instanceable flag, false otherwise.
SDF_API
bool HasInstanceable() const;
/// Clears the value for the prim's instanceable flag.
SDF_API
void ClearInstanceable();
/// @}
/// \name Payloads
/// @{
/// Returns a proxy for the prim's payloads.
///
/// Payloads for this prim may be modified through the proxy.
SDF_API
SdfPayloadsProxy GetPayloadList() const;
/// Returns true if this prim has payloads set.
SDF_API
bool HasPayloads() const;
/// Clears the payloads for this prim.
SDF_API
void ClearPayloadList();
/// @}
/// \name Inherits
/// @{
/// Returns a proxy for the prim's inherit paths.
///
/// Inherit paths for this prim may be modified through the proxy.
SDF_API
SdfInheritsProxy GetInheritPathList() const;
/// Returns true if this prim has inherit paths set.
SDF_API
bool HasInheritPaths() const;
/// Clears the inherit paths for this prim.
SDF_API
void ClearInheritPathList();
/// @}
/// \name Specializes
/// @{
/// Returns a proxy for the prim's specializes paths.
///
/// Specializes for this prim may be modified through the proxy.
SDF_API
SdfSpecializesProxy GetSpecializesList() const;
/// Returns true if this prim has specializes set.
SDF_API
bool HasSpecializes() const;
/// Clears the specializes for this prim.
SDF_API
void ClearSpecializesList();
/// @}
/// \name References
/// @{
/// Returns a proxy for the prim's references.
///
/// References for this prim may be modified through the proxy.
SDF_API
SdfReferencesProxy GetReferenceList() const;
/// Returns true if this prim has references set.
SDF_API
bool HasReferences() const;
/// Clears the references for this prim.
SDF_API
void ClearReferenceList();
/// @}
/// \name Variants
/// @{
/// Returns a proxy for the prim's variant sets.
///
/// Variant sets for this prim may be modified through the proxy.
SDF_API
SdfVariantSetNamesProxy GetVariantSetNameList() const;
/// Returns true if this prim has variant sets set.
SDF_API
bool HasVariantSetNames() const;
/// Returns list of variant names for the given variant set.
SDF_API
std::vector<std::string> GetVariantNames(const std::string& name) const;
/// Returns the variant sets.
///
/// The result maps variant set names to variant sets. Variant sets
/// may be removed through the proxy.
SDF_API
SdfVariantSetsProxy GetVariantSets() const;
/// Removes the variant set with the given \a name.
///
/// Note that the set's name should probably also be removed from
/// the variant set names list.
SDF_API
void RemoveVariantSet(const std::string& name);
/// Returns an editable map whose keys are variant set names and
/// whose values are the variants selected for each set.
SDF_API
SdfVariantSelectionProxy GetVariantSelections() const;
/// Sets the variant selected for the given variant set.
/// If \p variantName is empty, then this removes the variant
/// selection opinion for the variant set \p variantSetName. To
/// explicitly set the variant selection to be empty, use
/// BlockVariantSelection instead.
SDF_API
void SetVariantSelection(const std::string& variantSetName,
const std::string& variantName);
/// Blocks the variant selected for the given variant set by setting
/// the variant selection to empty.
SDF_API
void BlockVariantSelection(const std::string& variantSetName);
/// @}
/// \name Relocates
/// @{
/// Get an editing proxy for the map of namespace relocations
/// specified on this prim.
///
/// The map of namespace relocation paths is editable in-place via
/// this editing proxy. Individual source-target pairs can be added,
/// removed, or altered using common map operations.
///
/// The map is organized as target \c SdfPath indexed by source \c SdfPath.
/// Key and value paths are stored as absolute regardless of how they're
/// added.
SDF_API
SdfRelocatesMapProxy GetRelocates() const;
/// Set the entire map of namespace relocations specified on this prim.
/// Use the editing proxy for modifying single paths in the map.
SDF_API
void SetRelocates(const SdfRelocatesMap& newMap);
/// Returns true if this prim has any relocates opinion, including
/// that there should be no relocates (i.e. an empty map). An empty
/// map (no relocates) does not mean the same thing as a missing map
/// (no opinion).
SDF_API
bool HasRelocates() const;
/// Clears the relocates opinion for this prim.
SDF_API
void ClearRelocates();
/// @}
private:
// Returns true if this object is the pseudo-root.
bool _IsPseudoRoot() const;
// Raises an error and returns false if this is the pseudo-root,
// otherwise returns true. We want to allow clients to be able
// to use pseudo-roots as any other prim in namespace editing
// operations as well as silently permit read accesses on fields
// pseudo-roots don't actually have in order to promote generic
// algorithm programming. Mutating methods on SdfPrimSpec use
// this function as write access validation.
bool _ValidateEdit(const TfToken& key) const;
private:
static SdfPrimSpecHandle
_New(const SdfPrimSpecHandle &parentPrim,
const TfToken &name, SdfSpecifier spec,
const TfToken &typeName);
};
/// Convenience function to create a prim at the given path, and any
/// necessary parent prims, in the given layer.
///
/// If a prim already exists at the given path it will be returned
/// unmodified.
///
/// The new specs are created with SdfSpecifierOver and an empty type.
/// primPath must be a valid prim path.
SDF_API
SdfPrimSpecHandle SdfCreatePrimInLayer(const SdfLayerHandle& layer,
const SdfPath& primPath);
/// Convenience function to create a prim at the given path, and any
/// necessary parent prims, in the given layer.
///
/// If a prim already exists at the given path, do nothing and return true.
///
/// Any newly created specs have SdfSpecifierOver and an empty type. primPath
/// must be a valid prim path. Return false and issue an error if we fail to
/// author the required scene description.
SDF_API
bool SdfJustCreatePrimInLayer(const SdfLayerHandle& layer,
const SdfPath& primPath);
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_PRIM_SPEC_H
+378
View File
@@ -0,0 +1,378 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_PROPERTY_SPEC_H
#define PXR_USD_SDF_PROPERTY_SPEC_H
/// \file sdf/propertySpec.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/usd/sdf/declareSpec.h"
#include "pxr/usd/sdf/spec.h"
#include "pxr/usd/sdf/declareHandles.h"
#include "pxr/usd/sdf/proxyTypes.h"
#include "pxr/usd/sdf/types.h"
#include "pxr/base/vt/value.h"
#include "pxr/base/tf/declarePtrs.h"
#include "pxr/base/tf/token.h"
#include <iosfwd>
#include <string>
PXR_NAMESPACE_OPEN_SCOPE
/// \class SdfPropertySpec
///
/// Base class for SdfAttributeSpec and SdfRelationshipSpec.
///
/// Scene Spec Attributes (SdfAttributeSpec) and Relationships
/// (SdfRelationshipSpec) are the basic properties that make up Scene Spec Prims
/// (SdfPrimSpec). They share many qualities and can sometimes be treated
/// uniformly. The common qualities are provided by this base class.
///
/// NOTE: Do not use Python reserved words and keywords as attribute names.
/// This will cause attribute resolution to fail.
///
class SdfPropertySpec : public SdfSpec
{
SDF_DECLARE_ABSTRACT_SPEC(SdfPropertySpec, SdfSpec);
public:
///
/// \name Name
/// @{
/// Returns the property's name.
SDF_API
const std::string &GetName() const;
/// Returns the property's name, as a token.
SDF_API
TfToken GetNameToken() const;
/// Returns true if setting the property spec's name to \p newName
/// will succeed.
///
/// Returns false if it won't, and sets \p whyNot with a string
/// describing why not.
SDF_API
bool CanSetName(const std::string &newName, std::string *whyNot) const;
/// Sets the property's name.
///
/// A Prim's properties must be unique by name. Setting the
/// name to the same name as an existing property is an error.
///
/// Setting \p validate to false, will skip validation of the newName
/// (that is, CanSetName will not be called).
SDF_API
bool SetName(const std::string &newName, bool validate = true);
/// Returns true if the given name is considered a valid name for a
/// property. A valid name is not empty, and does not use invalid
/// characters (such as '/', '[', or '.').
SDF_API
static bool IsValidName(const std::string &name);
/// @}
/// \name Ownership
/// @{
/// Returns the owner prim or relationship of this property.
SDF_API
SdfSpecHandle GetOwner() const;
/// @}
/// \name Metadata
/// @{
/// Returns the property's custom data.
///
/// The default value for custom data is an empty dictionary.
///
/// Custom data is for use by plugins or other non-tools supplied
/// extensions that need to be able to store data attached to arbitrary
/// scene objects. Note that if the only objects you want to store data
/// on are prims, using custom attributes is probably a better choice.
/// But if you need to possibly store this data on attributes or
/// relationships or as annotations on reference arcs, then custom data
/// is an appropriate choice.
SDF_API
SdfDictionaryProxy GetCustomData() const;
/// Returns the asset info dictionary for this property.
///
/// The default value is an empty dictionary.
///
/// The asset info dictionary is used to annotate SdfAssetPath-valued
/// attributes pointing to the root-prims of assets (generally organized
/// as models) with various data related to asset management. For example,
/// asset name, root layer identifier, asset version etc.
///
/// \note It is only valid to author assetInfo on attributes that are of
/// type SdfAssetPath.
///
SDF_API
SdfDictionaryProxy GetAssetInfo() const;
/// Sets a property custom data entry.
///
/// If \p value is empty, then this removes the given custom data entry.
SDF_API
void SetCustomData(const std::string &name, const VtValue &value);
/// Sets a asset info entry for this property.
///
/// If \p value is empty, then this removes the given asset info entry.
///
/// \sa GetAssetInfo()
///
SDF_API
void SetAssetInfo(const std::string& name, const VtValue& value);
/// Returns the displayGroup string for this property spec.
///
/// The default value for displayGroup is empty string.
SDF_API
std::string GetDisplayGroup() const;
/// Sets the displayGroup string for this property spec.
SDF_API
void SetDisplayGroup(const std::string &value);
/// Returns the displayName string for this property spec.
///
/// The default value for displayName is empty string.
SDF_API
std::string GetDisplayName() const;
/// Sets the displayName string for this property spec.
SDF_API
void SetDisplayName(const std::string &value);
/// Returns the documentation string for this property spec.
///
/// The default value for documentation is empty string.
SDF_API
std::string GetDocumentation() const;
/// Sets the documentation string for this property spec.
SDF_API
void SetDocumentation(const std::string &value);
/// Returns whether this property spec will be hidden in browsers.
///
/// The default value for hidden is false.
SDF_API
bool GetHidden() const;
/// Sets whether this property spec will be hidden in browsers.
SDF_API
void SetHidden(bool value);
/// Returns the property's permission restriction.
///
/// The default value for permission is SdfPermissionPublic.
SDF_API
SdfPermission GetPermission() const;
/// Sets the property's permission restriction.
SDF_API
void SetPermission(SdfPermission value);
/// Returns the prefix string for this property spec.
///
/// The default value for prefix is "".
SDF_API
std::string GetPrefix() const;
/// Sets the prefix string for this property spec.
SDF_API
void SetPrefix(const std::string &value);
/// Returns the suffix string for this property spec.
///
/// The default value for suffix is "".
SDF_API
std::string GetSuffix() const;
/// Sets the suffix string for this property spec.
SDF_API
void SetSuffix(const std::string &value);
/// Returns the property's symmetric peer.
///
/// The default value for the symmetric peer is an empty string.
SDF_API
std::string GetSymmetricPeer() const;
/// Sets the property's symmetric peer.
///
/// If \p peerName is empty, then this removes any symmetric peer for the
/// given property.
SDF_API
void SetSymmetricPeer(const std::string &peerName);
/// Returns the property's symmetry arguments.
///
/// The default value for symmetry arguments is an empty dictionary.
SDF_API
SdfDictionaryProxy GetSymmetryArguments() const;
/// Sets a property symmetry argument.
///
/// If \p value is empty, then this removes the argument with the given
/// \p name.
SDF_API
void SetSymmetryArgument(const std::string &name, const VtValue &value);
/// Returns the property's symmetry function.
///
/// The default value for the symmetry function is an empty token.
SDF_API
TfToken GetSymmetryFunction() const;
/// Sets the property's symmetry function.
///
/// If \p functionName is empty, then this removes any symmetry function
/// for the given property.
SDF_API
void SetSymmetryFunction(const TfToken &functionName);
/// @}
/// \name Property value API
/// @{
/// Returns the entire set of time samples.
SDF_API
SdfTimeSampleMap GetTimeSampleMap() const;
/// Returns the TfType representing the value type this property holds.
SDF_API
TfType GetValueType() const;
/// Returns the name of the value type that this property holds.
///
/// Returns the typename used to represent the types of value held by
/// this attribute.
SDF_API
SdfValueTypeName GetTypeName() const;
/// Returns the attribute's default value.
///
/// If it doesn't have a default value, an empty VtValue is returned.
SDF_API
VtValue GetDefaultValue() const;
/// Sets the attribute's default value.
///
/// Returns true if successful, false otherwise. Fails if \p defaultValue
/// has wrong type.
SDF_API
bool SetDefaultValue(const VtValue &defaultValue);
/// Returns true if a default value is set for this attribute.
SDF_API
bool HasDefaultValue() const;
/// Clear the attribute's default value.
SDF_API
void ClearDefaultValue();
/// @}
/// \name Spec properties
/// @{
/// Returns the comment string for this property spec.
///
/// The default value for comment is "".
SDF_API
std::string GetComment() const;
/// Sets the comment string for this property spec.
SDF_API
void SetComment(const std::string &value);
/// Returns true if this spec declares a custom property
SDF_API
bool IsCustom() const;
/// Sets whether this spec declares a custom property
SDF_API
void SetCustom(bool custom);
/// Returns the variability of the property.
///
/// An attribute's variability may be \c Varying (the default),
/// \c Uniform, \c Config, or \c Computed.
///
/// A relationship's variability may be \c Varying or \c Uniform (the
/// default)
///
/// <ul>
/// <li>\c Varying attributes may be directly authored, animated and
/// affected by \p Actions. They are the most flexible.
/// Varying relationships can have a default and an anim spline,
/// in addition to a list of targets.
///
/// <li>\c Uniform attributes may be authored only with non-animated
/// values (default values). They cannot be affected by \p Actions,
/// but they can be connected to other Uniform attributes.
/// Uniform relationships have a list of targets but do not have
/// default or anim spline values.
///
/// <li>\c Config attributes are the same as Uniform except that a Prim
/// can choose to alter its collection of built-in properties based
/// on the values of its Config attributes.
///
/// <li>\c Computed attributes may not be authored in scene description.
/// Prims determine the values of their Computed attributes through
/// Prim-specific computation. They may not be connected.
/// </ul>
SDF_API
SdfVariability GetVariability() const;
/// Returns true if this PropertySpec has no significant data other than
/// just what is necessary for instantiation.
///
/// For example, "double foo" has only required fields, but "double foo = 3"
/// has more than just what is required.
///
/// This is similar to IsInert except that IsInert will always return false
/// even for properties that have only required fields; PropertySpecs are
/// never considered inert because even a spec with only required fields
/// will cause instantiation of on-demand properties.
///
SDF_API
bool HasOnlyRequiredFields() const;
private:
inline TfToken _GetAttributeValueTypeName() const;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // #ifndef PXR_USD_SDF_PROPERTY_SPEC_H
+285
View File
@@ -0,0 +1,285 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_PROXY_POLICIES_H
#define PXR_USD_SDF_PROXY_POLICIES_H
/// \file sdf/proxyPolicies.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/usd/sdf/declareHandles.h"
#include "pxr/usd/sdf/path.h"
#include "pxr/usd/sdf/spec.h"
PXR_NAMESPACE_OPEN_SCOPE
class SdfReference;
/// \class SdfNameKeyPolicy
///
/// Key policy for \c std::string names.
///
class SdfNameKeyPolicy {
public:
typedef std::string value_type;
static const value_type& Canonicalize(const value_type& x)
{
return x;
}
static const std::vector<value_type>& Canonicalize(
const std::vector<value_type>& x)
{
return x;
}
};
/// \class SdfNameTokenKeyPolicy
///
/// Key policy for \c TfToken names.
///
class SdfNameTokenKeyPolicy {
public:
typedef TfToken value_type;
static const value_type& Canonicalize(const value_type& x)
{
return x;
}
static const std::vector<value_type>& Canonicalize(
const std::vector<value_type>& x)
{
return x;
}
};
/// \class SdfPathKeyPolicy
///
/// Key policy for \c SdfPath; converts all SdfPaths to absolute.
///
class SdfPathKeyPolicy {
public:
typedef SdfPath value_type;
SdfPathKeyPolicy() { }
explicit SdfPathKeyPolicy(const SdfSpecHandle& owner) : _owner(owner) { }
value_type Canonicalize(const value_type& x) const
{
return _Canonicalize(x, _GetAnchor());
}
std::vector<value_type> Canonicalize(const std::vector<value_type>& x) const
{
if (x.empty()) {
return x;
}
const SdfPath anchor = _GetAnchor();
std::vector<value_type> result = x;
TF_FOR_ALL(it, result) {
*it = _Canonicalize(*it, anchor);
}
return result;
}
private:
// Get the most recent SdfPath of the owning object, for expanding
// relative SdfPaths to absolute
SdfPath _GetAnchor() const
{
return _owner ? _owner->GetPath().GetPrimPath() :
SdfPath::AbsoluteRootPath();
}
value_type _Canonicalize(const value_type& x, const SdfPath& primPath) const
{
return x.IsEmpty() ? value_type() : x.MakeAbsolutePath(primPath);
}
private:
SdfSpecHandle _owner;
};
// Cannot get from a VtValue except as the correct type.
template <>
struct Vt_DefaultValueFactory<SdfPathKeyPolicy> {
static Vt_DefaultValueHolder Invoke() {
TF_AXIOM(false && "Failed VtValue::Get<SdfPathKeyPolicy> not allowed");
return Vt_DefaultValueHolder::Create((void*)0);
}
};
/// \class SdfPayloadTypePolicy
///
/// List editor type policy for \c SdfPayload.
///
class SdfPayloadTypePolicy {
public:
typedef SdfPayload value_type;
static const value_type& Canonicalize(const value_type& x)
{
return x;
}
static const std::vector<value_type>& Canonicalize(
const std::vector<value_type>& x)
{
return x;
}
};
// Cannot get from a VtValue except as the correct type.
template <>
struct Vt_DefaultValueFactory<SdfPayloadTypePolicy> {
static Vt_DefaultValueHolder Invoke() {
TF_AXIOM(false && "Failed VtValue::Get<SdfPayloadTypePolicy> not allowed");
return Vt_DefaultValueHolder::Create((void*)0);
}
};
/// \class SdfReferenceTypePolicy
///
/// List editor type policy for \c SdfReference.
///
class SdfReferenceTypePolicy {
public:
typedef SdfReference value_type;
static const value_type& Canonicalize(const value_type& x)
{
return x;
}
static const std::vector<value_type>& Canonicalize(
const std::vector<value_type>& x)
{
return x;
}
};
// Cannot get from a VtValue except as the correct type.
template <>
struct Vt_DefaultValueFactory<SdfReferenceTypePolicy> {
static Vt_DefaultValueHolder Invoke() {
TF_AXIOM(false && "Failed VtValue::Get<SdfReferenceTypePolicy> not allowed");
return Vt_DefaultValueHolder::Create((void*)0);
}
};
/// \class SdfSubLayerTypePolicy
///
/// List editor type policy for sublayers.
///
class SdfSubLayerTypePolicy {
public:
typedef std::string value_type;
static const value_type& Canonicalize(const value_type& x)
{
return x;
}
static const std::vector<value_type>& Canonicalize(
const std::vector<value_type>& x)
{
return x;
}
};
/// \class SdfRelocatesMapProxyValuePolicy
///
/// Map edit proxy value policy for relocates maps. This absolutizes all
/// paths.
///
class SdfRelocatesMapProxyValuePolicy {
public:
typedef std::map<SdfPath, SdfPath> Type;
typedef Type::key_type key_type;
typedef Type::mapped_type mapped_type;
typedef Type::value_type value_type;
SDF_API
static Type CanonicalizeType(const SdfSpecHandle& v, const Type& x);
SDF_API
static key_type CanonicalizeKey(const SdfSpecHandle& v,
const key_type& x);
SDF_API
static mapped_type CanonicalizeValue(const SdfSpecHandle& v,
const mapped_type& x);
SDF_API
static value_type CanonicalizePair(const SdfSpecHandle& v,
const value_type& x);
};
/// \class SdfGenericSpecViewPredicate
///
/// Predicate for viewing properties.
///
class SdfGenericSpecViewPredicate {
public:
SdfGenericSpecViewPredicate(SdfSpecType type) : _type(type) { }
template <class T>
bool operator()(const SdfHandle<T>& x) const
{
// XXX: x is sometimes null. why?
if (x) {
return x->GetSpecType() == _type;
}
return false;
}
private:
SdfSpecType _type;
};
/// \class SdfAttributeViewPredicate
///
/// Predicate for viewing attributes.
///
class SdfAttributeViewPredicate : public SdfGenericSpecViewPredicate {
public:
SDF_API
SdfAttributeViewPredicate();
};
/// \class SdfRelationshipViewPredicate
///
/// Predicate for viewing relationships.
///
class SdfRelationshipViewPredicate : public SdfGenericSpecViewPredicate {
public:
SDF_API
SdfRelationshipViewPredicate();
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_PROXY_POLICIES_H
+104
View File
@@ -0,0 +1,104 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_PROXY_TYPES_H
#define PXR_USD_SDF_PROXY_TYPES_H
#include "pxr/pxr.h"
#include "pxr/usd/sdf/childrenProxy.h"
#include "pxr/usd/sdf/childrenView.h"
#include "pxr/usd/sdf/childrenPolicies.h"
#include "pxr/usd/sdf/declareHandles.h"
#include "pxr/usd/sdf/listEditorProxy.h"
#include "pxr/usd/sdf/listProxy.h"
#include "pxr/usd/sdf/mapEditProxy.h"
#include "pxr/usd/sdf/proxyPolicies.h"
PXR_NAMESPACE_OPEN_SCOPE
SDF_DECLARE_HANDLES(SdfSpec);
typedef SdfListProxy<SdfNameTokenKeyPolicy> SdfNameOrderProxy;
typedef SdfListProxy<SdfSubLayerTypePolicy> SdfSubLayerProxy;
typedef SdfListEditorProxy<SdfNameKeyPolicy> SdfNameEditorProxy;
typedef SdfListEditorProxy<SdfPathKeyPolicy> SdfPathEditorProxy;
typedef SdfListEditorProxy<SdfPayloadTypePolicy> SdfPayloadEditorProxy;
typedef SdfListEditorProxy<SdfReferenceTypePolicy> SdfReferenceEditorProxy;
typedef SdfChildrenView<Sdf_AttributeChildPolicy,
SdfAttributeViewPredicate> SdfAttributeSpecView;
typedef SdfChildrenView<Sdf_PrimChildPolicy> SdfPrimSpecView;
typedef SdfChildrenView<Sdf_PropertyChildPolicy> SdfPropertySpecView;
typedef SdfChildrenView<Sdf_AttributeChildPolicy > SdfRelationalAttributeSpecView;
typedef SdfChildrenView<Sdf_RelationshipChildPolicy, SdfRelationshipViewPredicate>
SdfRelationshipSpecView;
typedef SdfChildrenView<Sdf_VariantChildPolicy> SdfVariantView;
typedef SdfChildrenView<Sdf_VariantSetChildPolicy> SdfVariantSetView;
typedef SdfChildrenProxy<SdfVariantSetView> SdfVariantSetsProxy;
typedef SdfNameOrderProxy SdfNameChildrenOrderProxy;
typedef SdfNameOrderProxy SdfPropertyOrderProxy;
typedef SdfPathEditorProxy SdfConnectionsProxy;
typedef SdfPathEditorProxy SdfInheritsProxy;
typedef SdfPathEditorProxy SdfSpecializesProxy;
typedef SdfPathEditorProxy SdfTargetsProxy;
typedef SdfPayloadEditorProxy SdfPayloadsProxy;
typedef SdfReferenceEditorProxy SdfReferencesProxy;
typedef SdfNameEditorProxy SdfVariantSetNamesProxy;
typedef SdfMapEditProxy<VtDictionary> SdfDictionaryProxy;
typedef SdfMapEditProxy<SdfVariantSelectionMap> SdfVariantSelectionProxy;
typedef SdfMapEditProxy<SdfRelocatesMap,
SdfRelocatesMapProxyValuePolicy> SdfRelocatesMapProxy;
/// Returns a path list editor proxy for the path list op in the given
/// \p pathField on \p spec. If the value doesn't exist or \p spec is
/// invalid then this returns an invalid list editor.
SdfPathEditorProxy
SdfGetPathEditorProxy(
const SdfSpecHandle& spec, const TfToken& pathField);
/// Returns a reference list editor proxy for the references list op in the
/// given \p referenceField on \p spec. If the value doesn't exist or the object
/// is invalid then this returns an invalid list editor.
SdfReferenceEditorProxy
SdfGetReferenceEditorProxy(
const SdfSpecHandle& spec, const TfToken& referenceField);
/// Returns a payload list editor proxy for the payloads list op in the given
/// \p payloadField on \p spec. If the value doesn't exist or the object is
/// invalid then this returns an invalid list editor.
SdfPayloadEditorProxy
SdfGetPayloadEditorProxy(
const SdfSpecHandle& spec, const TfToken& payloadField);
/// Returns a name order list proxy for the ordering specified in the given
/// \p orderField on \p spec. If the value doesn't exist or the object is
/// invalid then this returns an invalid list editor.
SdfNameOrderProxy
SdfGetNameOrderProxy(
const SdfSpecHandle& spec, const TfToken& orderField);
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_PROXY_TYPES_H
+44
View File
@@ -0,0 +1,44 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_PSEUDO_ROOT_SPEC_H
#define PXR_USD_SDF_PSEUDO_ROOT_SPEC_H
/// \file sdf/pseudoRootSpec.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/declareSpec.h"
#include "pxr/usd/sdf/primSpec.h"
PXR_NAMESPACE_OPEN_SCOPE
SDF_DECLARE_HANDLES(SdfPseudoRootSpec);
class SdfPseudoRootSpec : public SdfPrimSpec
{
SDF_DECLARE_SPEC(SdfPseudoRootSpec, SdfPrimSpec);
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_PSEUDO_ROOT_SPEC_H
+400
View File
@@ -0,0 +1,400 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_PY_CHILDREN_PROXY_H
#define PXR_USD_SDF_PY_CHILDREN_PROXY_H
/// \file sdf/pyChildrenProxy.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/childrenProxy.h"
#include "pxr/base/arch/demangle.h"
#include "pxr/base/tf/pyError.h"
#include "pxr/base/tf/pyUtils.h"
#include "pxr/base/tf/stringUtils.h"
#include <boost/python.hpp>
#include <boost/python/slice.hpp>
PXR_NAMESPACE_OPEN_SCOPE
template <class _View>
class SdfPyChildrenProxy {
public:
typedef _View View;
typedef SdfChildrenProxy<View> Proxy;
typedef typename Proxy::key_type key_type;
typedef typename Proxy::mapped_type mapped_type;
typedef typename Proxy::mapped_vector_type mapped_vector_type;
typedef typename Proxy::size_type size_type;
typedef SdfPyChildrenProxy<View> This;
SdfPyChildrenProxy(const Proxy& proxy) : _proxy(proxy)
{
_Init();
}
SdfPyChildrenProxy(const View& view, const std::string& type,
int permission = Proxy::CanSet |
Proxy::CanInsert |
Proxy::CanErase) :
_proxy(view, type, permission)
{
_Init();
}
bool operator==(const This& other) const
{
return _proxy == other._proxy;
}
bool operator!=(const This& other) const
{
return _proxy != other._proxy;
}
private:
typedef typename Proxy::const_iterator _const_iterator;
typedef typename View::const_iterator _view_const_iterator;
struct _ExtractItem {
static boost::python::object Get(const _const_iterator& i)
{
return boost::python::make_tuple(i->first, i->second);
}
};
struct _ExtractKey {
static boost::python::object Get(const _const_iterator& i)
{
return boost::python::object(i->first);
}
};
struct _ExtractValue {
static boost::python::object Get(const _const_iterator& i)
{
return boost::python::object(i->second);
}
};
template <class E>
class _Iterator {
public:
_Iterator(const boost::python::object& object) :
_object(object),
_owner(boost::python::extract<const This&>(object)()._proxy)
{
_cur = _owner.begin();
}
_Iterator<E> GetCopy() const
{
return *this;
}
boost::python::object GetNext()
{
if (_cur == _owner.end()) {
TfPyThrowStopIteration("End of ChildrenProxy iteration");
}
boost::python::object result = E::Get(_cur);
++_cur;
return result;
}
private:
boost::python::object _object;
const Proxy& _owner;
_const_iterator _cur;
};
void _Init()
{
TfPyWrapOnce<This>(&This::_Wrap);
}
static void _Wrap()
{
using namespace boost::python;
std::string name = _GetName();
scope thisScope =
class_<This>(name.c_str(), no_init)
.def("__repr__", &This::_GetRepr, TfPyRaiseOnError<>())
.def("__len__", &This::_GetSize, TfPyRaiseOnError<>())
.def("__getitem__", &This::_GetItemByKey, TfPyRaiseOnError<>())
.def("__getitem__", &This::_GetItemByIndex, TfPyRaiseOnError<>())
.def("__setitem__", &This::_SetItemByKey, TfPyRaiseOnError<>())
.def("__setitem__", &This::_SetItemBySlice, TfPyRaiseOnError<>())
.def("__delitem__", &This::_DelItemByKey, TfPyRaiseOnError<>())
.def("__delitem__", &This::_DelItemByIndex, TfPyRaiseOnError<>())
.def("__contains__", &This::_HasKey, TfPyRaiseOnError<>())
.def("__contains__", &This::_HasValue, TfPyRaiseOnError<>())
.def("__iter__", &This::_GetValueIterator, TfPyRaiseOnError<>())
.def("clear", &This::_Clear, TfPyRaiseOnError<>())
.def("append", &This::_AppendItem, TfPyRaiseOnError<>())
.def("insert", &This::_InsertItemByIndex, TfPyRaiseOnError<>())
.def("get", &This::_PyGet, TfPyRaiseOnError<>())
.def("get", &This::_PyGetDefault, TfPyRaiseOnError<>())
#if PY_MAJOR_VERSION < 3
.def("has_key", &This::_HasKey, TfPyRaiseOnError<>())
.def("itervalues", &This::_GetValueIterator, TfPyRaiseOnError<>())
.def("iterkeys", &This::_GetKeyIterator, TfPyRaiseOnError<>())
.def("iteritems", &This::_GetItemIterator, TfPyRaiseOnError<>())
.def("items", &This::_GetItems, TfPyRaiseOnError<>())
.def("keys", &This::_GetKeys, TfPyRaiseOnError<>())
.def("values", &This::_GetValues, TfPyRaiseOnError<>())
#else
.def("items", &This::_GetItemIterator, TfPyRaiseOnError<>())
.def("keys", &This::_GetKeyIterator, TfPyRaiseOnError<>())
.def("values", &This::_GetValueIterator, TfPyRaiseOnError<>())
#endif
.def("index", &This::_FindIndexByKey, TfPyRaiseOnError<>())
.def("index", &This::_FindIndexByValue, TfPyRaiseOnError<>())
.def("__eq__", &This::operator==, TfPyRaiseOnError<>())
.def("__ne__", &This::operator!=, TfPyRaiseOnError<>())
;
class_<_Iterator<_ExtractItem> >
((name + "_Iterator").c_str(), no_init)
.def("__iter__", &This::template _Iterator<_ExtractItem>::GetCopy)
.def(TfPyIteratorNextMethodName, &This::template _Iterator<_ExtractItem>::GetNext)
;
class_<_Iterator<_ExtractKey> >
((name + "_KeyIterator").c_str(), no_init)
.def("__iter__", &This::template _Iterator<_ExtractKey>::GetCopy)
.def(TfPyIteratorNextMethodName, &This::template _Iterator<_ExtractKey>::GetNext)
;
class_<_Iterator<_ExtractValue> >
((name + "_ValueIterator").c_str(), no_init)
.def("__iter__", &This::template _Iterator<_ExtractValue>::GetCopy)
.def(TfPyIteratorNextMethodName, &This::template _Iterator<_ExtractValue>::GetNext)
;
}
static std::string _GetName()
{
std::string name = "ChildrenProxy_" +
ArchGetDemangled<View>();
name = TfStringReplace(name, " ", "_");
name = TfStringReplace(name, ",", "_");
name = TfStringReplace(name, "::", "_");
name = TfStringReplace(name, "<", "_");
name = TfStringReplace(name, ">", "_");
return name;
}
const View& _GetView() const
{
return _proxy._view;
}
View& _GetView()
{
return _proxy._view;
}
std::string _GetRepr() const
{
std::string result("{");
if (! _proxy.empty()) {
_const_iterator i = _proxy.begin(), n = _proxy.end();
result += TfPyRepr(i->first) + ": " + TfPyRepr(i->second);
while (++i != n) {
result += ", " + TfPyRepr(i->first) +
": " + TfPyRepr(i->second);
}
}
result += "}";
return result;
}
size_type _GetSize() const
{
return _proxy.size();
}
mapped_type _GetItemByKey(const key_type& key) const
{
_view_const_iterator i = _GetView().find(key);
if (i == _GetView().end()) {
TfPyThrowIndexError(TfPyRepr(key));
return mapped_type();
}
else {
return *i;
}
}
mapped_type _GetItemByIndex(int index) const
{
index = TfPyNormalizeIndex(index, _proxy.size(), true /*throwError*/);
return _GetView()[index];
}
void _SetItemByKey(const key_type& key, const mapped_type& value)
{
TF_CODING_ERROR("can't directly reparent a %s",
_proxy._GetType().c_str());
}
void _SetItemBySlice(const boost::python::slice& slice,
const mapped_vector_type& values)
{
if (! TfPyIsNone(slice.start()) ||
! TfPyIsNone(slice.stop()) ||
! TfPyIsNone(slice.step())) {
TfPyThrowIndexError("can only assign to full slice [:]");
}
else {
_proxy._Copy(values);
}
}
void _DelItemByKey(const key_type& key)
{
if (_GetView().find(key) == _GetView().end()) {
TfPyThrowIndexError(TfPyRepr(key));
}
_proxy._Erase(key);
}
void _DelItemByIndex(int index)
{
_proxy._Erase(_GetView().key(_GetItemByIndex(index)));
}
void _Clear()
{
_proxy._Copy(mapped_vector_type());
}
void _AppendItem(const mapped_type& value)
{
_proxy._Insert(value, _proxy.size());
}
void _InsertItemByIndex(int index, const mapped_type& value)
{
// Note that -1 below means to insert at end for the _proxy._Insert API.
index = index < (int)_proxy.size()
? TfPyNormalizeIndex(index, _proxy.size(), false /*throwError*/)
: -1;
_proxy._Insert(value, index);
}
boost::python::object _PyGet(const key_type& key) const
{
_view_const_iterator i = _GetView().find(key);
return i == _GetView().end() ? boost::python::object() :
boost::python::object(*i);
}
boost::python::object _PyGetDefault(const key_type& key,
const mapped_type& def) const
{
_view_const_iterator i = _GetView().find(key);
return i == _GetView().end() ? boost::python::object(def) :
boost::python::object(*i);
}
bool _HasKey(const key_type& key) const
{
return _GetView().find(key) != _GetView().end();
}
bool _HasValue(const mapped_type& value) const
{
return _GetView().find(value) != _GetView().end();
}
static
_Iterator<_ExtractItem> _GetItemIterator(const boost::python::object &x)
{
return _Iterator<_ExtractItem>(x);
}
static
_Iterator<_ExtractKey> _GetKeyIterator(const boost::python::object &x)
{
return _Iterator<_ExtractKey>(x);
}
static
_Iterator<_ExtractValue> _GetValueIterator(const boost::python::object &x)
{
return _Iterator<_ExtractValue>(x);
}
template <class E>
boost::python::list _Get() const
{
boost::python::list result;
for (_const_iterator i = _proxy.begin(), n = _proxy.end(); i != n; ++i){
result.append(E::Get(i));
}
return result;
}
#if PY_MAJOR_VERSION < 3
boost::python::list _GetItems() const
{
return _Get<_ExtractItem>();
}
boost::python::list _GetKeys() const
{
return _Get<_ExtractKey>();
}
boost::python::list _GetValues() const
{
return _Get<_ExtractValue>();
}
#endif
int _FindIndexByKey(const key_type& key) const
{
size_t i = std::distance(_GetView().begin(), _GetView().find(key));
return i == _GetView().size() ? -1 : i;
}
int _FindIndexByValue(const mapped_type& value) const
{
size_t i = std::distance(_GetView().begin(), _GetView().find(value));
return i == _GetView().size() ? -1 : i;
}
private:
Proxy _proxy;
template <class E> friend class _Iterator;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_PY_CHILDREN_PROXY_H
+292
View File
@@ -0,0 +1,292 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_PY_CHILDREN_VIEW_H
#define PXR_USD_SDF_PY_CHILDREN_VIEW_H
/// \file sdf/pyChildrenView.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/childrenView.h"
#include "pxr/base/arch/demangle.h"
#include "pxr/base/tf/pyUtils.h"
#include "pxr/base/tf/stringUtils.h"
#include <boost/python.hpp>
PXR_NAMESPACE_OPEN_SCOPE
template <class _View>
class SdfPyWrapChildrenView {
public:
typedef _View View;
typedef typename View::ChildPolicy ChildPolicy;
typedef typename View::Predicate Predicate;
typedef typename View::key_type key_type;
typedef typename View::value_type value_type;
typedef typename View::const_iterator const_iterator;
typedef SdfPyWrapChildrenView<View> This;
SdfPyWrapChildrenView()
{
TfPyWrapOnce<View>(&This::_Wrap);
}
private:
struct _ExtractItem {
static boost::python::object Get(const View& x, const const_iterator& i)
{
return boost::python::make_tuple(x.key(i), *i);
}
};
struct _ExtractKey {
static boost::python::object Get(const View& x, const const_iterator& i)
{
return boost::python::object(x.key(i));
}
};
struct _ExtractValue {
static boost::python::object Get(const View& x, const const_iterator& i)
{
return boost::python::object(*i);
}
};
template <class E>
class _Iterator {
public:
_Iterator(const boost::python::object& object) :
_object(object),
_owner(boost::python::extract<const View&>(object)),
_cur(_owner.begin()),
_end(_owner.end())
{
// Do nothing
}
_Iterator<E> GetCopy() const
{
return *this;
}
boost::python::object GetNext()
{
if (_cur == _end) {
TfPyThrowStopIteration("End of ChildrenProxy iteration");
}
boost::python::object result = E::Get(_owner, _cur);
++_cur;
return result;
}
private:
boost::python::object _object;
const View& _owner;
const_iterator _cur;
const_iterator _end;
};
static void _Wrap()
{
using namespace boost::python;
std::string name = _GetName();
// Note: Using the value iterator for the __iter__ method is not
// consistent with Python dicts (which iterate over keys).
// However, we're emulating TfPyKeyedVector, which iterates
// over values as a vector would.
scope thisScope =
class_<View>(name.c_str(), no_init)
.def("__repr__", &This::_GetRepr)
.def("__len__", &View::size)
.def("__getitem__", &This::_GetItemByKey)
.def("__getitem__", &This::_GetItemByIndex)
.def("get", &This::_PyGet)
.def("__contains__", &This::_HasKey)
.def("__contains__", &This::_HasValue)
.def("__iter__", &This::_GetValueIterator)
#if PY_MAJOR_VERSION < 3
.def("has_key", &This::_HasKey)
.def("itervalues", &This::_GetValueIterator)
.def("iterkeys", &This::_GetKeyIterator)
.def("iteritems", &This::_GetItemIterator)
.def("items", &This::_GetItems)
.def("keys", &This::_GetKeys)
.def("values", &This::_GetValues)
#else
.def("items", &This::_GetItemIterator)
.def("keys", &This::_GetKeyIterator)
.def("values", &This::_GetValueIterator)
#endif
.def("index", &This::_FindIndexByKey)
.def("index", &This::_FindIndexByValue)
.def(self == self)
.def(self != self)
;
class_<_Iterator<_ExtractItem> >
((name + "_Iterator").c_str(), no_init)
.def("__iter__", &This::template _Iterator<_ExtractItem>::GetCopy)
.def(TfPyIteratorNextMethodName, &This::template _Iterator<_ExtractItem>::GetNext)
;
class_<_Iterator<_ExtractKey> >
((name + "_KeyIterator").c_str(), no_init)
.def("__iter__", &This::template _Iterator<_ExtractKey>::GetCopy)
.def(TfPyIteratorNextMethodName, &This::template _Iterator<_ExtractKey>::GetNext)
;
class_<_Iterator<_ExtractValue> >
((name + "_ValueIterator").c_str(), no_init)
.def("__iter__", &This::template _Iterator<_ExtractValue>::GetCopy)
.def(TfPyIteratorNextMethodName, &This::template _Iterator<_ExtractValue>::GetNext)
;
}
static std::string _GetName()
{
std::string name = "ChildrenView_" +
ArchGetDemangled<ChildPolicy>() + "_" +
ArchGetDemangled<Predicate>();
name = TfStringReplace(name, " ", "_");
name = TfStringReplace(name, ",", "_");
name = TfStringReplace(name, "::", "_");
name = TfStringReplace(name, "<", "_");
name = TfStringReplace(name, ">", "_");
return name;
}
static std::string _GetRepr(const View& x)
{
std::string result("{");
if (! x.empty()) {
const_iterator i = x.begin(), n = x.end();
result += TfPyRepr(x.key(i)) + ": " + TfPyRepr(*i);
while (++i != n) {
result += ", " + TfPyRepr(x.key(i)) + ": " + TfPyRepr(*i);
}
}
result += "}";
return result;
}
static value_type _GetItemByKey(const View& x, const key_type& key)
{
const_iterator i = x.find(key);
if (i == x.end()) {
TfPyThrowIndexError(TfPyRepr(key));
return value_type();
}
else {
return *i;
}
}
static value_type _GetItemByIndex(const View& x, size_t index)
{
if (index >= x.size()) {
TfPyThrowIndexError("list index out of range");
}
return x[index];
}
static boost::python::object _PyGet(const View& x, const key_type& key)
{
const_iterator i = x.find(key);
return i == x.end() ? boost::python::object() :
boost::python::object(*i);
}
static bool _HasKey(const View& x, const key_type& key)
{
return x.find(key) != x.end();
}
static bool _HasValue(const View& x, const value_type& value)
{
return x.find(value) != x.end();
}
static
_Iterator<_ExtractItem> _GetItemIterator(const boost::python::object& x)
{
return _Iterator<_ExtractItem>(x);
}
static
_Iterator<_ExtractKey> _GetKeyIterator(const boost::python::object& x)
{
return _Iterator<_ExtractKey>(x);
}
static
_Iterator<_ExtractValue> _GetValueIterator(const boost::python::object& x)
{
return _Iterator<_ExtractValue>(x);
}
template <class E>
static boost::python::list _Get(const View& x)
{
boost::python::list result;
for (const_iterator i = x.begin(), n = x.end(); i != n; ++i) {
result.append(E::Get(x, i));
}
return result;
}
#if PY_MAJOR_VERSION < 3
static boost::python::list _GetItems(const View& x)
{
return _Get<_ExtractItem>(x);
}
static boost::python::list _GetKeys(const View& x)
{
return _Get<_ExtractKey>(x);
}
static boost::python::list _GetValues(const View& x)
{
return _Get<_ExtractValue>(x);
}
#endif
static int _FindIndexByKey(const View& x, const key_type& key)
{
size_t i = std::distance(x.begin(), x.find(key));
return i == x.size() ? -1 : i;
}
static int _FindIndexByValue(const View& x, const value_type& value)
{
size_t i = std::distance(x.begin(), x.find(value));
return i == x.size() ? -1 : i;
}
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_PY_CHILDREN_VIEW_H
+261
View File
@@ -0,0 +1,261 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_PY_LIST_EDITOR_PROXY_H
#define PXR_USD_SDF_PY_LIST_EDITOR_PROXY_H
/// \file sdf/pyListEditorProxy.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/listEditorProxy.h"
#include "pxr/usd/sdf/listOp.h"
#include "pxr/usd/sdf/pyListProxy.h"
#include "pxr/base/arch/demangle.h"
#include "pxr/base/tf/diagnostic.h"
#include "pxr/base/tf/pyCall.h"
#include "pxr/base/tf/pyResultConversions.h"
#include "pxr/base/tf/pyLock.h"
#include "pxr/base/tf/pyUtils.h"
#include "pxr/base/tf/stringUtils.h"
#include <boost/python.hpp>
PXR_NAMESPACE_OPEN_SCOPE
class Sdf_PyListEditorUtils {
public:
template <class T, class V>
class ApplyHelper {
public:
ApplyHelper(const T& owner, const boost::python::object& callback) :
_owner(owner),
_callback(callback)
{
// Do nothing
}
boost::optional<V> operator()(SdfListOpType op, const V& value)
{
using namespace boost::python;
TfPyLock pyLock;
object result = _callback(_owner, value, op);
if (! TfPyIsNone(result)) {
extract<V> e(result);
if (e.check()) {
return boost::optional<V>(e());
}
else {
TF_CODING_ERROR("ApplyEditsToList callback has "
"incorrect return type.");
}
}
return boost::optional<V>();
}
private:
const T& _owner;
TfPyCall<boost::python::object> _callback;
};
template <class V>
class ModifyHelper {
public:
ModifyHelper(const boost::python::object& callback) :
_callback(callback)
{
// Do nothing
}
boost::optional<V> operator()(const V& value)
{
using namespace boost::python;
TfPyLock pyLock;
object result = _callback(value);
if (! TfPyIsNone(result)) {
extract<V> e(result);
if (e.check()) {
return boost::optional<V>(e());
}
else {
TF_CODING_ERROR("ModifyItemEdits callback has "
"incorrect return type.");
}
}
return boost::optional<V>();
}
private:
TfPyCall<boost::python::object> _callback;
};
};
template <class T>
class SdfPyWrapListEditorProxy {
public:
typedef T Type;
typedef typename Type::TypePolicy TypePolicy;
typedef typename Type::value_type value_type;
typedef typename Type::value_vector_type value_vector_type;
typedef typename Type::ApplyCallback ApplyCallback;
typedef typename Type::ModifyCallback ModifyCallback;
typedef SdfPyWrapListEditorProxy<Type> This;
typedef SdfListProxy<TypePolicy> ListProxy;
SdfPyWrapListEditorProxy()
{
TfPyWrapOnce<Type>(&This::_Wrap);
SdfPyWrapListProxy<ListProxy>();
}
private:
static void _Wrap()
{
using namespace boost::python;
class_<Type>(_GetName().c_str(), no_init)
.def("__str__", &This::_GetStr)
.add_property("isExpired", &Type::IsExpired)
.add_property("explicitItems",
&Type::GetExplicitItems,
&This::_SetExplicitProxy)
.add_property("addedItems",
&Type::GetAddedItems,
&This::_SetAddedProxy)
.add_property("prependedItems",
&Type::GetPrependedItems,
&This::_SetPrependedProxy)
.add_property("appendedItems",
&Type::GetAppendedItems,
&This::_SetAppendedProxy)
.add_property("deletedItems",
&Type::GetDeletedItems,
&This::_SetDeletedProxy)
.add_property("orderedItems",
&Type::GetOrderedItems,
&This::_SetOrderedProxy)
.def("GetAddedOrExplicitItems", &Type::GetAddedOrExplicitItems,
return_value_policy<TfPySequenceToTuple>())
.add_property("isExplicit", &Type::IsExplicit)
.add_property("isOrderedOnly", &Type::IsOrderedOnly)
.def("ApplyEditsToList",
&This::_ApplyEditsToList,
return_value_policy<TfPySequenceToList>())
.def("ApplyEditsToList",
&This::_ApplyEditsToList2,
return_value_policy<TfPySequenceToList>())
.def("CopyItems", &Type::CopyItems)
.def("ClearEdits", &Type::ClearEdits)
.def("ClearEditsAndMakeExplicit", &Type::ClearEditsAndMakeExplicit)
.def("ContainsItemEdit", &Type::ContainsItemEdit,
(arg("item"), arg("onlyAddOrExplicit")=false))
.def("RemoveItemEdits", &Type::RemoveItemEdits)
.def("ReplaceItemEdits", &Type::ReplaceItemEdits)
.def("ModifyItemEdits", &This::_ModifyEdits)
// New API (see bug 8710)
.def("Add", &Type::Add)
.def("Prepend", &Type::Prepend)
.def("Append", &Type::Append)
.def("Remove", &Type::Remove)
.def("Erase", &Type::Erase)
;
}
static std::string _GetName()
{
std::string name = "ListEditorProxy_" +
ArchGetDemangled<TypePolicy>();
name = TfStringReplace(name, " ", "_");
name = TfStringReplace(name, ",", "_");
name = TfStringReplace(name, "::", "_");
name = TfStringReplace(name, "<", "_");
name = TfStringReplace(name, ">", "_");
return name;
}
static std::string _GetStr(const Type& x)
{
return x._listEditor ?
boost::lexical_cast<std::string>(*x._listEditor) : std::string();
}
static void _SetExplicitProxy(Type& x, const value_vector_type& v)
{
x.GetExplicitItems() = v;
}
static void _SetAddedProxy(Type& x, const value_vector_type& v)
{
x.GetAddedItems() = v;
}
static void _SetPrependedProxy(Type& x, const value_vector_type& v)
{
x.GetPrependedItems() = v;
}
static void _SetAppendedProxy(Type& x, const value_vector_type& v)
{
x.GetAppendedItems() = v;
}
static void _SetDeletedProxy(Type& x, const value_vector_type& v)
{
x.GetDeletedItems() = v;
}
static void _SetOrderedProxy(Type& x, const value_vector_type& v)
{
x.GetOrderedItems() = v;
}
static value_vector_type _ApplyEditsToList(const Type& x,
const value_vector_type& v)
{
value_vector_type tmp = v;
x.ApplyEditsToList(&tmp);
return tmp;
}
static value_vector_type _ApplyEditsToList2(const Type& x,
const value_vector_type& v,
const boost::python::object& cb)
{
value_vector_type tmp = v;
x.ApplyEditsToList(&tmp,
Sdf_PyListEditorUtils::ApplyHelper<Type, value_type>(x, cb));
return tmp;
}
static void _ModifyEdits(Type& x, const boost::python::object& cb)
{
x.ModifyItemEdits(Sdf_PyListEditorUtils::ModifyHelper<value_type>(cb));
}
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_PY_LIST_EDITOR_PROXY_H
+149
View File
@@ -0,0 +1,149 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_PY_LIST_OP_H
#define PXR_USD_SDF_PY_LIST_OP_H
#include "pxr/pxr.h"
#include "pxr/usd/sdf/listOp.h"
#include "pxr/base/arch/demangle.h"
#include "pxr/base/tf/pyUtils.h"
#include "pxr/base/tf/stringUtils.h"
#include <boost/python.hpp>
PXR_NAMESPACE_OPEN_SCOPE
/// \class SdfPyWrapListOp
///
/// Helper class for wrapping SdfListOp objects for Python. The template
/// parameter is the specific SdfListOp type being wrapped (e.g.,
/// SdfPathListOp)
///
template <class T>
class SdfPyWrapListOp {
public:
typedef typename T::ItemType ItemType;
typedef typename T::ItemVector ItemVector;
typedef SdfPyWrapListOp<T> This;
SdfPyWrapListOp(const std::string& name)
{
TfPyWrapOnce<T>([name]() { SdfPyWrapListOp::_Wrap(name); });
}
private:
static ItemVector _ApplyOperations1(const T& listOp, ItemVector input) {
ItemVector result = input;
listOp.ApplyOperations(&result);
return result;
}
static boost::python::object
_ApplyOperations2(const T& outer, const T& inner) {
if (boost::optional<T> r = outer.ApplyOperations(inner)) {
return boost::python::object(*r);
} else {
return boost::python::object();
}
}
static void _Wrap(const std::string& name)
{
using namespace boost::python;
using ItemVector = typename T::ItemVector;
class_<T>(name.c_str())
.def("__str__", &This::_GetStr)
.def("Create", &T::Create,
(arg("prependedItems") = ItemVector(),
arg("appendedItems") = ItemVector(),
arg("deletedItems") = ItemVector()))
.staticmethod("Create")
.def("CreateExplicit", &T::CreateExplicit,
(arg("explicitItems") = ItemVector()))
.staticmethod("CreateExplicit")
.def(self == self)
.def(self != self)
.def("HasItem", &T::HasItem)
.def("Clear", &T::Clear)
.def("ClearAndMakeExplicit", &T::ClearAndMakeExplicit)
.def("ApplyOperations", &This::_ApplyOperations1)
.def("ApplyOperations", &This::_ApplyOperations2)
.add_property("explicitItems",
make_function(&T::GetExplicitItems,
return_value_policy<return_by_value>()),
&T::SetExplicitItems)
.add_property("addedItems",
make_function(&T::GetAddedItems,
return_value_policy<return_by_value>()),
&T::SetAddedItems)
.add_property("prependedItems",
make_function(&T::GetPrependedItems,
return_value_policy<return_by_value>()),
&T::SetPrependedItems)
.add_property("appendedItems",
make_function(&T::GetAppendedItems,
return_value_policy<return_by_value>()),
&T::SetAppendedItems)
.add_property("deletedItems",
make_function(&T::GetDeletedItems,
return_value_policy<return_by_value>()),
&T::SetDeletedItems)
.add_property("orderedItems",
make_function(&T::GetOrderedItems,
return_value_policy<return_by_value>()),
&T::SetOrderedItems)
.def("GetAddedOrExplicitItems",
&This::_GetAddedOrExplicitItems)
.add_property("isExplicit", &T::IsExplicit)
;
}
static std::string _GetStr(const T& listOp)
{
return TfStringify(listOp);
}
static
ItemVector _GetAddedOrExplicitItems(const T& listOp)
{
ItemVector result;
listOp.ApplyOperations(&result);
return result;
}
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_PY_LIST_OP_H
+274
View File
@@ -0,0 +1,274 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_PY_LIST_PROXY_H
#define PXR_USD_SDF_PY_LIST_PROXY_H
/// \file sdf/pyListProxy.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/changeBlock.h"
#include "pxr/usd/sdf/listProxy.h"
#include "pxr/base/arch/demangle.h"
#include "pxr/base/tf/pyLock.h"
#include "pxr/base/tf/pyUtils.h"
#include "pxr/base/tf/pyResultConversions.h"
#include "pxr/base/tf/stringUtils.h"
#include <stdexcept>
#include <boost/python.hpp>
#include <boost/python/slice.hpp>
PXR_NAMESPACE_OPEN_SCOPE
template <class T>
class SdfPyWrapListProxy {
public:
typedef T Type;
typedef typename Type::TypePolicy TypePolicy;
typedef typename Type::value_type value_type;
typedef typename Type::value_vector_type value_vector_type;
typedef SdfPyWrapListProxy<Type> This;
SdfPyWrapListProxy()
{
TfPyWrapOnce<Type>(&This::_Wrap);
}
private:
static void _Wrap()
{
using namespace boost::python;
class_<Type>(_GetName().c_str(), no_init)
.def("__str__", &This::_GetStr)
.def("__len__", &Type::size)
.def("__getitem__", &This::_GetItemIndex)
.def("__getitem__", &This::_GetItemSlice)
.def("__setitem__", &This::_SetItemIndex)
.def("__setitem__", &This::_SetItemSlice)
.def("__delitem__", &This::_DelItemIndex)
.def("__delitem__", &This::_DelItemSlice)
.def("__delitem__", &Type::Remove)
.def("count", &Type::Count)
.def("copy", &Type::operator value_vector_type,
return_value_policy<TfPySequenceToList>())
.def("index", &This::_FindIndex)
.def("clear", &Type::clear)
.def("insert", &This::_Insert)
.def("append", &Type::push_back)
.def("remove", &Type::Remove)
.def("replace", &Type::Replace)
.def("ApplyList", &Type::ApplyList)
.def("ApplyEditsToList", &This::_ApplyEditsToList)
.add_property("expired", &This::_IsExpired)
.def(self == self)
.def(self != self)
.def(self < self)
.def(self <= self)
.def(self > self)
.def(self >= self)
.def(self == other<value_vector_type>())
.def(self != other<value_vector_type>())
.def(self < other<value_vector_type>())
.def(self <= other<value_vector_type>())
.def(self > other<value_vector_type>())
.def(self >= other<value_vector_type>())
;
}
static std::string _GetName()
{
std::string name = "ListProxy_" +
ArchGetDemangled<TypePolicy>();
name = TfStringReplace(name, " ", "_");
name = TfStringReplace(name, ",", "_");
name = TfStringReplace(name, "::", "_");
name = TfStringReplace(name, "<", "_");
name = TfStringReplace(name, ">", "_");
return name;
}
static std::string _GetStr(const Type& x)
{
return TfPyRepr(static_cast<value_vector_type>(x));
}
static value_type _GetItemIndex(const Type& x, int index)
{
return x[TfPyNormalizeIndex(index, x._GetSize(), true)];
}
static boost::python::list _GetItemSlice(const Type& x,
const boost::python::slice& index)
{
using namespace boost::python;
list result;
if (x._Validate()) {
try {
slice::range<typename Type::const_iterator> range =
index.get_indicies(x.begin(), x.end());
for (; range.start != range.stop; range.start += range.step) {
result.append(*range.start);
}
result.append(*range.start);
}
catch (const std::invalid_argument&) {
// Ignore.
}
}
return result;
}
static void _SetItemIndex(Type& x, int index, const value_type& value)
{
x[TfPyNormalizeIndex(index, x._GetSize(), true)] = value;
}
static void _SetItemSlice(Type& x, const boost::python::slice& index,
const value_vector_type& values)
{
using namespace boost::python;
if (! x._Validate()) {
return;
}
// Get the range and the number of items in the slice.
size_t start, step, count;
try {
slice::range<typename Type::iterator> range =
index.get_indicies(x.begin(), x.end());
start = range.start - x.begin();
step = range.step;
count = 1 + (range.stop - range.start) / range.step;
}
catch (const std::invalid_argument&) {
// Empty range.
extract<int> e(index.start());
start = e.check() ? TfPyNormalizeIndex(e(), x._GetSize(), true) : 0;
step = 0;
count = 0;
}
if (TfPyIsNone(index.step())) {
// Replace contiguous sequence with values.
x._Edit(start, count, values);
}
else {
// Replace exactly the selected items.
if (count != values.size()) {
TfPyThrowValueError(
TfStringPrintf("attempt to assign sequence of size %zd "
"to extended slice of size %zd",
values.size(), count).c_str());
}
else if (step == 1) {
x._Edit(start, count, values);
}
else {
SdfChangeBlock block;
for (size_t i = 0, j = start; i != count; j += step, ++i) {
x._Edit(j, 1, value_vector_type(1, values[i]));
}
}
}
}
static void _DelItemIndex(Type& x, int i)
{
x._Edit(TfPyNormalizeIndex(i, x._GetSize(), true),
1, value_vector_type());
}
static void _DelItemSlice(Type& x, const boost::python::slice& index)
{
using namespace boost::python;
if (x._Validate()) {
try {
// Get the range and the number of items in the slice.
slice::range<typename Type::iterator> range =
index.get_indicies(x.begin(), x.end());
size_t start = range.start - x.begin();
size_t step = range.step;
size_t count = 1 + (range.stop - range.start) / range.step;
// Erase items.
if (step == 1) {
x._Edit(start, count, value_vector_type());
}
else {
SdfChangeBlock block;
value_vector_type empty;
for (size_t j = start; count > 0; j += step - 1, --count) {
x._Edit(j, 1, empty);
}
}
}
catch (const std::invalid_argument&) {
// Empty slice -- do nothing.
}
}
}
static int _FindIndex(const Type& x, const value_type& value)
{
if (x._Validate()) {
return static_cast<int>(x.Find(value));
}
else {
return -1;
}
}
static void _Insert(Type& x, int index, const value_type& value)
{
if (index < 0) {
index += x._GetSize();
}
if (index < 0 || index > static_cast<int>(x._GetSize())) {
TfPyThrowIndexError("list index out of range");
}
x._Edit(index, 0, value_vector_type(1, value));
}
static bool _IsExpired(const Type& x)
{
return x.IsExpired();
}
static value_vector_type _ApplyEditsToList(Type& x,
const value_vector_type& values)
{
value_vector_type newValues = values;
x.ApplyEditsToList(&newValues);
return newValues;
}
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_PY_LIST_PROXY_H
+383
View File
@@ -0,0 +1,383 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_PY_MAP_EDIT_PROXY_H
#define PXR_USD_SDF_PY_MAP_EDIT_PROXY_H
/// \file sdf/pyMapEditProxy.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/changeBlock.h"
#include "pxr/base/arch/demangle.h"
#include "pxr/base/tf/iterator.h"
#include "pxr/base/tf/pyUtils.h"
#include "pxr/base/tf/stringUtils.h"
#include <boost/python.hpp>
PXR_NAMESPACE_OPEN_SCOPE
template <class T>
class SdfPyWrapMapEditProxy {
public:
typedef T Type;
typedef typename Type::key_type key_type;
typedef typename Type::mapped_type mapped_type;
typedef typename Type::value_type value_type;
typedef typename Type::iterator iterator;
typedef typename Type::const_iterator const_iterator;
typedef SdfPyWrapMapEditProxy<Type> This;
SdfPyWrapMapEditProxy()
{
TfPyWrapOnce<Type>(&This::_Wrap);
}
private:
typedef std::pair<key_type, mapped_type> pair_type;
struct _ExtractItem {
static boost::python::object Get(const const_iterator& i)
{
return boost::python::make_tuple(i->first, i->second);
}
};
struct _ExtractKey {
static boost::python::object Get(const const_iterator& i)
{
return boost::python::object(i->first);
}
};
struct _ExtractValue {
static boost::python::object Get(const const_iterator& i)
{
return boost::python::object(i->second);
}
};
template <class E>
class _Iterator {
public:
_Iterator(const boost::python::object& object) :
_object(object),
_owner(boost::python::extract<const Type&>(object)),
_cur(_owner.begin()),
_end(_owner.end())
{
// Do nothing
}
_Iterator<E> GetCopy() const
{
return *this;
}
boost::python::object GetNext()
{
if (_cur == _end) {
TfPyThrowStopIteration("End of MapEditProxy iteration");
}
boost::python::object result = E::Get(_cur);
++_cur;
return result;
}
private:
boost::python::object _object;
const Type& _owner;
const_iterator _cur;
const_iterator _end;
};
static void _Wrap()
{
using namespace boost::python;
std::string name = _GetName();
scope thisScope =
class_<Type>(name.c_str())
.def("__repr__", &This::_GetRepr)
.def("__str__", &This::_GetStr)
.def("__len__", &Type::size)
.def("__getitem__", &This::_GetItem)
.def("__setitem__", &This::_SetItem)
.def("__delitem__", &This::_DelItem)
.def("__contains__", &This::_HasKey)
.def("__iter__", &This::_GetKeyIterator)
#if PY_MAJOR_VERSION < 3
.def("itervalues", &This::_GetValueIterator)
.def("iterkeys", &This::_GetKeyIterator)
.def("iteritems", &This::_GetItemIterator)
.def("values", &This::_GetValues)
.def("keys", &This::_GetKeys)
.def("items", &This::_GetItems)
.def("has_key", &This::_HasKey)
#else
.def("values", &This::_GetValueIterator)
.def("keys", &This::_GetKeyIterator)
.def("items", &This::_GetItemIterator)
#endif
.def("clear", &Type::clear)
.def("get", &This::_PyGet)
.def("get", &This::_PyGetDefault)
.def("pop", &This::_Pop)
.def("popitem", &This::_PopItem)
.def("setdefault", &This::_SetDefault)
.def("update", &This::_UpdateDict)
.def("update", &This::_UpdateList)
.def("copy", &This::_Copy)
.add_property("expired", &Type::IsExpired)
.def(TfPyBoolBuiltinFuncName, &This::_NonZero)
.def(self == self)
.def(self != self)
;
class_<_Iterator<_ExtractItem> >
((name + "_Iterator").c_str(), no_init)
.def("__iter__", &This::template _Iterator<_ExtractItem>::GetCopy)
.def(TfPyIteratorNextMethodName, &This::template _Iterator<_ExtractItem>::GetNext)
;
class_<_Iterator<_ExtractKey> >
((name + "_KeyIterator").c_str(), no_init)
.def("__iter__", &This::template _Iterator<_ExtractKey>::GetCopy)
.def(TfPyIteratorNextMethodName, &This::template _Iterator<_ExtractKey>::GetNext)
;
class_<_Iterator<_ExtractValue> >
((name + "_ValueIterator").c_str(), no_init)
.def("__iter__", &This::template _Iterator<_ExtractValue>::GetCopy)
.def(TfPyIteratorNextMethodName, &This::template _Iterator<_ExtractValue>::GetNext)
;
}
static std::string _GetName()
{
std::string name = "MapEditProxy_" +
ArchGetDemangled<typename Type::Type>();
name = TfStringReplace(name, " ", "_");
name = TfStringReplace(name, ",", "_");
name = TfStringReplace(name, "::", "_");
name = TfStringReplace(name, "<", "_");
name = TfStringReplace(name, ">", "_");
return name;
}
static std::string _GetRepr(const Type& x)
{
std::string arg;
if (x) {
arg = TfStringPrintf("<%s>", x._Location().c_str());
}
else {
arg = "<invalid>";
}
return TF_PY_REPR_PREFIX + _GetName() + "(" + arg + ")";
}
static std::string _GetStr(const Type& x)
{
std::string result("{");
if (x && ! x.empty()) {
const_iterator i = x.begin(), n = x.end();
result += TfPyRepr(i->first) + ": " + TfPyRepr(i->second);
while (++i != n) {
result +=", " + TfPyRepr(i->first) + ": " + TfPyRepr(i->second);
}
}
result += "}";
return result;
}
static mapped_type _GetItem(const Type& x, const key_type& key)
{
const_iterator i = x.find(key);
if (i == x.end()) {
TfPyThrowKeyError(TfPyRepr(key));
return mapped_type();
}
else {
return i->second;
}
}
static void _SetItem(Type& x, const key_type& key, const mapped_type& value)
{
std::pair<typename Type::iterator, bool> i =
x.insert(value_type(key, value));
if (! i.second && i.first != typename Type::iterator()) {
i.first->second = value;
}
}
static void _DelItem(Type& x, const key_type& key)
{
x.erase(key);
}
static bool _HasKey(const Type& x, const key_type& key)
{
return x.count(key) != 0;
}
static _Iterator<_ExtractItem>
_GetItemIterator(const boost::python::object& x)
{
return _Iterator<_ExtractItem>(x);
}
static _Iterator<_ExtractKey>
_GetKeyIterator(const boost::python::object& x)
{
return _Iterator<_ExtractKey>(x);
}
static _Iterator<_ExtractValue>
_GetValueIterator(const boost::python::object& x)
{
return _Iterator<_ExtractValue>(x);
}
static boost::python::object _PyGet(const Type& x, const key_type& key)
{
const_iterator i = x.find(key);
return i == x.end() ? boost::python::object() :
boost::python::object(i->second);
}
static mapped_type _PyGetDefault(const Type& x, const key_type& key,
const mapped_type& def)
{
const_iterator i = x.find(key);
return i == x.end() ? def : i->second;
}
template <class E>
static boost::python::list _Get(const Type& x)
{
boost::python::list result;
for (const_iterator i = x.begin(), n = x.end(); i != n; ++i) {
result.append(E::Get(i));
}
return result;
}
#if PY_MAJOR_VERSION < 3
static boost::python::list _GetItems(const Type& x)
{
return _Get<_ExtractItem>(x);
}
static boost::python::list _GetKeys(const Type& x)
{
return _Get<_ExtractKey>(x);
}
static boost::python::list _GetValues(const Type& x)
{
return _Get<_ExtractValue>(x);
}
#endif
static mapped_type _Pop(Type& x, const key_type& key)
{
iterator i = x.find(key);
if (i == x.end()) {
TfPyThrowKeyError(TfPyRepr(key));
return mapped_type();
}
else {
mapped_type result = i->second;
x.erase(i);
return result;
}
}
static boost::python::tuple _PopItem(Type& x)
{
if (x.empty()) {
TfPyThrowKeyError("MapEditProxy is empty");
return boost::python::tuple();
}
else {
iterator i = x.begin();
value_type result = *i;
x.erase(i);
return boost::python::make_tuple(result.first, result.second);
}
}
static mapped_type _SetDefault(Type& x, const key_type& key,
const mapped_type& def)
{
const_iterator i = x.find(key);
if (i != x.end()) {
return i->second;
}
else {
return x[key] = def;
}
}
static void _Update(Type& x, const std::vector<pair_type>& values)
{
SdfChangeBlock block;
TF_FOR_ALL(i, values) {
x[i->first] = i->second;
}
}
static void _UpdateDict(Type& x, const boost::python::dict& d)
{
_UpdateList(x, d.items());
}
static void _UpdateList(Type& x, const boost::python::list& pairs)
{
using namespace boost::python;
std::vector<pair_type> values;
for (int i = 0, n = len(pairs); i != n; ++i) {
values.push_back(pair_type(
extract<key_type>(pairs[i][0])(),
extract<mapped_type>(pairs[i][1])()));
}
_Update(x, values);
}
static void _Copy(Type& x, const typename Type::Type& other)
{
x = other;
}
static bool _NonZero(const Type& x)
{
return static_cast<bool>(x);
}
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_PY_MAP_EDIT_PROXY_H
+507
View File
@@ -0,0 +1,507 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
#ifndef PXR_USD_SDF_PY_SPEC_H
#define PXR_USD_SDF_PY_SPEC_H
/// \file sdf/pySpec.h
///
/// SdfSpec Python wrapping utilities.
///
/// An SdfSpec subclass is not the representation of scene data. An SdfSpec
/// simply provides an interface to data stored in some internal representation.
/// SdfSpec subclasses are value types and their lifetimes don't reflect the
/// lifetime of the scene data. However, clients still create scene data using
/// the New methods on SdfSpec subclasses.
///
/// When wrapping to Python we need to wrap the New methods as the constructors.
/// This used to look like this:
///
/// \code
/// class_<MyClass, MyClassHandle>("MyClass", no_init)
/// .def(TfPyRefAndWeakPtr())
/// .def(TfMakePyConstructor(&MyClass::New))
/// ...
/// \endcode
///
/// But we can't use TfMakePyConstructor() because an SdfSpec handle is
/// not a weak pointer. Furthermore, we don't have the problem of needing
/// to store a ref pointer in the Python object. But we do still need
/// conversion of spec types to yield the most-derived type in python.
///
/// This file introduces a few boost::python::class_ def visitors to make
/// wrapping specs easy. Spec wrapping should now look like:
///
/// \code
/// class_<MyClass, SdfHandle<MyClass>, bases<SdfSpec>, boost::noncopyable>
/// ("MyClass", no_init)
/// .def(SdfPySpec()) // or SdfPyAbstractSpec()
/// .def(SdfMakePySpecConstructor(&MyClass::New))
/// ...
/// \endcode
///
/// If you need a custom repr you can use SdfPySpecNoRepr() or
/// SdfPyAbstractSpecNoRepr() and def("__repr__", ...).
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include <boost/python/def_visitor.hpp>
#include <boost/python/dict.hpp>
#include <boost/python/errors.hpp>
#include <boost/python/raw_function.hpp>
#include <boost/python/pointee.hpp>
#include <boost/python/to_python_converter.hpp>
#include <boost/python/tuple.hpp>
#include "pxr/base/tf/pyError.h"
#include "pxr/base/tf/pyUtils.h"
#include "pxr/usd/sdf/declareHandles.h"
#include "pxr/base/tf/tf.h"
#include "pxr/base/tf/diagnostic.h"
#include "pxr/base/tf/stringUtils.h"
#include "pxr/base/arch/demangle.h"
#include <string>
#include <type_traits>
namespace boost{
namespace python {
template <typename T>
struct pointee<PXR_NS::SdfHandle<T> > {
typedef T type;
};
}
}
PXR_NAMESPACE_OPEN_SCOPE
class SdfSpec;
namespace Sdf_PySpecDetail {
namespace bp = boost::python;
SDF_API bp::object _DummyInit(bp::tuple const & /* args */, bp::dict const & /* kw */);
template <typename CTOR>
struct NewVisitor : bp::def_visitor<NewVisitor<CTOR> > {
public:
NewVisitor(const std::string &doc = std::string()) : _doc(doc) {}
template <typename CLS>
void visit(CLS& c) const
{
// If there's already a __new__ method, look through the staticmethod to
// get the underlying function, replace __new__ with that, then add the
// overload, and recreate the staticmethod. This is required because
// boost python needs to have all overloads exported before you say
// .staticmethod.
// Note that it looks like this should do nothing, but it actually does
// something! Here's what it does: looking up __new__ on c doesn't
// actually produce the staticmethod object -- it does a "descriptor
// __get__" which produces the underlying function. Replacing __new__
// with that underlying thing has the effect of unwrapping the
// staticmethod, which is exactly what we want.
if (PyObject_HasAttrString(c.ptr(), "__new__"))
c.attr("__new__") = c.attr("__new__");
c.def("__new__", CTOR::template __new__<CLS>, _doc.c_str());
c.staticmethod("__new__");
c.def("__init__", bp::raw_function(_DummyInit));
}
template <class CLS, class Options>
void visit(CLS& c, char const* name, Options& options) const
{
// If there's already a __new__ method, look through the staticmethod to
// get the underlying function, replace __new__ with that, then add the
// overload, and recreate the staticmethod. This is required because
// boost python needs to have all overloads exported before you say
// .staticmethod.
// Note that it looks like this should do nothing, but it actually does
// something! Here's what it does: looking up __new__ on c doesn't
// actually produce the staticmethod object -- it does a "descriptor
// __get__" which produces the underlying function. Replacing __new__
// with that underlying thing has the effect of unwrapping the
// staticmethod, which is exactly what we want.
if (PyObject_HasAttrString(c.ptr(), "__new__"))
c.attr("__new__") = c.attr("__new__");
c.def("__new__", CTOR::template __new__<CLS>,
// Note: we ignore options.doc() in favor of _doc
_doc.c_str(),
options.keywords(),
options.policies()
);
c.staticmethod("__new__");
c.def("__init__", bp::raw_function(_DummyInit));
}
private:
const std::string _doc;
friend class bp::def_visitor_access;
};
template <typename SIG>
struct CtorBase {
public:
typedef SIG Sig;
static Sig *_func;
static void SetFunc(Sig *func)
{
if (! _func) {
_func = func;
}
else {
// CODE_COVERAGE_OFF
TF_CODING_ERROR("Ctor with signature '%s' is already registered. "
"Duplicate will be ignored.",
ArchGetDemangled(typeid(Sig)).c_str());
// CODE_COVERAGE_ON
}
}
};
template <typename SIG> SIG *CtorBase<SIG>::_func = 0;
template <typename SIG> struct NewCtor;
} // namespace Sdf_PySpecDetail
template <typename T>
Sdf_PySpecDetail::NewVisitor<typename Sdf_PySpecDetail::NewCtor<T> >
SdfMakePySpecConstructor(T *func, const std::string &doc = std::string())
{
// Instantiate to set static constructor pointer, then return the visitor.
Sdf_PySpecDetail::NewCtor<T> Ctor(func);
return Sdf_PySpecDetail::NewVisitor<Sdf_PySpecDetail::NewCtor<T> >(doc);
}
namespace Sdf_PySpecDetail {
// Create the repr for a spec using Sdf.Find().
SDF_API std::string _SpecRepr(const bp::object&, const SdfSpec*);
// Registration for spec types to functions to create a holder with the spec
// corresponding to the spec type.
typedef PyObject* (*_HolderCreator)(const SdfSpec&);
SDF_API void _RegisterHolderCreator(const std::type_info&, _HolderCreator);
SDF_API PyObject* _CreateHolder(const std::type_info&, const SdfSpec&);
template <class _SpecType>
struct _ConstHandleToPython {
typedef _SpecType SpecType;
typedef SdfHandle<SpecType> Handle;
typedef SdfHandle<const SpecType> ConstHandle;
_ConstHandleToPython() {
bp::to_python_converter<ConstHandle, _ConstHandleToPython<SpecType> >();
}
static PyObject *convert(ConstHandle const &p) {
return bp::incref(bp::object(TfConst_cast<Handle>(p)).ptr());
}
};
// Register and perform python conversions of SdfHandles to holders.
template <class _SpecType, class _Held, class _Holder>
struct _HandleToPython {
public:
typedef _SpecType SpecType;
typedef _Holder Holder;
typedef _Held Handle;
typedef _HandleToPython<SpecType, Handle, Holder> This;
static void Register()
{
_originalConverter = _RegisterConverter<Handle>(&This::_Convert);
_RegisterHolderCreator(typeid(SpecType), &This::_Creator);
}
static PyObject* convert(const Handle& x)
{
return _CreateHolder(typeid(SpecType), x.GetSpec());
}
private:
static PyObject* _Creator(const SdfSpec& spec)
{
Handle x(Sdf_CastAccess::CastSpec<SpecType,SdfSpec>(spec));
return bp::objects::make_ptr_instance<SpecType, Holder>::execute(x);
}
template <class T>
static
bp::converter::to_python_function_t
_RegisterConverter(bp::converter::to_python_function_t f)
{
// Replace the old converter, installed automatically when we
// registered the class. WBN if boost python let us do this
// without playing games.
bp::converter::registration* r =
const_cast<bp::converter::registration*>(
bp::converter::registry::query(bp::type_id<T>()));
if (r) {
bp::converter::to_python_function_t old = r->m_to_python;
r->m_to_python = f;
return old;
}
else {
// CODE_COVERAGE_OFF Can only happen if there's a bug.
TF_CODING_ERROR("No python registration for '%s'!",
ArchGetDemangled(typeid(Handle)).c_str());
return 0;
// CODE_COVERAGE_ON
}
}
static PyObject* _Convert(const void* p)
{
const Handle& x = *static_cast<const Handle*>(p);
return _CreateHolder(typeid(SpecType), x.GetSpec());
}
private:
static bp::converter::to_python_function_t _originalConverter;
};
template <class SpecType, class Held, class Holder>
bp::converter::to_python_function_t
_HandleToPython<SpecType, Held, Holder>::_originalConverter = 0;
template <class _SpecType>
struct _HandleFromPython {
typedef _SpecType SpecType;
typedef SdfHandle<SpecType> Handle;
_HandleFromPython()
{
bp::converter::registry::insert(&convertible, &construct,
bp::type_id<Handle>());
}
private:
static void *convertible(PyObject *p)
{
if (p == Py_None)
return p;
void *result =
bp::converter::get_lvalue_from_python(p,
bp::converter::registered<SpecType>::converters);
return result;
}
static void construct(PyObject* source,
bp::converter::rvalue_from_python_stage1_data* data)
{
void* const storage =
((bp::converter::rvalue_from_python_storage<Handle>*)
data)->storage.bytes;
// Deal with the "None" case.
if (data->convertible == source)
new (storage) Handle();
else {
new (storage) Handle(*static_cast<SpecType*>(data->convertible));
}
data->convertible = storage;
}
};
// Visitor for def().
template <bool Abstract>
struct SpecVisitor : bp::def_visitor<SpecVisitor<Abstract> > {
template<typename CLS>
struct _Helper {
typedef typename CLS::wrapped_type SpecType;
typedef typename CLS::metadata::held_type HeldType;
typedef typename CLS::metadata::held_type_arg HeldArgType;
typedef typename CLS::metadata::holder HolderType;
public:
static std::string Repr(const bp::object& self)
{
const HeldType& held = bp::extract<const HeldType&>(self);
return _SpecRepr(self, get_pointer(held));
}
static bool IsExpired(const HeldType& self)
{
return !self;
}
static bool NonZero(const HeldType& self)
{
return self;
}
static size_t __hash__(const HeldType& self)
{
return hash_value(self);
}
static bool __eq__(const HeldType& a, const HeldType& b)
{
return a == b;
}
static bool __ne__(const HeldType& a, const HeldType& b)
{
return a != b;
}
static bool __lt__(const HeldType& a, const HeldType& b)
{
return a < b;
}
static bool __le__(const HeldType& a, const HeldType& b)
{
return a <= b;
}
static bool __gt__(const HeldType& a, const HeldType& b)
{
return a > b;
}
static bool __ge__(const HeldType& a, const HeldType& b)
{
return a >= b;
}
};
public:
SpecVisitor(bool addRepr = true) : _addRepr(addRepr) { }
template <typename CLS>
void visit(CLS& c) const
{
typedef typename CLS::wrapped_type SpecType;
typedef typename CLS::metadata::held_type HeldType;
typedef typename CLS::metadata::held_type_arg HeldArgType;
typedef typename CLS::metadata::holder HolderType;
static_assert(std::is_same<HeldType, SdfHandle<SpecType> >::value,
"HeldType must be SdfHandle<SpecType>.");
// Add methods.
c.add_property("expired", &_Helper<CLS>::IsExpired);
c.def(TfPyBoolBuiltinFuncName, &_Helper<CLS>::NonZero);
c.def("__hash__", &_Helper<CLS>::__hash__);
c.def("__eq__", &_Helper<CLS>::__eq__);
c.def("__ne__", &_Helper<CLS>::__ne__);
c.def("__lt__", &_Helper<CLS>::__lt__);
c.def("__le__", &_Helper<CLS>::__le__);
c.def("__gt__", &_Helper<CLS>::__gt__);
c.def("__ge__", &_Helper<CLS>::__ge__);
// Add python conversion to cast away constness.
_ConstHandleToPython<SpecType>();
// Add python conversion for SdfHandle<SpecType>.
_HandleFromPython<SpecType>();
_HandleFromPython<const SpecType>();
_HandleToPython<SpecType, HeldArgType, HolderType>::Register();
// Add __repr__.
if (_addRepr) {
c.def("__repr__", &_Helper<CLS>::Repr);
}
}
private:
bool _addRepr;
};
} // namespace Sdf_PySpecDetail
inline
Sdf_PySpecDetail::SpecVisitor<false>
SdfPySpec()
{
return Sdf_PySpecDetail::SpecVisitor<false>();
}
inline
Sdf_PySpecDetail::SpecVisitor<true>
SdfPyAbstractSpec()
{
return Sdf_PySpecDetail::SpecVisitor<true>();
}
inline
Sdf_PySpecDetail::SpecVisitor<false>
SdfPySpecNoRepr()
{
return Sdf_PySpecDetail::SpecVisitor<false>(false);
}
inline
Sdf_PySpecDetail::SpecVisitor<true>
SdfPyAbstractSpecNoRepr()
{
return Sdf_PySpecDetail::SpecVisitor<true>(false);
}
namespace Sdf_PySpecDetail
{
// This generates multi-argument specializations for NewCtor.
template <typename R, typename... Args>
struct NewCtor<R(Args...)> : CtorBase<R(Args...)> {
typedef CtorBase<R(Args...)> Base;
typedef typename Base::Sig Sig;
NewCtor(Sig *func) { Base::SetFunc(func); }
template <class CLS>
static bp::object __new__(bp::object &cls, Args... args) {
typedef typename CLS::metadata::held_type HeldType;
TfErrorMark m;
HeldType specHandle(Base::_func(args...));
if (TfPyConvertTfErrorsToPythonException(m))
bp::throw_error_already_set();
bp::object result = TfPyObject(specHandle);
if (TfPyIsNone(result))
TfPyThrowRuntimeError("could not construct " +
ArchGetDemangled(typeid(HeldType)));
bp::detail::initialize_wrapper(result.ptr(), get_pointer(specHandle));
// make the object have the right class.
bp::setattr(result, "__class__", cls);
return result;
}
};
} // namespace Sdf_PySpecDetail
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_PY_SPEC_H
+50
View File
@@ -0,0 +1,50 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_PY_UTILS_H
#define PXR_USD_SDF_PY_UTILS_H
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/usd/sdf/layer.h"
#include <boost/python/dict.hpp>
#include <string>
PXR_NAMESPACE_OPEN_SCOPE
/// Convert the Python dictionary \p dict to an SdfLayer::FileFormatArguments
/// object and return it via \p args.
///
/// If a non-string key or value is encountered, \p errMsg will be filled in
/// (if given) and this function will return false. Otherwise, this function
/// will return true.
SDF_API bool
SdfFileFormatArgumentsFromPython(
const boost::python::dict& dict,
SdfLayer::FileFormatArguments* args,
std::string* errMsg = NULL);
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_PY_UTILS_H
+228
View File
@@ -0,0 +1,228 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_REFERENCE_H
#define PXR_USD_SDF_REFERENCE_H
/// \file sdf/reference.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/usd/sdf/layerOffset.h"
#include "pxr/usd/sdf/path.h"
#include "pxr/base/vt/dictionary.h"
#include "pxr/base/vt/value.h"
#include <boost/operators.hpp>
#include <iosfwd>
#include <string>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
class SdfReference;
typedef std::vector<SdfReference> SdfReferenceVector;
/// \class SdfReference
///
/// Represents a reference and all its meta data.
///
/// A reference is expressed on a prim in a given layer and it identifies a
/// prim in a layer stack. All opinions in the namespace hierarchy
/// under the referenced prim will be composed with the opinions in the
/// namespace hierarchy under the referencing prim.
///
/// The asset path specifies the layer stack being referenced. If this
/// asset path is non-empty, this reference is considered an 'external'
/// reference to the layer stack rooted at the specified layer. If this
/// is empty, this reference is considered an 'internal' reference to the
/// layer stack containing (but not necessarily rooted at) the layer where
/// the reference is authored.
///
/// The prim path specifies the prim in the referenced layer stack from
/// which opinions will be composed. If this prim path is empty, it will
/// be considered a reference to the default prim specified in the root layer
/// of the referenced layer stack -- see SdfLayer::GetDefaultPrim.
///
/// The meta data for a reference is its layer offset and custom data. The
/// layer offset is an affine transformation applied to all anim splines in
/// the referenced prim's namespace hierarchy, see SdfLayerOffset for details.
/// Custom data is for use by plugins or other non-tools supplied extensions
/// that need to be able to store data associated with references.
///
class SdfReference : boost::totally_ordered<SdfReference> {
public:
/// Creates a reference with all its meta data. The default
/// reference is an internal reference to the default prim.
///
SDF_API SdfReference(
const std::string &assetPath = std::string(),
const SdfPath &primPath = SdfPath(),
const SdfLayerOffset &layerOffset = SdfLayerOffset(),
const VtDictionary &customData = VtDictionary());
/// Returns the asset path to the root layer of the referenced layer
/// stack. This will be empty in the case of an internal reference.
///
const std::string &GetAssetPath() const {
return _assetPath;
}
/// Sets the asset path for the root layer of the referenced layer stack.
/// This may be set to an empty string to specify an internal reference.
///
void SetAssetPath(const std::string &assetPath) {
_assetPath = assetPath;
}
/// Returns the path of the referenced prim.
/// This will be empty if the referenced prim is the default prim specified
/// in the referenced layer stack.
///
const SdfPath &GetPrimPath() const {
return _primPath;
}
/// Sets the path of the referenced prim.
/// This may be set to an empty path to specify a reference to the default
/// prim in the referenced layer stack.
///
void SetPrimPath(const SdfPath &primPath) {
_primPath = primPath;
}
/// Returns the layer offset associated with the reference.
///
const SdfLayerOffset &GetLayerOffset() const {
return _layerOffset;
}
/// Sets a new layer offset.
///
void SetLayerOffset(const SdfLayerOffset &layerOffset) {
_layerOffset = layerOffset;
}
/// Returns the custom data associated with the reference.
///
const VtDictionary &GetCustomData() const {
return _customData;
}
/// Sets the custom data associated with the reference.
///
void SetCustomData(const VtDictionary &customData) {
_customData = customData;
}
/// Sets a custom data entry for the reference.
///
/// If \a value is empty, then this removes the given custom data entry.
///
SDF_API void SetCustomData(const std::string &name, const VtValue &value);
/// Swaps the custom data dictionary for this reference.
void SwapCustomData(VtDictionary &customData) {
_customData.swap(customData);
}
/// Returns \c true in the case of an internal reference.
///
/// An internal reference is a reference with an empty asset path.
///
SDF_API bool IsInternal() const;
friend inline size_t hash_value(const SdfReference &r) {
size_t h = 0;
boost::hash_combine(h, r._assetPath);
boost::hash_combine(h, r._primPath);
boost::hash_combine(h, r._layerOffset);
boost::hash_combine(h, r._customData);
return h;
}
/// Returns whether this reference equals \a rhs.
SDF_API bool operator==(const SdfReference &rhs) const;
/// Returns whether this reference is less than \a rhs. The meaning
/// of less than is somewhat arbitrary.
SDF_API bool operator<(const SdfReference &rhs) const;
/// Struct that defines equality of SdfReferences based on their
/// identity (the asset path and prim path).
///
struct IdentityEqual {
bool operator()(const SdfReference &lhs, const SdfReference &rhs) const {
return lhs._assetPath == rhs._assetPath &&
lhs._primPath == rhs._primPath;
}
};
/// Struct that defines a strict weak ordering of SdfReferences based on
/// their identity (the asset path and prim path).
///
struct IdentityLessThan {
bool operator()(const SdfReference &lhs, const SdfReference &rhs) const {
return lhs._assetPath < rhs._assetPath ||
(lhs._assetPath == rhs._assetPath &&
lhs._primPath < rhs._primPath);
}
};
private:
// The asset path to the external layer.
std::string _assetPath;
// The path to the referenced prim in the external layer.
SdfPath _primPath;
// The layer offset to transform time.
SdfLayerOffset _layerOffset;
// The custom data associated with the reference.
VtDictionary _customData;
};
/// Convenience function to find the index of the reference in \a references
/// that has the same identity as the given reference \a referenceId.
///
/// A reference's identity is given by its asset path and prim path alone
/// (i.e. the layer offset and custom data is ignored).
///
/// If no reference with the same identity exists in \a reference, -1 is
/// returned. If more than one reference with the same identity exist in
/// \a references the index of the first one is returned.
///
SDF_API int SdfFindReferenceByIdentity(
const SdfReferenceVector &references,
const SdfReference &referenceId);
/// Writes the string representation of \a SdfReference to \a out.
SDF_API std::ostream & operator<<( std::ostream &out,
const SdfReference &reference );
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_REFERENCE_H
+138
View File
@@ -0,0 +1,138 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_RELATIONSHIP_SPEC_H
#define PXR_USD_SDF_RELATIONSHIP_SPEC_H
/// \file sdf/relationshipSpec.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/usd/sdf/declareSpec.h"
#include "pxr/usd/sdf/propertySpec.h"
#include "pxr/usd/sdf/types.h"
PXR_NAMESPACE_OPEN_SCOPE
/// \class SdfRelationshipSpec
///
/// A property that contains a reference to one or more SdfPrimSpec instances.
///
/// A relationship may refer to one or more target prims or attributes.
/// All targets of a single relationship are considered to be playing the same
/// role. Note that \c role does not imply that the target prims or attributes
/// are of the same \c type.
///
/// Relationships may be annotated with relational attributes.
/// Relational attributes are named SdfAttributeSpec objects containing
/// values that describe the relationship. For example, point weights are
/// commonly expressed as relational attributes.
///
class SdfRelationshipSpec : public SdfPropertySpec
{
SDF_DECLARE_SPEC(SdfRelationshipSpec, SdfPropertySpec);
public:
typedef SdfRelationshipSpec This;
typedef SdfPropertySpec Parent;
///
/// \name Spec creation
/// @{
/// Creates a new prim relationship instance.
///
/// Creates and returns a new relationship for the given prim.
/// The \p owner will own the newly created relationship.
SDF_API
static SdfRelationshipSpecHandle
New(const SdfPrimSpecHandle& owner,
const std::string& name,
bool custom = true,
SdfVariability variability = SdfVariabilityUniform);
/// @}
/// \name Relationship targets
/// @{
/// Returns the relationship's target path list editor.
///
/// The list of the target paths for this relationship may be modified
/// through the proxy.
SDF_API
SdfTargetsProxy GetTargetPathList() const;
/// Returns true if the relationship has any target paths.
SDF_API
bool HasTargetPathList() const;
/// Clears the list of target paths on this relationship.
SDF_API
void ClearTargetPathList() const;
/// Updates the specified target path.
///
/// Replaces the path given by \p oldPath with the one specified by
/// \p newPath. Relational attributes are updated if necessary.
SDF_API
void ReplaceTargetPath(const SdfPath& oldPath, const SdfPath& newPath);
/// Removes the specified target path.
///
/// Removes the given target path and any relational attributes for the
/// given target path. If \p preserveTargetOrder is \c true, Erase() is
/// called on the list editor instead of RemoveItemEdits(). This preserves
/// the ordered items list.
SDF_API
void RemoveTargetPath(const SdfPath& path, bool preserveTargetOrder = false);
/// @}
/// Get whether loading the target of this relationship is necessary
/// to load the prim we're attached to
SDF_API
bool GetNoLoadHint(void) const;
/// Set whether loading the target of this relationship is necessary
/// to load the prim we're attached to
SDF_API
void SetNoLoadHint(bool noload);
private:
SdfPath _CanonicalizeTargetPath(const SdfPath& path) const;
SdfPath _MakeCompleteTargetSpecPath(const SdfPath& srcPath) const;
SdfSpecHandle _GetTargetSpec(const SdfPath& path) const;
// Allow access to _GetTarget() for the relational attribute c'tor
friend class SdfAttributeSpec;
// Allow access to retrieve relationship spec for this API object.
friend class Sdf_PyRelationshipAccess;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_RELATIONSHIP_SPEC_H
+648
View File
@@ -0,0 +1,648 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_SCHEMA_H
#define PXR_USD_SDF_SCHEMA_H
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/usd/sdf/allowed.h"
#include "pxr/usd/sdf/types.h"
#include "pxr/usd/sdf/valueTypeName.h"
#include "pxr/base/plug/notice.h"
#include "pxr/base/tf/hash.h"
#include "pxr/base/tf/hashmap.h"
#include "pxr/base/tf/singleton.h"
#include "pxr/base/tf/staticTokens.h"
#include "pxr/base/tf/token.h"
#include "pxr/base/tf/type.h"
#include "pxr/base/tf/weakBase.h"
#include "pxr/base/vt/value.h"
#include <memory>
#include <string>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
class JsValue;
class SdfPath;
class SdfPayload;
class SdfReference;
class Sdf_ValueTypeRegistry;
TF_DECLARE_WEAK_PTRS(PlugPlugin);
/// \class SdfSchemaBase
///
/// Generic class that provides information about scene description fields
/// but doesn't actually provide any fields.
///
class SdfSchemaBase : public TfWeakBase, public boost::noncopyable {
protected:
class _SpecDefiner;
public:
/// \class FieldDefinition
///
/// Class defining various attributes for a field.
///
class FieldDefinition {
public:
FieldDefinition(
const SdfSchemaBase& schema,
const TfToken& name,
const VtValue& fallbackValue);
typedef std::vector< std::pair<TfToken, JsValue> > InfoVec;
SDF_API const TfToken& GetName() const;
SDF_API const VtValue& GetFallbackValue() const;
SDF_API const InfoVec& GetInfo() const;
SDF_API bool IsPlugin() const;
SDF_API bool IsReadOnly() const;
SDF_API bool HoldsChildren() const;
/// Validation functions that return true if a given value passes
/// the registered validator or if no validator has been set.
/// @{
template <class T>
SdfAllowed IsValidValue(const T& value) const
{
return (_valueValidator ?
_valueValidator(_schema, VtValue(value)) :
SdfAllowed(true));
}
template <class T>
SdfAllowed IsValidListValue(const T& value) const
{
return (_listValueValidator ?
_listValueValidator(_schema, VtValue(value)) :
SdfAllowed(true));
}
template <class T>
SdfAllowed IsValidMapKey(const T& value) const
{
return (_mapKeyValidator ?
_mapKeyValidator(_schema, VtValue(value)) :
SdfAllowed(true));
}
template <class T>
SdfAllowed IsValidMapValue(const T& value) const
{
return (_mapValueValidator ?
_mapValueValidator(_schema, VtValue(value)) :
SdfAllowed(true));
}
/// @}
/// Functions for setting field attributes during registration.
/// @{
FieldDefinition& FallbackValue(const VtValue& v);
FieldDefinition& Plugin();
FieldDefinition& Children();
FieldDefinition& ReadOnly();
FieldDefinition& AddInfo(const TfToken& tok, const JsValue& val);
using Validator =
SdfAllowed (*) (const SdfSchemaBase&, const VtValue&);
FieldDefinition& ValueValidator(Validator v);
FieldDefinition& ListValueValidator(Validator v);
FieldDefinition& MapKeyValidator(Validator v);
FieldDefinition& MapValueValidator(Validator v);
/// @}
private:
const SdfSchemaBase& _schema;
TfToken _name;
VtValue _fallbackValue;
InfoVec _info;
bool _isPlugin;
bool _isReadOnly;
bool _holdsChildren;
Validator _valueValidator;
Validator _listValueValidator;
Validator _mapKeyValidator;
Validator _mapValueValidator;
};
// Structure containing information about a field as it pertains to the
// spec this object defines.
struct _FieldInfo {
_FieldInfo(): required(false), metadata(false) { }
bool required;
bool metadata;
TfToken metadataDisplayGroup;
};
class SpecDefinition;
/// \class SpecDefinition
///
/// Class representing fields and other information for a spec type.
///
class SpecDefinition {
public:
/// Returns all fields for this spec.
SDF_API TfTokenVector GetFields() const;
/// Returns all value fields marked as required for this spec.
TfTokenVector const &GetRequiredFields() const {
return _requiredFields;
}
/// Returns all value fields marked as metadata for this spec.
SDF_API TfTokenVector GetMetadataFields() const;
/// Returns whether the given field is valid for this spec.
SDF_API bool IsValidField(const TfToken& name) const;
/// Returns whether the given field is metadata for this spec.
SDF_API bool IsMetadataField(const TfToken& name) const;
/// Returns the display group for this metadata field. Returns the
/// empty token if this field is not a metadata field or if this
/// metadata field has no display group.
SDF_API
TfToken GetMetadataFieldDisplayGroup(const TfToken& name) const;
/// Returns whether the given field is required for this spec.
SDF_API bool IsRequiredField(const TfToken& name) const;
private:
typedef TfHashMap<TfToken, _FieldInfo, TfToken::HashFunctor>
_FieldMap;
_FieldMap _fields;
// A separate vector of required field names from _fields. Access to
// these is in a hot path, so we cache them separately.
TfTokenVector _requiredFields;
private:
friend class _SpecDefiner;
void _AddField(const TfToken& name, const _FieldInfo& fieldInfo);
};
/// Returns the field definition for the given field.
/// Returns NULL if no definition exists for given field.
SDF_API
const FieldDefinition* GetFieldDefinition(const TfToken &fieldKey) const;
/// Returns the spec definition for the given spec type.
/// Returns NULL if no definition exists for the given spec type.
inline const SpecDefinition* GetSpecDefinition(SdfSpecType specType) const {
return _specDefinitions[specType].second ?
&_specDefinitions[specType].first : nullptr;
}
/// Convenience functions for accessing specific field information.
/// @{
/// Return whether the specified field has been registered. Also
/// optionally return the fallback value.
SDF_API
bool IsRegistered(const TfToken &fieldKey, VtValue *fallback=NULL) const;
/// Returns whether the given field is a 'children' field -- that is, it
/// indexes certain children beneath the owning spec.
SDF_API
bool HoldsChildren(const TfToken &fieldKey) const;
/// Return the fallback value for the specified \p fieldKey or the
/// empty value if \p fieldKey is not registered.
SDF_API
const VtValue& GetFallback(const TfToken &fieldKey) const;
/// Coerce \p value to the correct type for the specified field.
SDF_API
VtValue CastToTypeOf(const TfToken &fieldKey, const VtValue &value) const;
/// Return whether the given field is valid for the given spec type.
SDF_API
bool IsValidFieldForSpec(const TfToken &fieldKey, SdfSpecType specType) const;
/// Returns all fields registered for the given spec type.
SDF_API TfTokenVector GetFields(SdfSpecType specType) const;
/// Returns all metadata fields registered for the given spec type.
SDF_API TfTokenVector GetMetadataFields(SdfSpecType specType) const;
/// Return the metadata field display group for metadata \a metadataField on
/// \a specType. Return the empty token if \a metadataField is not a
/// metadata field, or if it has no display group.
SDF_API
TfToken GetMetadataFieldDisplayGroup(SdfSpecType specType,
TfToken const &metadataField) const;
/// Returns all required fields registered for the given spec type.
SDF_API const TfTokenVector &GetRequiredFields(SdfSpecType specType) const;
/// Return true if \p fieldName is a required field name for at least one
/// spec type, return false otherwise. The main use of this function is to
/// quickly rule out field names that aren't required (and thus don't need
/// special handling).
inline bool IsRequiredFieldName(const TfToken &fieldName) const {
for (size_t i = 0; i != _requiredFieldNames.size(); ++i) {
if (_requiredFieldNames[i] == fieldName)
return true;
}
return false;
}
/// @}
/// Specific validation functions for various fields. These are internally
/// registered as validators for the associated field, but can also be
/// used directly.
/// @{
static SdfAllowed IsValidAttributeConnectionPath(const SdfPath& path);
static SdfAllowed IsValidIdentifier(const std::string& name);
static SdfAllowed IsValidNamespacedIdentifier(const std::string& name);
static SdfAllowed IsValidInheritPath(const SdfPath& path);
static SdfAllowed IsValidPayload(const SdfPayload& payload);
static SdfAllowed IsValidReference(const SdfReference& ref);
static SdfAllowed IsValidRelationshipTargetPath(const SdfPath& path);
static SdfAllowed IsValidRelocatesPath(const SdfPath& path);
static SdfAllowed IsValidSpecializesPath(const SdfPath& path);
static SdfAllowed IsValidSubLayer(const std::string& sublayer);
static SdfAllowed IsValidVariantIdentifier(const std::string& name);
/// @}
/// Scene description value types
/// @{
/// Given a value, check if it is a valid value type.
/// This function only checks that the type of the value is valid
/// for this schema. It does not imply that the value is valid for
/// a particular field -- the field's validation function must be
/// used for that.
SDF_API
SdfAllowed IsValidValue(const VtValue& value) const;
/// Returns all registered type names.
std::vector<SdfValueTypeName> GetAllTypes() const;
/// Return the type name object for the given type name token.
SDF_API
SdfValueTypeName FindType(const TfToken& typeName) const;
/// \overload
SDF_API
SdfValueTypeName FindType(const char *typeName) const;
/// \overload
SDF_API
SdfValueTypeName FindType(std::string const &typeName) const;
/// Return the type name object for the given type and optional role.
SDF_API
SdfValueTypeName FindType(const TfType& type,
const TfToken& role = TfToken()) const;
/// Return the type name object for the value's type and optional role.
SDF_API
SdfValueTypeName FindType(const VtValue& value,
const TfToken& role = TfToken()) const;
/// Return the type name object for the given type name string if it
/// exists otherwise create a temporary type name object. Clients
/// should not normally need to call this.
SDF_API
SdfValueTypeName FindOrCreateType(const TfToken& typeName) const;
/// @}
protected:
/// \class _SpecDefiner
///
/// Class that defines fields for a spec type.
///
class _SpecDefiner {
public:
/// Functions for setting spec attributes during registration
/// @{
_SpecDefiner& Field(
const TfToken& name, bool required = false);
_SpecDefiner& MetadataField(
const TfToken& name, bool required = false);
_SpecDefiner& MetadataField(
const TfToken& name, const TfToken& displayGroup,
bool required = false);
_SpecDefiner &CopyFrom(const SpecDefinition &other);
/// @}
private:
friend class SdfSchemaBase;
explicit _SpecDefiner(SdfSchemaBase *schema, SpecDefinition *definition)
: _schema(schema)
, _definition(definition)
{}
SdfSchemaBase *_schema;
SpecDefinition *_definition;
};
/// A helper for registering value types.
class _ValueTypeRegistrar {
public:
explicit _ValueTypeRegistrar(Sdf_ValueTypeRegistry*);
class Type
{
public:
~Type();
// Specify a type with the given name, default value, and default
// array value of VtArray<T>.
template <class T>
Type(const TfToken& name, const T& defaultValue)
: Type(name, VtValue(defaultValue), VtValue(VtArray<T>()))
{ }
template <class T>
Type(char const *name, const T& defaultValue)
: Type(TfToken(name),
VtValue(defaultValue), VtValue(VtArray<T>()))
{ }
// Specify a type with the given name and underlying C++ type.
// No default value or array value will be registered.
Type(const TfToken& name, const TfType& type);
// Set C++ type name string for this type. Defaults to type name
// from TfType.
Type& CPPTypeName(const std::string& cppTypeName);
// Set shape for this type. Defaults to shapeless.
Type& Dimensions(const SdfTupleDimensions& dims);
// Set default unit for this type. Defaults to dimensionless unit.
Type& DefaultUnit(TfEnum unit);
// Set role for this type. Defaults to no role.
Type& Role(const TfToken& role);
// Indicate that arrays of this type are not supported.
Type& NoArrays();
private:
Type(const TfToken& name,
const VtValue& defaultValue,
const VtValue& defaultArrayValue);
class _Impl;
std::unique_ptr<_Impl> _impl;
friend class _ValueTypeRegistrar;
};
/// Register a value type and its corresponding array value type.
void AddType(const Type& type);
private:
Sdf_ValueTypeRegistry* _registry;
};
SdfSchemaBase();
/// Construct an SdfSchemaBase but does not populate it with standard
/// fields and types.
class EmptyTag {};
SdfSchemaBase(EmptyTag);
virtual ~SdfSchemaBase();
/// Creates and registers a new field named \p fieldKey with the fallback
/// value \p fallback. If \p plugin is specified, it indicates that this
/// field is not a built-in field from this schema, but rather a field
/// that was externally registered.
///
/// It is a fatal error to call this function with a key that has already
/// been used for another field.
template <class T>
FieldDefinition& _RegisterField(
const TfToken &fieldKey, const T &fallback, bool plugin = false)
{
return _CreateField(fieldKey, VtValue(fallback), plugin);
}
/// Registers the given spec \p type with this schema and return a
/// _SpecDefiner for specifying additional fields.
_SpecDefiner _Define(SdfSpecType type) {
// Mark the definition as valid and return a pointer to it.
_specDefinitions[type].second = true;
return _SpecDefiner(this, &_specDefinitions[type].first);
}
/// Returns a _SpecDefiner for the previously-defined spec \p type
/// for specifying additional fields.
_SpecDefiner _ExtendSpecDefinition(SdfSpecType specType);
/// Registers the standard fields.
void _RegisterStandardFields();
/// Registers plugin fields and sets up handling so that fields will
/// be added when additional plugins are registered.
void _RegisterPluginFields();
/// Registers standard attribute value types.
void _RegisterStandardTypes();
/// Registers legacy attribute value types.
void _RegisterLegacyTypes();
/// Returns a type registrar.
_ValueTypeRegistrar _GetTypeRegistrar() const;
/// Factory function for creating a default value for a metadata
/// field. The parameters are the value type name and default
/// value (if any) specified in the defining plugin.
typedef std::function<VtValue(const std::string&, const JsValue&)>
_DefaultValueFactoryFn;
/// Registers all metadata fields specified in the given plugins
/// under the given metadata tag.
const std::vector<const SdfSchemaBase::FieldDefinition *>
_UpdateMetadataFromPlugins(const PlugPluginPtrVector& plugins,
const std::string& metadataTag =
std::string(),
const _DefaultValueFactoryFn& defFactory =
_DefaultValueFactoryFn());
private:
friend class _SpecDefiner;
void _OnDidRegisterPlugins(const PlugNotice::DidRegisterPlugins& n);
// Return a _SpecDefiner for an existing spec definition, \p local.
_SpecDefiner _Define(SpecDefinition *local) {
return _SpecDefiner(this, local);
}
void _AddRequiredFieldName(const TfToken &name);
const SpecDefinition* _CheckAndGetSpecDefinition(SdfSpecType type) const;
friend struct Sdf_SchemaFieldTypeRegistrar;
FieldDefinition& _CreateField(
const TfToken &fieldKey, const VtValue &fallback, bool plugin = false);
template <class T>
FieldDefinition& _DoRegisterField(const TfToken &fieldKey, const T &fallback)
{
return _DoRegisterField(fieldKey, VtValue(fallback));
}
FieldDefinition& _DoRegisterField(
const TfToken &fieldKey, const VtValue &fallback);
private:
typedef TfHashMap<TfToken, SdfSchemaBase::FieldDefinition,
TfToken::HashFunctor>
_FieldDefinitionMap;
_FieldDefinitionMap _fieldDefinitions;
// Pair of definition and flag indicating validity.
std::pair<SdfSchemaBase::SpecDefinition, bool>
_specDefinitions[SdfNumSpecTypes];
std::unique_ptr<Sdf_ValueTypeRegistry> _valueTypeRegistry;
TfTokenVector _requiredFieldNames;
};
/// \class SdfSchema
///
/// Class that provides information about the various scene description
/// fields.
///
class SdfSchema : public SdfSchemaBase {
public:
SDF_API
static const SdfSchema& GetInstance()
{
return TfSingleton<SdfSchema>::GetInstance();
}
private:
friend class TfSingleton<SdfSchema>;
SdfSchema();
virtual ~SdfSchema();
};
SDF_API_TEMPLATE_CLASS(TfSingleton<SdfSchema>);
///
/// The following fields are pre-registered by Sdf.
/// \showinitializer
#define SDF_FIELD_KEYS \
((Active, "active")) \
((AllowedTokens, "allowedTokens")) \
((AssetInfo, "assetInfo")) \
((ColorConfiguration, "colorConfiguration")) \
((ColorManagementSystem, "colorManagementSystem")) \
((ColorSpace, "colorSpace")) \
((Comment, "comment")) \
((ConnectionPaths, "connectionPaths")) \
((Custom, "custom")) \
((CustomData, "customData")) \
((CustomLayerData, "customLayerData")) \
((Default, "default")) \
((DefaultPrim, "defaultPrim")) \
((DisplayGroup, "displayGroup")) \
((DisplayGroupOrder, "displayGroupOrder")) \
((DisplayName, "displayName")) \
((DisplayUnit, "displayUnit")) \
((Documentation, "documentation")) \
((EndTimeCode, "endTimeCode")) \
((FramePrecision, "framePrecision")) \
((FramesPerSecond, "framesPerSecond")) \
((Hidden, "hidden")) \
((HasOwnedSubLayers, "hasOwnedSubLayers")) \
((InheritPaths, "inheritPaths")) \
((Instanceable, "instanceable")) \
((Kind, "kind")) \
((PrimOrder, "primOrder")) \
((NoLoadHint, "noLoadHint")) \
((Owner, "owner")) \
((Payload, "payload")) \
((Permission, "permission")) \
((Prefix, "prefix")) \
((PrefixSubstitutions, "prefixSubstitutions")) \
((PropertyOrder, "propertyOrder")) \
((References, "references")) \
((Relocates, "relocates")) \
((SessionOwner, "sessionOwner")) \
((Specializes, "specializes")) \
((Specifier, "specifier")) \
((StartTimeCode, "startTimeCode")) \
((SubLayers, "subLayers")) \
((SubLayerOffsets, "subLayerOffsets")) \
((Suffix, "suffix")) \
((SuffixSubstitutions, "suffixSubstitutions")) \
((SymmetricPeer, "symmetricPeer")) \
((SymmetryArgs, "symmetryArgs")) \
((SymmetryArguments, "symmetryArguments")) \
((SymmetryFunction, "symmetryFunction")) \
((TargetPaths, "targetPaths")) \
((TimeSamples, "timeSamples")) \
((TimeCodesPerSecond, "timeCodesPerSecond")) \
((TypeName, "typeName")) \
((VariantSelection, "variantSelection")) \
((Variability, "variability")) \
((VariantSetNames, "variantSetNames")) \
\
/* XXX: These fields should move into Sd. See bug 123508. */ \
((EndFrame, "endFrame")) \
((StartFrame, "startFrame"))
#define SDF_CHILDREN_KEYS \
((ConnectionChildren, "connectionChildren")) \
((ExpressionChildren, "expressionChildren")) \
((MapperArgChildren, "mapperArgChildren")) \
((MapperChildren, "mapperChildren")) \
((PrimChildren, "primChildren")) \
((PropertyChildren, "properties")) \
((RelationshipTargetChildren, "targetChildren")) \
((VariantChildren, "variantChildren")) \
((VariantSetChildren, "variantSetChildren"))
TF_DECLARE_PUBLIC_TOKENS(SdfFieldKeys, SDF_API, SDF_FIELD_KEYS);
TF_DECLARE_PUBLIC_TOKENS(SdfChildrenKeys, SDF_API, SDF_CHILDREN_KEYS);
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_SCHEMA_H
@@ -0,0 +1,181 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_SCHEMA_TYPE_REGISTRATION_H
#define PXR_USD_SDF_SCHEMA_TYPE_REGISTRATION_H
#include "pxr/pxr.h"
#include "pxr/usd/sdf/layerOffset.h"
#include "pxr/usd/sdf/listOp.h"
#include "pxr/usd/sdf/path.h"
#include "pxr/usd/sdf/schema.h"
#include "pxr/usd/sdf/types.h"
#include "pxr/base/vt/dictionary.h"
#include "pxr/base/vt/value.h"
#include "pxr/base/tf/enum.h"
#include "pxr/base/tf/token.h"
#include <string>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
// Defines the built-in scene description fields supplied by Sdf as
// well as their C++ value types. SdfSchema supplies additional information
// about these fields, such as their default value and validation functions.
//
// XXX: bug 123508
// StartFrame and EndFrame should be migrated to Sd.
//
#define _SDF_FIELDS \
((SdfFieldKeys->Active, bool)) \
((SdfFieldKeys->AllowedTokens, VtTokenArray)) \
((SdfFieldKeys->AssetInfo, VtDictionary)) \
((SdfFieldKeys->ColorConfiguration, SdfAssetPath)) \
((SdfFieldKeys->ColorManagementSystem, TfToken)) \
((SdfFieldKeys->ColorSpace, TfToken)) \
((SdfFieldKeys->Comment, std::string)) \
((SdfFieldKeys->ConnectionPaths, SdfPathListOp)) \
((SdfFieldKeys->Custom, bool)) \
((SdfFieldKeys->CustomData, VtDictionary)) \
((SdfFieldKeys->CustomLayerData, VtDictionary)) \
((SdfFieldKeys->Default, VtValue)) \
((SdfFieldKeys->DefaultPrim, TfToken)) \
((SdfFieldKeys->DisplayGroup, std::string)) \
((SdfFieldKeys->DisplayGroupOrder, VtStringArray)) \
((SdfFieldKeys->DisplayName, std::string)) \
((SdfFieldKeys->DisplayUnit, TfEnum)) \
((SdfFieldKeys->Documentation, std::string)) \
((SdfFieldKeys->EndFrame, double)) \
((SdfFieldKeys->EndTimeCode, double)) \
((SdfFieldKeys->FramePrecision, int)) \
((SdfFieldKeys->FramesPerSecond, double)) \
((SdfFieldKeys->Hidden, bool)) \
((SdfFieldKeys->HasOwnedSubLayers, bool)) \
((SdfFieldKeys->InheritPaths, SdfPathListOp)) \
((SdfFieldKeys->Instanceable, bool)) \
((SdfFieldKeys->Kind, TfToken)) \
((SdfFieldKeys->Owner, std::string)) \
((SdfFieldKeys->PrimOrder, std::vector<TfToken>)) \
((SdfFieldKeys->NoLoadHint, bool)) \
((SdfFieldKeys->Payload, SdfPayloadListOp)) \
((SdfFieldKeys->Permission, SdfPermission)) \
((SdfFieldKeys->Prefix, std::string)) \
((SdfFieldKeys->PrefixSubstitutions, VtDictionary)) \
((SdfFieldKeys->PropertyOrder, std::vector<TfToken>)) \
((SdfFieldKeys->References, SdfReferenceListOp)) \
((SdfFieldKeys->SessionOwner, std::string)) \
((SdfFieldKeys->TargetPaths, SdfPathListOp)) \
((SdfFieldKeys->TimeSamples, SdfTimeSampleMap)) \
((SdfFieldKeys->Relocates, SdfRelocatesMap)) \
((SdfFieldKeys->Specializes, SdfPathListOp)) \
((SdfFieldKeys->Specifier, SdfSpecifier)) \
((SdfFieldKeys->StartFrame, double)) \
((SdfFieldKeys->StartTimeCode, double)) \
((SdfFieldKeys->SubLayers, std::vector<std::string>)) \
((SdfFieldKeys->SubLayerOffsets, std::vector<SdfLayerOffset>)) \
((SdfFieldKeys->Suffix, std::string)) \
((SdfFieldKeys->SuffixSubstitutions, VtDictionary)) \
((SdfFieldKeys->SymmetricPeer, std::string)) \
((SdfFieldKeys->SymmetryArgs, VtDictionary)) \
((SdfFieldKeys->SymmetryArguments, VtDictionary)) \
((SdfFieldKeys->SymmetryFunction, TfToken)) \
((SdfFieldKeys->TimeCodesPerSecond, double)) \
((SdfFieldKeys->TypeName, TfToken)) \
((SdfFieldKeys->VariantSetNames, SdfStringListOp)) \
((SdfFieldKeys->VariantSelection, SdfVariantSelectionMap)) \
((SdfFieldKeys->Variability, SdfVariability)) \
((SdfChildrenKeys->ConnectionChildren, std::vector<SdfPath>)) \
((SdfChildrenKeys->ExpressionChildren, std::vector<TfToken>)) \
((SdfChildrenKeys->MapperArgChildren, std::vector<TfToken>)) \
((SdfChildrenKeys->MapperChildren, std::vector<SdfPath>)) \
((SdfChildrenKeys->PrimChildren, std::vector<TfToken>)) \
((SdfChildrenKeys->PropertyChildren, std::vector<TfToken>)) \
((SdfChildrenKeys->RelationshipTargetChildren, std::vector<SdfPath>)) \
((SdfChildrenKeys->VariantChildren, std::vector<TfToken>)) \
((SdfChildrenKeys->VariantSetChildren, std::vector<TfToken>))
#define _SDF_FIELDS_NAME(tup) BOOST_PP_TUPLE_ELEM(2, 0, tup)
#define _SDF_FIELDS_TYPE(tup) BOOST_PP_TUPLE_ELEM(2, 1, tup)
/// Registers each built-in Sd field along with its C++ value type with
/// \p reg. \p reg can be any type that has a member function:
/// template <class T> void RegisterField(const TfToken&);
///
/// This function will be invoked for each (field, type) pair. The template
/// type T will be the C++ value type and the TfToken will be the field name.
template <class Registrar>
inline void
SdfRegisterFields(Registrar* reg)
{
#define _SDF_REGISTER_FIELDS(r, unused, elem) \
reg->template RegisterField< _SDF_FIELDS_TYPE(elem) >(_SDF_FIELDS_NAME(elem));
BOOST_PP_SEQ_FOR_EACH(_SDF_REGISTER_FIELDS, ~, _SDF_FIELDS)
#undef _SDF_REGISTER_FIELDS
}
/// Registers all possible C++ value types for built-in fields with \p reg.
/// This is the set of C++ types that are used by built-in fields and could
/// be returned from an SdfAbstractData container. \p reg can be any type that
/// has a member function:
/// template <class T> void RegisterType();
///
/// This function will be invoked for each C++ value type, which will be
/// given to the function as the template type T. Note that this function may
/// be called with the same T multiple times.
template <class Registrar>
inline void
SdfRegisterTypes(Registrar* reg)
{
// Register all of the C++ value types from the field list above.
#define _SDF_REGISTER_TYPES(r, unused, elem) \
reg->template RegisterType< _SDF_FIELDS_TYPE(elem) >();
BOOST_PP_SEQ_FOR_EACH(_SDF_REGISTER_TYPES, ~, _SDF_FIELDS)
#undef _SDF_REGISTER_TYPES
// Also register all of the C++ value types for value types.
#define _SDF_REGISTER_VALUE_TYPES(r, unused, elem) \
{ \
reg->template RegisterType<SDF_VALUE_CPP_TYPE(elem)>(); \
reg->template RegisterType<SDF_VALUE_CPP_ARRAY_TYPE(elem)>(); \
}
BOOST_PP_SEQ_FOR_EACH(_SDF_REGISTER_VALUE_TYPES, ~, SDF_VALUE_TYPES)
#undef _SDF_REGISTER_VALUE_TYPES
// Also register all of the C++ list op types supported for
// generic plugin metadata.
reg->template RegisterType<SdfIntListOp>();
reg->template RegisterType<SdfInt64ListOp>();
reg->template RegisterType<SdfUIntListOp>();
reg->template RegisterType<SdfUInt64ListOp>();
reg->template RegisterType<SdfStringListOp>();
reg->template RegisterType<SdfTokenListOp>();
reg->template RegisterType<SdfValueBlock>();
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_SCHEMA_TYPE_REGISTRATION_H
+83
View File
@@ -0,0 +1,83 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_SITE_H
#define PXR_USD_SDF_SITE_H
#include "pxr/pxr.h"
#include "pxr/usd/sdf/layer.h"
#include "pxr/usd/sdf/path.h"
#include <set>
#include <vector>
#include <boost/operators.hpp>
PXR_NAMESPACE_OPEN_SCOPE
/// \class SdfSite
///
/// An SdfSite is a simple representation of a location in a layer where
/// opinions may possibly be found. It is simply a pair of layer and path
/// within that layer.
///
class SdfSite
: public boost::totally_ordered<SdfSite>
{
public:
SdfSite() { }
SdfSite(const SdfLayerHandle& layer_, const SdfPath& path_)
: layer(layer_)
, path(path_)
{ }
bool operator==(const SdfSite& other) const
{
return layer == other.layer && path == other.path;
}
bool operator<(const SdfSite& other) const
{
return layer < other.layer ||
(!(other.layer < layer) && path < other.path);
}
/// Explicit bool conversion operator. A site object converts to \c true iff
/// both the layer and path fields are filled with valid values, \c false
/// otherwise.
/// This does NOT imply that there are opinions in the layer at that path.
explicit operator bool() const
{
return layer && !path.IsEmpty();
}
public:
SdfLayerHandle layer;
SdfPath path;
};
typedef std::set<SdfSite> SdfSiteSet;
typedef std::vector<SdfSite> SdfSiteVector;
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_SITE_H
+95
View File
@@ -0,0 +1,95 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_SITE_UTILS_H
#define PXR_USD_SDF_SITE_UTILS_H
/// \file sdf/siteUtils.h
///
/// Convenience API for working with SdfSite.
///
/// These functions simply forward to the indicated functions on SdfLayer.
#include "pxr/pxr.h"
#include "pxr/usd/sdf/site.h"
#include "pxr/usd/sdf/layer.h"
#include "pxr/usd/sdf/primSpec.h"
#include "pxr/usd/sdf/propertySpec.h"
#include "pxr/usd/sdf/spec.h"
PXR_NAMESPACE_OPEN_SCOPE
inline
SdfSpecHandle
SdfGetObjectAtPath(const SdfSite& site)
{
return site.layer->GetObjectAtPath(site.path);
}
inline
SdfPrimSpecHandle
SdfGetPrimAtPath(const SdfSite& site)
{
return site.layer->GetPrimAtPath(site.path);
}
inline
SdfPropertySpecHandle
SdfGetPropertyAtPath(const SdfSite& site)
{
return site.layer->GetPropertyAtPath(site.path);
}
inline
bool
SdfHasField(const SdfSite& site, const TfToken& field)
{
return site.layer->HasField(site.path, field);
}
template <class T>
inline bool
SdfHasField(const SdfSite& site, const TfToken& field, T* value)
{
return site.layer->HasField(site.path, field, value);
}
inline
const VtValue
SdfGetField(const SdfSite& site, const TfToken& field)
{
return site.layer->GetField(site.path, field);
}
template <class T>
inline
T
SdfGetFieldAs(const SdfSite& site, const TfToken& field,
const T& defaultValue = T())
{
return site.layer->GetFieldAs<T>(site.path, field, defaultValue);
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_SITE_UTILS_H
+276
View File
@@ -0,0 +1,276 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_SPEC_H
#define PXR_USD_SDF_SPEC_H
/// \file sdf/spec.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/usd/sdf/abstractData.h"
#include "pxr/usd/sdf/identity.h"
#include "pxr/usd/sdf/declareSpec.h"
#include "pxr/usd/sdf/schema.h"
#include "pxr/usd/sdf/types.h"
#include "pxr/base/vt/value.h"
#include "pxr/base/tf/token.h"
#include "pxr/base/tf/type.h"
#include <boost/type_traits/is_base_of.hpp>
#include <boost/utility/enable_if.hpp>
#include <iosfwd>
PXR_NAMESPACE_OPEN_SCOPE
/// \class SdfSpec
///
/// Base class for all Sdf spec classes.
///
class SdfSpec
{
SDF_DECLARE_BASE_SPEC(SdfSpec);
public:
SDF_API
SdfSpec &operator=(const SdfSpec &other);
SDF_API
~SdfSpec();
/// \name SdSpec generic API
///
/// @{
/// Returns the SdfSchemaBase for the layer that owns this spec.
SDF_API
const SdfSchemaBase& GetSchema() const;
/// Returns the SdfSpecType specifying the spec type this object
/// represents.
SDF_API
SdfSpecType GetSpecType() const;
/// Returns true if this object is invalid or expired.
SDF_API
bool IsDormant() const;
/// Returns the layer that this object belongs to.
SDF_API
SdfLayerHandle GetLayer() const;
/// Returns the scene path of this object.
SDF_API
SdfPath GetPath() const;
/// Returns whether this object's layer can be edited.
SDF_API
bool PermissionToEdit() const;
/// Returns the full list of info keys currently set on this object.
/// \note This does not include fields that represent names of children.
SDF_API
std::vector<TfToken> ListInfoKeys() const;
/// Returns the list of metadata info keys for this object.
///
/// This is not the complete list of keys, it is only those that
/// should be considered to be metadata by inspectors or other
/// presentation UI.
///
/// This is interim API which is likely to change. Only editors with
/// an immediate specific need (like the Inspector) should use this API.
SDF_API
std::vector<TfToken> GetMetaDataInfoKeys() const;
/// Returns this metadata key's displayGroup.
///
SDF_API
TfToken GetMetaDataDisplayGroup(TfToken const &key) const;
/// Gets the value for the given metadata key.
///
/// This is interim API which is likely to change. Only editors with
/// an immediate specific need (like the Inspector) should use this API.
SDF_API
VtValue GetInfo(const TfToken &key) const;
/// Sets the value for the given metadata key.
///
/// It is an error to pass a value that is not the correct type for
/// that given key.
///
/// This is interim API which is likely to change. Only editors with
/// an immediate specific need (like the Inspector) should use this API.
SDF_API
void SetInfo(const TfToken &key, const VtValue &value);
/// Sets the value for \p entryKey to \p value within the dictionary
/// with the given metadata key \p dictionaryKey
SDF_API
void SetInfoDictionaryValue(const TfToken &dictionaryKey,
const TfToken &entryKey, const VtValue &value);
/// Returns whether there is a setting for the scene spec info
/// with the given key.
///
/// When asked for a value for one of its scene spec info, a valid value
/// will always be returned. But if this API returns \b false for a scene
/// spec info, the value of that info will be the defined default value.
///
/// When dealing with a composedLayer, it is not necessary to worry about
/// whether a scene spec info "has a value" because the composed layer will
/// always have a valid value, even if it is the default.
///
/// A spec may or may not have an expressed value for some of its
/// scene spec info.
///
/// This is interim API which is likely to change. Only editors with
/// an immediate specific need (like the Inspector) should use this API.
SDF_API
bool HasInfo(const TfToken &key) const;
/// Clears the value for scene spec info with the given \a key.
///
/// After calling this, HasInfo() will return \b false.
/// To make HasInfo() return \b true just set a value for that
/// scene spec info.
///
/// This is interim API which is likely to change. Only editors with
/// an immediate specific need (like the Inspector) should use this API.
SDF_API
void ClearInfo(const TfToken &key);
/// Returns the data type for the info with the given \a key.
SDF_API
TfType GetTypeForInfo(const TfToken &key) const;
/// Returns the fallback for the info with the given \a key.
SDF_API
const VtValue& GetFallbackForInfo(const TfToken &key) const;
/// Writes this spec to the given stream.
SDF_API
bool WriteToStream(std::ostream&, size_t indent = 0) const;
/// Returns whether this object has no significant data.
///
/// "Significant" here means that the object contributes opinions to
/// a scene. If this spec has any child scenegraph objects (e.g.,
/// prim or property spec), it will be considered significant even if
/// those child objects are not.
/// However, if \p ignoreChildren is \c true, these child objects
/// will be ignored.
SDF_API
bool IsInert(bool ignoreChildren = false) const;
/// @}
/// \name Field-based Generic API
/// @{
/// Returns all fields with values.
SDF_API
std::vector<TfToken> ListFields() const;
/// Returns \c true if the spec has a non-empty value with field
/// name \p name.
SDF_API
bool HasField(const TfToken &name) const;
/// Returns \c true if the object has a non-empty value with name
/// \p name and type \p T. If value ptr is provided, returns the
/// value found.
template <class T>
bool HasField(const TfToken &name, T* value) const
{
if (!value) {
return HasField(name);
}
SdfAbstractDataTypedValue<T> outValue(value);
return _HasField(name, &outValue);
}
/// Returns a field value by name.
SDF_API
VtValue GetField(const TfToken &name) const;
/// Returns a field value by name. If the object is invalid, or the
/// value doesn't exist, isn't set, or isn't of the given type then
/// returns defaultValue.
template <typename T>
T GetFieldAs(const TfToken & name, const T& defaultValue = T()) const
{
VtValue v = GetField(name);
if (v.IsEmpty() || !v.IsHolding<T>())
return defaultValue;
return v.UncheckedGet<T>();
}
/// Sets a field value as a boxed VtValue.
SDF_API
bool SetField(const TfToken & name, const VtValue& value);
/// Sets a field value of type T.
template <typename T>
bool SetField(const TfToken & name, const T& value)
{
return SetField(name, VtValue(value));
}
/// Clears a field.
SDF_API
bool ClearField(const TfToken & name);
/// @}
/// \name Comparison operators
/// @{
SDF_API bool operator==(const SdfSpec& rhs) const;
SDF_API bool operator<(const SdfSpec& rhs) const;
/// @}
/// Hash.
friend size_t hash_value(const SdfSpec &x) {
return hash_value(x._id);
}
private:
SDF_API
bool _HasField(const TfToken& name, SdfAbstractDataValue* value) const;
protected:
bool _MoveSpec(const SdfPath &oldPath, const SdfPath &newPath) const;
bool _DeleteSpec(const SdfPath &path);
private:
Sdf_IdentityRefPtr _id;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_SPEC_H
+103
View File
@@ -0,0 +1,103 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_SPEC_TYPE_H
#define PXR_USD_SDF_SPEC_TYPE_H
/// \file sdf/specType.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/types.h"
#include <typeinfo>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
class SdfSpec;
class TfType;
/// \class SdfSpecTypeRegistration
///
/// Provides functions to register spec types with the runtime typing system
/// used to cast between C++ spec types. Implementations of C++ spec types
/// should use as follows:
///
/// For a concrete spec type that corresponds to a specific SdfSpecType:
/// TF_REGISTRY_FUNCTION(SdfSpecTypeRegistration) {
/// SdfSpecTypeRegistration::RegisterSpecType<MyPrimSpec>();
/// }
///
/// For an abstract spec type that has no corresponding SdfSpecType:
/// TF_REGISTRY_FUNCTION(SdfSpecTypeRegistration) {
/// SdfSpecTypeRegistration::RegisterAbstractSpecType<MyPropertySpec>();
/// }
///
class SdfSpecTypeRegistration
{
public:
/// Registers the C++ type T as a concrete spec class.
template <class SchemaType, class SpecType>
static void RegisterSpecType(SdfSpecType specTypeEnum)
{
_RegisterSpecType(typeid(SpecType), specTypeEnum, typeid(SchemaType));
}
/// Registers the C++ type T as an abstract spec class.
template <class SchemaType, class SpecType>
static void RegisterAbstractSpecType()
{
_RegisterAbstractSpecType(typeid(SpecType), typeid(SchemaType));
}
private:
static void _RegisterSpecType(
const std::type_info& specCPPType, SdfSpecType specEnumType,
const std::type_info& schemaType);
static void _RegisterAbstractSpecType(
const std::type_info& specCPPType,
const std::type_info& schemaType);
};
// This class holds type information for specs. It associates a
// spec type with the corresponding TfType.
class Sdf_SpecType {
public:
// If \p spec can be represented by the C++ spec class \p to, returns
// the TfType for \p to. This includes verifying that \p spec's schema
// matches the schema associated with \p to.
static TfType Cast(const SdfSpec& spec, const std::type_info& to);
// Returns whether the \p spec can be represented by the C++ spec
// class \p to. This includes verifying that \p spec's schema matches
// the schema associated with \p to.
static bool CanCast(const SdfSpec& spec, const std::type_info& to);
// Returns whether a spec with spec type \p from can be represented by
// the C++ spec class \p to, regardless of schema.
static bool CanCast(SdfSpecType from, const std::type_info& to);
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_SPEC_TYPE_H
+122
View File
@@ -0,0 +1,122 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_TEXT_FILE_FORMAT_H
#define PXR_USD_SDF_TEXT_FILE_FORMAT_H
/// \file sdf/textFileFormat.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/usd/sdf/declareHandles.h"
#include "pxr/usd/sdf/fileFormat.h"
#include "pxr/base/tf/staticTokens.h"
#include <iosfwd>
#include <string>
PXR_NAMESPACE_OPEN_SCOPE
#define SDF_TEXT_FILE_FORMAT_TOKENS \
((Id, "sdf")) \
((Version, "1.4.32")) \
((Target, "sdf"))
TF_DECLARE_PUBLIC_TOKENS(SdfTextFileFormatTokens,
SDF_API, SDF_TEXT_FILE_FORMAT_TOKENS);
TF_DECLARE_WEAK_AND_REF_PTRS(SdfTextFileFormat);
SDF_DECLARE_HANDLES(SdfSpec);
/// \class SdfTextFileFormat
///
/// Sdf text file format
///
class SdfTextFileFormat : public SdfFileFormat
{
public:
// SdfFileFormat overrides.
SDF_API
virtual bool CanRead(const std::string &file) const override;
SDF_API
virtual bool Read(
SdfLayer* layer,
const std::string& resolvedPath,
bool metadataOnly) const override;
SDF_API
virtual bool WriteToFile(
const SdfLayer& layer,
const std::string& filePath,
const std::string& comment = std::string(),
const FileFormatArguments& args = FileFormatArguments()) const override;
SDF_API
virtual bool ReadFromString(
SdfLayer* layer,
const std::string& str) const override;
SDF_API
virtual bool WriteToString(
const SdfLayer& layer,
std::string* str,
const std::string& comment = std::string()) const override;
SDF_API
virtual bool WriteToStream(
const SdfSpecHandle &spec,
std::ostream& out,
size_t indent) const override;
protected:
SDF_FILE_FORMAT_FACTORY_ACCESS;
/// Destructor.
SDF_API
virtual ~SdfTextFileFormat();
/// Constructor.
SDF_API
SdfTextFileFormat();
/// Constructor. This form of the constructor may be used by formats that
/// use the .sdf text format as their internal representation.
/// If a non-empty versionString and target are provided, they will be
/// used as the file format version and target; otherwise the .sdf format
/// version and target will be implicitly used.
SDF_API
explicit SdfTextFileFormat(const TfToken& formatId,
const TfToken& versionString = TfToken(),
const TfToken& target = TfToken());
private:
// Override to return false. Reloading anonymous text layers clears their
// content.
SDF_API virtual bool _ShouldSkipAnonymousReload() const override;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // SDF_TEXT_FILE_FORMAT_H
+132
View File
@@ -0,0 +1,132 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
/* A Bison parser, made by GNU Bison 2.4.1. */
/* Skeleton interface for Bison's Yacc-like parsers in C
Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006
Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* As a special exception, you may create a larger work that contains
part or all of the Bison parser skeleton and distribute that work
under terms of your choice, so long as that work isn't itself a
parser generator using the skeleton or a modified version thereof
as a parser skeleton. Alternatively, if you modify or redistribute
the parser skeleton itself, you may (at your option) remove this
special exception, which will cause the skeleton and the resulting
Bison output files to be licensed under the GNU General Public
License without this special exception.
This special exception was added by the Free Software Foundation in
version 2.2 of Bison. */
/* Tokens. */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
/* Put the tokens into the symbol table, so that GDB and other debuggers
know about them. */
enum yytokentype {
TOK_NL = 258,
TOK_MAGIC = 259,
TOK_SYNTAX_ERROR = 260,
TOK_ASSETREF = 261,
TOK_PATHREF = 262,
TOK_IDENTIFIER = 263,
TOK_CXX_NAMESPACED_IDENTIFIER = 264,
TOK_NAMESPACED_IDENTIFIER = 265,
TOK_NUMBER = 266,
TOK_STRING = 267,
TOK_ABSTRACT = 268,
TOK_ADD = 269,
TOK_APPEND = 270,
TOK_CLASS = 271,
TOK_CONFIG = 272,
TOK_CONNECT = 273,
TOK_CUSTOM = 274,
TOK_CUSTOMDATA = 275,
TOK_DEF = 276,
TOK_DEFAULT = 277,
TOK_DELETE = 278,
TOK_DICTIONARY = 279,
TOK_DISPLAYUNIT = 280,
TOK_DOC = 281,
TOK_INHERITS = 282,
TOK_KIND = 283,
TOK_NAMECHILDREN = 284,
TOK_NONE = 285,
TOK_OFFSET = 286,
TOK_OVER = 287,
TOK_PERMISSION = 288,
TOK_PAYLOAD = 289,
TOK_PREFIX_SUBSTITUTIONS = 290,
TOK_SUFFIX_SUBSTITUTIONS = 291,
TOK_PREPEND = 292,
TOK_PROPERTIES = 293,
TOK_REFERENCES = 294,
TOK_RELOCATES = 295,
TOK_REL = 296,
TOK_RENAMES = 297,
TOK_REORDER = 298,
TOK_ROOTPRIMS = 299,
TOK_SCALE = 300,
TOK_SPECIALIZES = 301,
TOK_SUBLAYERS = 302,
TOK_SYMMETRYARGUMENTS = 303,
TOK_SYMMETRYFUNCTION = 304,
TOK_TIME_SAMPLES = 305,
TOK_UNIFORM = 306,
TOK_VARIANTS = 307,
TOK_VARIANTSET = 308,
TOK_VARIANTSETS = 309,
TOK_VARYING = 310
};
#endif
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
typedef int YYSTYPE;
# define YYSTYPE_IS_TRIVIAL 1
# define yystype YYSTYPE /* obsolescent; will be withdrawn */
# define YYSTYPE_IS_DECLARED 1
#endif
+172
View File
@@ -0,0 +1,172 @@
//
// Copyright 2019 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_TIME_CODE_H
#define PXR_USD_SDF_TIME_CODE_H
/// \file sdf/timeCode.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include <algorithm>
#include <functional>
#include <iosfwd>
PXR_NAMESPACE_OPEN_SCOPE
/// \class SdfTimeCode
///
/// Value type that represents a time code. It's equivalent to a double type
/// value but is used to indicate that this value should be resolved by any
/// time based value resolution.
///
class SdfTimeCode
{
public:
/// \name Constructors
/// @{
///
/// Construct a time code with the given time.
/// A default constructed SdfTimeCode has a time of 0.0.
/// A double value can implicitly cast to SdfTimeCode.
constexpr SdfTimeCode(double time = 0.0) noexcept : _time(time) {};
/// @}
///\name Operators
/// @{
constexpr bool operator==(const SdfTimeCode &rhs) const noexcept
{ return _time == rhs._time; }
constexpr bool operator!=(const SdfTimeCode &rhs) const noexcept
{ return _time != rhs._time; }
constexpr bool operator<(const SdfTimeCode &rhs) const noexcept
{ return _time < rhs._time; }
constexpr bool operator>(const SdfTimeCode &rhs) const noexcept
{ return _time > rhs._time; }
constexpr bool operator<=(const SdfTimeCode &rhs) const noexcept
{ return _time <= rhs._time; }
constexpr bool operator>=(const SdfTimeCode &rhs) const noexcept
{ return _time >= rhs._time; }
constexpr SdfTimeCode operator*(const SdfTimeCode &rhs) const noexcept
{ return SdfTimeCode(_time * rhs._time); }
constexpr SdfTimeCode operator/(const SdfTimeCode &rhs) const noexcept
{ return SdfTimeCode(_time / rhs._time); }
constexpr SdfTimeCode operator+(const SdfTimeCode &rhs) const noexcept
{ return SdfTimeCode(_time + rhs._time); }
constexpr SdfTimeCode operator-(const SdfTimeCode &rhs) const noexcept
{ return SdfTimeCode(_time - rhs._time); }
/// Explicit conversion to double
explicit constexpr operator double() const noexcept {return _time;}
/// Hash function
size_t GetHash() const {
return std::hash<double>()(_time);
}
/// \class Hash
struct Hash
{
size_t operator()(const SdfTimeCode &ap) const {
return ap.GetHash();
}
};
friend size_t hash_value(const SdfTimeCode &ap) { return ap.GetHash(); }
/// @}
/// \name Accessors
/// @{
/// Return the time value.
constexpr double GetValue() const noexcept {
return _time;
}
/// @}
private:
friend inline void swap(SdfTimeCode &lhs, SdfTimeCode &rhs) {
std::swap(lhs._time, rhs._time);
}
double _time;
};
/// \name Related
/// Binary arithmetic and comparison operators with double valued lefthand side.
/// @{
inline constexpr
SdfTimeCode operator*(double time, const SdfTimeCode &timeCode) noexcept
{ return SdfTimeCode(time) * timeCode; }
inline constexpr
SdfTimeCode operator/(double time, const SdfTimeCode &timeCode) noexcept
{ return SdfTimeCode(time) / timeCode; }
inline constexpr
SdfTimeCode operator+(double time, const SdfTimeCode &timeCode) noexcept
{ return SdfTimeCode(time) + timeCode; }
inline constexpr
SdfTimeCode operator-(double time, const SdfTimeCode &timeCode) noexcept
{ return SdfTimeCode(time) - timeCode; }
inline constexpr
bool operator==(double time, const SdfTimeCode &timeCode) noexcept
{ return SdfTimeCode(time) == timeCode; }
inline constexpr
bool operator!=(double time, const SdfTimeCode &timeCode) noexcept
{ return SdfTimeCode(time) != timeCode; }
inline constexpr
bool operator<(double time, const SdfTimeCode &timeCode) noexcept
{ return SdfTimeCode(time) < timeCode; }
inline constexpr
bool operator>(double time, const SdfTimeCode &timeCode) noexcept
{ return SdfTimeCode(time) > timeCode; }
inline constexpr
bool operator<=(double time, const SdfTimeCode &timeCode) noexcept
{ return SdfTimeCode(time) <= timeCode; }
inline constexpr
bool operator>=(double time, const SdfTimeCode &timeCode) noexcept
{ return SdfTimeCode(time) >= timeCode; }
/// Stream insertion operator for the string representation of this time code.
SDF_API std::ostream& operator<<(std::ostream& out, const SdfTimeCode& ap);
/// @}
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_TIME_CODE_H
+74
View File
@@ -0,0 +1,74 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_TOKENS_H
#define PXR_USD_SDF_TOKENS_H
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/base/tf/staticTokens.h"
PXR_NAMESPACE_OPEN_SCOPE
// Miscellaneous Tokens
#define SDF_TOKENS \
((AnyTypeToken, "__AnyType__"))
TF_DECLARE_PUBLIC_TOKENS(SdfTokens, SDF_API, SDF_TOKENS);
#define SDF_PATH_NS_DELIMITER_CHAR ':'
#define SDF_PATH_NS_DELIMITER_STR ":"
#define SDF_PATH_TOKENS \
((menvaStart, "<")) \
((menvaEnd, ">")) \
((absoluteIndicator, "/")) \
((relativeRoot, ".")) \
((childDelimiter, "/")) \
((propertyDelimiter, ".")) \
((relationshipTargetStart, "[")) \
((relationshipTargetEnd, "]")) \
((parentPathElement, "..")) \
((mapperIndicator, "mapper")) \
((expressionIndicator, "expression")) \
((mapperArgDelimiter, ".")) \
((namespaceDelimiter, SDF_PATH_NS_DELIMITER_STR)) \
((empty, ""))
TF_DECLARE_PUBLIC_TOKENS(SdfPathTokens, SDF_API, SDF_PATH_TOKENS);
#define SDF_METADATA_DISPLAYGROUP_TOKENS \
((core, "")) \
((internal, "Internal")) \
((dmanip, "Direct Manip")) \
((pipeline, "Pipeline")) \
((symmetry, "Symmetry")) \
((ui, "User Interface"))
TF_DECLARE_PUBLIC_TOKENS(SdfMetadataDisplayGroupTokens,
SDF_API,
SDF_METADATA_DISPLAYGROUP_TOKENS);
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_TOKENS_H
+632
View File
@@ -0,0 +1,632 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_TYPES_H
#define PXR_USD_SDF_TYPES_H
/// \file sdf/types.h
/// Basic Sdf data types
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/usd/sdf/assetPath.h"
#include "pxr/usd/sdf/declareHandles.h"
#include "pxr/usd/sdf/listOp.h"
#include "pxr/usd/sdf/timeCode.h"
#include "pxr/usd/sdf/valueTypeName.h"
#include "pxr/base/arch/demangle.h"
#include "pxr/base/arch/inttypes.h"
#include "pxr/base/gf/half.h"
#include "pxr/base/gf/matrix2d.h"
#include "pxr/base/gf/matrix3d.h"
#include "pxr/base/gf/matrix4d.h"
#include "pxr/base/gf/quatd.h"
#include "pxr/base/gf/quatf.h"
#include "pxr/base/gf/quath.h"
#include "pxr/base/gf/vec2d.h"
#include "pxr/base/gf/vec2f.h"
#include "pxr/base/gf/vec2h.h"
#include "pxr/base/gf/vec2i.h"
#include "pxr/base/gf/vec3d.h"
#include "pxr/base/gf/vec3f.h"
#include "pxr/base/gf/vec3h.h"
#include "pxr/base/gf/vec3i.h"
#include "pxr/base/gf/vec4d.h"
#include "pxr/base/gf/vec4f.h"
#include "pxr/base/gf/vec4h.h"
#include "pxr/base/gf/vec4i.h"
#include "pxr/base/tf/enum.h"
#include "pxr/base/tf/preprocessorUtils.h"
#include "pxr/base/tf/staticTokens.h"
#include "pxr/base/tf/token.h"
#include "pxr/base/tf/type.h"
#include "pxr/base/vt/array.h"
#include "pxr/base/vt/dictionary.h"
#include "pxr/base/vt/value.h"
#include <boost/noncopyable.hpp>
#include <boost/preprocessor/list/for_each.hpp>
#include <boost/preprocessor/list/size.hpp>
#include <boost/preprocessor/punctuation/comma.hpp>
#include <boost/preprocessor/selection/max.hpp>
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/seq/seq.hpp>
#include <boost/preprocessor/tuple/elem.hpp>
#include <boost/shared_ptr.hpp>
#include <iosfwd>
#include <list>
#include <map>
#include <stdint.h>
#include <string>
#include <typeinfo>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
class SdfPath;
/// An enum that specifies the type of an object. Objects
/// are entities that have fields and are addressable by path.
enum SdfSpecType {
// The unknown type has a value of 0 so that SdfSpecType() is unknown.
SdfSpecTypeUnknown = 0,
// Real concrete types
SdfSpecTypeAttribute,
SdfSpecTypeConnection,
SdfSpecTypeExpression,
SdfSpecTypeMapper,
SdfSpecTypeMapperArg,
SdfSpecTypePrim,
SdfSpecTypePseudoRoot,
SdfSpecTypeRelationship,
SdfSpecTypeRelationshipTarget,
SdfSpecTypeVariant,
SdfSpecTypeVariantSet,
SdfNumSpecTypes
};
/// An enum that identifies the possible specifiers for an
/// SdfPrimSpec. The SdfSpecifier enum is registered as a TfEnum
/// for converting to and from <c>std::string</c>.
///
/// <b>SdfSpecifier:</b>
/// <ul>
/// <li><b>SdfSpecifierDef.</b> Defines a concrete prim.
/// <li><b>SdfSpecifierOver.</b> Overrides an existing prim.
/// <li><b>SdfSpecifierClass.</b> Defines an abstract prim.
/// <li><b>SdfNumSpecifiers.</b> The number of specifiers.
/// </ul>
///
enum SdfSpecifier {
SdfSpecifierDef,
SdfSpecifierOver,
SdfSpecifierClass,
SdfNumSpecifiers
};
/// Returns true if the specifier defines a prim.
inline
bool
SdfIsDefiningSpecifier(SdfSpecifier spec)
{
return (spec != SdfSpecifierOver);
}
/// An enum that defines permission levels.
///
/// Permissions control which layers may refer to or express
/// opinions about a prim. Opinions expressed about a prim, or
/// relationships to that prim, by layers that are not allowed
/// permission to access the prim will be ignored.
///
/// <b>SdfPermission:</b>
/// <ul>
/// <li><b>SdfPermissionPublic.</b> Public prims can be referred to by
/// anything. (Available to any client.)
/// <li><b>SdfPermissionPrivate.</b> Private prims can be referred to
/// only within the local layer stack, and not across references
/// or inherits. (Not available to clients.)
/// <li><b>SdfNumPermission.</b> Internal sentinel value.
/// </ul>
///
enum SdfPermission {
SdfPermissionPublic,
SdfPermissionPrivate,
SdfNumPermissions
};
/// An enum that identifies variability types for attributes.
/// Variability indicates whether the attribute may vary over time and
/// value coordinates, and if its value comes through authoring or
/// or from its owner.
///
/// <b>SdfVariability:</b>
/// <ul>
/// <li><b>SdfVariabilityVarying.</b> Varying attributes may be directly
/// authored, animated and affected on by Actions. They are the
/// most flexible.
/// <li><b>SdfVariabilityUniform.</b> Uniform attributes may be authored
/// only with non-animated values (default values). They cannot
/// be affected by Actions, but they can be connected to other
/// Uniform attributes.
/// <li><b>SdNumVariabilities.</b> Internal sentinel value.
/// </ul>
///
enum SdfVariability {
SdfVariabilityVarying,
SdfVariabilityUniform,
SdfNumVariabilities
};
/// An enum for TfError codes related to authoring operations.
///
/// <b>SdfAuthoringError:</b>
/// <ul>
/// <li><b>SdfAuthoringErrorUnrecognizedFields.</b> This error is raised if
/// SdfLayer::TransferContent, or SdfLayer::SetField API is called
/// for layers of differing schema, and fields from the source layer
/// are not recognized by the target layer's schema.
/// <li><b>SdfAuthoringErrorUnrecognizedSpecType.</b> This error is raised
/// in attempts to create specs on layers with spec types that are
/// not recognized by the layer's schema.
/// </ul>
///
enum SdfAuthoringError
{
SdfAuthoringErrorUnrecognizedFields,
SdfAuthoringErrorUnrecognizedSpecType
};
// Each category of compatible units of measurement is defined by a
// preprocessor sequence of tuples. Each such sequence gives rise to an enum
// representing the corresponding unit category. All the unit categories are
// listed in _SDF_UNITS where each entry is a two-tuple with the unit category
// name as the first element, and the second element is the units in that
// category. Each tuple in a unit category sequence corresponds to a unit of
// measurement represented by an enumerant whose name is given by concatenating
// 'Sdf', the unit category name, the word 'Unit' and the first entry in the
// tuple. (E.g. units of category 'Length' are represented by an enum named
// SdfLengthUnit with enumerants SdfLengthUnitInch, SdfLengthUnitMeter and so
// forth.) The second element in the tuple is the display name for the unit,
// and the third element is the relative size of the unit compared to the menv
// default unit for the unit category (which has a relative size of 1.0).
// Dimensionless quantities use a special 'Dimensionless' unit category
// represented by the enum SdfDimensionlessUnit.
#define _SDF_LENGTH_UNITS \
((Millimeter, "mm", 0.001)) \
((Centimeter, "cm", 0.01)) \
((Decimeter, "dm", 0.1)) \
((Meter, "m", 1.0)) \
((Kilometer, "km", 1000.0)) \
((Inch, "in", 0.0254)) \
((Foot, "ft", 0.3048)) \
((Yard, "yd", 0.9144)) \
((Mile, "mi", 1609.344))
#define _SDF_ANGULAR_UNITS \
((Degrees, "deg", 1.0)) \
((Radians, "rad", 57.2957795130823208768))
#define _SDF_DIMENSIONLESS_UNITS \
((Percent, "%", 0.01)) \
((Default, "default", 1.0))
#define _SDF_UNITS \
((Length, _SDF_LENGTH_UNITS), \
((Angular, _SDF_ANGULAR_UNITS), \
((Dimensionless, _SDF_DIMENSIONLESS_UNITS), \
BOOST_PP_NIL)))
#define _SDF_UNIT_TAG(tup) BOOST_PP_TUPLE_ELEM(3, 0, tup)
#define _SDF_UNIT_NAME(tup) BOOST_PP_TUPLE_ELEM(3, 1, tup)
#define _SDF_UNIT_SCALE(tup) BOOST_PP_TUPLE_ELEM(3, 2, tup)
#define _SDF_UNITSLIST_CATEGORY(tup) BOOST_PP_TUPLE_ELEM(2, 0, tup)
#define _SDF_UNITSLIST_TUPLES(tup) BOOST_PP_TUPLE_ELEM(2, 1, tup)
#define _SDF_UNITSLIST_ENUM(elem) BOOST_PP_CAT(BOOST_PP_CAT(Sdf, \
_SDF_UNITSLIST_CATEGORY(elem)), Unit)
#define _SDF_DECLARE_UNIT_ENUMERANT(r, tag, elem) \
BOOST_PP_CAT(Sdf ## tag ## Unit, _SDF_UNIT_TAG(elem)),
#define _SDF_DECLARE_UNIT_ENUM(r, unused, elem) \
enum _SDF_UNITSLIST_ENUM(elem) { \
BOOST_PP_SEQ_FOR_EACH(_SDF_DECLARE_UNIT_ENUMERANT, \
_SDF_UNITSLIST_CATEGORY(elem), \
_SDF_UNITSLIST_TUPLES(elem)) \
};
BOOST_PP_LIST_FOR_EACH(_SDF_DECLARE_UNIT_ENUM, ~, _SDF_UNITS)
// Compute the max number of enumerants over all unit enums
#define _SDF_MAX_UNITS_OP(d, state, list) \
BOOST_PP_MAX_D(d, state, BOOST_PP_SEQ_SIZE(_SDF_UNITSLIST_TUPLES(list)))
#define _SDF_UNIT_MAX_UNITS \
BOOST_PP_LIST_FOLD_LEFT(_SDF_MAX_UNITS_OP, 0, _SDF_UNITS)
// Compute the number of unit enums
#define _SDF_UNIT_NUM_TYPES BOOST_PP_LIST_SIZE(_SDF_UNITS)
// Compute the number of bits needed to hold _SDF_UNIT_MAX_UNITS and
// _SDF_UNIT_NUM_TYPES.
#define _SDF_UNIT_MAX_UNITS_BITS TF_BITS_FOR_VALUES(_SDF_UNIT_MAX_UNITS)
#define _SDF_UNIT_TYPES_BITS TF_BITS_FOR_VALUES(_SDF_UNIT_NUM_TYPES)
/// A map of mapper parameter names to parameter values.
typedef std::map<std::string, VtValue> SdfMapperParametersMap;
/// A map of reference variant set names to variants in those sets.
typedef std::map<std::string, std::string> SdfVariantSelectionMap;
/// A map of variant set names to list of variants in those sets.
typedef std::map<std::string, std::vector<std::string> > SdfVariantsMap;
/// A map of source SdfPaths to target SdfPaths for relocation.
// Note: This map needs to be lexicographically sorted for Csd composition
// implementation, so SdfPath::FastLessThan is explicitly omitted as
// the Compare template parameter.
typedef std::map<SdfPath, SdfPath> SdfRelocatesMap;
/// A map from sample times to sample values.
typedef std::map<double, VtValue> SdfTimeSampleMap;
/// Gets the show default unit for the given /a typeName.
SDF_API TfEnum SdfDefaultUnit( TfToken const &typeName );
/// Gets the show default unit for the given /a unit.
SDF_API const TfEnum &SdfDefaultUnit( const TfEnum &unit );
/// Gets the unit category for a given /a unit.
SDF_API const std::string &SdfUnitCategory( const TfEnum &unit );
/// Converts from one unit of measure to another. The \a fromUnit and \a toUnit
/// units must be of the same type (for example, both of type SdfLengthUnit).
SDF_API double SdfConvertUnit( const TfEnum &fromUnit, const TfEnum &toUnit );
/// Gets the name for a given /a unit.
SDF_API const std::string &SdfGetNameForUnit( const TfEnum &unit );
/// Gets a unit for the given /a name
SDF_API const TfEnum &SdfGetUnitFromName( const std::string &name );
/// Given a value, returns if there is a valid corresponding valueType.
SDF_API bool SdfValueHasValidType(VtValue const& value);
/// Given an sdf valueType name, produce TfType if the type name specifies a
/// valid sdf value type.
SDF_API TfType SdfGetTypeForValueTypeName(TfToken const &name);
/// Given a value, produce the sdf valueType name. If you provide a value that
/// does not return true for SdfValueHasValidType, the return value is
/// unspecified.
SDF_API SdfValueTypeName SdfGetValueTypeNameForValue(VtValue const &value);
/// Return role name for \p typeName. Return empty token if \p typeName has no
/// associated role name.
SDF_API TfToken SdfGetRoleNameForValueTypeName(TfToken const &typeName);
// Sdf allows a specific set of types for attribute and metadata values.
// These types and some additional metadata are listed in the preprocessor
// sequence of tuples below. First element is a tag name that is appended to
// 'SdfValueType' to produce the C++ traits type for the value type.
// Second element is the value type name, third element is the corresponding
// C++ type, and the fourth element is the tuple of tuple dimensions.
//
// Libraries may extend this list and define additional value types.
// When doing so, the type must be declared using the SDF_DECLARE_VALUE_TYPE
// macro below. The type must also be registered in the associated schema using
// SdfSchema::_RegisterValueType(s).
#define _SDF_SCALAR_VALUE_TYPES \
((Bool, bool, bool, () )) \
((UChar, uchar, unsigned char, () )) \
((Int, int, int, () )) \
((UInt, uint, unsigned int, () )) \
((Int64, int64, int64_t, () )) \
((UInt64, uint64, uint64_t, () )) \
((Half, half, GfHalf, () )) \
((Float, float, float, () )) \
((Double, double, double, () )) \
((TimeCode, timecode, SdfTimeCode, () )) \
((String, string, std::string, () )) \
((Token, token, TfToken, () )) \
((Asset, asset, SdfAssetPath, () ))
#define _SDF_DIMENSIONED_VALUE_TYPES \
((Matrix2d, matrix2d, GfMatrix2d, (2,2) )) \
((Matrix3d, matrix3d, GfMatrix3d, (3,3) )) \
((Matrix4d, matrix4d, GfMatrix4d, (4,4) )) \
((Quath, quath, GfQuath, (4) )) \
((Quatf, quatf, GfQuatf, (4) )) \
((Quatd, quatd, GfQuatd, (4) )) \
((Int2, int2, GfVec2i, (2) )) \
((Half2, half2, GfVec2h, (2) )) \
((Float2, float2, GfVec2f, (2) )) \
((Double2, double2, GfVec2d, (2) )) \
((Int3, int3, GfVec3i, (3) )) \
((Half3, half3, GfVec3h, (3) )) \
((Float3, float3, GfVec3f, (3) )) \
((Double3, double3, GfVec3d, (3) )) \
((Int4, int4, GfVec4i, (4) )) \
((Half4, half4, GfVec4h, (4) )) \
((Float4, float4, GfVec4f, (4) )) \
((Double4, double4, GfVec4d, (4) ))
#define SDF_VALUE_TYPES _SDF_SCALAR_VALUE_TYPES _SDF_DIMENSIONED_VALUE_TYPES
// Accessors for individual elements in the value types tuples.
#define SDF_VALUE_CPP_TYPE(tup) BOOST_PP_TUPLE_ELEM(4, 2, tup)
#define SDF_VALUE_CPP_ARRAY_TYPE(tup) VtArray<BOOST_PP_TUPLE_ELEM(4, 2, tup)>
template <class T>
struct SdfValueTypeTraits {
static const bool IsValueType = false;
};
// Allow character arrays to be treated as Sdf value types.
// Sdf converts character arrays to strings for scene description.
template <int N>
struct SdfValueTypeTraits<char[N]> {
static const bool IsValueType = true;
};
#define SDF_DECLARE_VALUE_TYPE_TRAITS(r, unused, elem) \
template <> \
struct SdfValueTypeTraits<SDF_VALUE_CPP_TYPE(elem)> { \
static const bool IsValueType = true; \
}; \
template <> \
struct SdfValueTypeTraits<SDF_VALUE_CPP_ARRAY_TYPE(elem)> { \
static const bool IsValueType = true; \
};
BOOST_PP_SEQ_FOR_EACH(SDF_DECLARE_VALUE_TYPE_TRAITS, ~, SDF_VALUE_TYPES);
/// Convert \p dict to a valid metadata dictionary for scene description. Valid
/// metadata dictionaries have values that are any of SDF_VALUE_TYPES (or
/// VtArrays of those), plus VtDictionary with values of those types (or
/// similarly nested VtDictionaries).
///
/// Certain conversions are performed in an attempt to produce a valid metadata
/// dictionary. For example:
///
/// Convert std::vector<VtValue> to VtArray<T> where T is the type of the first
/// element in the vector. Fail conversion for empty vectors where a concrete
/// type cannot be inferred.
///
/// Convert python sequences to VtArray<T> where T is the type of the first
/// element in the python sequence, when converted to VtValue, if that T is an
/// SDF_VALUE_TYPE). Fail conversion for empty sequences where a concrete type
/// cannot be inferred.
///
/// If any values cannot be converted to valid SDF_VALUE_TYPES, omit those
/// elements and add a message to \p errMsg indicating which values were
/// omitted.
///
SDF_API
bool
SdfConvertToValidMetadataDictionary(VtDictionary *dict, std::string *errMsg);
#define SDF_VALUE_ROLE_NAME_TOKENS \
(Point) \
(Normal) \
(Vector) \
(Color) \
(Frame) \
(Transform) \
(PointIndex) \
(EdgeIndex) \
(FaceIndex) \
(TextureCoordinate)
TF_DECLARE_PUBLIC_TOKENS(SdfValueRoleNames, SDF_API, SDF_VALUE_ROLE_NAME_TOKENS);
SDF_DECLARE_HANDLES(SdfLayer);
SDF_DECLARE_HANDLES(SdfAttributeSpec);
SDF_DECLARE_HANDLES(SdfPrimSpec);
SDF_DECLARE_HANDLES(SdfPropertySpec);
SDF_DECLARE_HANDLES(SdfSpec);
SDF_DECLARE_HANDLES(SdfRelationshipSpec);
SDF_DECLARE_HANDLES(SdfVariantSetSpec);
SDF_DECLARE_HANDLES(SdfVariantSpec);
typedef std::map<std::string, SdfVariantSetSpecHandle>
SdfVariantSetSpecHandleMap;
/// Writes the string representation of \c SdfSpecifier to \a out.
SDF_API
std::ostream & operator<<( std::ostream &out, const SdfSpecifier &spec );
/// Writes the string representation of \c SdfRelocatesMap to \a out.
SDF_API
std::ostream & operator<<( std::ostream &out,
const SdfRelocatesMap &reloMap );
/// Writes the string representation of \c SdfTimeSampleMap to \a out.
SDF_API
std::ostream & operator<<( std::ostream &out,
const SdfTimeSampleMap &sampleMap );
SDF_API
std::ostream &VtStreamOut(const SdfVariantSelectionMap &, std::ostream &);
/// \class SdfUnregisteredValue
/// Stores a representation of the value for an unregistered metadata
/// field encountered during text layer parsing.
///
/// This provides the ability to serialize this data to a layer, as
/// well as limited inspection and editing capabilities (e.g., moving
/// this data to a different spec or field) even when the data type
/// of the value isn't known.
class SdfUnregisteredValue :
public boost::equality_comparable<SdfUnregisteredValue>
{
public:
/// Wraps an empty VtValue
SDF_API SdfUnregisteredValue();
/// Wraps a std::string
SDF_API explicit SdfUnregisteredValue(const std::string &value);
/// Wraps a VtDictionary
SDF_API explicit SdfUnregisteredValue(const VtDictionary &value);
/// Wraps a SdfUnregisteredValueListOp
SDF_API explicit SdfUnregisteredValue(const SdfUnregisteredValueListOp &value);
/// Returns the wrapped VtValue specified in the constructor
const VtValue& GetValue() const {
return _value;
}
/// Hash.
friend size_t hash_value(const SdfUnregisteredValue &uv) {
return uv._value.GetHash();
}
/// Returns true if the wrapped VtValues are equal
SDF_API bool operator==(const SdfUnregisteredValue &other) const;
private:
VtValue _value;
};
/// Writes the string representation of \c SdfUnregisteredValue to \a out.
SDF_API std::ostream &operator << (std::ostream &out, const SdfUnregisteredValue &value);
class Sdf_ValueTypeNamesType : boost::noncopyable {
public:
SdfValueTypeName Bool;
SdfValueTypeName UChar, Int, UInt, Int64, UInt64;
SdfValueTypeName Half, Float, Double, TimeCode;
SdfValueTypeName String, Token, Asset;
SdfValueTypeName Int2, Int3, Int4;
SdfValueTypeName Half2, Half3, Half4;
SdfValueTypeName Float2, Float3, Float4;
SdfValueTypeName Double2, Double3, Double4;
SdfValueTypeName Point3h, Point3f, Point3d;
SdfValueTypeName Vector3h, Vector3f, Vector3d;
SdfValueTypeName Normal3h, Normal3f, Normal3d;
SdfValueTypeName Color3h, Color3f, Color3d;
SdfValueTypeName Color4h, Color4f, Color4d;
SdfValueTypeName Quath, Quatf, Quatd;
SdfValueTypeName Matrix2d, Matrix3d, Matrix4d;
SdfValueTypeName Frame4d;
SdfValueTypeName TexCoord2h, TexCoord2f, TexCoord2d;
SdfValueTypeName TexCoord3h, TexCoord3f, TexCoord3d;
SdfValueTypeName BoolArray;
SdfValueTypeName UCharArray, IntArray, UIntArray, Int64Array, UInt64Array;
SdfValueTypeName HalfArray, FloatArray, DoubleArray, TimeCodeArray;
SdfValueTypeName StringArray, TokenArray, AssetArray;
SdfValueTypeName Int2Array, Int3Array, Int4Array;
SdfValueTypeName Half2Array, Half3Array, Half4Array;
SdfValueTypeName Float2Array, Float3Array, Float4Array;
SdfValueTypeName Double2Array, Double3Array, Double4Array;
SdfValueTypeName Point3hArray, Point3fArray, Point3dArray;
SdfValueTypeName Vector3hArray, Vector3fArray, Vector3dArray;
SdfValueTypeName Normal3hArray, Normal3fArray, Normal3dArray;
SdfValueTypeName Color3hArray, Color3fArray, Color3dArray;
SdfValueTypeName Color4hArray, Color4fArray, Color4dArray;
SdfValueTypeName QuathArray, QuatfArray, QuatdArray;
SdfValueTypeName Matrix2dArray, Matrix3dArray, Matrix4dArray;
SdfValueTypeName Frame4dArray;
SdfValueTypeName TexCoord2hArray, TexCoord2fArray, TexCoord2dArray;
SdfValueTypeName TexCoord3hArray, TexCoord3fArray, TexCoord3dArray;
SDF_API ~Sdf_ValueTypeNamesType();
struct _Init {
SDF_API static const Sdf_ValueTypeNamesType* New();
};
// For Pixar internal backwards compatibility.
TfToken GetSerializationName(const SdfValueTypeName&) const;
TfToken GetSerializationName(const VtValue&) const;
TfToken GetSerializationName(const TfToken&) const;
private:
friend const Sdf_ValueTypeNamesType* Sdf_InitializeValueTypeNames();
Sdf_ValueTypeNamesType();
};
extern SDF_API TfStaticData<const Sdf_ValueTypeNamesType,
Sdf_ValueTypeNamesType::_Init> SdfValueTypeNames;
/// \class SdfValueBlock
/// A special value type that can be used to explicitly author an
/// opinion for an attribute's default value or time sample value
/// that represents having no value. Note that this is different
/// from not having a value authored.
///
/// One could author such a value in two ways.
///
/// \code
/// attribute->SetDefaultValue(VtValue(SdfValueBlock());
/// ...
/// layer->SetTimeSample(attribute->GetPath(), 101, VtValue(SdfValueBlock()));
/// \endcode
///
struct SdfValueBlock {
bool operator==(const SdfValueBlock& block) const { return true; }
bool operator!=(const SdfValueBlock& block) const { return false; }
private:
friend inline size_t hash_value(const SdfValueBlock &block) { return 0; }
};
// Write out the string representation of a block.
SDF_API std::ostream& operator<<(std::ostream&, SdfValueBlock const&);
// A class that represents a human-readable value. This is used for the special
// purpose of producing layers that serialize field values in alternate ways; to
// produce more human-readable output, for example.
struct SdfHumanReadableValue {
SdfHumanReadableValue() = default;
explicit SdfHumanReadableValue(std::string const &text) : _text(text) {}
bool operator==(SdfHumanReadableValue const &other) const {
return GetText() == other.GetText();
}
bool operator!=(SdfHumanReadableValue const &other) const {
return !(*this == other);
}
std::string const &GetText() const { return _text; }
private:
std::string _text;
};
SDF_API
std::ostream &operator<<(std::ostream &out, const SdfHumanReadableValue &hrval);
SDF_API
size_t hash_value(const SdfHumanReadableValue &hrval);
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_TYPES_H
+238
View File
@@ -0,0 +1,238 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_VALUE_TYPE_NAME_H
#define PXR_USD_SDF_VALUE_TYPE_NAME_H
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/base/tf/token.h"
#include <iosfwd>
#include <string>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
class TfEnum;
class TfType;
class VtValue;
class Sdf_ValueTypeImpl;
/// \struct SdfTupleDimensions
///
/// Represents the shape of a value type (or that of an element in an array).
///
struct SdfTupleDimensions
{
public:
SdfTupleDimensions() : size(0) {}
SdfTupleDimensions(size_t m) : size(1) { d[0] = m; }
SdfTupleDimensions(size_t m, size_t n) : size(2) { d[0] = m; d[1] = n; }
SdfTupleDimensions(const size_t (&s)[2])
: size(2) { d[0] = s[0]; d[1] = s[1]; }
SDF_API
bool operator==(const SdfTupleDimensions& rhs) const;
bool operator!=(const SdfTupleDimensions& rhs) const {
return !(*this == rhs);
}
public:
size_t d[2];
size_t size;
};
/// \class SdfValueTypeName
///
/// Represents a value type name, i.e. an attribute's type name. Usually,
/// a value type name associates a string with a \c TfType and an optional
/// role, along with additional metadata. A schema registers all known
/// value type names and may register multiple names for the same TfType
/// and role pair. All name strings for a given pair are collectively
/// called its aliases.
///
/// A value type name may also represent just a name string, without a
/// \c TfType, role or other metadata. This is currently used exclusively
/// to unserialize and re-serialize an attribute's type name where that
/// name is not known to the schema.
///
/// Because value type names can have aliases and those aliases may change
/// in the future, clients should avoid using the value type name's string
/// representation except to report human readable messages and when
/// serializing. Clients can look up a value type name by string using
/// \c SdfSchemaBase::FindType() and shouldn't otherwise need the string.
/// Aliases compare equal, even if registered by different schemas.
///
class SdfValueTypeName
{
public:
/// Constructs an invalid type name.
SDF_API
SdfValueTypeName();
/// Returns the type name as a token. This should not be used for
/// comparison purposes.
SDF_API
TfToken GetAsToken() const;
/// Returns the \c TfType of the type.
SDF_API
const TfType& GetType() const;
/// Returns the C++ type name for this type. This may not be the same
/// as the type name returned by GetType().GetTypeName(), since that
/// method may have had additional transformations applied for
/// readability.
SDF_API
const std::string& GetCPPTypeName() const;
/// Returns the type's role.
SDF_API
const TfToken& GetRole() const;
/// Returns the default value for the type.
SDF_API
const VtValue& GetDefaultValue() const;
/// Returns the default unit enum for the type.
SDF_API
const TfEnum& GetDefaultUnit() const;
/// Returns the scalar version of this type name if it's an array type
/// name, otherwise returns this type name. If there is no scalar type
/// name then this returns the invalid type name.
SDF_API
SdfValueTypeName GetScalarType() const;
/// Returns the array version of this type name if it's an scalar type
/// name, otherwise returns this type name. If there is no array type
/// name then this returns the invalid type name.
SDF_API
SdfValueTypeName GetArrayType() const;
/// Returns \c true iff this type is a scalar. The invalid type is
/// considered neither scalar nor array.
SDF_API
bool IsScalar() const;
/// Returns \c true iff this type is an array. The invalid type is
/// considered neither scalar nor array.
SDF_API
bool IsArray() const;
/// Returns the dimensions of the scalar value, e.g. 3 for a 3D point.
SDF_API
SdfTupleDimensions GetDimensions() const;
/// Returns \c true if this type name is equal to \p rhs. Aliases
/// compare equal.
SDF_API
bool operator==(const SdfValueTypeName& rhs) const;
bool operator!=(const SdfValueTypeName& rhs) const {
return !(*this == rhs);
}
/// Returns \c true if this type name is equal to \p rhs. Aliases
/// compare equal. Avoid relying on this overload.
SDF_API
bool operator==(const std::string& rhs) const;
bool operator!=(const std::string& rhs) const {
return !(*this == rhs);
}
/// Returns \c true if this type name is equal to \p rhs. Aliases
/// compare equal. Avoid relying on this overload.
SDF_API
bool operator==(const TfToken& rhs) const;
bool operator!=(const TfToken& rhs) const {
return !(*this == rhs);
}
friend inline
bool operator==(const std::string& lhs, const SdfValueTypeName& rhs) {
return rhs == lhs;
}
friend inline
bool operator!=(const std::string& lhs, const SdfValueTypeName& rhs) {
return !(rhs == lhs);
}
friend inline
bool operator==(const TfToken& lhs, const SdfValueTypeName &rhs) {
return rhs == lhs;
}
friend inline
bool operator!=(const TfToken& lhs, const SdfValueTypeName &rhs) {
return !(rhs == lhs);
}
/// Returns a hash value for this type name.
SDF_API
size_t GetHash() const;
/// Explicit bool conversion operator. Converts to \c true if this is a
/// valid, non-empty type, \c false otherwise.
explicit operator bool() const
{
return !_IsEmpty();
}
/// Returns all aliases of the type name as tokens. These should not
/// be used for comparison purposes.
SDF_API
std::vector<TfToken> GetAliasesAsTokens() const;
private:
friend class Sdf_ValueTypeRegistry;
friend struct Sdf_ValueTypePrivate;
SDF_API
explicit SdfValueTypeName(const Sdf_ValueTypeImpl*);
SDF_API
bool _IsEmpty() const;
private:
const Sdf_ValueTypeImpl* _impl;
};
/// Functor for hashing a \c SdfValueTypeName.
struct SdfValueTypeNameHash {
size_t operator()(const SdfValueTypeName& x) const
{
return x.GetHash();
}
};
inline size_t
hash_value(const SdfValueTypeName& typeName)
{
return typeName.GetHash();
}
SDF_API std::ostream& operator<<(std::ostream&, const SdfValueTypeName& typeName);
PXR_NAMESPACE_CLOSE_SCOPE
#endif // PXR_USD_SDF_VALUE_TYPE_NAME_H
+126
View File
@@ -0,0 +1,126 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_VARIANT_SET_SPEC_H
#define PXR_USD_SDF_VARIANT_SET_SPEC_H
/// \file sdf/variantSetSpec.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/usd/sdf/declareSpec.h"
#include "pxr/usd/sdf/spec.h"
#include "pxr/usd/sdf/proxyTypes.h"
#include "pxr/usd/sdf/types.h"
#include <iosfwd>
#include <map>
#include <string>
#include <vector>
PXR_NAMESPACE_OPEN_SCOPE
/// \class SdfVariantSetSpec
///
/// Represents a coherent set of alternate representations for part of a
/// scene.
///
/// An SdfPrimSpec object may contain one or more named SdfVariantSetSpec
/// objects that define variations on the prim.
///
/// An SdfVariantSetSpec object contains one or more named SdfVariantSpec
/// objects. It may also define the name of one of its variants to be used by
/// default.
///
/// When a prim references another prim, the referencing prim may specify
/// one of the variants from each of the variant sets of the target prim.
/// The chosen variant from each set (or the default variant from those sets
/// that the referencing prim does not explicitly specify) is composited
/// over the target prim, and then the referencing prim is composited over
/// the result.
///
class SdfVariantSetSpec : public SdfSpec
{
SDF_DECLARE_SPEC(SdfVariantSetSpec, SdfSpec);
public:
///
/// \name Spec construction
/// @{
/// Constructs a new instance.
SDF_API
static SdfVariantSetSpecHandle
New(const SdfPrimSpecHandle& prim, const std::string& name);
/// Constructs a new instance.
SDF_API
static SdfVariantSetSpecHandle
New(const SdfVariantSpecHandle& prim, const std::string& name);
/// @}
/// \name Name
/// @{
/// Returns the name of this variant set.
SDF_API
std::string GetName() const;
/// Returns the name of this variant set.
SDF_API
TfToken GetNameToken() const;
/// @}
/// \name Namespace hierarchy
/// @{
/// Returns the prim or variant that this variant set belongs to.
SDF_API
SdfSpecHandle GetOwner() const;
/// @}
/// \name Variants
/// @{
/// Returns the variants as a map.
SDF_API
SdfVariantView GetVariants() const;
/// Returns the variants as a vector.
SDF_API
SdfVariantSpecHandleVector GetVariantList() const;
/// Removes \p variant from the list of variants.
///
/// If the variant set does not currently own \p variant, no action
/// is taken.
SDF_API
void RemoveVariant(const SdfVariantSpecHandle& variant);
/// @}
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // SD_VARIANTSETSPEC_H
+126
View File
@@ -0,0 +1,126 @@
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef PXR_USD_SDF_VARIANT_SPEC_H
#define PXR_USD_SDF_VARIANT_SPEC_H
/// \file sdf/variantSpec.h
#include "pxr/pxr.h"
#include "pxr/usd/sdf/api.h"
#include "pxr/usd/sdf/declareSpec.h"
#include "pxr/usd/sdf/proxyTypes.h"
#include "pxr/usd/sdf/spec.h"
#include <string>
PXR_NAMESPACE_OPEN_SCOPE
SDF_DECLARE_HANDLES(SdfLayer);
SDF_DECLARE_HANDLES(SdfPrimSpec);
SDF_DECLARE_HANDLES(SdfVariantSpec);
SDF_DECLARE_HANDLES(SdfVariantSetSpec);
class SdfPath;
/// \class SdfVariantSpec
///
/// Represents a single variant in a variant set.
///
/// A variant contains a prim. This prim is the root prim of the variant.
///
/// SdfVariantSpecs are value objects. This means they are immutable
/// once created and they are passed by copy-in APIs. To change a variant
/// spec, you make a new one and replace the existing one.
///
class SdfVariantSpec : public SdfSpec
{
SDF_DECLARE_SPEC(SdfVariantSpec, SdfSpec);
public:
///
/// \name Spec construction
/// @{
/// Constructs a new instance.
SDF_API
static SdfVariantSpecHandle New(const SdfVariantSetSpecHandle& owner,
const std::string& name);
/// @}
/// \name Name
/// @{
/// Returns the name of this variant.
SDF_API
std::string GetName() const;
/// Returns the name of this variant.
SDF_API
TfToken GetNameToken() const;
/// @}
/// \name Namespace hierarchy
/// @{
/// Return the SdfVariantSetSpec that owns this variant.
SDF_API
SdfVariantSetSpecHandle GetOwner() const;
/// Get the prim spec owned by this variant.
SDF_API
SdfPrimSpecHandle GetPrimSpec() const;
/// Returns the nested variant sets.
///
/// The result maps variant set names to variant sets. Variant sets
/// may be removed through the proxy.
SDF_API
SdfVariantSetsProxy GetVariantSets() const;
/// Returns list of variant names for the given variant set.
SDF_API
std::vector<std::string> GetVariantNames(const std::string& name) const;
/// @}
};
/// Convenience function to create a variant spec for a given variant set and
/// a prim at the given path with.
///
/// The function creates the prim spec if it doesn't exist already and any
/// necessary parent prims, in the given layer.
///
/// It adds the variant set to the variant set list if it doesn't already exist.
///
/// It creates a variant spec with the given name under the specified variant
/// set if it doesn't already exist.
SDF_API SdfVariantSpecHandle SdfCreateVariantInLayer(
const SdfLayerHandle &layer,
const SdfPath &primPath,
const std::string &variantSetName,
const std::string &variantName );
PXR_NAMESPACE_CLOSE_SCOPE
#endif /* SDF_VARIANT_SPEC_H */