file_path
stringlengths
21
207
content
stringlengths
5
1.02M
size
int64
5
1.02M
lang
stringclasses
9 values
avg_line_length
float64
1.33
100
max_line_length
int64
4
993
alphanum_fraction
float64
0.27
0.93
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdSchemaExamples/__init__.py
# # 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. # from pxr import Tf Tf.PreparePythonModule() del Tf
1,110
Python
40.148147
74
0.766667
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdSchemaExamples/__DOC.py
def Execute(result): pass
29
Python
13.999993
20
0.689655
omniverse-code/kit/exts/omni.usd.libs/pxr/Vt/__init__.py
# # 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. # """Vt Value Types library This package defines classes for creating objects that behave like value types. It contains facilities for creating simple copy-on-write implicitly shared types. """ from pxr import Tf Tf.PreparePythonModule() del Tf # For ease-of-use, put each XXXArrayFromBuffer method on its corresponding array # wrapper class, also alias it as 'FromNumpy' for compatibility. def _CopyArrayFromBufferFuncs(moduleContents): funcs = dict([(key, val) for (key, val) in moduleContents.items() if key.endswith('FromBuffer')]) classes = dict([(key, val) for (key, val) in moduleContents.items() if key.endswith('Array') and isinstance(val, type)]) for funcName, func in funcs.items(): className = funcName[:-len('FromBuffer')] cls = classes.get(className) if cls: setattr(cls, 'FromBuffer', staticmethod(func)) setattr(cls, 'FromNumpy', staticmethod(func)) _CopyArrayFromBufferFuncs(dict(vars())) del _CopyArrayFromBufferFuncs
2,097
Python
39.346153
80
0.729614
omniverse-code/kit/exts/omni.usd.libs/pxr/Vt/__DOC.py
def Execute(result): pass
29
Python
13.999993
20
0.689655
omniverse-code/kit/exts/omni.usd.libs/pxr/Vt/__init__.pyi
from __future__ import annotations import pxr.Vt._vt import typing import Boost.Python __all__ = [ "AllTrue", "AnyTrue", "Bool", "BoolArray", "BoolArrayFromBuffer", "Cat", "CharArray", "CharArrayFromBuffer", "Double", "DoubleArray", "DoubleArrayFromBuffer", "DualQuatdArray", "DualQuatdArrayFromBuffer", "DualQuatfArray", "DualQuatfArrayFromBuffer", "DualQuathArray", "DualQuathArrayFromBuffer", "Equal", "Float", "FloatArray", "FloatArrayFromBuffer", "Greater", "GreaterOrEqual", "Half", "HalfArray", "HalfArrayFromBuffer", "Int", "Int64", "Int64Array", "Int64ArrayFromBuffer", "IntArray", "IntArrayFromBuffer", "IntervalArray", "Less", "LessOrEqual", "Long", "Matrix2dArray", "Matrix2dArrayFromBuffer", "Matrix2fArray", "Matrix2fArrayFromBuffer", "Matrix3dArray", "Matrix3dArrayFromBuffer", "Matrix3fArray", "Matrix3fArrayFromBuffer", "Matrix4dArray", "Matrix4dArrayFromBuffer", "Matrix4fArray", "Matrix4fArrayFromBuffer", "NotEqual", "QuatdArray", "QuatdArrayFromBuffer", "QuaternionArray", "QuatfArray", "QuatfArrayFromBuffer", "QuathArray", "QuathArrayFromBuffer", "Range1dArray", "Range1dArrayFromBuffer", "Range1fArray", "Range1fArrayFromBuffer", "Range2dArray", "Range2dArrayFromBuffer", "Range2fArray", "Range2fArrayFromBuffer", "Range3dArray", "Range3dArrayFromBuffer", "Range3fArray", "Range3fArrayFromBuffer", "Rect2iArray", "Rect2iArrayFromBuffer", "Short", "ShortArray", "ShortArrayFromBuffer", "StringArray", "Token", "TokenArray", "UChar", "UCharArray", "UCharArrayFromBuffer", "UInt", "UInt64", "UInt64Array", "UInt64ArrayFromBuffer", "UIntArray", "UIntArrayFromBuffer", "ULong", "UShort", "UShortArray", "UShortArrayFromBuffer", "Vec2dArray", "Vec2dArrayFromBuffer", "Vec2fArray", "Vec2fArrayFromBuffer", "Vec2hArray", "Vec2hArrayFromBuffer", "Vec2iArray", "Vec2iArrayFromBuffer", "Vec3dArray", "Vec3dArrayFromBuffer", "Vec3fArray", "Vec3fArrayFromBuffer", "Vec3hArray", "Vec3hArrayFromBuffer", "Vec3iArray", "Vec3iArrayFromBuffer", "Vec4dArray", "Vec4dArrayFromBuffer", "Vec4fArray", "Vec4fArrayFromBuffer", "Vec4hArray", "Vec4hArrayFromBuffer", "Vec4iArray", "Vec4iArrayFromBuffer" ] class BoolArray(Boost.Python.instance): """ An array of type bool. """ _isVtArray = True pass class CharArray(Boost.Python.instance): """ An array of type char. """ _isVtArray = True pass class DoubleArray(Boost.Python.instance): """ An array of type double. """ _isVtArray = True pass class DualQuatdArray(Boost.Python.instance): """ An array of type GfDualQuatd. """ _isVtArray = True pass class DualQuatfArray(Boost.Python.instance): """ An array of type GfDualQuatf. """ _isVtArray = True pass class DualQuathArray(Boost.Python.instance): """ An array of type GfDualQuath. """ _isVtArray = True pass class FloatArray(Boost.Python.instance): """ An array of type float. """ _isVtArray = True pass class HalfArray(Boost.Python.instance): """ An array of type pxr_half::half. """ _isVtArray = True pass class Int64Array(Boost.Python.instance): """ An array of type __int64. """ _isVtArray = True pass class IntArray(Boost.Python.instance): """ An array of type int. """ _isVtArray = True pass class IntervalArray(Boost.Python.instance): """ An array of type GfInterval. """ _isVtArray = True pass class Matrix2dArray(Boost.Python.instance): """ An array of type GfMatrix2d. """ _isVtArray = True pass class Matrix2fArray(Boost.Python.instance): """ An array of type GfMatrix2f. """ _isVtArray = True pass class Matrix3dArray(Boost.Python.instance): """ An array of type GfMatrix3d. """ _isVtArray = True pass class Matrix3fArray(Boost.Python.instance): """ An array of type GfMatrix3f. """ _isVtArray = True pass class Matrix4dArray(Boost.Python.instance): """ An array of type GfMatrix4d. """ _isVtArray = True pass class Matrix4fArray(Boost.Python.instance): """ An array of type GfMatrix4f. """ _isVtArray = True pass class QuatdArray(Boost.Python.instance): """ An array of type GfQuatd. """ _isVtArray = True pass class QuaternionArray(Boost.Python.instance): """ An array of type GfQuaternion. """ _isVtArray = True pass class QuatfArray(Boost.Python.instance): """ An array of type GfQuatf. """ _isVtArray = True pass class QuathArray(Boost.Python.instance): """ An array of type GfQuath. """ _isVtArray = True pass class Range1dArray(Boost.Python.instance): """ An array of type GfRange1d. """ _isVtArray = True pass class Range1fArray(Boost.Python.instance): """ An array of type GfRange1f. """ _isVtArray = True pass class Range2dArray(Boost.Python.instance): """ An array of type GfRange2d. """ _isVtArray = True pass class Range2fArray(Boost.Python.instance): """ An array of type GfRange2f. """ _isVtArray = True pass class Range3dArray(Boost.Python.instance): """ An array of type GfRange3d. """ _isVtArray = True pass class Range3fArray(Boost.Python.instance): """ An array of type GfRange3f. """ _isVtArray = True pass class Rect2iArray(Boost.Python.instance): """ An array of type GfRect2i. """ _isVtArray = True pass class ShortArray(Boost.Python.instance): """ An array of type short. """ _isVtArray = True pass class StringArray(Boost.Python.instance): """ An array of type string. """ _isVtArray = True pass class TokenArray(Boost.Python.instance): """ An array of type TfToken. """ _isVtArray = True pass class UCharArray(Boost.Python.instance): """ An array of type unsigned char. """ _isVtArray = True pass class UInt64Array(Boost.Python.instance): """ An array of type unsigned __int64. """ _isVtArray = True pass class UIntArray(Boost.Python.instance): """ An array of type unsigned int. """ _isVtArray = True pass class UShortArray(Boost.Python.instance): """ An array of type unsigned short. """ _isVtArray = True pass class Vec2dArray(Boost.Python.instance): """ An array of type GfVec2d. """ _isVtArray = True pass class Vec2fArray(Boost.Python.instance): """ An array of type GfVec2f. """ _isVtArray = True pass class Vec2hArray(Boost.Python.instance): """ An array of type GfVec2h. """ _isVtArray = True pass class Vec2iArray(Boost.Python.instance): """ An array of type GfVec2i. """ _isVtArray = True pass class Vec3dArray(Boost.Python.instance): """ An array of type GfVec3d. """ _isVtArray = True pass class Vec3fArray(Boost.Python.instance): """ An array of type GfVec3f. """ _isVtArray = True pass class Vec3hArray(Boost.Python.instance): """ An array of type GfVec3h. """ _isVtArray = True pass class Vec3iArray(Boost.Python.instance): """ An array of type GfVec3i. """ _isVtArray = True pass class Vec4dArray(Boost.Python.instance): """ An array of type GfVec4d. """ _isVtArray = True pass class Vec4fArray(Boost.Python.instance): """ An array of type GfVec4f. """ _isVtArray = True pass class Vec4hArray(Boost.Python.instance): """ An array of type GfVec4h. """ _isVtArray = True pass class Vec4iArray(Boost.Python.instance): """ An array of type GfVec4i. """ _isVtArray = True pass class _ValueWrapper(Boost.Python.instance): pass def AllTrue(*args, **kwargs) -> None: pass def AnyTrue(*args, **kwargs) -> None: pass def Bool(value) -> _ValueWrapper: """ value : bool Use this function to specify a value with the explicit C++ type bool when calling a C++ wrapped function that expects a VtValue. (There are some C++ types that have no equivalents in Python, such as short.) """ def BoolArrayFromBuffer(*args, **kwargs) -> None: pass def Cat(*args, **kwargs) -> None: pass def CharArrayFromBuffer(*args, **kwargs) -> None: pass def Double(value) -> _ValueWrapper: """ value : double Use this function to specify a value with the explicit C++ type double when calling a C++ wrapped function that expects a VtValue. (There are some C++ types that have no equivalents in Python, such as short.) """ def DoubleArrayFromBuffer(*args, **kwargs) -> None: pass def DualQuatdArrayFromBuffer(*args, **kwargs) -> None: pass def DualQuatfArrayFromBuffer(*args, **kwargs) -> None: pass def DualQuathArrayFromBuffer(*args, **kwargs) -> None: pass def Equal(*args, **kwargs) -> None: pass def Float(value) -> _ValueWrapper: """ value : float Use this function to specify a value with the explicit C++ type float when calling a C++ wrapped function that expects a VtValue. (There are some C++ types that have no equivalents in Python, such as short.) """ def FloatArrayFromBuffer(*args, **kwargs) -> None: pass def Greater(*args, **kwargs) -> None: pass def GreaterOrEqual(*args, **kwargs) -> None: pass def Half(value) -> _ValueWrapper: """ value : half Use this function to specify a value with the explicit C++ type GfHalf when calling a C++ wrapped function that expects a VtValue. (There are some C++ types that have no equivalents in Python, such as short.) """ def HalfArrayFromBuffer(*args, **kwargs) -> None: pass def Int(value) -> _ValueWrapper: """ value : int Use this function to specify a value with the explicit C++ type int when calling a C++ wrapped function that expects a VtValue. (There are some C++ types that have no equivalents in Python, such as short.) """ def Int64(value) -> _ValueWrapper: """ value : int64_t Use this function to specify a value with the explicit C++ type int64_t when calling a C++ wrapped function that expects a VtValue. (There are some C++ types that have no equivalents in Python, such as short.) """ def Int64ArrayFromBuffer(*args, **kwargs) -> None: pass def IntArrayFromBuffer(*args, **kwargs) -> None: pass def Less(*args, **kwargs) -> None: pass def LessOrEqual(*args, **kwargs) -> None: pass def Long(value) -> _ValueWrapper: """ value : long Use this function to specify a value with the explicit C++ type long when calling a C++ wrapped function that expects a VtValue. (There are some C++ types that have no equivalents in Python, such as short.) """ def Matrix2dArrayFromBuffer(*args, **kwargs) -> None: pass def Matrix2fArrayFromBuffer(*args, **kwargs) -> None: pass def Matrix3dArrayFromBuffer(*args, **kwargs) -> None: pass def Matrix3fArrayFromBuffer(*args, **kwargs) -> None: pass def Matrix4dArrayFromBuffer(*args, **kwargs) -> None: pass def Matrix4fArrayFromBuffer(*args, **kwargs) -> None: pass def NotEqual(*args, **kwargs) -> None: pass def QuatdArrayFromBuffer(*args, **kwargs) -> None: pass def QuatfArrayFromBuffer(*args, **kwargs) -> None: pass def QuathArrayFromBuffer(*args, **kwargs) -> None: pass def Range1dArrayFromBuffer(*args, **kwargs) -> None: pass def Range1fArrayFromBuffer(*args, **kwargs) -> None: pass def Range2dArrayFromBuffer(*args, **kwargs) -> None: pass def Range2fArrayFromBuffer(*args, **kwargs) -> None: pass def Range3dArrayFromBuffer(*args, **kwargs) -> None: pass def Range3fArrayFromBuffer(*args, **kwargs) -> None: pass def Rect2iArrayFromBuffer(*args, **kwargs) -> None: pass def Short(value) -> _ValueWrapper: """ value : short Use this function to specify a value with the explicit C++ type short when calling a C++ wrapped function that expects a VtValue. (There are some C++ types that have no equivalents in Python, such as short.) """ def ShortArrayFromBuffer(*args, **kwargs) -> None: pass def Token(*args, **kwargs) -> None: """ value : TfToken Use this function to specify a value with the explicit C++ type TfToken when calling a C++ wrapped function that expects a VtValue. (There are some C++ types that have no equivalents in Python, such as short.) """ def UChar(value) -> _ValueWrapper: """ value : unsigned char Use this function to specify a value with the explicit C++ type unsigned char when calling a C++ wrapped function that expects a VtValue. (There are some C++ types that have no equivalents in Python, such as short.) """ def UCharArrayFromBuffer(*args, **kwargs) -> None: pass def UInt(value) -> _ValueWrapper: """ value : unsigned int Use this function to specify a value with the explicit C++ type unsigned int when calling a C++ wrapped function that expects a VtValue. (There are some C++ types that have no equivalents in Python, such as short.) """ def UInt64(value) -> _ValueWrapper: """ value : uint64_t Use this function to specify a value with the explicit C++ type uint64_t when calling a C++ wrapped function that expects a VtValue. (There are some C++ types that have no equivalents in Python, such as short.) """ def UInt64ArrayFromBuffer(*args, **kwargs) -> None: pass def UIntArrayFromBuffer(*args, **kwargs) -> None: pass def ULong(value) -> _ValueWrapper: """ value : unsigned long Use this function to specify a value with the explicit C++ type unsigned long when calling a C++ wrapped function that expects a VtValue. (There are some C++ types that have no equivalents in Python, such as short.) """ def UShort(value) -> _ValueWrapper: """ value : unsigned short Use this function to specify a value with the explicit C++ type unsigned short when calling a C++ wrapped function that expects a VtValue. (There are some C++ types that have no equivalents in Python, such as short.) """ def UShortArrayFromBuffer(*args, **kwargs) -> None: pass def Vec2dArrayFromBuffer(*args, **kwargs) -> None: pass def Vec2fArrayFromBuffer(*args, **kwargs) -> None: pass def Vec2hArrayFromBuffer(*args, **kwargs) -> None: pass def Vec2iArrayFromBuffer(*args, **kwargs) -> None: pass def Vec3dArrayFromBuffer(*args, **kwargs) -> None: pass def Vec3fArrayFromBuffer(*args, **kwargs) -> None: pass def Vec3hArrayFromBuffer(*args, **kwargs) -> None: pass def Vec3iArrayFromBuffer(*args, **kwargs) -> None: pass def Vec4dArrayFromBuffer(*args, **kwargs) -> None: pass def Vec4fArrayFromBuffer(*args, **kwargs) -> None: pass def Vec4hArrayFromBuffer(*args, **kwargs) -> None: pass def Vec4iArrayFromBuffer(*args, **kwargs) -> None: pass def _ReturnDictionary(*args, **kwargs) -> None: pass def _test_Ident(*args, **kwargs) -> None: pass def _test_Str(*args, **kwargs) -> None: pass def _test_ValueTypeName(*args, **kwargs) -> None: pass __MFB_FULL_PACKAGE_NAME = 'vt'
15,587
unknown
24.807947
220
0.648168
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdGeom/__init__.py
# # 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. # from pxr import Tf Tf.PreparePythonModule() del Tf
1,110
Python
40.148147
74
0.766667
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdGeom/__DOC.py
def Execute(result): result["BasisCurves"].__doc__ = """ BasisCurves are a batched curve representation analogous to the classic RIB definition via Basis and Curves statements. BasisCurves are often used to render dense aggregate geometry like hair or grass. A'matrix'and'vstep'associated with the *basis* are used to interpolate the vertices of a cubic BasisCurves. (The basis attribute is unused for linear BasisCurves.) A single prim may have many curves whose count is determined implicitly by the length of the *curveVertexCounts* vector. Each individual curve is composed of one or more segments. Each segment is defined by four vertices for cubic curves and two vertices for linear curves. See the next section for more information on how to map curve vertex counts to segment counts. Segment Indexing ================ Interpolating a curve requires knowing how to decompose it into its individual segments. The segments of a cubic curve are determined by the vertex count, the *wrap* (periodicity), and the vstep of the basis. For linear curves, the basis token is ignored and only the vertex count and wrap are needed. cubic basis vstep bezier 3 catmullRom 1 bspline 1 The first segment of a cubic (nonperiodic) curve is always defined by its first four points. The vstep is the increment used to determine what vertex indices define the next segment. For a two segment (nonperiodic) bspline basis curve (vstep = 1), the first segment will be defined by interpolating vertices [0, 1, 2, 3] and the second segment will be defined by [1, 2, 3, 4]. For a two segment bezier basis curve (vstep = 3), the first segment will be defined by interpolating vertices [0, 1, 2, 3] and the second segment will be defined by [3, 4, 5, 6]. If the vstep is not one, then you must take special care to make sure that the number of cvs properly divides by your vstep. (The indices described are relative to the initial vertex index for a batched curve.) For periodic curves, at least one of the curve's initial vertices are repeated to close the curve. For cubic curves, the number of vertices repeated is'4 - vstep'. For linear curves, only one vertex is repeated to close the loop. Pinned curves are a special case of nonperiodic curves that only affects the behavior of cubic Bspline and Catmull-Rom curves. To evaluate or render pinned curves, a client must effectively add'phantom points'at the beginning and end of every curve in a batch. These phantom points are injected to ensure that the interpolated curve begins at P[0] and ends at P[n-1]. For a curve with initial point P[0] and last point P[n-1], the phantom points are defined as. P[-1] = 2 \\* P[0] - P[1] P[n] = 2 \\* P[n-1] - P[n-2] Pinned cubic curves will (usually) have to be unpacked into the standard nonperiodic representation before rendering. This unpacking can add some additional overhead. However, using pinned curves reduces the amount of data recorded in a scene and (more importantly) better records the authors'intent for interchange. The additional phantom points mean that the minimum curve vertex count for cubic bspline and catmullRom curves is 2. Linear curve segments are defined by two vertices. A two segment linear curve's first segment would be defined by interpolating vertices [0, 1]. The second segment would be defined by vertices [1, 2]. (Again, for a batched curve, indices are relative to the initial vertex index.) When validating curve topology, each renderable entry in the curveVertexCounts vector must pass this check. type wrap validitity linear nonperiodic curveVertexCounts[i]>2 linear periodic curveVertexCounts[i]>3 cubic nonperiodic (curveVertexCounts[i] - 4) % vstep == 0 cubic periodic (curveVertexCounts[i]) % vstep == 0 cubic pinned (catmullRom/bspline) (curveVertexCounts[i] - 2)>= 0 Cubic Vertex Interpolation ========================== Linear Vertex Interpolation =========================== Linear interpolation is always used on curves of type linear.'t'with domain [0, 1], the curve is defined by the equation P0 \\* (1-t) + P1 \\* t. t at 0 describes the first point and t at 1 describes the end point. Primvar Interpolation ===================== For cubic curves, primvar data can be either interpolated cubically between vertices or linearly across segments. The corresponding token for cubic interpolation is'vertex'and for linear interpolation is'varying'. Per vertex data should be the same size as the number of vertices in your curve. Segment varying data is dependent on the wrap (periodicity) and number of segments in your curve. For linear curves, varying and vertex data would be interpolated the same way. By convention varying is the preferred interpolation because of the association of varying with linear interpolation. To convert an entry in the curveVertexCounts vector into a segment count for an individual curve, apply these rules. Sum up all the results in order to compute how many total segments all curves have. The following tables describe the expected segment count for the'i'th curve in a curve batch as well as the entire batch. Python syntax like'[:]'(to describe all members of an array) and'len(\\.\\.\\.)'(to describe the length of an array) are used. type wrap curve segment count batch segment count linear nonperiodic curveVertexCounts[i] - 1 sum(curveVertexCounts[:]) - len(curveVertexCounts) linear periodic curveVertexCounts[i] sum(curveVertexCounts[:]) cubic nonperiodic (curveVertexCounts[i] - 4) / vstep + 1 sum(curveVertexCounts[:] - 4) / vstep + len(curveVertexCounts) cubic periodic curveVertexCounts[i] / vstep sum(curveVertexCounts[:]) / vstep cubic pinned (catmullRom/bspline) (curveVertexCounts[i] - 2) + 1 sum(curveVertexCounts[:] - 2) + len(curveVertexCounts) The following table descrives the expected size of varying (linearly interpolated) data, derived from the segment counts computed above. wrap curve varying count batch varying count nonperiodic/pinned segmentCounts[i] + 1 sum(segmentCounts[:]) + len(curveVertexCounts) periodic segmentCounts[i] sum(segmentCounts[:]) Both curve types additionally define'constant'interpolation for the entire prim and'uniform'interpolation as per curve data. Take care when providing support for linearly interpolated data for cubic curves. Its shape doesn't provide a one to one mapping with either the number of curves (like'uniform') or the number of vertices (like'vertex') and so it is often overlooked. This is the only primitive in UsdGeom (as of this writing) where this is true. For meshes, while they use different interpolation methods,'varying'and'vertex'are both specified per point. It's common to assume that curves follow a similar pattern and build in structures and language for per primitive, per element, and per point data only to come upon these arrays that don't quite fit into either of those categories. It is also common to conflate'varying'with being per segment data and use the segmentCount rules table instead of its neighboring varying data table rules. We suspect that this is because for the common case of nonperiodic cubic curves, both the provided segment count and varying data size formula end with'+ 1'. While debugging, users may look at the double'+ 1'as a mistake and try to remove it. We take this time to enumerate these issues because we've fallen into them before and hope that we save others time in their own implementations. As an example of deriving per curve segment and varying primvar data counts from the wrap, type, basis, and curveVertexCount, the following table is provided. wrap type basis curveVertexCount curveSegmentCount varyingDataCount nonperiodic linear N/A [2 3 2 5] [1 2 1 4] [2 3 2 5] nonperiodic cubic bezier [4 7 10 4 7] [1 2 3 1 2] [2 3 4 2 3] nonperiodic cubic bspline [5 4 6 7] [2 1 3 4] [3 2 4 5] periodic cubic bezier [6 9 6] [2 3 2] [2 3 2] periodic linear N/A [3 7] [3 7] [3 7] Tubes and Ribbons ================= The strictest definition of a curve as an infinitely thin wire is not particularly useful for describing production scenes. The additional *widths* and *normals* attributes can be used to describe cylindrical tubes and or flat oriented ribbons. Curves with only widths defined are imaged as tubes with radius'width / 2'. Curves with both widths and normals are imaged as ribbons oriented in the direction of the interpolated normal vectors. While not technically UsdGeomPrimvars, widths and normals also have interpolation metadata. It's common for authored widths to have constant, varying, or vertex interpolation (see UsdGeomCurves::GetWidthsInterpolation() ). It's common for authored normals to have varying interpolation (see UsdGeomPointBased::GetNormalsInterpolation() ). The file used to generate these curves can be found in pxr/extras/examples/usdGeomExamples/basisCurves.usda. It's provided as a reference on how to properly image both tubes and ribbons. The first row of curves are linear; the second are cubic bezier. (We aim in future releases of HdSt to fix the discontinuity seen with broken tangents to better match offline renderers like RenderMan.) The yellow and violet cubic curves represent cubic vertex width interpolation for which there is no equivalent for linear curves. How did this prim type get its name? This prim is a portmanteau of two different statements in the original RenderMan specification:'Basis'and'Curves'. For any described attribute *Fallback* *Value* or *Allowed* *Values* below that are text/tokens, the actual token is published and defined in UsdGeomTokens. So to set an attribute to the value"rightHanded", use UsdGeomTokens->rightHanded as the value. """ result["BasisCurves"].ComputeInterpolationForSize.func_doc = """ComputeInterpolationForSize(n, timeCode, info) -> str Computes interpolation token for ``n`` . If this returns an empty token and ``info`` was non-None, it'll contain the expected value for each token. The topology is determined using ``timeCode`` . Parameters ---------- n : int timeCode : TimeCode info : ComputeInterpolationInfo """ result["BasisCurves"].ComputeUniformDataSize.func_doc = """ComputeUniformDataSize(timeCode) -> int Computes the expected size for data with"uniform"interpolation. If you're trying to determine what interpolation to use, it is more efficient to use ``ComputeInterpolationForSize`` Parameters ---------- timeCode : TimeCode """ result["BasisCurves"].ComputeVaryingDataSize.func_doc = """ComputeVaryingDataSize(timeCode) -> int Computes the expected size for data with"varying"interpolation. If you're trying to determine what interpolation to use, it is more efficient to use ``ComputeInterpolationForSize`` Parameters ---------- timeCode : TimeCode """ result["BasisCurves"].ComputeVertexDataSize.func_doc = """ComputeVertexDataSize(timeCode) -> int Computes the expected size for data with"vertex"interpolation. If you're trying to determine what interpolation to use, it is more efficient to use ``ComputeInterpolationForSize`` Parameters ---------- timeCode : TimeCode """ result["BasisCurves"].__init__.func_doc = """__init__(prim) Construct a UsdGeomBasisCurves on UsdPrim ``prim`` . Equivalent to UsdGeomBasisCurves::Get (prim.GetStage(), prim.GetPath()) for a *valid* ``prim`` , but will not immediately throw an error for an invalid ``prim`` Parameters ---------- prim : Prim ---------------------------------------------------------------------- __init__(schemaObj) Construct a UsdGeomBasisCurves on the prim held by ``schemaObj`` . Should be preferred over UsdGeomBasisCurves (schemaObj.GetPrim()), as it preserves SchemaBase state. Parameters ---------- schemaObj : SchemaBase """ result["BasisCurves"].GetTypeAttr.func_doc = """GetTypeAttr() -> Attribute Linear curves interpolate linearly between two vertices. Cubic curves use a basis matrix with four vertices to interpolate a segment. Declaration ``uniform token type ="cubic"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values linear, cubic """ result["BasisCurves"].CreateTypeAttr.func_doc = """CreateTypeAttr(defaultValue, writeSparsely) -> Attribute See GetTypeAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["BasisCurves"].GetBasisAttr.func_doc = """GetBasisAttr() -> Attribute The basis specifies the vstep and matrix used for cubic interpolation. The'hermite'and'power'tokens have been removed. We've provided UsdGeomHermiteCurves as an alternative for the'hermite'basis. Declaration ``uniform token basis ="bezier"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values bezier, bspline, catmullRom """ result["BasisCurves"].CreateBasisAttr.func_doc = """CreateBasisAttr(defaultValue, writeSparsely) -> Attribute See GetBasisAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["BasisCurves"].GetWrapAttr.func_doc = """GetWrapAttr() -> Attribute If wrap is set to periodic, the curve when rendered will repeat the initial vertices (dependent on the vstep) to close the curve. If wrap is set to'pinned', phantom points may be created to ensure that the curve interpolation starts at P[0] and ends at P[n-1]. Declaration ``uniform token wrap ="nonperiodic"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values nonperiodic, periodic, pinned """ result["BasisCurves"].CreateWrapAttr.func_doc = """CreateWrapAttr(defaultValue, writeSparsely) -> Attribute See GetWrapAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["BasisCurves"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ result["BasisCurves"].Get.func_doc = """**classmethod** Get(stage, path) -> BasisCurves Return a UsdGeomBasisCurves holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomBasisCurves(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ result["BasisCurves"].Define.func_doc = """**classmethod** Define(stage, path) -> BasisCurves Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ result["BasisCurves"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type """ result["BBoxCache"].__doc__ = """ Caches bounds by recursively computing and aggregating bounds of children in world space and aggregating the result back into local space. The cache is configured for a specific time and UsdGeomImageable::GetPurposeAttr() set of purposes. When querying a bound, transforms and extents are read either from the time specified or UsdTimeCode::Default() , following TimeSamples, Defaults, and Value Resolution standard time-sample value resolution. As noted in SetIncludedPurposes() , changing the included purposes does not invalidate the cache, because we cache purpose along with the geometric data. Child prims that are invisible at the requested time are excluded when computing a prim's bounds. However, if a bound is requested directly for an excluded prim, it will be computed. Additionally, only prims deriving from UsdGeomImageable are included in child bounds computations. Unlike standard UsdStage traversals, the traversal performed by the UsdGeomBBoxCache includesprims that are unloaded (see UsdPrim::IsLoaded() ). This makes it possible to fetch bounds for a UsdStage that has been opened without *forcePopulate*, provided the unloaded model prims have authored extent hints (see UsdGeomModelAPI::GetExtentsHint() ). This class is optimized for computing tight **untransformed"object"space** bounds for component-models. In the absence of component models, bounds are optimized for world-space, since there is no other easily identifiable space for which to optimize, and we cannot optimize for every prim's local space without performing quadratic work. The TfDebug flag, USDGEOM_BBOX, is provided for debugging. Warnings: - This class should only be used with valid UsdPrim objects. - This cache does not listen for change notifications; the user is responsible for clearing the cache when changes occur. - Thread safety: instances of this class may not be used concurrently. - Plugins may be loaded in order to compute extents for prim types provided by that plugin. See UsdGeomBoundable::ComputeExtentFromPlugins """ result["BBoxCache"].__init__.func_doc = """__init__(time, includedPurposes, useExtentsHint, ignoreVisibility) Construct a new BBoxCache for a specific ``time`` and set of ``includedPurposes`` . Only prims with a purpose that matches the ``includedPurposes`` will be considered when accumulating child bounds. See UsdGeomImageable for allowed purpose values. If ``useExtentsHint`` is true, then when computing the bounds for any model-root prim, if the prim is visible at ``time`` , we will fetch its extents hint (via UsdGeomModelAPI::GetExtentsHint() ). If it is authored, we use it to compute the bounding box for the selected combination of includedPurposes by combining bounding box hints that have been cached for various values of purposes. If ``ignoreVisibility`` is true invisible prims will be included during bounds computations. Parameters ---------- time : TimeCode includedPurposes : list[TfToken] useExtentsHint : bool ignoreVisibility : bool ---------------------------------------------------------------------- __init__(other) Copy constructor. Parameters ---------- other : BBoxCache """ result["BBoxCache"].ComputeWorldBound.func_doc = """ComputeWorldBound(prim) -> BBox3d Compute the bound of the given prim in world space, leveraging any pre-existing, cached bounds. The bound of the prim is computed, including the transform (if any) authored on the node itself, and then transformed to world space. Error handling note: No checking of ``prim`` validity is performed. If ``prim`` is invalid, this method will abort the program; therefore it is the client's responsibility to ensure ``prim`` is valid. Parameters ---------- prim : Prim """ result["BBoxCache"].ComputeWorldBoundWithOverrides.func_doc = """ComputeWorldBoundWithOverrides(prim, pathsToSkip, primOverride, ctmOverrides) -> BBox3d Computes the bound of the prim's descendents in world space while excluding the subtrees rooted at the paths in ``pathsToSkip`` . Additionally, the parameter ``primOverride`` overrides the local-to- world transform of the prim and ``ctmOverrides`` is used to specify overrides the local-to-world transforms of certain paths underneath the prim. This leverages any pre-existing, cached bounds, but does not include the transform (if any) authored on the prim itself. See ComputeWorldBound() for notes on performance and error handling. Parameters ---------- prim : Prim pathsToSkip : SdfPathSet primOverride : Matrix4d ctmOverrides : TfHashMap[Path, Matrix4d, Path.Hash] """ result["BBoxCache"].ComputeRelativeBound.func_doc = """ComputeRelativeBound(prim, relativeToAncestorPrim) -> BBox3d Compute the bound of the given prim in the space of an ancestor prim, ``relativeToAncestorPrim`` , leveraging any pre-existing cached bounds. The computed bound excludes the local transform at ``relativeToAncestorPrim`` . The computed bound may be incorrect if ``relativeToAncestorPrim`` is not an ancestor of ``prim`` . Parameters ---------- prim : Prim relativeToAncestorPrim : Prim """ result["BBoxCache"].ComputeLocalBound.func_doc = """ComputeLocalBound(prim) -> BBox3d Computes the oriented bounding box of the given prim, leveraging any pre-existing, cached bounds. The computed bound includes the transform authored on the prim itself, but does not include any ancestor transforms (it does not include the local-to-world transform). See ComputeWorldBound() for notes on performance and error handling. Parameters ---------- prim : Prim """ result["BBoxCache"].ComputeUntransformedBound.func_doc = """ComputeUntransformedBound(prim) -> BBox3d Computes the bound of the prim's children leveraging any pre-existing, cached bounds, but does not include the transform (if any) authored on the prim itself. **IMPORTANT:** while the BBox does not contain the local transformation, in general it may still contain a non-identity transformation matrix to put the bounds in the correct space. Therefore, to obtain the correct axis-aligned bounding box, the client must call ComputeAlignedRange(). See ComputeWorldBound() for notes on performance and error handling. Parameters ---------- prim : Prim ---------------------------------------------------------------------- ComputeUntransformedBound(prim, pathsToSkip, ctmOverrides) -> BBox3d This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Computes the bound of the prim's descendents while excluding the subtrees rooted at the paths in ``pathsToSkip`` . Additionally, the parameter ``ctmOverrides`` is used to specify overrides to the CTM values of certain paths underneath the prim. The CTM values in the ``ctmOverrides`` map are in the space of the given prim, ``prim`` . This leverages any pre-existing, cached bounds, but does not include the transform (if any) authored on the prim itself. **IMPORTANT:** while the BBox does not contain the local transformation, in general it may still contain a non-identity transformation matrix to put the bounds in the correct space. Therefore, to obtain the correct axis-aligned bounding box, the client must call ComputeAlignedRange(). See ComputeWorldBound() for notes on performance and error handling. Parameters ---------- prim : Prim pathsToSkip : SdfPathSet ctmOverrides : TfHashMap[Path, Matrix4d, Path.Hash] """ result["BBoxCache"].ComputePointInstanceWorldBounds.func_doc = """ComputePointInstanceWorldBounds(instancer, instanceIdBegin, numIds, result) -> bool Compute the bound of the given point instances in world space. The bounds of each instance is computed and then transformed to world space. The ``result`` pointer must point to ``numIds`` GfBBox3d instances to be filled. Parameters ---------- instancer : PointInstancer instanceIdBegin : int numIds : int result : BBox3d """ result["BBoxCache"].ComputePointInstanceWorldBound.func_doc = """ComputePointInstanceWorldBound(instancer, instanceId) -> BBox3d Compute the bound of the given point instance in world space. Parameters ---------- instancer : PointInstancer instanceId : int """ result["BBoxCache"].ComputePointInstanceRelativeBounds.func_doc = """ComputePointInstanceRelativeBounds(instancer, instanceIdBegin, numIds, relativeToAncestorPrim, result) -> bool Compute the bounds of the given point instances in the space of an ancestor prim ``relativeToAncestorPrim`` . Write the results to ``result`` . The computed bound excludes the local transform at ``relativeToAncestorPrim`` . The computed bound may be incorrect if ``relativeToAncestorPrim`` is not an ancestor of ``prim`` . The ``result`` pointer must point to ``numIds`` GfBBox3d instances to be filled. Parameters ---------- instancer : PointInstancer instanceIdBegin : int numIds : int relativeToAncestorPrim : Prim result : BBox3d """ result["BBoxCache"].ComputePointInstanceRelativeBound.func_doc = """ComputePointInstanceRelativeBound(instancer, instanceId, relativeToAncestorPrim) -> BBox3d Compute the bound of the given point instance in the space of an ancestor prim ``relativeToAncestorPrim`` . Parameters ---------- instancer : PointInstancer instanceId : int relativeToAncestorPrim : Prim """ result["BBoxCache"].ComputePointInstanceLocalBounds.func_doc = """ComputePointInstanceLocalBounds(instancer, instanceIdBegin, numIds, result) -> bool Compute the oriented bounding boxes of the given point instances. The computed bounds include the transform authored on the instancer itself, but does not include any ancestor transforms (it does not include the local-to-world transform). The ``result`` pointer must point to ``numIds`` GfBBox3d instances to be filled. Parameters ---------- instancer : PointInstancer instanceIdBegin : int numIds : int result : BBox3d """ result["BBoxCache"].ComputePointInstanceLocalBound.func_doc = """ComputePointInstanceLocalBound(instancer, instanceId) -> BBox3d Compute the oriented bounding boxes of the given point instances. Parameters ---------- instancer : PointInstancer instanceId : int """ result["BBoxCache"].ComputePointInstanceUntransformedBounds.func_doc = """ComputePointInstanceUntransformedBounds(instancer, instanceIdBegin, numIds, result) -> bool Computes the bound of the given point instances, but does not include the transform (if any) authored on the instancer itself. **IMPORTANT:** while the BBox does not contain the local transformation, in general it may still contain a non-identity transformation matrix to put the bounds in the correct space. Therefore, to obtain the correct axis-aligned bounding box, the client must call ComputeAlignedRange(). The ``result`` pointer must point to ``numIds`` GfBBox3d instances to be filled. Parameters ---------- instancer : PointInstancer instanceIdBegin : int numIds : int result : BBox3d """ result["BBoxCache"].ComputePointInstanceUntransformedBound.func_doc = """ComputePointInstanceUntransformedBound(instancer, instanceId) -> BBox3d Computes the bound of the given point instances, but does not include the instancer's transform. Parameters ---------- instancer : PointInstancer instanceId : int """ result["BBoxCache"].Clear.func_doc = """Clear() -> None Clears all pre-cached values. """ result["BBoxCache"].SetIncludedPurposes.func_doc = """SetIncludedPurposes(includedPurposes) -> None Indicate the set of ``includedPurposes`` to use when resolving child bounds. Each child's purpose must match one of the elements of this set to be included in the computation; if it does not, child is excluded. Note the use of *child* in the docs above, purpose is ignored for the prim for whose bounds are directly queried. Changing this value **does not invalidate existing caches**. Parameters ---------- includedPurposes : list[TfToken] """ result["BBoxCache"].GetIncludedPurposes.func_doc = """GetIncludedPurposes() -> list[TfToken] Get the current set of included purposes. """ result["BBoxCache"].GetUseExtentsHint.func_doc = """GetUseExtentsHint() -> bool Returns whether authored extent hints are used to compute bounding boxes. """ result["BBoxCache"].SetTime.func_doc = """SetTime(time) -> None Use the new ``time`` when computing values and may clear any existing values cached for the previous time. Setting ``time`` to the current time is a no-op. Parameters ---------- time : TimeCode """ result["BBoxCache"].GetTime.func_doc = """GetTime() -> TimeCode Get the current time from which this cache is reading values. """ result["BBoxCache"].SetBaseTime.func_doc = """SetBaseTime(baseTime) -> None Set the base time value for this bbox cache. This value is used only when computing bboxes for point instancer instances (see ComputePointInstanceWorldBounds() , for example). See UsdGeomPointInstancer::ComputeExtentAtTime() for more information. If unset, the bbox cache uses its time ( GetTime() / SetTime() ) for this value. Note that setting the base time does not invalidate any cache entries. Parameters ---------- baseTime : TimeCode """ result["BBoxCache"].GetBaseTime.func_doc = """GetBaseTime() -> TimeCode Return the base time if set, otherwise GetTime() . Use HasBaseTime() to observe if a base time has been set. """ result["BBoxCache"].ClearBaseTime.func_doc = """ClearBaseTime() -> None Clear this cache's baseTime if one has been set. After calling this, the cache will use its time as the baseTime value. """ result["BBoxCache"].HasBaseTime.func_doc = """HasBaseTime() -> bool Return true if this cache has a baseTime that's been explicitly set, false otherwise. """ result["Boundable"].__doc__ = """ Boundable introduces the ability for a prim to persistently cache a rectilinear, local-space, extent. Why Extent and not Bounds ? =========================== Boundable introduces the notion of"extent", which is a cached computation of a prim's local-space 3D range for its resolved attributes **at the layer and time in which extent is authored**. We have found that with composed scene description, attempting to cache pre-computed bounds at interior prims in a scene graph is very fragile, given the ease with which one can author a single attribute in a stronger layer that can invalidate many authored caches - or with which a re-published, referenced asset can do the same. Therefore, we limit to precomputing (generally) leaf-prim extent, which avoids the need to read in large point arrays to compute bounds, and provides UsdGeomBBoxCache the means to efficiently compute and (session-only) cache intermediate bounds. You are free to compute and author intermediate bounds into your scenes, of course, which may work well if you have sufficient locks on your pipeline to guarantee that once authored, the geometry and transforms upon which they are based will remain unchanged, or if accuracy of the bounds is not an ironclad requisite. When intermediate bounds are authored on Boundable parents, the child prims will be pruned from BBox computation; the authored extent is expected to incorporate all child bounds. """ result["Boundable"].__init__.func_doc = """__init__(prim) Construct a UsdGeomBoundable on UsdPrim ``prim`` . Equivalent to UsdGeomBoundable::Get (prim.GetStage(), prim.GetPath()) for a *valid* ``prim`` , but will not immediately throw an error for an invalid ``prim`` Parameters ---------- prim : Prim ---------------------------------------------------------------------- __init__(schemaObj) Construct a UsdGeomBoundable on the prim held by ``schemaObj`` . Should be preferred over UsdGeomBoundable (schemaObj.GetPrim()), as it preserves SchemaBase state. Parameters ---------- schemaObj : SchemaBase """ result["Boundable"].GetExtentAttr.func_doc = """GetExtentAttr() -> Attribute Extent is a three dimensional range measuring the geometric extent of the authored gprim in its own local space (i.e. its own transform not applied), *without* accounting for any shader- induced displacement. If **any** extent value has been authored for a given Boundable, then it should be authored at every timeSample at which geometry-affecting properties are authored, to ensure correct evaluation via ComputeExtent() . If **no** extent value has been authored, then ComputeExtent() will call the Boundable's registered ComputeExtentFunction(), which may be expensive, which is why we strongly encourage proper authoring of extent. ComputeExtent() Why Extent and not Bounds? . An authored extent on a prim which has children is expected to include the extent of all children, as they will be pruned from BBox computation during traversal. Declaration ``float3[] extent`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Float3Array """ result["Boundable"].CreateExtentAttr.func_doc = """CreateExtentAttr(defaultValue, writeSparsely) -> Attribute See GetExtentAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Boundable"].ComputeExtent.func_doc = """ComputeExtent(time, extent) -> bool If an extent is authored on this boundable, it queries the ``extent`` from the extent attribute, otherwise if ComputeExtentFunction is registered for the boundable's type, it computes the ``extent`` at ``time`` . Returns true when extent is successfully populated, false otherwise. ComputeExtentFromPlugins UsdGeomRegisterComputeExtentFunction Parameters ---------- time : TimeCode extent : Vec3fArray """ result["Boundable"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ result["Boundable"].Get.func_doc = """**classmethod** Get(stage, path) -> Boundable Return a UsdGeomBoundable holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomBoundable(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ result["Boundable"].ComputeExtentFromPlugins.func_doc = """**classmethod** ComputeExtentFromPlugins(boundable, time, extent) -> bool Compute the extent for the Boundable prim ``boundable`` at time ``time`` . If successful, populates ``extent`` with the result and returns ``true`` , otherwise returns ``false`` . The extent computation is based on the concrete type of the prim represented by ``boundable`` . Plugins that provide a Boundable prim type may implement and register an extent computation for that type using UsdGeomRegisterComputeExtentFunction. ComputeExtentFromPlugins will use this function to compute extents for all prims of that type. If no function has been registered for a prim type, but a function has been registered for one of its base types, that function will be used instead. This function may load plugins in order to access the extent computation for a prim type. Parameters ---------- boundable : Boundable time : TimeCode extent : Vec3fArray ---------------------------------------------------------------------- ComputeExtentFromPlugins(boundable, time, transform, extent) -> bool This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Computes the extent as if the matrix ``transform`` was first applied. Parameters ---------- boundable : Boundable time : TimeCode transform : Matrix4d extent : Vec3fArray """ result["Boundable"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type """ result["Camera"].__doc__ = """ Transformable camera. Describes optical properties of a camera via a common set of attributes that provide control over the camera's frustum as well as its depth of field. For stereo, the left and right camera are individual prims tagged through the stereoRole attribute. There is a corresponding class GfCamera, which can hold the state of a camera (at a particular time). UsdGeomCamera::GetCamera() and UsdGeomCamera::SetFromCamera() convert between a USD camera prim and a GfCamera. To obtain the camera's location in world space, call the following on a UsdGeomCamera 'camera': .. code-block:: text GfMatrix4d camXform = camera.ComputeLocalToWorldTransform(time); **Cameras in USD are always"Y up", regardless of the stage's orientation (i.e. UsdGeomGetStageUpAxis() ).** This means that the inverse of'camXform'(the VIEW half of the MODELVIEW transform in OpenGL parlance) will transform the world such that the camera is at the origin, looking down the -Z axis, with +Y as the up axis, and +X pointing to the right. This describes a **right handed coordinate system**. Units of Measure for Camera Properties ====================================== Despite the familiarity of millimeters for specifying some physical camera properties, UsdGeomCamera opts for greater consistency with all other UsdGeom schemas, which measure geometric properties in scene units, as determined by UsdGeomGetStageMetersPerUnit() . We do make a concession, however, in that lens and filmback properties are measured in **tenths of a scene unit** rather than"raw"scene units. This means that with the fallback value of.01 for *metersPerUnit* - i.e. scene unit of centimeters - then these"tenth of scene unit"properties are effectively millimeters. If one adds a Camera prim to a UsdStage whose scene unit is not centimeters, the fallback values for filmback properties will be incorrect (or at the least, unexpected) in an absolute sense; however, proper imaging through a"default camera"with focusing disabled depends only on ratios of the other properties, so the camera is still usable. However, it follows that if even one property is authored in the correct scene units, then they all must be. Linear Algebra in UsdGeom For any described attribute *Fallback* *Value* or *Allowed* *Values* below that are text/tokens, the actual token is published and defined in UsdGeomTokens. So to set an attribute to the value"rightHanded", use UsdGeomTokens->rightHanded as the value. """ result["Camera"].__init__.func_doc = """__init__(prim) Construct a UsdGeomCamera on UsdPrim ``prim`` . Equivalent to UsdGeomCamera::Get (prim.GetStage(), prim.GetPath()) for a *valid* ``prim`` , but will not immediately throw an error for an invalid ``prim`` Parameters ---------- prim : Prim ---------------------------------------------------------------------- __init__(schemaObj) Construct a UsdGeomCamera on the prim held by ``schemaObj`` . Should be preferred over UsdGeomCamera (schemaObj.GetPrim()), as it preserves SchemaBase state. Parameters ---------- schemaObj : SchemaBase """ result["Camera"].GetProjectionAttr.func_doc = """GetProjectionAttr() -> Attribute Declaration ``token projection ="perspective"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Allowed Values perspective, orthographic """ result["Camera"].CreateProjectionAttr.func_doc = """CreateProjectionAttr(defaultValue, writeSparsely) -> Attribute See GetProjectionAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Camera"].GetHorizontalApertureAttr.func_doc = """GetHorizontalApertureAttr() -> Attribute Horizontal aperture in tenths of a scene unit; see Units of Measure for Camera Properties. Default is the equivalent of the standard 35mm spherical projector aperture. Declaration ``float horizontalAperture = 20.955`` C++ Type float Usd Type SdfValueTypeNames->Float """ result["Camera"].CreateHorizontalApertureAttr.func_doc = """CreateHorizontalApertureAttr(defaultValue, writeSparsely) -> Attribute See GetHorizontalApertureAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Camera"].GetVerticalApertureAttr.func_doc = """GetVerticalApertureAttr() -> Attribute Vertical aperture in tenths of a scene unit; see Units of Measure for Camera Properties. Default is the equivalent of the standard 35mm spherical projector aperture. Declaration ``float verticalAperture = 15.2908`` C++ Type float Usd Type SdfValueTypeNames->Float """ result["Camera"].CreateVerticalApertureAttr.func_doc = """CreateVerticalApertureAttr(defaultValue, writeSparsely) -> Attribute See GetVerticalApertureAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Camera"].GetHorizontalApertureOffsetAttr.func_doc = """GetHorizontalApertureOffsetAttr() -> Attribute Horizontal aperture offset in the same units as horizontalAperture. Defaults to 0. Declaration ``float horizontalApertureOffset = 0`` C++ Type float Usd Type SdfValueTypeNames->Float """ result["Camera"].CreateHorizontalApertureOffsetAttr.func_doc = """CreateHorizontalApertureOffsetAttr(defaultValue, writeSparsely) -> Attribute See GetHorizontalApertureOffsetAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Camera"].GetVerticalApertureOffsetAttr.func_doc = """GetVerticalApertureOffsetAttr() -> Attribute Vertical aperture offset in the same units as verticalAperture. Defaults to 0. Declaration ``float verticalApertureOffset = 0`` C++ Type float Usd Type SdfValueTypeNames->Float """ result["Camera"].CreateVerticalApertureOffsetAttr.func_doc = """CreateVerticalApertureOffsetAttr(defaultValue, writeSparsely) -> Attribute See GetVerticalApertureOffsetAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Camera"].GetFocalLengthAttr.func_doc = """GetFocalLengthAttr() -> Attribute Perspective focal length in tenths of a scene unit; see Units of Measure for Camera Properties. Declaration ``float focalLength = 50`` C++ Type float Usd Type SdfValueTypeNames->Float """ result["Camera"].CreateFocalLengthAttr.func_doc = """CreateFocalLengthAttr(defaultValue, writeSparsely) -> Attribute See GetFocalLengthAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Camera"].GetClippingRangeAttr.func_doc = """GetClippingRangeAttr() -> Attribute Near and far clipping distances in scene units; see Units of Measure for Camera Properties. Declaration ``float2 clippingRange = (1, 1000000)`` C++ Type GfVec2f Usd Type SdfValueTypeNames->Float2 """ result["Camera"].CreateClippingRangeAttr.func_doc = """CreateClippingRangeAttr(defaultValue, writeSparsely) -> Attribute See GetClippingRangeAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Camera"].GetClippingPlanesAttr.func_doc = """GetClippingPlanesAttr() -> Attribute Additional, arbitrarily oriented clipping planes. A vector (a,b,c,d) encodes a clipping plane that cuts off (x,y,z) with a \\* x + b \\* y + c \\* z + d \\* 1<0 where (x,y,z) are the coordinates in the camera's space. Declaration ``float4[] clippingPlanes = []`` C++ Type VtArray<GfVec4f> Usd Type SdfValueTypeNames->Float4Array """ result["Camera"].CreateClippingPlanesAttr.func_doc = """CreateClippingPlanesAttr(defaultValue, writeSparsely) -> Attribute See GetClippingPlanesAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Camera"].GetFStopAttr.func_doc = """GetFStopAttr() -> Attribute Lens aperture. Defaults to 0.0, which turns off focusing. Declaration ``float fStop = 0`` C++ Type float Usd Type SdfValueTypeNames->Float """ result["Camera"].CreateFStopAttr.func_doc = """CreateFStopAttr(defaultValue, writeSparsely) -> Attribute See GetFStopAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Camera"].GetFocusDistanceAttr.func_doc = """GetFocusDistanceAttr() -> Attribute Distance from the camera to the focus plane in scene units; see Units of Measure for Camera Properties. Declaration ``float focusDistance = 0`` C++ Type float Usd Type SdfValueTypeNames->Float """ result["Camera"].CreateFocusDistanceAttr.func_doc = """CreateFocusDistanceAttr(defaultValue, writeSparsely) -> Attribute See GetFocusDistanceAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Camera"].GetStereoRoleAttr.func_doc = """GetStereoRoleAttr() -> Attribute If different from mono, the camera is intended to be the left or right camera of a stereo setup. Declaration ``uniform token stereoRole ="mono"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values mono, left, right """ result["Camera"].CreateStereoRoleAttr.func_doc = """CreateStereoRoleAttr(defaultValue, writeSparsely) -> Attribute See GetStereoRoleAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Camera"].GetShutterOpenAttr.func_doc = """GetShutterOpenAttr() -> Attribute Frame relative shutter open time in UsdTimeCode units (negative value indicates that the shutter opens before the current frame time). Used for motion blur. Declaration ``double shutter:open = 0`` C++ Type double Usd Type SdfValueTypeNames->Double """ result["Camera"].CreateShutterOpenAttr.func_doc = """CreateShutterOpenAttr(defaultValue, writeSparsely) -> Attribute See GetShutterOpenAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Camera"].GetShutterCloseAttr.func_doc = """GetShutterCloseAttr() -> Attribute Frame relative shutter close time, analogous comments from shutter:open apply. A value greater or equal to shutter:open should be authored, otherwise there is no exposure and a renderer should produce a black image. Declaration ``double shutter:close = 0`` C++ Type double Usd Type SdfValueTypeNames->Double """ result["Camera"].CreateShutterCloseAttr.func_doc = """CreateShutterCloseAttr(defaultValue, writeSparsely) -> Attribute See GetShutterCloseAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Camera"].GetExposureAttr.func_doc = """GetExposureAttr() -> Attribute Exposure adjustment, as a log base-2 value. The default of 0.0 has no effect. A value of 1.0 will double the image-plane intensities in a rendered image; a value of -1.0 will halve them. Declaration ``float exposure = 0`` C++ Type float Usd Type SdfValueTypeNames->Float """ result["Camera"].CreateExposureAttr.func_doc = """CreateExposureAttr(defaultValue, writeSparsely) -> Attribute See GetExposureAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Camera"].GetCamera.func_doc = """GetCamera(time) -> Camera Creates a GfCamera object from the attribute values at ``time`` . Parameters ---------- time : TimeCode """ result["Camera"].SetFromCamera.func_doc = """SetFromCamera(camera, time) -> None Write attribute values from ``camera`` for ``time`` . These attributes will be updated: - projection - horizontalAperture - horizontalApertureOffset - verticalAperture - verticalApertureOffset - focalLength - clippingRange - clippingPlanes - fStop - focalDistance - xformOpOrder and xformOp:transform This will clear any existing xformOpOrder and replace it with a single xformOp:transform entry. The xformOp:transform property is created or updated here to match the transform on ``camera`` . This operation will fail if there are stronger xform op opinions in the composed layer stack that are stronger than that of the current edit target. Parameters ---------- camera : Camera time : TimeCode """ result["Camera"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ result["Camera"].Get.func_doc = """**classmethod** Get(stage, path) -> Camera Return a UsdGeomCamera holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomCamera(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ result["Camera"].Define.func_doc = """**classmethod** Define(stage, path) -> Camera Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ result["Camera"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type """ result["Capsule"].__doc__ = """ Defines a primitive capsule, i.e. a cylinder capped by two half spheres, centered at the origin, whose spine is along the specified *axis*. For any described attribute *Fallback* *Value* or *Allowed* *Values* below that are text/tokens, the actual token is published and defined in UsdGeomTokens. So to set an attribute to the value"rightHanded", use UsdGeomTokens->rightHanded as the value. """ result["Capsule"].__init__.func_doc = """__init__(prim) Construct a UsdGeomCapsule on UsdPrim ``prim`` . Equivalent to UsdGeomCapsule::Get (prim.GetStage(), prim.GetPath()) for a *valid* ``prim`` , but will not immediately throw an error for an invalid ``prim`` Parameters ---------- prim : Prim ---------------------------------------------------------------------- __init__(schemaObj) Construct a UsdGeomCapsule on the prim held by ``schemaObj`` . Should be preferred over UsdGeomCapsule (schemaObj.GetPrim()), as it preserves SchemaBase state. Parameters ---------- schemaObj : SchemaBase """ result["Capsule"].GetHeightAttr.func_doc = """GetHeightAttr() -> Attribute The size of the capsule's spine along the specified *axis* excluding the size of the two half spheres, i.e. the size of the cylinder portion of the capsule. If you author *height* you must also author *extent*. GetExtentAttr() Declaration ``double height = 1`` C++ Type double Usd Type SdfValueTypeNames->Double """ result["Capsule"].CreateHeightAttr.func_doc = """CreateHeightAttr(defaultValue, writeSparsely) -> Attribute See GetHeightAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Capsule"].GetRadiusAttr.func_doc = """GetRadiusAttr() -> Attribute The radius of the capsule. If you author *radius* you must also author *extent*. GetExtentAttr() Declaration ``double radius = 0.5`` C++ Type double Usd Type SdfValueTypeNames->Double """ result["Capsule"].CreateRadiusAttr.func_doc = """CreateRadiusAttr(defaultValue, writeSparsely) -> Attribute See GetRadiusAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Capsule"].GetAxisAttr.func_doc = """GetAxisAttr() -> Attribute The axis along which the spine of the capsule is aligned. Declaration ``uniform token axis ="Z"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values X, Y, Z """ result["Capsule"].CreateAxisAttr.func_doc = """CreateAxisAttr(defaultValue, writeSparsely) -> Attribute See GetAxisAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Capsule"].GetExtentAttr.func_doc = """GetExtentAttr() -> Attribute Extent is re-defined on Capsule only to provide a fallback value. UsdGeomGprim::GetExtentAttr() . Declaration ``float3[] extent = [(-0.5, -0.5, -1), (0.5, 0.5, 1)]`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Float3Array """ result["Capsule"].CreateExtentAttr.func_doc = """CreateExtentAttr(defaultValue, writeSparsely) -> Attribute See GetExtentAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Capsule"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ result["Capsule"].Get.func_doc = """**classmethod** Get(stage, path) -> Capsule Return a UsdGeomCapsule holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomCapsule(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ result["Capsule"].Define.func_doc = """**classmethod** Define(stage, path) -> Capsule Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ result["Capsule"].ComputeExtent.func_doc = """**classmethod** ComputeExtent(height, radius, axis, extent) -> bool Compute the extent for the capsule defined by the height, radius, and axis. true upon success, false if unable to calculate extent. On success, extent will contain an approximate axis-aligned bounding box of the capsule defined by the height, radius, and axis. This function is to provide easy authoring of extent for usd authoring tools, hence it is static and acts outside a specific prim (as in attribute based methods). Parameters ---------- height : float radius : float axis : str extent : Vec3fArray ---------------------------------------------------------------------- ComputeExtent(height, radius, axis, transform, extent) -> bool This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Computes the extent as if the matrix ``transform`` was first applied. Parameters ---------- height : float radius : float axis : str transform : Matrix4d extent : Vec3fArray """ result["Capsule"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type """ result["Cone"].__doc__ = """ Defines a primitive cone, centered at the origin, whose spine is along the specified *axis*, with the apex of the cone pointing in the direction of the positive axis. The fallback values for Cube, Sphere, Cone, and Cylinder are set so that they all pack into the same volume/bounds. For any described attribute *Fallback* *Value* or *Allowed* *Values* below that are text/tokens, the actual token is published and defined in UsdGeomTokens. So to set an attribute to the value"rightHanded", use UsdGeomTokens->rightHanded as the value. """ result["Cone"].__init__.func_doc = """__init__(prim) Construct a UsdGeomCone on UsdPrim ``prim`` . Equivalent to UsdGeomCone::Get (prim.GetStage(), prim.GetPath()) for a *valid* ``prim`` , but will not immediately throw an error for an invalid ``prim`` Parameters ---------- prim : Prim ---------------------------------------------------------------------- __init__(schemaObj) Construct a UsdGeomCone on the prim held by ``schemaObj`` . Should be preferred over UsdGeomCone (schemaObj.GetPrim()), as it preserves SchemaBase state. Parameters ---------- schemaObj : SchemaBase """ result["Cone"].GetHeightAttr.func_doc = """GetHeightAttr() -> Attribute The size of the cone's spine along the specified *axis*. If you author *height* you must also author *extent*. GetExtentAttr() Declaration ``double height = 2`` C++ Type double Usd Type SdfValueTypeNames->Double """ result["Cone"].CreateHeightAttr.func_doc = """CreateHeightAttr(defaultValue, writeSparsely) -> Attribute See GetHeightAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Cone"].GetRadiusAttr.func_doc = """GetRadiusAttr() -> Attribute The radius of the cone. If you author *radius* you must also author *extent*. GetExtentAttr() Declaration ``double radius = 1`` C++ Type double Usd Type SdfValueTypeNames->Double """ result["Cone"].CreateRadiusAttr.func_doc = """CreateRadiusAttr(defaultValue, writeSparsely) -> Attribute See GetRadiusAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Cone"].GetAxisAttr.func_doc = """GetAxisAttr() -> Attribute The axis along which the spine of the cone is aligned. Declaration ``uniform token axis ="Z"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values X, Y, Z """ result["Cone"].CreateAxisAttr.func_doc = """CreateAxisAttr(defaultValue, writeSparsely) -> Attribute See GetAxisAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Cone"].GetExtentAttr.func_doc = """GetExtentAttr() -> Attribute Extent is re-defined on Cone only to provide a fallback value. UsdGeomGprim::GetExtentAttr() . Declaration ``float3[] extent = [(-1, -1, -1), (1, 1, 1)]`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Float3Array """ result["Cone"].CreateExtentAttr.func_doc = """CreateExtentAttr(defaultValue, writeSparsely) -> Attribute See GetExtentAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Cone"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ result["Cone"].Get.func_doc = """**classmethod** Get(stage, path) -> Cone Return a UsdGeomCone holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomCone(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ result["Cone"].Define.func_doc = """**classmethod** Define(stage, path) -> Cone Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ result["Cone"].ComputeExtent.func_doc = """**classmethod** ComputeExtent(height, radius, axis, extent) -> bool Compute the extent for the cone defined by the height, radius, and axis. true upon success, false if unable to calculate extent. On success, extent will contain an approximate axis-aligned bounding box of the cone defined by the height, radius, and axis. This function is to provide easy authoring of extent for usd authoring tools, hence it is static and acts outside a specific prim (as in attribute based methods). Parameters ---------- height : float radius : float axis : str extent : Vec3fArray ---------------------------------------------------------------------- ComputeExtent(height, radius, axis, transform, extent) -> bool This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Computes the extent as if the matrix ``transform`` was first applied. Parameters ---------- height : float radius : float axis : str transform : Matrix4d extent : Vec3fArray """ result["Cone"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type """ result["ConstraintTarget"].__doc__ = """ Schema wrapper for UsdAttribute for authoring and introspecting attributes that are constraint targets. Constraint targets correspond roughly to what some DCC's call locators. They are coordinate frames, represented as (animated or static) GfMatrix4d values. We represent them as attributes in USD rather than transformable prims because generally we require no other coordinated information about a constraint target other than its name and its matrix value, and because attributes are more concise than prims. Because consumer clients often care only about the identity and value of constraint targets and may be able to usefully consume them without caring about the actual geometry with which they may logically correspond, UsdGeom aggregates all constraint targets onto a model's root prim, assuming that an exporter will use property namespacing within the constraint target attribute's name to indicate a path to a prim within the model with which the constraint target may correspond. To facilitate instancing, and also position-tweaking of baked assets, we stipulate that constraint target values always be recorded in **model-relative transformation space**. In other words, to get the world-space value of a constraint target, transform it by the local- to-world transformation of the prim on which it is recorded. ComputeInWorldSpace() will perform this calculation. """ result["ConstraintTarget"].GetAttr.func_doc = """GetAttr() -> Attribute Explicit UsdAttribute extractor. """ result["ConstraintTarget"].IsDefined.func_doc = """IsDefined() -> bool Return true if the wrapped UsdAttribute::IsDefined() , and in addition the attribute is identified as a ConstraintTarget. """ result["ConstraintTarget"].Get.func_doc = """Get(value, time) -> bool Get the attribute value of the ConstraintTarget at ``time`` . Parameters ---------- value : Matrix4d time : TimeCode """ result["ConstraintTarget"].Set.func_doc = """Set(value, time) -> bool Set the attribute value of the ConstraintTarget at ``time`` . Parameters ---------- value : Matrix4d time : TimeCode """ result["ConstraintTarget"].GetIdentifier.func_doc = """GetIdentifier() -> str Get the stored identifier unique to the enclosing model's namespace for this constraint target. SetIdentifier() """ result["ConstraintTarget"].SetIdentifier.func_doc = """SetIdentifier(identifier) -> None Explicitly sets the stored identifier to the given string. Clients are responsible for ensuring the uniqueness of this identifier within the enclosing model's namespace. Parameters ---------- identifier : str """ result["ConstraintTarget"].ComputeInWorldSpace.func_doc = """ComputeInWorldSpace(time, xfCache) -> Matrix4d Computes the value of the constraint target in world space. If a valid UsdGeomXformCache is provided in the argument ``xfCache`` , it is used to evaluate the CTM of the model to which the constraint target belongs. To get the constraint value in model-space (or local space), simply use UsdGeomConstraintTarget::Get() , since the authored values must already be in model-space. Parameters ---------- time : TimeCode xfCache : XformCache """ result["ConstraintTarget"].GetConstraintAttrName.func_doc = """**classmethod** GetConstraintAttrName(constraintName) -> str Returns the fully namespaced constraint attribute name, given the constraint name. Parameters ---------- constraintName : str """ result["ConstraintTarget"].__init__.func_doc = """__init__() ---------------------------------------------------------------------- __init__(attr) Speculative constructor that will produce a valid UsdGeomConstraintTarget when ``attr`` already represents an attribute that is a UsdGeomConstraintTarget, and produces an *invalid* UsdGeomConstraintTarget otherwise (i.e. UsdGeomConstraintTarget_explicit_bool will return false). Calling ``UsdGeomConstraintTarget::IsValid(attr)`` will return the same truth value as the object returned by this constructor, but if you plan to subsequently use the ConstraintTarget anyways, just construct the object and bool-evaluate it before proceeding. Parameters ---------- attr : Attribute """ result["ConstraintTarget"].IsValid.func_doc = """**classmethod** IsValid(attr) -> bool Test whether a given UsdAttribute represents valid ConstraintTarget, which implies that creating a UsdGeomConstraintTarget from the attribute will succeed. Success implies that ``attr.IsDefined()`` is true. Parameters ---------- attr : Attribute """ result["Cube"].__doc__ = """ Defines a primitive rectilinear cube centered at the origin. The fallback values for Cube, Sphere, Cone, and Cylinder are set so that they all pack into the same volume/bounds. """ result["Cube"].__init__.func_doc = """__init__(prim) Construct a UsdGeomCube on UsdPrim ``prim`` . Equivalent to UsdGeomCube::Get (prim.GetStage(), prim.GetPath()) for a *valid* ``prim`` , but will not immediately throw an error for an invalid ``prim`` Parameters ---------- prim : Prim ---------------------------------------------------------------------- __init__(schemaObj) Construct a UsdGeomCube on the prim held by ``schemaObj`` . Should be preferred over UsdGeomCube (schemaObj.GetPrim()), as it preserves SchemaBase state. Parameters ---------- schemaObj : SchemaBase """ result["Cube"].GetSizeAttr.func_doc = """GetSizeAttr() -> Attribute Indicates the length of each edge of the cube. If you author *size* you must also author *extent*. GetExtentAttr() Declaration ``double size = 2`` C++ Type double Usd Type SdfValueTypeNames->Double """ result["Cube"].CreateSizeAttr.func_doc = """CreateSizeAttr(defaultValue, writeSparsely) -> Attribute See GetSizeAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Cube"].GetExtentAttr.func_doc = """GetExtentAttr() -> Attribute Extent is re-defined on Cube only to provide a fallback value. UsdGeomGprim::GetExtentAttr() . Declaration ``float3[] extent = [(-1, -1, -1), (1, 1, 1)]`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Float3Array """ result["Cube"].CreateExtentAttr.func_doc = """CreateExtentAttr(defaultValue, writeSparsely) -> Attribute See GetExtentAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Cube"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ result["Cube"].Get.func_doc = """**classmethod** Get(stage, path) -> Cube Return a UsdGeomCube holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomCube(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ result["Cube"].Define.func_doc = """**classmethod** Define(stage, path) -> Cube Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ result["Cube"].ComputeExtent.func_doc = """**classmethod** ComputeExtent(size, extent) -> bool Compute the extent for the cube defined by the size of each dimension. true upon success, false if unable to calculate extent. On success, extent will contain an approximate axis-aligned bounding box of the cube defined by the size of each dimension. This function is to provide easy authoring of extent for usd authoring tools, hence it is static and acts outside a specific prim (as in attribute based methods). Parameters ---------- size : float extent : Vec3fArray ---------------------------------------------------------------------- ComputeExtent(size, transform, extent) -> bool This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Computes the extent as if the matrix ``transform`` was first applied. Parameters ---------- size : float transform : Matrix4d extent : Vec3fArray """ result["Cube"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type """ result["Curves"].__doc__ = """ Base class for UsdGeomBasisCurves, UsdGeomNurbsCurves, and UsdGeomHermiteCurves. The BasisCurves schema is designed to be analagous to offline renderers'notion of batched curves (such as the classical RIB definition via Basis and Curves statements), while the NurbsCurve schema is designed to be analgous to the NURBS curves found in packages like Maya and Houdini while retaining their consistency with the RenderMan specification for NURBS Patches. HermiteCurves are useful for the interchange of animation guides and paths. It is safe to use the length of the curve vertex count to derive the number of curves and the number and layout of curve vertices, but this schema should NOT be used to derive the number of curve points. While vertex indices are implicit in all shipped descendent types of this schema, one should not assume that all internal or future shipped schemas will follow this pattern. Be sure to key any indexing behavior off the concrete type, not this abstract type. """ result["Curves"].__init__.func_doc = """__init__(prim) Construct a UsdGeomCurves on UsdPrim ``prim`` . Equivalent to UsdGeomCurves::Get (prim.GetStage(), prim.GetPath()) for a *valid* ``prim`` , but will not immediately throw an error for an invalid ``prim`` Parameters ---------- prim : Prim ---------------------------------------------------------------------- __init__(schemaObj) Construct a UsdGeomCurves on the prim held by ``schemaObj`` . Should be preferred over UsdGeomCurves (schemaObj.GetPrim()), as it preserves SchemaBase state. Parameters ---------- schemaObj : SchemaBase """ result["Curves"].GetCurveVertexCountsAttr.func_doc = """GetCurveVertexCountsAttr() -> Attribute Curves-derived primitives can represent multiple distinct, potentially disconnected curves. The length of'curveVertexCounts'gives the number of such curves, and each element describes the number of vertices in the corresponding curve Declaration ``int[] curveVertexCounts`` C++ Type VtArray<int> Usd Type SdfValueTypeNames->IntArray """ result["Curves"].CreateCurveVertexCountsAttr.func_doc = """CreateCurveVertexCountsAttr(defaultValue, writeSparsely) -> Attribute See GetCurveVertexCountsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Curves"].GetWidthsAttr.func_doc = """GetWidthsAttr() -> Attribute Provides width specification for the curves, whose application will depend on whether the curve is oriented (normals are defined for it), in which case widths are"ribbon width", or unoriented, in which case widths are cylinder width. 'widths'is not a generic Primvar, but the number of elements in this attribute will be determined by its'interpolation'. See SetWidthsInterpolation() . If'widths'and'primvars:widths'are both specified, the latter has precedence. Declaration ``float[] widths`` C++ Type VtArray<float> Usd Type SdfValueTypeNames->FloatArray """ result["Curves"].CreateWidthsAttr.func_doc = """CreateWidthsAttr(defaultValue, writeSparsely) -> Attribute See GetWidthsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Curves"].GetWidthsInterpolation.func_doc = """GetWidthsInterpolation() -> str Get the interpolation for the *widths* attribute. Although'widths'is not classified as a generic UsdGeomPrimvar (and will not be included in the results of UsdGeomPrimvarsAPI::GetPrimvars() ) it does require an interpolation specification. The fallback interpolation, if left unspecified, is UsdGeomTokens->vertex, which means a width value is specified at the end of each curve segment. """ result["Curves"].SetWidthsInterpolation.func_doc = """SetWidthsInterpolation(interpolation) -> bool Set the interpolation for the *widths* attribute. true upon success, false if ``interpolation`` is not a legal value as defined by UsdPrimvar::IsValidInterpolation(), or if there was a problem setting the value. No attempt is made to validate that the widths attr's value contains the right number of elements to match its interpolation to its prim's topology. GetWidthsInterpolation() Parameters ---------- interpolation : str """ result["Curves"].GetCurveCount.func_doc = """GetCurveCount(timeCode) -> int Returns the number of curves as defined by the size of the *curveVertexCounts* array at *timeCode*. For most code, this check will be performant. When using file formats where the cost of attribute reading is high and the time sampled array will be read into memory later, it may be better to explicitly read the value once and check the size of the array directly. GetCurveVertexCountsAttr() Parameters ---------- timeCode : TimeCode """ result["Curves"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ result["Curves"].Get.func_doc = """**classmethod** Get(stage, path) -> Curves Return a UsdGeomCurves holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomCurves(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ result["Curves"].ComputeExtent.func_doc = """**classmethod** ComputeExtent(points, widths, extent) -> bool Compute the extent for the curves defined by points and widths. true upon success, false if unable to calculate extent. On success, extent will contain an approximate axis-aligned bounding box of the curve defined by points with the given widths. This function is to provide easy authoring of extent for usd authoring tools, hence it is static and acts outside a specific prim (as in attribute based methods). Parameters ---------- points : Vec3fArray widths : FloatArray extent : Vec3fArray ---------------------------------------------------------------------- ComputeExtent(points, widths, transform, extent) -> bool This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Computes the extent as if the matrix ``transform`` was first applied. Parameters ---------- points : Vec3fArray widths : FloatArray transform : Matrix4d extent : Vec3fArray """ result["Curves"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type """ result["Cylinder"].__doc__ = """ Defines a primitive cylinder with closed ends, centered at the origin, whose spine is along the specified *axis*. The fallback values for Cube, Sphere, Cone, and Cylinder are set so that they all pack into the same volume/bounds. For any described attribute *Fallback* *Value* or *Allowed* *Values* below that are text/tokens, the actual token is published and defined in UsdGeomTokens. So to set an attribute to the value"rightHanded", use UsdGeomTokens->rightHanded as the value. """ result["Cylinder"].__init__.func_doc = """__init__(prim) Construct a UsdGeomCylinder on UsdPrim ``prim`` . Equivalent to UsdGeomCylinder::Get (prim.GetStage(), prim.GetPath()) for a *valid* ``prim`` , but will not immediately throw an error for an invalid ``prim`` Parameters ---------- prim : Prim ---------------------------------------------------------------------- __init__(schemaObj) Construct a UsdGeomCylinder on the prim held by ``schemaObj`` . Should be preferred over UsdGeomCylinder (schemaObj.GetPrim()), as it preserves SchemaBase state. Parameters ---------- schemaObj : SchemaBase """ result["Cylinder"].GetHeightAttr.func_doc = """GetHeightAttr() -> Attribute The size of the cylinder's spine along the specified *axis*. If you author *height* you must also author *extent*. GetExtentAttr() Declaration ``double height = 2`` C++ Type double Usd Type SdfValueTypeNames->Double """ result["Cylinder"].CreateHeightAttr.func_doc = """CreateHeightAttr(defaultValue, writeSparsely) -> Attribute See GetHeightAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Cylinder"].GetRadiusAttr.func_doc = """GetRadiusAttr() -> Attribute The radius of the cylinder. If you author *radius* you must also author *extent*. GetExtentAttr() Declaration ``double radius = 1`` C++ Type double Usd Type SdfValueTypeNames->Double """ result["Cylinder"].CreateRadiusAttr.func_doc = """CreateRadiusAttr(defaultValue, writeSparsely) -> Attribute See GetRadiusAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Cylinder"].GetAxisAttr.func_doc = """GetAxisAttr() -> Attribute The axis along which the spine of the cylinder is aligned. Declaration ``uniform token axis ="Z"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values X, Y, Z """ result["Cylinder"].CreateAxisAttr.func_doc = """CreateAxisAttr(defaultValue, writeSparsely) -> Attribute See GetAxisAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Cylinder"].GetExtentAttr.func_doc = """GetExtentAttr() -> Attribute Extent is re-defined on Cylinder only to provide a fallback value. UsdGeomGprim::GetExtentAttr() . Declaration ``float3[] extent = [(-1, -1, -1), (1, 1, 1)]`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Float3Array """ result["Cylinder"].CreateExtentAttr.func_doc = """CreateExtentAttr(defaultValue, writeSparsely) -> Attribute See GetExtentAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Cylinder"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ result["Cylinder"].Get.func_doc = """**classmethod** Get(stage, path) -> Cylinder Return a UsdGeomCylinder holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomCylinder(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ result["Cylinder"].Define.func_doc = """**classmethod** Define(stage, path) -> Cylinder Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ result["Cylinder"].ComputeExtent.func_doc = """**classmethod** ComputeExtent(height, radius, axis, extent) -> bool Compute the extent for the cylinder defined by the height, radius, and axis. true upon success, false if unable to calculate extent. On success, extent will contain an approximate axis-aligned bounding box of the cylinder defined by the height, radius, and axis. This function is to provide easy authoring of extent for usd authoring tools, hence it is static and acts outside a specific prim (as in attribute based methods). Parameters ---------- height : float radius : float axis : str extent : Vec3fArray ---------------------------------------------------------------------- ComputeExtent(height, radius, axis, transform, extent) -> bool This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Computes the extent as if the matrix ``transform`` was first applied. Parameters ---------- height : float radius : float axis : str transform : Matrix4d extent : Vec3fArray """ result["Cylinder"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type """ result["Gprim"].__doc__ = """ Base class for all geometric primitives. Gprim encodes basic graphical properties such as *doubleSided* and *orientation*, and provides primvars for"display color"and"displayopacity"that travel with geometry to be used as shader overrides. For any described attribute *Fallback* *Value* or *Allowed* *Values* below that are text/tokens, the actual token is published and defined in UsdGeomTokens. So to set an attribute to the value"rightHanded", use UsdGeomTokens->rightHanded as the value. """ result["Gprim"].__init__.func_doc = """__init__(prim) Construct a UsdGeomGprim on UsdPrim ``prim`` . Equivalent to UsdGeomGprim::Get (prim.GetStage(), prim.GetPath()) for a *valid* ``prim`` , but will not immediately throw an error for an invalid ``prim`` Parameters ---------- prim : Prim ---------------------------------------------------------------------- __init__(schemaObj) Construct a UsdGeomGprim on the prim held by ``schemaObj`` . Should be preferred over UsdGeomGprim (schemaObj.GetPrim()), as it preserves SchemaBase state. Parameters ---------- schemaObj : SchemaBase """ result["Gprim"].GetDisplayColorAttr.func_doc = """GetDisplayColorAttr() -> Attribute It is useful to have an"official"colorSet that can be used as a display or modeling color, even in the absence of any specified shader for a gprim. DisplayColor serves this role; because it is a UsdGeomPrimvar, it can also be used as a gprim override for any shader that consumes a *displayColor* parameter. Declaration ``color3f[] primvars:displayColor`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Color3fArray """ result["Gprim"].CreateDisplayColorAttr.func_doc = """CreateDisplayColorAttr(defaultValue, writeSparsely) -> Attribute See GetDisplayColorAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Gprim"].GetDisplayOpacityAttr.func_doc = """GetDisplayOpacityAttr() -> Attribute Companion to *displayColor* that specifies opacity, broken out as an independent attribute rather than an rgba color, both so that each can be independently overridden, and because shaders rarely consume rgba parameters. Declaration ``float[] primvars:displayOpacity`` C++ Type VtArray<float> Usd Type SdfValueTypeNames->FloatArray """ result["Gprim"].CreateDisplayOpacityAttr.func_doc = """CreateDisplayOpacityAttr(defaultValue, writeSparsely) -> Attribute See GetDisplayOpacityAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Gprim"].GetDoubleSidedAttr.func_doc = """GetDoubleSidedAttr() -> Attribute Although some renderers treat all parametric or polygonal surfaces as if they were effectively laminae with outward-facing normals on both sides, some renderers derive significant optimizations by considering these surfaces to have only a single outward side, typically determined by control-point winding order and/or *orientation*. By doing so they can perform"backface culling"to avoid drawing the many polygons of most closed surfaces that face away from the viewer. However, it is often advantageous to model thin objects such as paper and cloth as single, open surfaces that must be viewable from both sides, always. Setting a gprim's *doubleSided* attribute to ``true`` instructs all renderers to disable optimizations such as backface culling for the gprim, and attempt (not all renderers are able to do so, but the USD reference GL renderer always will) to provide forward- facing normals on each side of the surface for lighting calculations. Declaration ``uniform bool doubleSided = 0`` C++ Type bool Usd Type SdfValueTypeNames->Bool Variability SdfVariabilityUniform """ result["Gprim"].CreateDoubleSidedAttr.func_doc = """CreateDoubleSidedAttr(defaultValue, writeSparsely) -> Attribute See GetDoubleSidedAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Gprim"].GetOrientationAttr.func_doc = """GetOrientationAttr() -> Attribute Orientation specifies whether the gprim's surface normal should be computed using the right hand rule, or the left hand rule. Please see Coordinate System, Winding Order, Orientation, and Surface Normals for a deeper explanation and generalization of orientation to composed scenes with transformation hierarchies. Declaration ``uniform token orientation ="rightHanded"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values rightHanded, leftHanded """ result["Gprim"].CreateOrientationAttr.func_doc = """CreateOrientationAttr(defaultValue, writeSparsely) -> Attribute See GetOrientationAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Gprim"].GetDisplayColorPrimvar.func_doc = """GetDisplayColorPrimvar() -> Primvar Convenience function to get the displayColor Attribute as a Primvar. GetDisplayColorAttr() , CreateDisplayColorPrimvar() """ result["Gprim"].CreateDisplayColorPrimvar.func_doc = """CreateDisplayColorPrimvar(interpolation, elementSize) -> Primvar Convenience function to create the displayColor primvar, optionally specifying interpolation and elementSize. CreateDisplayColorAttr() , GetDisplayColorPrimvar() Parameters ---------- interpolation : str elementSize : int """ result["Gprim"].GetDisplayOpacityPrimvar.func_doc = """GetDisplayOpacityPrimvar() -> Primvar Convenience function to get the displayOpacity Attribute as a Primvar. GetDisplayOpacityAttr() , CreateDisplayOpacityPrimvar() """ result["Gprim"].CreateDisplayOpacityPrimvar.func_doc = """CreateDisplayOpacityPrimvar(interpolation, elementSize) -> Primvar Convenience function to create the displayOpacity primvar, optionally specifying interpolation and elementSize. CreateDisplayOpacityAttr() , GetDisplayOpacityPrimvar() Parameters ---------- interpolation : str elementSize : int """ result["Gprim"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ result["Gprim"].Get.func_doc = """**classmethod** Get(stage, path) -> Gprim Return a UsdGeomGprim holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomGprim(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ result["Gprim"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type """ result["HermiteCurves"].__doc__ = """ This schema specifies a cubic hermite interpolated curve batch as sometimes used for defining guides for animation. While hermite curves can be useful because they interpolate through their control points, they are not well supported by high-end renderers for imaging. Therefore, while we include this schema for interchange, we strongly recommend the use of UsdGeomBasisCurves as the representation of curves intended to be rendered (ie. hair or grass). Hermite curves can be converted to a Bezier representation (though not from Bezier back to Hermite in general). Point Interpolation =================== The initial cubic curve segment is defined by the first two points and first two tangents. Additional segments are defined by additional point / tangent pairs. The number of segments for each non-batched hermite curve would be len(curve.points) - 1. The total number of segments for the batched UsdGeomHermiteCurves representation is len(points) - len(curveVertexCounts). Primvar, Width, and Normal Interpolation ======================================== Primvar interpolation is not well specified for this type as it is not intended as a rendering representation. We suggest that per point primvars would be linearly interpolated across each segment and should be tagged as'varying'. It is not immediately clear how to specify cubic or'vertex'interpolation for this type, as we lack a specification for primvar tangents. This also means that width and normal interpolation should be restricted to varying (linear), uniform (per curve element), or constant (per prim). """ result["HermiteCurves"].__init__.func_doc = """__init__(prim) Construct a UsdGeomHermiteCurves on UsdPrim ``prim`` . Equivalent to UsdGeomHermiteCurves::Get (prim.GetStage(), prim.GetPath()) for a *valid* ``prim`` , but will not immediately throw an error for an invalid ``prim`` Parameters ---------- prim : Prim ---------------------------------------------------------------------- __init__(schemaObj) Construct a UsdGeomHermiteCurves on the prim held by ``schemaObj`` . Should be preferred over UsdGeomHermiteCurves (schemaObj.GetPrim()), as it preserves SchemaBase state. Parameters ---------- schemaObj : SchemaBase """ result["HermiteCurves"].GetTangentsAttr.func_doc = """GetTangentsAttr() -> Attribute Defines the outgoing trajectory tangent for each point. Tangents should be the same size as the points attribute. Declaration ``vector3f[] tangents = []`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Vector3fArray """ result["HermiteCurves"].CreateTangentsAttr.func_doc = """CreateTangentsAttr(defaultValue, writeSparsely) -> Attribute See GetTangentsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["HermiteCurves"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ result["HermiteCurves"].Get.func_doc = """**classmethod** Get(stage, path) -> HermiteCurves Return a UsdGeomHermiteCurves holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomHermiteCurves(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ result["HermiteCurves"].Define.func_doc = """**classmethod** Define(stage, path) -> HermiteCurves Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ result["HermiteCurves"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type """ result["Imageable"].__doc__ = """ Base class for all prims that may require rendering or visualization of some sort. The primary attributes of Imageable are *visibility* and *purpose*, which each provide instructions for what geometry should be included for processing by rendering and other computations. Deprecated Imageable also provides API for accessing primvars, which has been moved to the UsdGeomPrimvarsAPI schema, because primvars can now be applied on non-Imageable prim types. This API is planned to be removed, UsdGeomPrimvarsAPI should be used directly instead. For any described attribute *Fallback* *Value* or *Allowed* *Values* below that are text/tokens, the actual token is published and defined in UsdGeomTokens. So to set an attribute to the value"rightHanded", use UsdGeomTokens->rightHanded as the value. """ result["Imageable"].MakeVisible.func_doc = """MakeVisible(time) -> None Make the imageable visible if it is invisible at the given time. Since visibility is pruning, this may need to override some ancestor's visibility and all-but-one of the ancestor's children's visibility, for all the ancestors of this prim up to the highest ancestor that is explicitly invisible, to preserve the visibility state. If MakeVisible() (or MakeInvisible() ) is going to be applied to all the prims on a stage, ancestors must be processed prior to descendants to get the correct behavior. When visibility is animated, this only works when it is invoked sequentially at increasing time samples. If visibility is already authored and animated in the scene, calling MakeVisible() at an arbitrary (in-between) frame isn't guaranteed to work. This will only work properly if all ancestor prims of the imageable are **defined**, as the imageable schema is only valid on defined prims. Be sure to set the edit target to the layer containing the strongest visibility opinion or to a stronger layer. MakeInvisible() ComputeVisibility() Parameters ---------- time : TimeCode """ result["Imageable"].MakeInvisible.func_doc = """MakeInvisible(time) -> None Makes the imageable invisible if it is visible at the given time. When visibility is animated, this only works when it is invoked sequentially at increasing time samples. If visibility is already authored and animated in the scene, calling MakeVisible() at an arbitrary (in-between) frame isn't guaranteed to work. Be sure to set the edit target to the layer containing the strongest visibility opinion or to a stronger layer. MakeVisible() ComputeVisibility() Parameters ---------- time : TimeCode """ result["Imageable"].ComputeVisibility.func_doc = """ComputeVisibility(time) -> str Calculate the effective visibility of this prim, as defined by its most ancestral authored"invisible"opinion, if any. A prim is considered visible at the current ``time`` if none of its Imageable ancestors express an authored"invisible"opinion, which is what leads to the"simple pruning"behavior described in GetVisibilityAttr() . This function should be considered a reference implementation for correctness. **If called on each prim in the context of a traversal we will perform massive overcomputation, because sibling prims share sub- problems in the query that can be efficiently cached, but are not (cannot be) by this simple implementation.** If you have control of your traversal, it will be far more efficient to manage visibility on a stack as you traverse. GetVisibilityAttr() Parameters ---------- time : TimeCode """ result["Imageable"].GetPurposeVisibilityAttr.func_doc = """GetPurposeVisibilityAttr(purpose) -> Attribute Return the attribute that is used for expressing visibility opinions for the given ``purpose`` . For"default"purpose, return the overall *visibility* attribute. For"guide","proxy", or"render"purpose, return *guideVisibility*, *proxyVisibility*, or *renderVisibility* if UsdGeomVisibilityAPI is applied to the prim. If UsdGeomvVisibiltyAPI is not applied, an empty attribute is returned for purposes other than default. UsdGeomVisibilityAPI::Apply UsdGeomVisibilityAPI::GetPurposeVisibilityAttr Parameters ---------- purpose : str """ result["Imageable"].ComputeEffectiveVisibility.func_doc = """ComputeEffectiveVisibility(purpose, time) -> str Calculate the effective purpose visibility of this prim for the given ``purpose`` , taking into account opinions for the corresponding purpose attribute, along with overall visibility opinions. If ComputeVisibility() returns"invisible", then ComputeEffectiveVisibility() is"invisible"for all purpose values. Otherwise, ComputeEffectiveVisibility() returns the value of the nearest ancestral authored opinion for the corresponding purpose visibility attribute, as retured by GetPurposeVisibilityAttr(purpose). Note that the value returned here can be"invisible"(indicating the prim is invisible for the given purpose),"visible"(indicating that it's visible), or"inherited"(indicating that the purpose visibility is context-dependent and the fallback behavior must be determined by the caller. This function should be considered a reference implementation for correctness. **If called on each prim in the context of a traversal we will perform massive overcomputation, because sibling prims share sub- problems in the query that can be efficiently cached, but are not (cannot be) by this simple implementation.** If you have control of your traversal, it will be far more efficient to manage visibility on a stack as you traverse. UsdGeomVisibilityAPI GetPurposeVisibilityAttr() ComputeVisibility() Parameters ---------- purpose : str time : TimeCode """ result["Imageable"].ComputePurposeInfo.func_doc = """ComputePurposeInfo() -> PurposeInfo Calculate the effective purpose information about this prim which includes final computed purpose value of the prim as well as whether the purpose value should be inherited by namespace children without their own purpose opinions. This function should be considered a reference implementation for correctness. **If called on each prim in the context of a traversal we will perform massive overcomputation, because sibling prims share sub- problems in the query that can be efficiently cached, but are not (cannot be) by this simple implementation.** If you have control of your traversal, it will be far more efficient to manage purpose, along with visibility, on a stack as you traverse. GetPurposeAttr() , Imageable Purpose ---------------------------------------------------------------------- ComputePurposeInfo(parentPurposeInfo) -> PurposeInfo This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Calculates the effective purpose information about this prim, given the computed purpose information of its parent prim. This can be much more efficient than using CommputePurposeInfo() when PurposeInfo values are properly computed and cached for a hierarchy of prims using this function. GetPurposeAttr() , Imageable Purpose Parameters ---------- parentPurposeInfo : PurposeInfo """ result["Imageable"].ComputePurpose.func_doc = """ComputePurpose() -> str Calculate the effective purpose information about this prim. This is equivalent to extracting the purpose from the value returned by ComputePurposeInfo() . This function should be considered a reference implementation for correctness. **If called on each prim in the context of a traversal we will perform massive overcomputation, because sibling prims share sub- problems in the query that can be efficiently cached, but are not (cannot be) by this simple implementation.** If you have control of your traversal, it will be far more efficient to manage purpose, along with visibility, on a stack as you traverse. GetPurposeAttr() , Imageable Purpose """ result["Imageable"].SetProxyPrim.func_doc = """SetProxyPrim(proxy) -> bool Convenience function for authoring the *renderProxy* rel on this prim to target the given ``proxy`` prim. To facilitate authoring on sparse or unloaded stages, we do not perform any validation of this prim's purpose or the type or purpose of the specified prim. ComputeProxyPrim() , GetProxyPrimRel() Parameters ---------- proxy : Prim ---------------------------------------------------------------------- SetProxyPrim(proxy) -> bool Parameters ---------- proxy : SchemaBase """ result["Imageable"].ComputeWorldBound.func_doc = """ComputeWorldBound(time, purpose1, purpose2, purpose3, purpose4) -> BBox3d Compute the bound of this prim in world space, at the specified ``time`` , and for the specified purposes. The bound of the prim is computed, including the transform (if any) authored on the node itself, and then transformed to world space. It is an error to not specify any purposes, which will result in the return of an empty box. **If you need to compute bounds for multiple prims on a stage, it will be much, much more efficient to instantiate a UsdGeomBBoxCache and query it directly; doing so will reuse sub-computations shared by the prims.** Parameters ---------- time : TimeCode purpose1 : str purpose2 : str purpose3 : str purpose4 : str """ result["Imageable"].ComputeLocalBound.func_doc = """ComputeLocalBound(time, purpose1, purpose2, purpose3, purpose4) -> BBox3d Compute the bound of this prim in local space, at the specified ``time`` , and for the specified purposes. The bound of the prim is computed, including the transform (if any) authored on the node itself. It is an error to not specify any purposes, which will result in the return of an empty box. **If you need to compute bounds for multiple prims on a stage, it will be much, much more efficient to instantiate a UsdGeomBBoxCache and query it directly; doing so will reuse sub-computations shared by the prims.** Parameters ---------- time : TimeCode purpose1 : str purpose2 : str purpose3 : str purpose4 : str """ result["Imageable"].ComputeUntransformedBound.func_doc = """ComputeUntransformedBound(time, purpose1, purpose2, purpose3, purpose4) -> BBox3d Compute the untransformed bound of this prim, at the specified ``time`` , and for the specified purposes. The bound of the prim is computed in its object space, ignoring any transforms authored on or above the prim. It is an error to not specify any purposes, which will result in the return of an empty box. **If you need to compute bounds for multiple prims on a stage, it will be much, much more efficient to instantiate a UsdGeomBBoxCache and query it directly; doing so will reuse sub-computations shared by the prims.** Parameters ---------- time : TimeCode purpose1 : str purpose2 : str purpose3 : str purpose4 : str """ result["Imageable"].ComputeLocalToWorldTransform.func_doc = """ComputeLocalToWorldTransform(time) -> Matrix4d Compute the transformation matrix for this prim at the given time, including the transform authored on the Prim itself, if present. **If you need to compute the transform for multiple prims on a stage, it will be much, much more efficient to instantiate a UsdGeomXformCache and query it directly; doing so will reuse sub- computations shared by the prims.** Parameters ---------- time : TimeCode """ result["Imageable"].ComputeParentToWorldTransform.func_doc = """ComputeParentToWorldTransform(time) -> Matrix4d Compute the transformation matrix for this prim at the given time, *NOT* including the transform authored on the prim itself. **If you need to compute the transform for multiple prims on a stage, it will be much, much more efficient to instantiate a UsdGeomXformCache and query it directly; doing so will reuse sub- computations shared by the prims.** Parameters ---------- time : TimeCode """ result["Imageable"].__init__.func_doc = """__init__(prim) Construct a UsdGeomImageable on UsdPrim ``prim`` . Equivalent to UsdGeomImageable::Get (prim.GetStage(), prim.GetPath()) for a *valid* ``prim`` , but will not immediately throw an error for an invalid ``prim`` Parameters ---------- prim : Prim ---------------------------------------------------------------------- __init__(schemaObj) Construct a UsdGeomImageable on the prim held by ``schemaObj`` . Should be preferred over UsdGeomImageable (schemaObj.GetPrim()), as it preserves SchemaBase state. Parameters ---------- schemaObj : SchemaBase """ result["Imageable"].GetVisibilityAttr.func_doc = """GetVisibilityAttr() -> Attribute Visibility is meant to be the simplest form of"pruning"visibility that is supported by most DCC apps. Visibility is animatable, allowing a sub-tree of geometry to be present for some segment of a shot, and absent from others; unlike the action of deactivating geometry prims, invisible geometry is still available for inspection, for positioning, for defining volumes, etc. Declaration ``token visibility ="inherited"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Allowed Values inherited, invisible """ result["Imageable"].CreateVisibilityAttr.func_doc = """CreateVisibilityAttr(defaultValue, writeSparsely) -> Attribute See GetVisibilityAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Imageable"].GetPurposeAttr.func_doc = """GetPurposeAttr() -> Attribute Purpose is a classification of geometry into categories that can each be independently included or excluded from traversals of prims on a stage, such as rendering or bounding-box computation traversals. See Imageable Purpose for more detail about how *purpose* is computed and used. Declaration ``uniform token purpose ="default"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values default, render, proxy, guide """ result["Imageable"].CreatePurposeAttr.func_doc = """CreatePurposeAttr(defaultValue, writeSparsely) -> Attribute See GetPurposeAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Imageable"].GetProxyPrimRel.func_doc = """GetProxyPrimRel() -> Relationship The *proxyPrim* relationship allows us to link a prim whose *purpose* is"render"to its (single target) purpose="proxy"prim. This is entirely optional, but can be useful in several scenarios: - In a pipeline that does pruning (for complexity management) by deactivating prims composed from asset references, when we deactivate a purpose="render"prim, we will be able to discover and additionally deactivate its associated purpose="proxy"prim, so that preview renders reflect the pruning accurately. - DCC importers may be able to make more aggressive optimizations for interactive processing and display if they can discover the proxy for a given render prim. - With a little more work, a Hydra-based application will be able to map a picked proxy prim back to its render geometry for selection. It is only valid to author the proxyPrim relationship on prims whose purpose is"render". """ result["Imageable"].CreateProxyPrimRel.func_doc = """CreateProxyPrimRel() -> Relationship See GetProxyPrimRel() , and also Create vs Get Property Methods for when to use Get vs Create. """ result["Imageable"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ result["Imageable"].Get.func_doc = """**classmethod** Get(stage, path) -> Imageable Return a UsdGeomImageable holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomImageable(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ result["Imageable"].GetOrderedPurposeTokens.func_doc = """**classmethod** GetOrderedPurposeTokens() -> list[TfToken] Returns an ordered list of allowed values of the purpose attribute. The ordering is important because it defines the protocol between UsdGeomModelAPI and UsdGeomBBoxCache for caching and retrieving extents hints by purpose. The order is: [default, render, proxy, guide] See UsdGeomModelAPI::GetExtentsHint() . GetOrderedPurposeTokens() """ result["Imageable"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type """ result["LinearUnits"].__doc__ = """ Container class for static double-precision symbols representing common units of measure expressed in meters. Encoding Stage Linear Units """ result["Mesh"].__doc__ = """ Encodes a mesh with optional subdivision properties and features. As a point-based primitive, meshes are defined in terms of points that are connected into edges and faces. Many references to meshes use the term'vertex'in place of or interchangeably with'points', while some use'vertex'to refer to the'face-vertices'that define a face. To avoid confusion, the term'vertex'is intentionally avoided in favor of'points'or'face-vertices'. The connectivity between points, edges and faces is encoded using a common minimal topological description of the faces of the mesh. Each face is defined by a set of face-vertices using indices into the Mesh's *points* array (inherited from UsdGeomPointBased) and laid out in a single linear *faceVertexIndices* array for efficiency. A companion *faceVertexCounts* array provides, for each face, the number of consecutive face-vertices in *faceVertexIndices* that define the face. No additional connectivity information is required or constructed, so no adjacency or neighborhood queries are available. A key property of this mesh schema is that it encodes both subdivision surfaces and simpler polygonal meshes. This is achieved by varying the *subdivisionScheme* attribute, which is set to specify Catmull-Clark subdivision by default, so polygonal meshes must always be explicitly declared. The available subdivision schemes and additional subdivision features encoded in optional attributes conform to the feature set of OpenSubdiv ( https://graphics.pixar.com/opensubdiv/docs/subdivision_surfaces.html). **A Note About Primvars** The following list clarifies the number of elements for and the interpolation behavior of the different primvar interpolation types for meshes: - **constant** : One element for the entire mesh; no interpolation. - **uniform** : One element for each face of the mesh; elements are typically not interpolated but are inherited by other faces derived from a given face (via subdivision, tessellation, etc.). - **varying** : One element for each point of the mesh; interpolation of point data is always linear. - **vertex** : One element for each point of the mesh; interpolation of point data is applied according to the *subdivisionScheme* attribute. - **faceVarying** : One element for each of the face-vertices that define the mesh topology; interpolation of face-vertex data may be smooth or linear, according to the *subdivisionScheme* and *faceVaryingLinearInterpolation* attributes. Primvar interpolation types and related utilities are described more generally in Interpolation of Geometric Primitive Variables. **A Note About Normals** Normals should not be authored on a subdivision mesh, since subdivision algorithms define their own normals. They should only be authored for polygonal meshes ( *subdivisionScheme* ="none"). The *normals* attribute inherited from UsdGeomPointBased is not a generic primvar, but the number of elements in this attribute will be determined by its *interpolation*. See UsdGeomPointBased::GetNormalsInterpolation() . If *normals* and *primvars:normals* are both specified, the latter has precedence. If a polygonal mesh specifies **neither** *normals* nor *primvars:normals*, then it should be treated and rendered as faceted, with no attempt to compute smooth normals. The normals generated for smooth subdivision schemes, e.g. Catmull- Clark and Loop, will likewise be smooth, but others, e.g. Bilinear, may be discontinuous between faces and/or within non-planar irregular faces. For any described attribute *Fallback* *Value* or *Allowed* *Values* below that are text/tokens, the actual token is published and defined in UsdGeomTokens. So to set an attribute to the value"rightHanded", use UsdGeomTokens->rightHanded as the value. """ result["Mesh"].__init__.func_doc = """__init__(prim) Construct a UsdGeomMesh on UsdPrim ``prim`` . Equivalent to UsdGeomMesh::Get (prim.GetStage(), prim.GetPath()) for a *valid* ``prim`` , but will not immediately throw an error for an invalid ``prim`` Parameters ---------- prim : Prim ---------------------------------------------------------------------- __init__(schemaObj) Construct a UsdGeomMesh on the prim held by ``schemaObj`` . Should be preferred over UsdGeomMesh (schemaObj.GetPrim()), as it preserves SchemaBase state. Parameters ---------- schemaObj : SchemaBase """ result["Mesh"].GetFaceVertexIndicesAttr.func_doc = """GetFaceVertexIndicesAttr() -> Attribute Flat list of the index (into the *points* attribute) of each vertex of each face in the mesh. If this attribute has more than one timeSample, the mesh is considered to be topologically varying. Declaration ``int[] faceVertexIndices`` C++ Type VtArray<int> Usd Type SdfValueTypeNames->IntArray """ result["Mesh"].CreateFaceVertexIndicesAttr.func_doc = """CreateFaceVertexIndicesAttr(defaultValue, writeSparsely) -> Attribute See GetFaceVertexIndicesAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Mesh"].GetFaceVertexCountsAttr.func_doc = """GetFaceVertexCountsAttr() -> Attribute Provides the number of vertices in each face of the mesh, which is also the number of consecutive indices in *faceVertexIndices* that define the face. The length of this attribute is the number of faces in the mesh. If this attribute has more than one timeSample, the mesh is considered to be topologically varying. Declaration ``int[] faceVertexCounts`` C++ Type VtArray<int> Usd Type SdfValueTypeNames->IntArray """ result["Mesh"].CreateFaceVertexCountsAttr.func_doc = """CreateFaceVertexCountsAttr(defaultValue, writeSparsely) -> Attribute See GetFaceVertexCountsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Mesh"].GetSubdivisionSchemeAttr.func_doc = """GetSubdivisionSchemeAttr() -> Attribute The subdivision scheme to be applied to the surface. Valid values are: - **catmullClark** : The default, Catmull-Clark subdivision; preferred for quad-dominant meshes (generalizes B-splines); interpolation of point data is smooth (non-linear) - **loop** : Loop subdivision; preferred for purely triangular meshes; interpolation of point data is smooth (non-linear) - **bilinear** : Subdivision reduces all faces to quads (topologically similar to"catmullClark"); interpolation of point data is bilinear - **none** : No subdivision, i.e. a simple polygonal mesh; interpolation of point data is linear Polygonal meshes are typically lighter weight and faster to render, depending on renderer and render mode. Use of"bilinear"will produce a similar shape to a polygonal mesh and may offer additional guarantees of watertightness and additional subdivision features (e.g. holes) but may also not respect authored normals. Declaration ``uniform token subdivisionScheme ="catmullClark"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values catmullClark, loop, bilinear, none """ result["Mesh"].CreateSubdivisionSchemeAttr.func_doc = """CreateSubdivisionSchemeAttr(defaultValue, writeSparsely) -> Attribute See GetSubdivisionSchemeAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Mesh"].GetInterpolateBoundaryAttr.func_doc = """GetInterpolateBoundaryAttr() -> Attribute Specifies how subdivision is applied for faces adjacent to boundary edges and boundary points. Valid values correspond to choices available in OpenSubdiv: - **none** : No boundary interpolation is applied and boundary faces are effectively treated as holes - **edgeOnly** : A sequence of boundary edges defines a smooth curve to which the edges of subdivided boundary faces converge - **edgeAndCorner** : The default, similar to"edgeOnly"but the smooth boundary curve is made sharp at corner points These are illustrated and described in more detail in the OpenSubdiv documentation: https://graphics.pixar.com/opensubdiv/docs/subdivision_surfaces.html#boundary- interpolation-rules Declaration ``token interpolateBoundary ="edgeAndCorner"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Allowed Values none, edgeOnly, edgeAndCorner """ result["Mesh"].CreateInterpolateBoundaryAttr.func_doc = """CreateInterpolateBoundaryAttr(defaultValue, writeSparsely) -> Attribute See GetInterpolateBoundaryAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Mesh"].GetFaceVaryingLinearInterpolationAttr.func_doc = """GetFaceVaryingLinearInterpolationAttr() -> Attribute Specifies how elements of a primvar of interpolation type"faceVarying"are interpolated for subdivision surfaces. Interpolation can be as smooth as a"vertex"primvar or constrained to be linear at features specified by several options. Valid values correspond to choices available in OpenSubdiv: - **none** : No linear constraints or sharpening, smooth everywhere - **cornersOnly** : Sharpen corners of discontinuous boundaries only, smooth everywhere else - **cornersPlus1** : The default, same as"cornersOnly"plus additional sharpening at points where three or more distinct face- varying values occur - **cornersPlus2** : Same as"cornersPlus1"plus additional sharpening at points with at least one discontinuous boundary corner or only one discontinuous boundary edge (a dart) - **boundaries** : Piecewise linear along discontinuous boundaries, smooth interior - **all** : Piecewise linear everywhere These are illustrated and described in more detail in the OpenSubdiv documentation: https://graphics.pixar.com/opensubdiv/docs/subdivision_surfaces.html#face- varying-interpolation-rules Declaration ``token faceVaryingLinearInterpolation ="cornersPlus1"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Allowed Values none, cornersOnly, cornersPlus1, cornersPlus2, boundaries, all """ result["Mesh"].CreateFaceVaryingLinearInterpolationAttr.func_doc = """CreateFaceVaryingLinearInterpolationAttr(defaultValue, writeSparsely) -> Attribute See GetFaceVaryingLinearInterpolationAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Mesh"].GetTriangleSubdivisionRuleAttr.func_doc = """GetTriangleSubdivisionRuleAttr() -> Attribute Specifies an option to the subdivision rules for the Catmull-Clark scheme to try and improve undesirable artifacts when subdividing triangles. Valid values are"catmullClark"for the standard rules (the default) and"smooth"for the improvement. See https://graphics.pixar.com/opensubdiv/docs/subdivision_surfaces.html#triangle- subdivision-rule Declaration ``token triangleSubdivisionRule ="catmullClark"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Allowed Values catmullClark, smooth """ result["Mesh"].CreateTriangleSubdivisionRuleAttr.func_doc = """CreateTriangleSubdivisionRuleAttr(defaultValue, writeSparsely) -> Attribute See GetTriangleSubdivisionRuleAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Mesh"].GetHoleIndicesAttr.func_doc = """GetHoleIndicesAttr() -> Attribute The indices of all faces that should be treated as holes, i.e. made invisible. This is traditionally a feature of subdivision surfaces and not generally applied to polygonal meshes. Declaration ``int[] holeIndices = []`` C++ Type VtArray<int> Usd Type SdfValueTypeNames->IntArray """ result["Mesh"].CreateHoleIndicesAttr.func_doc = """CreateHoleIndicesAttr(defaultValue, writeSparsely) -> Attribute See GetHoleIndicesAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Mesh"].GetCornerIndicesAttr.func_doc = """GetCornerIndicesAttr() -> Attribute The indices of points for which a corresponding sharpness value is specified in *cornerSharpnesses* (so the size of this array must match that of *cornerSharpnesses*). Declaration ``int[] cornerIndices = []`` C++ Type VtArray<int> Usd Type SdfValueTypeNames->IntArray """ result["Mesh"].CreateCornerIndicesAttr.func_doc = """CreateCornerIndicesAttr(defaultValue, writeSparsely) -> Attribute See GetCornerIndicesAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Mesh"].GetCornerSharpnessesAttr.func_doc = """GetCornerSharpnessesAttr() -> Attribute The sharpness values associated with a corresponding set of points specified in *cornerIndices* (so the size of this array must match that of *cornerIndices*). Use the constant ``SHARPNESS_INFINITE`` for a perfectly sharp corner. Declaration ``float[] cornerSharpnesses = []`` C++ Type VtArray<float> Usd Type SdfValueTypeNames->FloatArray """ result["Mesh"].CreateCornerSharpnessesAttr.func_doc = """CreateCornerSharpnessesAttr(defaultValue, writeSparsely) -> Attribute See GetCornerSharpnessesAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Mesh"].GetCreaseIndicesAttr.func_doc = """GetCreaseIndicesAttr() -> Attribute The indices of points grouped into sets of successive pairs that identify edges to be creased. The size of this array must be equal to the sum of all elements of the *creaseLengths* attribute. Declaration ``int[] creaseIndices = []`` C++ Type VtArray<int> Usd Type SdfValueTypeNames->IntArray """ result["Mesh"].CreateCreaseIndicesAttr.func_doc = """CreateCreaseIndicesAttr(defaultValue, writeSparsely) -> Attribute See GetCreaseIndicesAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Mesh"].GetCreaseLengthsAttr.func_doc = """GetCreaseLengthsAttr() -> Attribute The length of this array specifies the number of creases (sets of adjacent sharpened edges) on the mesh. Each element gives the number of points of each crease, whose indices are successively laid out in the *creaseIndices* attribute. Since each crease must be at least one edge long, each element of this array must be at least two. Declaration ``int[] creaseLengths = []`` C++ Type VtArray<int> Usd Type SdfValueTypeNames->IntArray """ result["Mesh"].CreateCreaseLengthsAttr.func_doc = """CreateCreaseLengthsAttr(defaultValue, writeSparsely) -> Attribute See GetCreaseLengthsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Mesh"].GetCreaseSharpnessesAttr.func_doc = """GetCreaseSharpnessesAttr() -> Attribute The per-crease or per-edge sharpness values for all creases. Since *creaseLengths* encodes the number of points in each crease, the number of elements in this array will be either len(creaseLengths) or the sum over all X of (creaseLengths[X] - 1). Note that while the RI spec allows each crease to have either a single sharpness or a value per-edge, USD will encode either a single sharpness per crease on a mesh, or sharpnesses for all edges making up the creases on a mesh. Use the constant ``SHARPNESS_INFINITE`` for a perfectly sharp crease. Declaration ``float[] creaseSharpnesses = []`` C++ Type VtArray<float> Usd Type SdfValueTypeNames->FloatArray """ result["Mesh"].CreateCreaseSharpnessesAttr.func_doc = """CreateCreaseSharpnessesAttr(defaultValue, writeSparsely) -> Attribute See GetCreaseSharpnessesAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Mesh"].GetFaceCount.func_doc = """GetFaceCount(timeCode) -> int Returns the number of faces as defined by the size of the *faceVertexCounts* array at *timeCode*. For most code, this check will be performant. When using file formats where the cost of attribute reading is high and the time sampled array will be read into memory later, it may be better to explicitly read the value once and check the size of the array directly. GetFaceVertexCountsAttr() Parameters ---------- timeCode : TimeCode """ result["Mesh"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ result["Mesh"].Get.func_doc = """**classmethod** Get(stage, path) -> Mesh Return a UsdGeomMesh holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomMesh(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ result["Mesh"].Define.func_doc = """**classmethod** Define(stage, path) -> Mesh Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ result["Mesh"].ValidateTopology.func_doc = """**classmethod** ValidateTopology(faceVertexIndices, faceVertexCounts, numPoints, reason) -> bool Validate the topology of a mesh. This validates that the sum of ``faceVertexCounts`` is equal to the size of the ``faceVertexIndices`` array, and that all face vertex indices in the ``faceVertexIndices`` array are in the range [0, numPoints). Returns true if the topology is valid, or false otherwise. If the topology is invalid and ``reason`` is non-null, an error message describing the validation error will be set. Parameters ---------- faceVertexIndices : IntArray faceVertexCounts : IntArray numPoints : int reason : str """ result["Mesh"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type """ result["ModelAPI"].__doc__ = """ UsdGeomModelAPI extends the generic UsdModelAPI schema with geometry specific concepts such as cached extents for the entire model, constraint targets, and geometry-inspired extensions to the payload lofting process. As described in GetExtentsHint() below, it is useful to cache extents at the model level. UsdGeomModelAPI provides schema for computing and storing these cached extents, which can be consumed by UsdGeomBBoxCache to provide fast access to precomputed extents that will be used as the model's bounds ( see UsdGeomBBoxCache::UsdGeomBBoxCache() ). Draw Modes ========== Draw modes provide optional alternate imaging behavior for USD subtrees with kind model. *model:drawMode* (which is inheritable) and *model:applyDrawMode* (which is not) are resolved into a decision to stop traversing the scene graph at a certain point, and replace a USD subtree with proxy geometry. The value of *model:drawMode* determines the type of proxy geometry: - *origin* - Draw the model-space basis vectors of the replaced prim. - *bounds* - Draw the model-space bounding box of the replaced prim. - *cards* - Draw textured quads as a placeholder for the replaced prim. - *default* - An explicit opinion to draw the USD subtree as normal. - *inherited* - Defer to the parent opinion. *model:drawMode* falls back to *inherited* so that a whole scene, a large group, or all prototypes of a model hierarchy PointInstancer can be assigned a draw mode with a single attribute edit. If no draw mode is explicitly set in a hierarchy, the resolved value is *default*. *model:applyDrawMode* is meant to be written when an asset is authored, and provides flexibility for different asset types. For example, a character assembly (composed of character, clothes, etc) might have *model:applyDrawMode* set at the top of the subtree so the whole group can be drawn as a single card object. An effects subtree might have *model:applyDrawMode* set at a lower level so each particle group draws individually. Models of kind component are treated as if *model:applyDrawMode* were true. This means a prim is drawn with proxy geometry when: the prim has kind component, and/or *model:applyDrawMode* is set; and the prim's resolved value for *model:drawMode* is not *default*. Cards Geometry ============== The specific geometry used in cards mode is controlled by the *model:cardGeometry* attribute: - *cross* - Generate a quad normal to each basis direction and negative. Locate each quad so that it bisects the model extents. - *box* - Generate a quad normal to each basis direction and negative. Locate each quad on a face of the model extents, facing out. - *fromTexture* - Generate a quad for each supplied texture from attributes stored in that texture's metadata. For *cross* and *box* mode, the extents are calculated for purposes *default*, *proxy*, and *render*, at their earliest authored time. If the model has no textures, all six card faces are rendered using *model:drawModeColor*. If one or more textures are present, only axes with one or more textures assigned are drawn. For each axis, if both textures (positive and negative) are specified, they'll be used on the corresponding card faces; if only one texture is specified, it will be mapped to the opposite card face after being flipped on the texture's s-axis. Any card faces with invalid asset paths will be drawn with *model:drawModeColor*. Both *model:cardGeometry* and *model:drawModeColor* should be authored on the prim where the draw mode takes effect, since these attributes are not inherited. For *fromTexture* mode, only card faces with valid textures assigned are drawn. The geometry is generated by pulling the *worldtoscreen* attribute out of texture metadata. This is expected to be a 4x4 matrix mapping the model-space position of the card quad to the clip-space quad with corners (-1,-1,0) and (1,1,0). The card vertices are generated by transforming the clip-space corners by the inverse of *worldtoscreen*. Textures are mapped so that (s) and (t) map to (+x) and (+y) in clip space. If the metadata cannot be read in the right format, or the matrix can't be inverted, the card face is not drawn. All card faces are drawn and textured as single-sided. For any described attribute *Fallback* *Value* or *Allowed* *Values* below that are text/tokens, the actual token is published and defined in UsdGeomTokens. So to set an attribute to the value"rightHanded", use UsdGeomTokens->rightHanded as the value. """ result["ModelAPI"].GetExtentsHint.func_doc = """GetExtentsHint(extents, time) -> bool Retrieve the authored value (if any) of this model's"extentsHint". Persistent caching of bounds in USD is a potentially perilous endeavor, given that: - It is very easy to add overrides in new super-layers that invalidate the cached bounds, and no practical way to automatically detect when this happens - It is possible for references to be allowed to"float", so that asset updates can flow directly into cached scenes. Such changes in referenced scene description can also invalidate cached bounds in referencing layers. For these reasons, as a general rule, we only persistently cache leaf gprim extents in object space. However, even with cached gprim extents, computing bounds can be expensive. Since model-level bounds are so useful to many graphics applications, we make an exception, with some caveats. The"extentsHint"should be considered entirely optional (whereas gprim extent is not); if authored, it should contains the extents for various values of gprim purposes. The extents for different values of purpose are stored in a linear Vec3f array as pairs of GfVec3f values in the order specified by UsdGeomImageable::GetOrderedPurposeTokens() . This list is trimmed to only include non-empty extents. i.e., if a model has only default and render geoms, then it will only have 4 GfVec3f values in its extentsHint array. We do not skip over zero extents, so if a model has only default and proxy geom, we will author six GfVec3f 's, the middle two representing an zero extent for render geometry. A UsdGeomBBoxCache can be configured to first consult the cached extents when evaluating model roots, rather than descending into the models for the full computation. This is not the default behavior, and gives us a convenient way to validate that the cached extentsHint is still valid. ``true`` if a value was fetched; ``false`` if no value was authored, or on error. It is an error to make this query of a prim that is not a model root. UsdGeomImageable::GetPurposeAttr() , UsdGeomImageable::GetOrderedPurposeTokens() Parameters ---------- extents : Vec3fArray time : TimeCode """ result["ModelAPI"].SetExtentsHint.func_doc = """SetExtentsHint(extents, time) -> bool Authors the extentsHint array for this model at the given time. GetExtentsHint() Parameters ---------- extents : Vec3fArray time : TimeCode """ result["ModelAPI"].GetExtentsHintAttr.func_doc = """GetExtentsHintAttr() -> Attribute Returns the custom'extentsHint'attribute if it exits. """ result["ModelAPI"].ComputeExtentsHint.func_doc = """ComputeExtentsHint(bboxCache) -> Vec3fArray For the given model, compute the value for the extents hint with the given ``bboxCache`` . ``bboxCache`` should be setup with the appropriate time. After calling this function, the ``bboxCache`` may have it's included purposes changed. ``bboxCache`` should not be in use by any other thread while this method is using it in a thread. Parameters ---------- bboxCache : BBoxCache """ result["ModelAPI"].GetConstraintTarget.func_doc = """GetConstraintTarget(constraintName) -> ConstraintTarget Get the constraint target with the given name, ``constraintName`` . If the requested constraint target does not exist, then an invalid UsdConstraintTarget object is returned. Parameters ---------- constraintName : str """ result["ModelAPI"].CreateConstraintTarget.func_doc = """CreateConstraintTarget(constraintName) -> ConstraintTarget Creates a new constraint target with the given name, ``constraintName`` . If the constraint target already exists, then the existing target is returned. If it does not exist, a new one is created and returned. Parameters ---------- constraintName : str """ result["ModelAPI"].GetConstraintTargets.func_doc = """GetConstraintTargets() -> list[ConstraintTarget] Returns all the constraint targets belonging to the model. Only valid constraint targets in the"constraintTargets"namespace are returned by this method. """ result["ModelAPI"].__init__.func_doc = """__init__(prim) Construct a UsdGeomModelAPI on UsdPrim ``prim`` . Equivalent to UsdGeomModelAPI::Get (prim.GetStage(), prim.GetPath()) for a *valid* ``prim`` , but will not immediately throw an error for an invalid ``prim`` Parameters ---------- prim : Prim ---------------------------------------------------------------------- __init__(schemaObj) Construct a UsdGeomModelAPI on the prim held by ``schemaObj`` . Should be preferred over UsdGeomModelAPI (schemaObj.GetPrim()), as it preserves SchemaBase state. Parameters ---------- schemaObj : SchemaBase """ result["ModelAPI"].GetModelDrawModeAttr.func_doc = """GetModelDrawModeAttr() -> Attribute Alternate imaging mode; applied to this prim or child prims where *model:applyDrawMode* is true, or where the prim has kind *component*. See Draw Modes for mode descriptions. Declaration ``uniform token model:drawMode ="inherited"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values origin, bounds, cards, default, inherited """ result["ModelAPI"].CreateModelDrawModeAttr.func_doc = """CreateModelDrawModeAttr(defaultValue, writeSparsely) -> Attribute See GetModelDrawModeAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["ModelAPI"].GetModelApplyDrawModeAttr.func_doc = """GetModelApplyDrawModeAttr() -> Attribute If true, and the resolved value of *model:drawMode* is non-default, apply an alternate imaging mode to this prim. See Draw Modes. Declaration ``uniform bool model:applyDrawMode = 0`` C++ Type bool Usd Type SdfValueTypeNames->Bool Variability SdfVariabilityUniform """ result["ModelAPI"].CreateModelApplyDrawModeAttr.func_doc = """CreateModelApplyDrawModeAttr(defaultValue, writeSparsely) -> Attribute See GetModelApplyDrawModeAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["ModelAPI"].GetModelDrawModeColorAttr.func_doc = """GetModelDrawModeColorAttr() -> Attribute The base color of imaging prims inserted for alternate imaging modes. For *origin* and *bounds* modes, this controls line color; for *cards* mode, this controls the fallback quad color. Declaration ``uniform float3 model:drawModeColor = (0.18, 0.18, 0.18)`` C++ Type GfVec3f Usd Type SdfValueTypeNames->Float3 Variability SdfVariabilityUniform """ result["ModelAPI"].CreateModelDrawModeColorAttr.func_doc = """CreateModelDrawModeColorAttr(defaultValue, writeSparsely) -> Attribute See GetModelDrawModeColorAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["ModelAPI"].GetModelCardGeometryAttr.func_doc = """GetModelCardGeometryAttr() -> Attribute The geometry to generate for imaging prims inserted for *cards* imaging mode. See Cards Geometry for geometry descriptions. Declaration ``uniform token model:cardGeometry ="cross"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values cross, box, fromTexture """ result["ModelAPI"].CreateModelCardGeometryAttr.func_doc = """CreateModelCardGeometryAttr(defaultValue, writeSparsely) -> Attribute See GetModelCardGeometryAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["ModelAPI"].GetModelCardTextureXPosAttr.func_doc = """GetModelCardTextureXPosAttr() -> Attribute In *cards* imaging mode, the texture applied to the X+ quad. The texture axes (s,t) are mapped to model-space axes (-y, -z). Declaration ``asset model:cardTextureXPos`` C++ Type SdfAssetPath Usd Type SdfValueTypeNames->Asset """ result["ModelAPI"].CreateModelCardTextureXPosAttr.func_doc = """CreateModelCardTextureXPosAttr(defaultValue, writeSparsely) -> Attribute See GetModelCardTextureXPosAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["ModelAPI"].GetModelCardTextureYPosAttr.func_doc = """GetModelCardTextureYPosAttr() -> Attribute In *cards* imaging mode, the texture applied to the Y+ quad. The texture axes (s,t) are mapped to model-space axes (x, -z). Declaration ``asset model:cardTextureYPos`` C++ Type SdfAssetPath Usd Type SdfValueTypeNames->Asset """ result["ModelAPI"].CreateModelCardTextureYPosAttr.func_doc = """CreateModelCardTextureYPosAttr(defaultValue, writeSparsely) -> Attribute See GetModelCardTextureYPosAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["ModelAPI"].GetModelCardTextureZPosAttr.func_doc = """GetModelCardTextureZPosAttr() -> Attribute In *cards* imaging mode, the texture applied to the Z+ quad. The texture axes (s,t) are mapped to model-space axes (x, -y). Declaration ``asset model:cardTextureZPos`` C++ Type SdfAssetPath Usd Type SdfValueTypeNames->Asset """ result["ModelAPI"].CreateModelCardTextureZPosAttr.func_doc = """CreateModelCardTextureZPosAttr(defaultValue, writeSparsely) -> Attribute See GetModelCardTextureZPosAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["ModelAPI"].GetModelCardTextureXNegAttr.func_doc = """GetModelCardTextureXNegAttr() -> Attribute In *cards* imaging mode, the texture applied to the X- quad. The texture axes (s,t) are mapped to model-space axes (y, -z). Declaration ``asset model:cardTextureXNeg`` C++ Type SdfAssetPath Usd Type SdfValueTypeNames->Asset """ result["ModelAPI"].CreateModelCardTextureXNegAttr.func_doc = """CreateModelCardTextureXNegAttr(defaultValue, writeSparsely) -> Attribute See GetModelCardTextureXNegAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["ModelAPI"].GetModelCardTextureYNegAttr.func_doc = """GetModelCardTextureYNegAttr() -> Attribute In *cards* imaging mode, the texture applied to the Y- quad. The texture axes (s,t) are mapped to model-space axes (-x, -z). Declaration ``asset model:cardTextureYNeg`` C++ Type SdfAssetPath Usd Type SdfValueTypeNames->Asset """ result["ModelAPI"].CreateModelCardTextureYNegAttr.func_doc = """CreateModelCardTextureYNegAttr(defaultValue, writeSparsely) -> Attribute See GetModelCardTextureYNegAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["ModelAPI"].GetModelCardTextureZNegAttr.func_doc = """GetModelCardTextureZNegAttr() -> Attribute In *cards* imaging mode, the texture applied to the Z- quad. The texture axes (s,t) are mapped to model-space axes (-x, -y). Declaration ``asset model:cardTextureZNeg`` C++ Type SdfAssetPath Usd Type SdfValueTypeNames->Asset """ result["ModelAPI"].CreateModelCardTextureZNegAttr.func_doc = """CreateModelCardTextureZNegAttr(defaultValue, writeSparsely) -> Attribute See GetModelCardTextureZNegAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["ModelAPI"].ComputeModelDrawMode.func_doc = """ComputeModelDrawMode(parentDrawMode) -> str Calculate the effective model:drawMode of this prim. If the draw mode is authored on this prim, it's used. Otherwise, the fallback value is"inherited", which defers to the parent opinion. The first non-inherited opinion found walking from this prim towards the root is used. If the attribute isn't set on any ancestors, we return"default"(meaning, disable"drawMode"geometry). If this function is being called in a traversal context to compute the draw mode of an entire hierarchy of prims, it would be beneficial to cache and pass in the computed parent draw-mode via the ``parentDrawMode`` parameter. This avoids repeated upward traversal to look for ancestor opinions. When ``parentDrawMode`` is empty (or unspecified), this function does an upward traversal to find the closest ancestor with an authored model:drawMode. GetModelDrawModeAttr() Parameters ---------- parentDrawMode : str """ result["ModelAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ result["ModelAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> ModelAPI Return a UsdGeomModelAPI holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomModelAPI(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ result["ModelAPI"].CanApply.func_doc = """**classmethod** CanApply(prim, whyNot) -> bool Returns true if this **single-apply** API schema can be applied to the given ``prim`` . If this schema can not be a applied to the prim, this returns false and, if provided, populates ``whyNot`` with the reason it can not be applied. Note that if CanApply returns false, that does not necessarily imply that calling Apply will fail. Callers are expected to call CanApply before calling Apply if they want to ensure that it is valid to apply a schema. UsdPrim::GetAppliedSchemas() UsdPrim::HasAPI() UsdPrim::CanApplyAPI() UsdPrim::ApplyAPI() UsdPrim::RemoveAPI() Parameters ---------- prim : Prim whyNot : str """ result["ModelAPI"].Apply.func_doc = """**classmethod** Apply(prim) -> ModelAPI Applies this **single-apply** API schema to the given ``prim`` . This information is stored by adding"GeomModelAPI"to the token-valued, listOp metadata *apiSchemas* on the prim. A valid UsdGeomModelAPI object is returned upon success. An invalid (or empty) UsdGeomModelAPI object is returned upon failure. See UsdPrim::ApplyAPI() for conditions resulting in failure. UsdPrim::GetAppliedSchemas() UsdPrim::HasAPI() UsdPrim::CanApplyAPI() UsdPrim::ApplyAPI() UsdPrim::RemoveAPI() Parameters ---------- prim : Prim """ result["ModelAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type """ result["MotionAPI"].__doc__ = """ UsdGeomMotionAPI encodes data that can live on any prim that may affect computations involving: - computed motion for motion blur - sampling for motion blur The motion:blurScale attribute allows artists to scale the **amount** of motion blur to be rendered for parts of the scene without changing the recorded animation. See Effectively Applying motion:blurScale for use and implementation details. """ result["MotionAPI"].__init__.func_doc = """__init__(prim) Construct a UsdGeomMotionAPI on UsdPrim ``prim`` . Equivalent to UsdGeomMotionAPI::Get (prim.GetStage(), prim.GetPath()) for a *valid* ``prim`` , but will not immediately throw an error for an invalid ``prim`` Parameters ---------- prim : Prim ---------------------------------------------------------------------- __init__(schemaObj) Construct a UsdGeomMotionAPI on the prim held by ``schemaObj`` . Should be preferred over UsdGeomMotionAPI (schemaObj.GetPrim()), as it preserves SchemaBase state. Parameters ---------- schemaObj : SchemaBase """ result["MotionAPI"].GetMotionBlurScaleAttr.func_doc = """GetMotionBlurScaleAttr() -> Attribute BlurScale is an **inherited** float attribute that stipulates the rendered motion blur (as typically specified via UsdGeomCamera 's *shutter:open* and *shutter:close* properties) should be scaled for **all objects** at and beneath the prim in namespace on which the *motion:blurScale* value is specified. Without changing any other data in the scene, *blurScale* allows artists to"dial in"the amount of blur on a per-object basis. A *blurScale* value of zero removes all blur, a value of 0.5 reduces blur by half, and a value of 2.0 doubles the blur. The legal range for *blurScale* is [0, inf), although very high values may result in extremely expensive renders, and may exceed the capabilities of some renderers. Although renderers are free to implement this feature however they see fit, see Effectively Applying motion:blurScale for our guidance on implementing the feature universally and efficiently. ComputeMotionBlurScale() Declaration ``float motion:blurScale = 1`` C++ Type float Usd Type SdfValueTypeNames->Float """ result["MotionAPI"].CreateMotionBlurScaleAttr.func_doc = """CreateMotionBlurScaleAttr(defaultValue, writeSparsely) -> Attribute See GetMotionBlurScaleAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["MotionAPI"].GetVelocityScaleAttr.func_doc = """GetVelocityScaleAttr() -> Attribute Deprecated VelocityScale is an **inherited** float attribute that velocity-based schemas (e.g. PointBased, PointInstancer) can consume to compute interpolated positions and orientations by applying velocity and angularVelocity, which is required for interpolating between samples when topology is varying over time. Although these quantities are generally physically computed by a simulator, sometimes we require more or less motion-blur to achieve the desired look. VelocityScale allows artists to dial-in, as a post-sim correction, a scale factor to be applied to the velocity prior to computing interpolated positions from it. Declaration ``float motion:velocityScale = 1`` C++ Type float Usd Type SdfValueTypeNames->Float """ result["MotionAPI"].CreateVelocityScaleAttr.func_doc = """CreateVelocityScaleAttr(defaultValue, writeSparsely) -> Attribute See GetVelocityScaleAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["MotionAPI"].GetNonlinearSampleCountAttr.func_doc = """GetNonlinearSampleCountAttr() -> Attribute Determines the number of position or transformation samples created when motion is described by attributes contributing non-linear terms. To give an example, imagine an application (such as a renderer) consuming'points'and the USD document also contains'accelerations'for the same prim. Unless the application can consume these'accelerations'itself, an intermediate layer has to compute samples within the sampling interval for the point positions based on the value of'points','velocities'and'accelerations'. The number of these samples is given by'nonlinearSampleCount'. The samples are equally spaced within the sampling interval. Another example involves the PointInstancer where'nonlinearSampleCount'is relevant when'angularVelocities'or'accelerations'are authored. 'nonlinearSampleCount'is an **inherited** attribute, also see ComputeNonlinearSampleCount() Declaration ``int motion:nonlinearSampleCount = 3`` C++ Type int Usd Type SdfValueTypeNames->Int """ result["MotionAPI"].CreateNonlinearSampleCountAttr.func_doc = """CreateNonlinearSampleCountAttr(defaultValue, writeSparsely) -> Attribute See GetNonlinearSampleCountAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["MotionAPI"].ComputeVelocityScale.func_doc = """ComputeVelocityScale(time) -> float Deprecated Compute the inherited value of *velocityScale* at ``time`` , i.e. the authored value on the prim closest to this prim in namespace, resolved upwards through its ancestors in namespace. the inherited value, or 1.0 if neither the prim nor any of its ancestors possesses an authored value. this is a reference implementation that is not particularly efficient if evaluating over many prims, because it does not share inherited results. Parameters ---------- time : TimeCode """ result["MotionAPI"].ComputeNonlinearSampleCount.func_doc = """ComputeNonlinearSampleCount(time) -> int Compute the inherited value of *nonlinearSampleCount* at ``time`` , i.e. the authored value on the prim closest to this prim in namespace, resolved upwards through its ancestors in namespace. the inherited value, or 3 if neither the prim nor any of its ancestors possesses an authored value. this is a reference implementation that is not particularly efficient if evaluating over many prims, because it does not share inherited results. Parameters ---------- time : TimeCode """ result["MotionAPI"].ComputeMotionBlurScale.func_doc = """ComputeMotionBlurScale(time) -> float Compute the inherited value of *motion:blurScale* at ``time`` , i.e. the authored value on the prim closest to this prim in namespace, resolved upwards through its ancestors in namespace. the inherited value, or 1.0 if neither the prim nor any of its ancestors possesses an authored value. this is a reference implementation that is not particularly efficient if evaluating over many prims, because it does not share inherited results. Parameters ---------- time : TimeCode """ result["MotionAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ result["MotionAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> MotionAPI Return a UsdGeomMotionAPI holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomMotionAPI(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ result["MotionAPI"].CanApply.func_doc = """**classmethod** CanApply(prim, whyNot) -> bool Returns true if this **single-apply** API schema can be applied to the given ``prim`` . If this schema can not be a applied to the prim, this returns false and, if provided, populates ``whyNot`` with the reason it can not be applied. Note that if CanApply returns false, that does not necessarily imply that calling Apply will fail. Callers are expected to call CanApply before calling Apply if they want to ensure that it is valid to apply a schema. UsdPrim::GetAppliedSchemas() UsdPrim::HasAPI() UsdPrim::CanApplyAPI() UsdPrim::ApplyAPI() UsdPrim::RemoveAPI() Parameters ---------- prim : Prim whyNot : str """ result["MotionAPI"].Apply.func_doc = """**classmethod** Apply(prim) -> MotionAPI Applies this **single-apply** API schema to the given ``prim`` . This information is stored by adding"MotionAPI"to the token-valued, listOp metadata *apiSchemas* on the prim. A valid UsdGeomMotionAPI object is returned upon success. An invalid (or empty) UsdGeomMotionAPI object is returned upon failure. See UsdPrim::ApplyAPI() for conditions resulting in failure. UsdPrim::GetAppliedSchemas() UsdPrim::HasAPI() UsdPrim::CanApplyAPI() UsdPrim::ApplyAPI() UsdPrim::RemoveAPI() Parameters ---------- prim : Prim """ result["MotionAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type """ result["NurbsCurves"].__doc__ = """ This schema is analagous to NURBS Curves in packages like Maya and Houdini, often used for interchange of rigging and modeling curves. Unlike Maya, this curve spec supports batching of multiple curves into a single prim, widths, and normals in the schema. Additionally, we require'numSegments + 2 \\* degree + 1'knots (2 more than maya does). This is to be more consistent with RenderMan's NURBS patch specification. To express a periodic curve: - knot[0] = knot[1] - (knots[-2] - knots[-3]; - knot[-1] = knot[-2] + (knot[2] - knots[1]); To express a nonperiodic curve: - knot[0] = knot[1]; - knot[-1] = knot[-2]; In spite of these slight differences in the spec, curves generated in Maya should be preserved when roundtripping. *order* and *range*, when representing a batched NurbsCurve should be authored one value per curve. *knots* should be the concatentation of all batched curves. **NurbsCurve Form** **Form** is provided as an aid to interchange between modeling and animation applications so that they can robustly identify the intent with which the surface was modelled, and take measures (if they are able) to preserve the continuity/concidence constraints as the surface may be rigged or deformed. - An *open-form* NurbsCurve has no continuity constraints. - A *closed-form* NurbsCurve expects the first and last control points to overlap - A *periodic-form* NurbsCurve expects the first and last *order* - 1 control points to overlap. For any described attribute *Fallback* *Value* or *Allowed* *Values* below that are text/tokens, the actual token is published and defined in UsdGeomTokens. So to set an attribute to the value"rightHanded", use UsdGeomTokens->rightHanded as the value. """ result["NurbsCurves"].__init__.func_doc = """__init__(prim) Construct a UsdGeomNurbsCurves on UsdPrim ``prim`` . Equivalent to UsdGeomNurbsCurves::Get (prim.GetStage(), prim.GetPath()) for a *valid* ``prim`` , but will not immediately throw an error for an invalid ``prim`` Parameters ---------- prim : Prim ---------------------------------------------------------------------- __init__(schemaObj) Construct a UsdGeomNurbsCurves on the prim held by ``schemaObj`` . Should be preferred over UsdGeomNurbsCurves (schemaObj.GetPrim()), as it preserves SchemaBase state. Parameters ---------- schemaObj : SchemaBase """ result["NurbsCurves"].GetOrderAttr.func_doc = """GetOrderAttr() -> Attribute Order of the curve. Order must be positive and is equal to the degree of the polynomial basis to be evaluated, plus 1. Its value for the'i'th curve must be less than or equal to curveVertexCount[i] Declaration ``int[] order = []`` C++ Type VtArray<int> Usd Type SdfValueTypeNames->IntArray """ result["NurbsCurves"].CreateOrderAttr.func_doc = """CreateOrderAttr(defaultValue, writeSparsely) -> Attribute See GetOrderAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["NurbsCurves"].GetKnotsAttr.func_doc = """GetKnotsAttr() -> Attribute Knot vector providing curve parameterization. The length of the slice of the array for the ith curve must be ( curveVertexCount[i] + order[i] ), and its entries must take on monotonically increasing values. Declaration ``double[] knots`` C++ Type VtArray<double> Usd Type SdfValueTypeNames->DoubleArray """ result["NurbsCurves"].CreateKnotsAttr.func_doc = """CreateKnotsAttr(defaultValue, writeSparsely) -> Attribute See GetKnotsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["NurbsCurves"].GetRangesAttr.func_doc = """GetRangesAttr() -> Attribute Provides the minimum and maximum parametric values (as defined by knots) over which the curve is actually defined. The minimum must be less than the maximum, and greater than or equal to the value of the knots['i'th curve slice][order[i]-1]. The maxium must be less than or equal to the last element's value in knots['i'th curve slice]. Range maps to (vmin, vmax) in the RenderMan spec. Declaration ``double2[] ranges`` C++ Type VtArray<GfVec2d> Usd Type SdfValueTypeNames->Double2Array """ result["NurbsCurves"].CreateRangesAttr.func_doc = """CreateRangesAttr(defaultValue, writeSparsely) -> Attribute See GetRangesAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["NurbsCurves"].GetPointWeightsAttr.func_doc = """GetPointWeightsAttr() -> Attribute Optionally provides"w"components for each control point, thus must be the same length as the points attribute. If authored, the patch will be rational. If unauthored, the patch will be polynomial, i.e. weight for all points is 1.0. Some DCC's pre-weight the *points*, but in this schema, *points* are not pre-weighted. Declaration ``double[] pointWeights`` C++ Type VtArray<double> Usd Type SdfValueTypeNames->DoubleArray """ result["NurbsCurves"].CreatePointWeightsAttr.func_doc = """CreatePointWeightsAttr(defaultValue, writeSparsely) -> Attribute See GetPointWeightsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["NurbsCurves"].GetFormAttr.func_doc = """GetFormAttr() -> Attribute Interpret the control grid and knot vectors as representing an open, geometrically closed, or geometrically closed and C2 continuous curve. NurbsCurve Form Declaration ``uniform token form ="open"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values open, closed, periodic """ result["NurbsCurves"].CreateFormAttr.func_doc = """CreateFormAttr(defaultValue, writeSparsely) -> Attribute See GetFormAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["NurbsCurves"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ result["NurbsCurves"].Get.func_doc = """**classmethod** Get(stage, path) -> NurbsCurves Return a UsdGeomNurbsCurves holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomNurbsCurves(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ result["NurbsCurves"].Define.func_doc = """**classmethod** Define(stage, path) -> NurbsCurves Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ result["NurbsCurves"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type """ result["NurbsPatch"].__doc__ = """ Encodes a rational or polynomial non-uniform B-spline surface, with optional trim curves. The encoding mostly follows that of RiNuPatch and RiTrimCurve: https://renderman.pixar.com/resources/current/RenderMan/geometricPrimitives.html#rinupatch, with some minor renaming and coalescing for clarity. The layout of control vertices in the *points* attribute inherited from UsdGeomPointBased is row-major with U considered rows, and V columns. **NurbsPatch Form** The authored points, orders, knots, weights, and ranges are all that is required to render the nurbs patch. However, the only way to model closed surfaces with nurbs is to ensure that the first and last control points along the given axis are coincident. Similarly, to ensure the surface is not only closed but also C2 continuous, the last *order* - 1 control points must be (correspondingly) coincident with the first *order* - 1 control points, and also the spacing of the last corresponding knots must be the same as the first corresponding knots. **Form** is provided as an aid to interchange between modeling and animation applications so that they can robustly identify the intent with which the surface was modelled, and take measures (if they are able) to preserve the continuity/concidence constraints as the surface may be rigged or deformed. - An *open-form* NurbsPatch has no continuity constraints. - A *closed-form* NurbsPatch expects the first and last control points to overlap - A *periodic-form* NurbsPatch expects the first and last *order* - 1 control points to overlap. **Nurbs vs Subdivision Surfaces** Nurbs are an important modeling primitive in CAD/CAM tools and early computer graphics DCC's. Because they have a natural UV parameterization they easily support"trim curves", which allow smooth shapes to be carved out of the surface. However, the topology of the patch is always rectangular, and joining two nurbs patches together (especially when they have differing numbers of spans) is difficult to do smoothly. Also, nurbs are not supported by the Ptex texturing technology ( http://ptex.us). Neither of these limitations are shared by subdivision surfaces; therefore, although they do not subscribe to trim-curve-based shaping, subdivs are often considered a more flexible modeling primitive. For any described attribute *Fallback* *Value* or *Allowed* *Values* below that are text/tokens, the actual token is published and defined in UsdGeomTokens. So to set an attribute to the value"rightHanded", use UsdGeomTokens->rightHanded as the value. """ result["NurbsPatch"].__init__.func_doc = """__init__(prim) Construct a UsdGeomNurbsPatch on UsdPrim ``prim`` . Equivalent to UsdGeomNurbsPatch::Get (prim.GetStage(), prim.GetPath()) for a *valid* ``prim`` , but will not immediately throw an error for an invalid ``prim`` Parameters ---------- prim : Prim ---------------------------------------------------------------------- __init__(schemaObj) Construct a UsdGeomNurbsPatch on the prim held by ``schemaObj`` . Should be preferred over UsdGeomNurbsPatch (schemaObj.GetPrim()), as it preserves SchemaBase state. Parameters ---------- schemaObj : SchemaBase """ result["NurbsPatch"].GetUVertexCountAttr.func_doc = """GetUVertexCountAttr() -> Attribute Number of vertices in the U direction. Should be at least as large as uOrder. Declaration ``int uVertexCount`` C++ Type int Usd Type SdfValueTypeNames->Int """ result["NurbsPatch"].CreateUVertexCountAttr.func_doc = """CreateUVertexCountAttr(defaultValue, writeSparsely) -> Attribute See GetUVertexCountAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["NurbsPatch"].GetVVertexCountAttr.func_doc = """GetVVertexCountAttr() -> Attribute Number of vertices in the V direction. Should be at least as large as vOrder. Declaration ``int vVertexCount`` C++ Type int Usd Type SdfValueTypeNames->Int """ result["NurbsPatch"].CreateVVertexCountAttr.func_doc = """CreateVVertexCountAttr(defaultValue, writeSparsely) -> Attribute See GetVVertexCountAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["NurbsPatch"].GetUOrderAttr.func_doc = """GetUOrderAttr() -> Attribute Order in the U direction. Order must be positive and is equal to the degree of the polynomial basis to be evaluated, plus 1. Declaration ``int uOrder`` C++ Type int Usd Type SdfValueTypeNames->Int """ result["NurbsPatch"].CreateUOrderAttr.func_doc = """CreateUOrderAttr(defaultValue, writeSparsely) -> Attribute See GetUOrderAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["NurbsPatch"].GetVOrderAttr.func_doc = """GetVOrderAttr() -> Attribute Order in the V direction. Order must be positive and is equal to the degree of the polynomial basis to be evaluated, plus 1. Declaration ``int vOrder`` C++ Type int Usd Type SdfValueTypeNames->Int """ result["NurbsPatch"].CreateVOrderAttr.func_doc = """CreateVOrderAttr(defaultValue, writeSparsely) -> Attribute See GetVOrderAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["NurbsPatch"].GetUKnotsAttr.func_doc = """GetUKnotsAttr() -> Attribute Knot vector for U direction providing U parameterization. The length of this array must be ( uVertexCount + uOrder), and its entries must take on monotonically increasing values. Declaration ``double[] uKnots`` C++ Type VtArray<double> Usd Type SdfValueTypeNames->DoubleArray """ result["NurbsPatch"].CreateUKnotsAttr.func_doc = """CreateUKnotsAttr(defaultValue, writeSparsely) -> Attribute See GetUKnotsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["NurbsPatch"].GetVKnotsAttr.func_doc = """GetVKnotsAttr() -> Attribute Knot vector for V direction providing U parameterization. The length of this array must be ( vVertexCount + vOrder), and its entries must take on monotonically increasing values. Declaration ``double[] vKnots`` C++ Type VtArray<double> Usd Type SdfValueTypeNames->DoubleArray """ result["NurbsPatch"].CreateVKnotsAttr.func_doc = """CreateVKnotsAttr(defaultValue, writeSparsely) -> Attribute See GetVKnotsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["NurbsPatch"].GetUFormAttr.func_doc = """GetUFormAttr() -> Attribute Interpret the control grid and knot vectors as representing an open, geometrically closed, or geometrically closed and C2 continuous surface along the U dimension. NurbsPatch Form Declaration ``uniform token uForm ="open"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values open, closed, periodic """ result["NurbsPatch"].CreateUFormAttr.func_doc = """CreateUFormAttr(defaultValue, writeSparsely) -> Attribute See GetUFormAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["NurbsPatch"].GetVFormAttr.func_doc = """GetVFormAttr() -> Attribute Interpret the control grid and knot vectors as representing an open, geometrically closed, or geometrically closed and C2 continuous surface along the V dimension. NurbsPatch Form Declaration ``uniform token vForm ="open"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values open, closed, periodic """ result["NurbsPatch"].CreateVFormAttr.func_doc = """CreateVFormAttr(defaultValue, writeSparsely) -> Attribute See GetVFormAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["NurbsPatch"].GetURangeAttr.func_doc = """GetURangeAttr() -> Attribute Provides the minimum and maximum parametric values (as defined by uKnots) over which the surface is actually defined. The minimum must be less than the maximum, and greater than or equal to the value of uKnots[uOrder-1]. The maxium must be less than or equal to the last element's value in uKnots. Declaration ``double2 uRange`` C++ Type GfVec2d Usd Type SdfValueTypeNames->Double2 """ result["NurbsPatch"].CreateURangeAttr.func_doc = """CreateURangeAttr(defaultValue, writeSparsely) -> Attribute See GetURangeAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["NurbsPatch"].GetVRangeAttr.func_doc = """GetVRangeAttr() -> Attribute Provides the minimum and maximum parametric values (as defined by vKnots) over which the surface is actually defined. The minimum must be less than the maximum, and greater than or equal to the value of vKnots[vOrder-1]. The maxium must be less than or equal to the last element's value in vKnots. Declaration ``double2 vRange`` C++ Type GfVec2d Usd Type SdfValueTypeNames->Double2 """ result["NurbsPatch"].CreateVRangeAttr.func_doc = """CreateVRangeAttr(defaultValue, writeSparsely) -> Attribute See GetVRangeAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["NurbsPatch"].GetPointWeightsAttr.func_doc = """GetPointWeightsAttr() -> Attribute Optionally provides"w"components for each control point, thus must be the same length as the points attribute. If authored, the patch will be rational. If unauthored, the patch will be polynomial, i.e. weight for all points is 1.0. Some DCC's pre-weight the *points*, but in this schema, *points* are not pre-weighted. Declaration ``double[] pointWeights`` C++ Type VtArray<double> Usd Type SdfValueTypeNames->DoubleArray """ result["NurbsPatch"].CreatePointWeightsAttr.func_doc = """CreatePointWeightsAttr(defaultValue, writeSparsely) -> Attribute See GetPointWeightsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["NurbsPatch"].GetTrimCurveCountsAttr.func_doc = """GetTrimCurveCountsAttr() -> Attribute Each element specifies how many curves are present in each"loop"of the trimCurve, and the length of the array determines how many loops the trimCurve contains. The sum of all elements is the total nuber of curves in the trim, to which we will refer as *nCurves* in describing the other trim attributes. Declaration ``int[] trimCurve:counts`` C++ Type VtArray<int> Usd Type SdfValueTypeNames->IntArray """ result["NurbsPatch"].CreateTrimCurveCountsAttr.func_doc = """CreateTrimCurveCountsAttr(defaultValue, writeSparsely) -> Attribute See GetTrimCurveCountsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["NurbsPatch"].GetTrimCurveOrdersAttr.func_doc = """GetTrimCurveOrdersAttr() -> Attribute Flat list of orders for each of the *nCurves* curves. Declaration ``int[] trimCurve:orders`` C++ Type VtArray<int> Usd Type SdfValueTypeNames->IntArray """ result["NurbsPatch"].CreateTrimCurveOrdersAttr.func_doc = """CreateTrimCurveOrdersAttr(defaultValue, writeSparsely) -> Attribute See GetTrimCurveOrdersAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["NurbsPatch"].GetTrimCurveVertexCountsAttr.func_doc = """GetTrimCurveVertexCountsAttr() -> Attribute Flat list of number of vertices for each of the *nCurves* curves. Declaration ``int[] trimCurve:vertexCounts`` C++ Type VtArray<int> Usd Type SdfValueTypeNames->IntArray """ result["NurbsPatch"].CreateTrimCurveVertexCountsAttr.func_doc = """CreateTrimCurveVertexCountsAttr(defaultValue, writeSparsely) -> Attribute See GetTrimCurveVertexCountsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["NurbsPatch"].GetTrimCurveKnotsAttr.func_doc = """GetTrimCurveKnotsAttr() -> Attribute Flat list of parametric values for each of the *nCurves* curves. There will be as many knots as the sum over all elements of *vertexCounts* plus the sum over all elements of *orders*. Declaration ``double[] trimCurve:knots`` C++ Type VtArray<double> Usd Type SdfValueTypeNames->DoubleArray """ result["NurbsPatch"].CreateTrimCurveKnotsAttr.func_doc = """CreateTrimCurveKnotsAttr(defaultValue, writeSparsely) -> Attribute See GetTrimCurveKnotsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["NurbsPatch"].GetTrimCurveRangesAttr.func_doc = """GetTrimCurveRangesAttr() -> Attribute Flat list of minimum and maximum parametric values (as defined by *knots*) for each of the *nCurves* curves. Declaration ``double2[] trimCurve:ranges`` C++ Type VtArray<GfVec2d> Usd Type SdfValueTypeNames->Double2Array """ result["NurbsPatch"].CreateTrimCurveRangesAttr.func_doc = """CreateTrimCurveRangesAttr(defaultValue, writeSparsely) -> Attribute See GetTrimCurveRangesAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["NurbsPatch"].GetTrimCurvePointsAttr.func_doc = """GetTrimCurvePointsAttr() -> Attribute Flat list of homogeneous 2D points (u, v, w) that comprise the *nCurves* curves. The number of points should be equal to the um over all elements of *vertexCounts*. Declaration ``double3[] trimCurve:points`` C++ Type VtArray<GfVec3d> Usd Type SdfValueTypeNames->Double3Array """ result["NurbsPatch"].CreateTrimCurvePointsAttr.func_doc = """CreateTrimCurvePointsAttr(defaultValue, writeSparsely) -> Attribute See GetTrimCurvePointsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["NurbsPatch"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ result["NurbsPatch"].Get.func_doc = """**classmethod** Get(stage, path) -> NurbsPatch Return a UsdGeomNurbsPatch holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomNurbsPatch(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ result["NurbsPatch"].Define.func_doc = """**classmethod** Define(stage, path) -> NurbsPatch Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ result["NurbsPatch"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type """ result["Plane"].__doc__ = """ Defines a primitive plane, centered at the origin, and is defined by a cardinal axis, width, and length. The plane is double-sided by default. The axis of width and length are perpendicular to the plane's *axis*: axis width length X z-axis y-axis Y x-axis z-axis Z x-axis y-axis For any described attribute *Fallback* *Value* or *Allowed* *Values* below that are text/tokens, the actual token is published and defined in UsdGeomTokens. So to set an attribute to the value"rightHanded", use UsdGeomTokens->rightHanded as the value. """ result["Plane"].__init__.func_doc = """__init__(prim) Construct a UsdGeomPlane on UsdPrim ``prim`` . Equivalent to UsdGeomPlane::Get (prim.GetStage(), prim.GetPath()) for a *valid* ``prim`` , but will not immediately throw an error for an invalid ``prim`` Parameters ---------- prim : Prim ---------------------------------------------------------------------- __init__(schemaObj) Construct a UsdGeomPlane on the prim held by ``schemaObj`` . Should be preferred over UsdGeomPlane (schemaObj.GetPrim()), as it preserves SchemaBase state. Parameters ---------- schemaObj : SchemaBase """ result["Plane"].GetDoubleSidedAttr.func_doc = """GetDoubleSidedAttr() -> Attribute Planes are double-sided by default. Clients may also support single-sided planes. UsdGeomGprim::GetDoubleSidedAttr() Declaration ``uniform bool doubleSided = 1`` C++ Type bool Usd Type SdfValueTypeNames->Bool Variability SdfVariabilityUniform """ result["Plane"].CreateDoubleSidedAttr.func_doc = """CreateDoubleSidedAttr(defaultValue, writeSparsely) -> Attribute See GetDoubleSidedAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Plane"].GetWidthAttr.func_doc = """GetWidthAttr() -> Attribute The width of the plane, which aligns to the x-axis when *axis* is'Z'or'Y', or to the z-axis when *axis* is'X'. If you author *width* you must also author *extent*. UsdGeomGprim::GetExtentAttr() Declaration ``double width = 2`` C++ Type double Usd Type SdfValueTypeNames->Double """ result["Plane"].CreateWidthAttr.func_doc = """CreateWidthAttr(defaultValue, writeSparsely) -> Attribute See GetWidthAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Plane"].GetLengthAttr.func_doc = """GetLengthAttr() -> Attribute The length of the plane, which aligns to the y-axis when *axis* is'Z'or'X', or to the z-axis when *axis* is'Y'. If you author *length* you must also author *extent*. UsdGeomGprim::GetExtentAttr() Declaration ``double length = 2`` C++ Type double Usd Type SdfValueTypeNames->Double """ result["Plane"].CreateLengthAttr.func_doc = """CreateLengthAttr(defaultValue, writeSparsely) -> Attribute See GetLengthAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Plane"].GetAxisAttr.func_doc = """GetAxisAttr() -> Attribute The axis along which the surface of the plane is aligned. When set to'Z'the plane is in the xy-plane; when *axis* is'X'the plane is in the yz-plane, and when *axis* is'Y'the plane is in the xz-plane. UsdGeomGprim::GetAxisAttr(). Declaration ``uniform token axis ="Z"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values X, Y, Z """ result["Plane"].CreateAxisAttr.func_doc = """CreateAxisAttr(defaultValue, writeSparsely) -> Attribute See GetAxisAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Plane"].GetExtentAttr.func_doc = """GetExtentAttr() -> Attribute Extent is re-defined on Plane only to provide a fallback value. UsdGeomGprim::GetExtentAttr() . Declaration ``float3[] extent = [(-1, -1, 0), (1, 1, 0)]`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Float3Array """ result["Plane"].CreateExtentAttr.func_doc = """CreateExtentAttr(defaultValue, writeSparsely) -> Attribute See GetExtentAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Plane"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ result["Plane"].Get.func_doc = """**classmethod** Get(stage, path) -> Plane Return a UsdGeomPlane holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomPlane(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ result["Plane"].Define.func_doc = """**classmethod** Define(stage, path) -> Plane Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ result["Plane"].ComputeExtent.func_doc = """**classmethod** ComputeExtent(width, length, axis, extent) -> bool Compute the extent for the plane defined by the size of each dimension. true upon success, false if unable to calculate extent. On success, extent will contain an approximate axis-aligned bounding box of the plane defined by the size of each dimension. This function is to provide easy authoring of extent for usd authoring tools, hence it is static and acts outside a specific prim (as in attribute based methods). Parameters ---------- width : float length : float axis : str extent : Vec3fArray ---------------------------------------------------------------------- ComputeExtent(width, length, axis, transform, extent) -> bool This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Computes the extent as if the matrix ``transform`` was first applied. Parameters ---------- width : float length : float axis : str transform : Matrix4d extent : Vec3fArray """ result["Plane"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type """ result["PointBased"].__doc__ = """ Base class for all UsdGeomGprims that possess points, providing common attributes such as normals and velocities. """ result["PointBased"].__init__.func_doc = """__init__(prim) Construct a UsdGeomPointBased on UsdPrim ``prim`` . Equivalent to UsdGeomPointBased::Get (prim.GetStage(), prim.GetPath()) for a *valid* ``prim`` , but will not immediately throw an error for an invalid ``prim`` Parameters ---------- prim : Prim ---------------------------------------------------------------------- __init__(schemaObj) Construct a UsdGeomPointBased on the prim held by ``schemaObj`` . Should be preferred over UsdGeomPointBased (schemaObj.GetPrim()), as it preserves SchemaBase state. Parameters ---------- schemaObj : SchemaBase """ result["PointBased"].GetPointsAttr.func_doc = """GetPointsAttr() -> Attribute The primary geometry attribute for all PointBased primitives, describes points in (local) space. Declaration ``point3f[] points`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Point3fArray """ result["PointBased"].CreatePointsAttr.func_doc = """CreatePointsAttr(defaultValue, writeSparsely) -> Attribute See GetPointsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["PointBased"].GetVelocitiesAttr.func_doc = """GetVelocitiesAttr() -> Attribute If provided,'velocities'should be used by renderers to. compute positions between samples for the'points'attribute, rather than interpolating between neighboring'points'samples. This is the only reasonable means of computing motion blur for topologically varying PointBased primitives. It follows that the length of each'velocities'sample must match the length of the corresponding'points'sample. Velocity is measured in position units per second, as per most simulation software. To convert to position units per UsdTimeCode, divide by UsdStage::GetTimeCodesPerSecond() . See also Applying Timesampled Velocities to Geometry. Declaration ``vector3f[] velocities`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Vector3fArray """ result["PointBased"].CreateVelocitiesAttr.func_doc = """CreateVelocitiesAttr(defaultValue, writeSparsely) -> Attribute See GetVelocitiesAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["PointBased"].GetAccelerationsAttr.func_doc = """GetAccelerationsAttr() -> Attribute If provided,'accelerations'should be used with velocities to compute positions between samples for the'points'attribute rather than interpolating between neighboring'points'samples. Acceleration is measured in position units per second-squared. To convert to position units per squared UsdTimeCode, divide by the square of UsdStage::GetTimeCodesPerSecond() . Declaration ``vector3f[] accelerations`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Vector3fArray """ result["PointBased"].CreateAccelerationsAttr.func_doc = """CreateAccelerationsAttr(defaultValue, writeSparsely) -> Attribute See GetAccelerationsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["PointBased"].GetNormalsAttr.func_doc = """GetNormalsAttr() -> Attribute Provide an object-space orientation for individual points, which, depending on subclass, may define a surface, curve, or free points. Note that'normals'should not be authored on any Mesh that is subdivided, since the subdivision algorithm will define its own normals.'normals'is not a generic primvar, but the number of elements in this attribute will be determined by its'interpolation'. See SetNormalsInterpolation() . If'normals'and'primvars:normals'are both specified, the latter has precedence. Declaration ``normal3f[] normals`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Normal3fArray """ result["PointBased"].CreateNormalsAttr.func_doc = """CreateNormalsAttr(defaultValue, writeSparsely) -> Attribute See GetNormalsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["PointBased"].GetNormalsInterpolation.func_doc = """GetNormalsInterpolation() -> str Get the interpolation for the *normals* attribute. Although'normals'is not classified as a generic UsdGeomPrimvar (and will not be included in the results of UsdGeomPrimvarsAPI::GetPrimvars() ) it does require an interpolation specification. The fallback interpolation, if left unspecified, is UsdGeomTokens->vertex, which will generally produce smooth shading on a polygonal mesh. To achieve partial or fully faceted shading of a polygonal mesh with normals, one should use UsdGeomTokens->faceVarying or UsdGeomTokens->uniform interpolation. """ result["PointBased"].SetNormalsInterpolation.func_doc = """SetNormalsInterpolation(interpolation) -> bool Set the interpolation for the *normals* attribute. true upon success, false if ``interpolation`` is not a legal value as defined by UsdGeomPrimvar::IsValidInterpolation() , or if there was a problem setting the value. No attempt is made to validate that the normals attr's value contains the right number of elements to match its interpolation to its prim's topology. GetNormalsInterpolation() Parameters ---------- interpolation : str """ result["PointBased"].ComputePointsAtTime.func_doc = """**classmethod** ComputePointsAtTime(points, time, baseTime) -> bool Compute points given the positions, velocities and accelerations at ``time`` . This will return ``false`` and leave ``points`` untouched if: - ``points`` is None - one of ``time`` and ``baseTime`` is numeric and the other is UsdTimeCode::Default() (they must either both be numeric or both be default) - there is no authored points attribute If there is no error, we will return ``true`` and ``points`` will contain the computed points. points \\- the out parameter for the new points. Its size will depend on the authored data. time \\- UsdTimeCode at which we want to evaluate the transforms baseTime \\- required for correct interpolation between samples when *velocities* or *accelerations* are present. If there are samples for *positions* and *velocities* at t1 and t2, normal value resolution would attempt to interpolate between the two samples, and if they could not be interpolated because they differ in size (common in cases where velocity is authored), will choose the sample at t1. When sampling for the purposes of motion-blur, for example, it is common, when rendering the frame at t2, to sample at [ t2-shutter/2, t2+shutter/2 ] for a shutter interval of *shutter*. The first sample falls between t1 and t2, but we must sample at t2 and apply velocity-based interpolation based on those samples to get a correct result. In such scenarios, one should provide a ``baseTime`` of t2 when querying *both* samples. If your application does not care about off-sample interpolation, it can supply the same value for ``baseTime`` that it does for ``time`` . When ``baseTime`` is less than or equal to ``time`` , we will choose the lower bracketing timeSample. Parameters ---------- points : VtArray[Vec3f] time : TimeCode baseTime : TimeCode ---------------------------------------------------------------------- ComputePointsAtTime(points, stage, time, positions, velocities, velocitiesSampleTime, accelerations, velocityScale) -> bool This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Perform the point computation. This does the same computation as the non-static ComputePointsAtTime method, but takes all data as parameters rather than accessing authored data. points \\- the out parameter for the computed points. Its size will depend on the given data. stage \\- the UsdStage time \\- time at which we want to evaluate the transforms positions \\- array containing all current points. velocities \\- array containing all velocities. This array must be either the same size as ``positions`` or empty. If it is empty, points are computed as if all velocities were zero in all dimensions. velocitiesSampleTime \\- time at which the samples from ``velocities`` were taken. accelerations \\- array containing all accelerations. This array must be either the same size as ``positions`` or empty. If it is empty, points are computed as if all accelerations were zero in all dimensions. velocityScale \\- Deprecated Parameters ---------- points : VtArray[Vec3f] stage : UsdStageWeak time : TimeCode positions : Vec3fArray velocities : Vec3fArray velocitiesSampleTime : TimeCode accelerations : Vec3fArray velocityScale : float """ result["PointBased"].ComputePointsAtTimes.func_doc = """ComputePointsAtTimes(pointsArray, times, baseTime) -> bool Compute points as in ComputePointsAtTime, but using multiple sample times. An array of vector arrays is returned where each vector array contains the points for the corresponding time in ``times`` . times \\- A vector containing the UsdTimeCodes at which we want to sample. Parameters ---------- pointsArray : list[VtArray[Vec3f]] times : list[TimeCode] baseTime : TimeCode """ result["PointBased"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ result["PointBased"].Get.func_doc = """**classmethod** Get(stage, path) -> PointBased Return a UsdGeomPointBased holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomPointBased(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ result["PointBased"].ComputeExtent.func_doc = """**classmethod** ComputeExtent(points, extent) -> bool Compute the extent for the point cloud defined by points. true on success, false if extents was unable to be calculated. On success, extent will contain the axis-aligned bounding box of the point cloud defined by points. This function is to provide easy authoring of extent for usd authoring tools, hence it is static and acts outside a specific prim (as in attribute based methods). Parameters ---------- points : Vec3fArray extent : Vec3fArray ---------------------------------------------------------------------- ComputeExtent(points, transform, extent) -> bool This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Computes the extent as if the matrix ``transform`` was first applied. Parameters ---------- points : Vec3fArray transform : Matrix4d extent : Vec3fArray """ result["PointBased"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type """ result["PointInstancer"].__doc__ = """ Encodes vectorized instancing of multiple, potentially animated, prototypes (object/instance masters), which can be arbitrary prims/subtrees on a UsdStage. PointInstancer is a"multi instancer", as it allows multiple prototypes to be scattered among its"points". We use a UsdRelationship *prototypes* to identify and order all of the possible prototypes, by targeting the root prim of each prototype. The ordering imparted by relationships associates a zero-based integer with each prototype, and it is these integers we use to identify the prototype of each instance, compactly, and allowing prototypes to be swapped out without needing to reauthor all of the per-instance data. The PointInstancer schema is designed to scale to billions of instances, which motivates the choice to split the per-instance transformation into position, (quaternion) orientation, and scales, rather than a 4x4 matrix per-instance. In addition to requiring fewer bytes even if all elements are authored (32 bytes vs 64 for a single- precision 4x4 matrix), we can also be selective about which attributes need to animate over time, for substantial data reduction in many cases. Note that PointInstancer is *not* a Gprim, since it is not a graphical primitive by any stretch of the imagination. It *is*, however, Boundable, since we will sometimes want to treat the entire PointInstancer similarly to a procedural, from the perspective of inclusion or framing. Varying Instance Identity over Time =================================== PointInstancers originating from simulations often have the characteristic that points/instances are"born", move around for some time period, and then die (or leave the area of interest). In such cases, billions of instances may be birthed over time, while at any *specific* time, only a much smaller number are actually alive. To encode this situation efficiently, the simulator may re-use indices in the instance arrays, when a particle dies, its index will be taken over by a new particle that may be birthed in a much different location. This presents challenges both for identity-tracking, and for motion-blur. We facilitate identity tracking by providing an optional, animatable *ids* attribute, that specifies the 64 bit integer ID of the particle at each index, at each point in time. If the simulator keeps monotonically increasing a particle-count each time a new particle is birthed, it will serve perfectly as particle *ids*. We facilitate motion blur for varying-topology particle streams by optionally allowing per-instance *velocities* and *angularVelocities* to be authored. If instance transforms are requested at a time between samples and either of the velocity attributes is authored, then we will not attempt to interpolate samples of *positions* or *orientations*. If not authored, and the bracketing samples have the same length, then we will interpolate. Computing an Instance Transform =============================== Each instance's transformation is a combination of the SRT affine transform described by its scale, orientation, and position, applied *after* (i.e. less locally) than the transformation computed at the root of the prototype it is instancing. In other words, to put an instance of a PointInstancer into the space of the PointInstancer's parent prim: - Apply (most locally) the authored transformation for *prototypes[protoIndices[i]]* - If *scales* is authored, next apply the scaling matrix from *scales[i]* - If *orientations* is authored: **if *angularVelocities* is authored**, first multiply *orientations[i]* by the unit quaternion derived by scaling *angularVelocities[i]* by the time differential from the left-bracketing timeSample for *orientation* to the requested evaluation time *t*, storing the result in *R*, **else** assign *R* directly from *orientations[i]*. Apply the rotation matrix derived from *R*. - Apply the translation derived from *positions[i]*. If *velocities* is authored, apply the translation deriving from *velocities[i]* scaled by the time differential from the left- bracketing timeSample for *positions* to the requested evaluation time *t*. - Least locally, apply the transformation authored on the PointInstancer prim itself (or the UsdGeomImageable::ComputeLocalToWorldTransform() of the PointInstancer to put the instance directly into world space) If neither *velocities* nor *angularVelocities* are authored, we fallback to standard position and orientation computation logic (using linear interpolation between timeSamples) as described by Applying Timesampled Velocities to Geometry. **Scaling Velocities for Interpolation** When computing time-differentials by which to apply velocity or angularVelocity to positions or orientations, we must scale by ( 1.0 / UsdStage::GetTimeCodesPerSecond() ), because velocities are recorded in units/second, while we are interpolating in UsdTimeCode ordinates. We provide both high and low-level API's for dealing with the transformation as a matrix, both will compute the instance matrices using multiple threads; the low-level API allows the client to cache unvarying inputs so that they need not be read duplicately when computing over time. See also Applying Timesampled Velocities to Geometry. Primvars on PointInstancer ========================== Primvars authored on a PointInstancer prim should always be applied to each instance with *constant* interpolation at the root of the instance. When you are authoring primvars on a PointInstancer, think about it as if you were authoring them on a point-cloud (e.g. a UsdGeomPoints gprim). The same interpolation rules for points apply here, substituting"instance"for"point". In other words, the (constant) value extracted for each instance from the authored primvar value depends on the authored *interpolation* and *elementSize* of the primvar, as follows: - **constant** or **uniform** : the entire authored value of the primvar should be applied exactly to each instance. - **varying**, **vertex**, or **faceVarying** : the first *elementSize* elements of the authored primvar array should be assigned to instance zero, the second *elementSize* elements should be assigned to instance one, and so forth. Masking Instances:"Deactivating"and Invising ============================================ Often a PointInstancer is created"upstream"in a graphics pipeline, and the needs of"downstream"clients necessitate eliminating some of the instances from further consideration. Accomplishing this pruning by re-authoring all of the per-instance attributes is not very attractive, since it may mean destructively editing a large quantity of data. We therefore provide means of"masking"instances by ID, such that the instance data is unmolested, but per-instance transform and primvar data can be retrieved with the no-longer-desired instances eliminated from the (smaller) arrays. PointInstancer allows two independent means of masking instances by ID, each with different features that meet the needs of various clients in a pipeline. Both pruning features'lists of ID's are combined to produce the mask returned by ComputeMaskAtTime() . If a PointInstancer has no authored *ids* attribute, the masking features will still be available, with the integers specifying element position in the *protoIndices* array rather than ID. The first masking feature encodes a list of IDs in a list-editable metadatum called *inactiveIds*, which, although it does not have any similar impact to stage population as prim activation, it shares with that feature that its application is uniform over all time. Because it is list-editable, we can *sparsely* add and remove instances from it in many layers. This sparse application pattern makes *inactiveIds* a good choice when further downstream clients may need to reverse masking decisions made upstream, in a manner that is robust to many kinds of future changes to the upstream data. See ActivateId() , ActivateIds() , DeactivateId() , DeactivateIds() , ActivateAllIds() The second masking feature encodes a list of IDs in a time-varying Int64Array-valued UsdAttribute called *invisibleIds*, since it shares with Imageable visibility the ability to animate object visibility. Unlike *inactiveIds*, overriding a set of opinions for *invisibleIds* is not at all straightforward, because one will, in general need to reauthor (in the overriding layer) **all** timeSamples for the attribute just to change one Id's visibility state, so it cannot be authored sparsely. But it can be a very useful tool for situations like encoding pre-computed camera-frustum culling of geometry when either or both of the instances or the camera is animated. See VisId() , VisIds() , InvisId() , InvisIds() , VisAllIds() Processing and Not Processing Prototypes ======================================== Any prim in the scenegraph can be targeted as a prototype by the *prototypes* relationship. We do not, however, provide a specific mechanism for identifying prototypes as geometry that should not be drawn (or processed) in their own, local spaces in the scenegraph. We encourage organizing all prototypes as children of the PointInstancer prim that consumes them, and pruning"raw"processing and drawing traversals when they encounter a PointInstancer prim; this is what the UsdGeomBBoxCache and UsdImaging engines do. There *is* a pattern one can deploy for organizing the prototypes such that they will automatically be skipped by basic UsdPrim::GetChildren() or UsdPrimRange traversals. Usd prims each have a specifier of"def","over", or"class". The default traversals skip over prims that are"pure overs"or classes. So to protect prototypes from all generic traversals and processing, place them under a prim that is just an"over". For example, .. code-block:: text 01 def PointInstancer "Crowd_Mid" 02 { 03 rel prototypes = [ </Crowd_Mid/Prototypes/MaleThin_Business>, </Crowd_Mid/Prototypes/MaleThin_Casual> ] 04 05 over "Prototypes" 06 { 07 def "MaleThin_Business" ( 08 references = [@MaleGroupA/usd/MaleGroupA.usd@</MaleGroupA>] 09 variants = { 10 string modelingVariant = "Thin" 11 string costumeVariant = "BusinessAttire" 12 } 13 ) 14 { \\.\\.\\. } 15 16 def "MaleThin_Casual" 17 \\.\\.\\. 18 } 19 } """ result["PointInstancer"].ActivateId.func_doc = """ActivateId(id) -> bool Ensure that the instance identified by ``id`` is active over all time. This activation is encoded sparsely, affecting no other instances. This does not guarantee that the instance will be rendered, because it may still be"invisible"due to ``id`` being present in the *invisibleIds* attribute (see VisId() , InvisId() ) Parameters ---------- id : int """ result["PointInstancer"].ActivateIds.func_doc = """ActivateIds(ids) -> bool Ensure that the instances identified by ``ids`` are active over all time. This activation is encoded sparsely, affecting no other instances. This does not guarantee that the instances will be rendered, because each may still be"invisible"due to its presence in the *invisibleIds* attribute (see VisId() , InvisId() ) Parameters ---------- ids : Int64Array """ result["PointInstancer"].ActivateAllIds.func_doc = """ActivateAllIds() -> bool Ensure that all instances are active over all time. This does not guarantee that the instances will be rendered, because each may still be"invisible"due to its presence in the *invisibleIds* attribute (see VisId() , InvisId() ) """ result["PointInstancer"].DeactivateId.func_doc = """DeactivateId(id) -> bool Ensure that the instance identified by ``id`` is inactive over all time. This deactivation is encoded sparsely, affecting no other instances. A deactivated instance is guaranteed not to render if the renderer honors masking. Parameters ---------- id : int """ result["PointInstancer"].DeactivateIds.func_doc = """DeactivateIds(ids) -> bool Ensure that the instances identified by ``ids`` are inactive over all time. This deactivation is encoded sparsely, affecting no other instances. A deactivated instance is guaranteed not to render if the renderer honors masking. Parameters ---------- ids : Int64Array """ result["PointInstancer"].VisId.func_doc = """VisId(id, time) -> bool Ensure that the instance identified by ``id`` is visible at ``time`` . This will cause *invisibleIds* to first be broken down (keyed) at ``time`` , causing all animation in weaker layers that the current UsdEditTarget to be overridden. Has no effect on any timeSamples other than the one at ``time`` . If the *invisibleIds* attribute is not authored or is blocked, this operation is a no-op. This does not guarantee that the instance will be rendered, because it may still be"inactive"due to ``id`` being present in the *inactivevIds* metadata (see ActivateId() , DeactivateId() ) Parameters ---------- id : int time : TimeCode """ result["PointInstancer"].VisIds.func_doc = """VisIds(ids, time) -> bool Ensure that the instances identified by ``ids`` are visible at ``time`` . This will cause *invisibleIds* to first be broken down (keyed) at ``time`` , causing all animation in weaker layers that the current UsdEditTarget to be overridden. Has no effect on any timeSamples other than the one at ``time`` . If the *invisibleIds* attribute is not authored or is blocked, this operation is a no-op. This does not guarantee that the instances will be rendered, because each may still be"inactive"due to ``id`` being present in the *inactivevIds* metadata (see ActivateId() , DeactivateId() ) Parameters ---------- ids : Int64Array time : TimeCode """ result["PointInstancer"].VisAllIds.func_doc = """VisAllIds(time) -> bool Ensure that all instances are visible at ``time`` . Operates by authoring an empty array at ``time`` . This does not guarantee that the instances will be rendered, because each may still be"inactive"due to its id being present in the *inactivevIds* metadata (see ActivateId() , DeactivateId() ) Parameters ---------- time : TimeCode """ result["PointInstancer"].InvisId.func_doc = """InvisId(id, time) -> bool Ensure that the instance identified by ``id`` is invisible at ``time`` . This will cause *invisibleIds* to first be broken down (keyed) at ``time`` , causing all animation in weaker layers that the current UsdEditTarget to be overridden. Has no effect on any timeSamples other than the one at ``time`` . An invised instance is guaranteed not to render if the renderer honors masking. Parameters ---------- id : int time : TimeCode """ result["PointInstancer"].InvisIds.func_doc = """InvisIds(ids, time) -> bool Ensure that the instances identified by ``ids`` are invisible at ``time`` . This will cause *invisibleIds* to first be broken down (keyed) at ``time`` , causing all animation in weaker layers that the current UsdEditTarget to be overridden. Has no effect on any timeSamples other than the one at ``time`` . An invised instance is guaranteed not to render if the renderer honors masking. Parameters ---------- ids : Int64Array time : TimeCode """ result["PointInstancer"].ComputeMaskAtTime.func_doc = """ComputeMaskAtTime(time, ids) -> list[bool] Computes a presence mask to be applied to per-instance data arrays based on authored *inactiveIds*, *invisibleIds*, and *ids*. If no *ids* attribute has been authored, then the values in *inactiveIds* and *invisibleIds* will be interpreted directly as indices of *protoIndices*. If ``ids`` is non-None, it is assumed to be the id-mapping to apply, and must match the length of *protoIndices* at ``time`` . If None, we will call GetIdsAttr() .Get(time) If all"live"instances at UsdTimeCode ``time`` pass the mask, we will return an **empty** mask so that clients can trivially recognize the common"no masking"case. The returned mask can be used with ApplyMaskToArray() , and will contain a ``true`` value for every element that should survive. Parameters ---------- time : TimeCode ids : Int64Array """ result["PointInstancer"].ProtoXformInclusion.__doc__ = """ Encodes whether to include each prototype's root prim's transformation as the most-local component of computed instance transforms. """ result["PointInstancer"].MaskApplication.__doc__ = """ Encodes whether to evaluate and apply the PointInstancer's mask to computed results. ComputeMaskAtTime() """ result["PointInstancer"].__init__.func_doc = """__init__(prim) Construct a UsdGeomPointInstancer on UsdPrim ``prim`` . Equivalent to UsdGeomPointInstancer::Get (prim.GetStage(), prim.GetPath()) for a *valid* ``prim`` , but will not immediately throw an error for an invalid ``prim`` Parameters ---------- prim : Prim ---------------------------------------------------------------------- __init__(schemaObj) Construct a UsdGeomPointInstancer on the prim held by ``schemaObj`` . Should be preferred over UsdGeomPointInstancer (schemaObj.GetPrim()), as it preserves SchemaBase state. Parameters ---------- schemaObj : SchemaBase """ result["PointInstancer"].GetProtoIndicesAttr.func_doc = """GetProtoIndicesAttr() -> Attribute **Required property**. Per-instance index into *prototypes* relationship that identifies what geometry should be drawn for each instance. **Topology attribute** - can be animated, but at a potential performance impact for streaming. Declaration ``int[] protoIndices`` C++ Type VtArray<int> Usd Type SdfValueTypeNames->IntArray """ result["PointInstancer"].CreateProtoIndicesAttr.func_doc = """CreateProtoIndicesAttr(defaultValue, writeSparsely) -> Attribute See GetProtoIndicesAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["PointInstancer"].GetIdsAttr.func_doc = """GetIdsAttr() -> Attribute Ids are optional; if authored, the ids array should be the same length as the *protoIndices* array, specifying (at each timeSample if instance identities are changing) the id of each instance. The type is signed intentionally, so that clients can encode some binary state on Id'd instances without adding a separate primvar. See also Varying Instance Identity over Time Declaration ``int64[] ids`` C++ Type VtArray<int64_t> Usd Type SdfValueTypeNames->Int64Array """ result["PointInstancer"].CreateIdsAttr.func_doc = """CreateIdsAttr(defaultValue, writeSparsely) -> Attribute See GetIdsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["PointInstancer"].GetPositionsAttr.func_doc = """GetPositionsAttr() -> Attribute **Required property**. Per-instance position. See also Computing an Instance Transform. Declaration ``point3f[] positions`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Point3fArray """ result["PointInstancer"].CreatePositionsAttr.func_doc = """CreatePositionsAttr(defaultValue, writeSparsely) -> Attribute See GetPositionsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["PointInstancer"].GetOrientationsAttr.func_doc = """GetOrientationsAttr() -> Attribute If authored, per-instance orientation of each instance about its prototype's origin, represented as a unit length quaternion, which allows us to encode it with sufficient precision in a compact GfQuath. It is client's responsibility to ensure that authored quaternions are unit length; the convenience API below for authoring orientations from rotation matrices will ensure that quaternions are unit length, though it will not make any attempt to select the"better (for interpolationwith respect to neighboring samples)"of the two possible quaternions that encode the rotation. See also Computing an Instance Transform. Declaration ``quath[] orientations`` C++ Type VtArray<GfQuath> Usd Type SdfValueTypeNames->QuathArray """ result["PointInstancer"].CreateOrientationsAttr.func_doc = """CreateOrientationsAttr(defaultValue, writeSparsely) -> Attribute See GetOrientationsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["PointInstancer"].GetScalesAttr.func_doc = """GetScalesAttr() -> Attribute If authored, per-instance scale to be applied to each instance, before any rotation is applied. See also Computing an Instance Transform. Declaration ``float3[] scales`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Float3Array """ result["PointInstancer"].CreateScalesAttr.func_doc = """CreateScalesAttr(defaultValue, writeSparsely) -> Attribute See GetScalesAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["PointInstancer"].GetVelocitiesAttr.func_doc = """GetVelocitiesAttr() -> Attribute If provided, per-instance'velocities'will be used to compute positions between samples for the'positions'attribute, rather than interpolating between neighboring'positions'samples. Velocities should be considered mandatory if both *protoIndices* and *positions* are animated. Velocity is measured in position units per second, as per most simulation software. To convert to position units per UsdTimeCode, divide by UsdStage::GetTimeCodesPerSecond() . See also Computing an Instance Transform, Applying Timesampled Velocities to Geometry. Declaration ``vector3f[] velocities`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Vector3fArray """ result["PointInstancer"].CreateVelocitiesAttr.func_doc = """CreateVelocitiesAttr(defaultValue, writeSparsely) -> Attribute See GetVelocitiesAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["PointInstancer"].GetAccelerationsAttr.func_doc = """GetAccelerationsAttr() -> Attribute If authored, per-instance'accelerations'will be used with velocities to compute positions between samples for the'positions'attribute rather than interpolating between neighboring'positions'samples. Acceleration is measured in position units per second-squared. To convert to position units per squared UsdTimeCode, divide by the square of UsdStage::GetTimeCodesPerSecond() . Declaration ``vector3f[] accelerations`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Vector3fArray """ result["PointInstancer"].CreateAccelerationsAttr.func_doc = """CreateAccelerationsAttr(defaultValue, writeSparsely) -> Attribute See GetAccelerationsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["PointInstancer"].GetAngularVelocitiesAttr.func_doc = """GetAngularVelocitiesAttr() -> Attribute If authored, per-instance angular velocity vector to be used for interoplating orientations. Angular velocities should be considered mandatory if both *protoIndices* and *orientations* are animated. Angular velocity is measured in **degrees** per second. To convert to degrees per UsdTimeCode, divide by UsdStage::GetTimeCodesPerSecond() . See also Computing an Instance Transform. Declaration ``vector3f[] angularVelocities`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Vector3fArray """ result["PointInstancer"].CreateAngularVelocitiesAttr.func_doc = """CreateAngularVelocitiesAttr(defaultValue, writeSparsely) -> Attribute See GetAngularVelocitiesAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["PointInstancer"].GetInvisibleIdsAttr.func_doc = """GetInvisibleIdsAttr() -> Attribute A list of id's to make invisible at the evaluation time. See invisibleIds: Animatable Masking. Declaration ``int64[] invisibleIds = []`` C++ Type VtArray<int64_t> Usd Type SdfValueTypeNames->Int64Array """ result["PointInstancer"].CreateInvisibleIdsAttr.func_doc = """CreateInvisibleIdsAttr(defaultValue, writeSparsely) -> Attribute See GetInvisibleIdsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["PointInstancer"].GetPrototypesRel.func_doc = """GetPrototypesRel() -> Relationship **Required property**. Orders and targets the prototype root prims, which can be located anywhere in the scenegraph that is convenient, although we promote organizing prototypes as children of the PointInstancer. The position of a prototype in this relationship defines the value an instance would specify in the *protoIndices* attribute to instance that prototype. Since relationships are uniform, this property cannot be animated. """ result["PointInstancer"].CreatePrototypesRel.func_doc = """CreatePrototypesRel() -> Relationship See GetPrototypesRel() , and also Create vs Get Property Methods for when to use Get vs Create. """ result["PointInstancer"].ComputeInstanceTransformsAtTime.func_doc = """**classmethod** ComputeInstanceTransformsAtTime(xforms, time, baseTime, doProtoXforms, applyMask) -> bool Compute the per-instance,"PointInstancer relative"transforms given the positions, scales, orientations, velocities and angularVelocities at ``time`` , as described in Computing an Instance Transform. This will return ``false`` and leave ``xforms`` untouched if: - ``xforms`` is None - one of ``time`` and ``baseTime`` is numeric and the other is UsdTimeCode::Default() (they must either both be numeric or both be default) - there is no authored *protoIndices* attribute or *positions* attribute - the size of any of the per-instance attributes does not match the size of *protoIndices* - ``doProtoXforms`` is ``IncludeProtoXform`` but an index value in *protoIndices* is outside the range [0, prototypes.size()) - ``applyMask`` is ``ApplyMask`` and a mask is set but the size of the mask does not match the size of *protoIndices*. If there is no error, we will return ``true`` and ``xforms`` will contain the computed transformations. xforms \\- the out parameter for the transformations. Its size will depend on the authored data and ``applyMask`` time \\- UsdTimeCode at which we want to evaluate the transforms baseTime \\- required for correct interpolation between samples when *velocities* or *angularVelocities* are present. If there are samples for *positions* and *velocities* at t1 and t2, normal value resolution would attempt to interpolate between the two samples, and if they could not be interpolated because they differ in size (common in cases where velocity is authored), will choose the sample at t1. When sampling for the purposes of motion-blur, for example, it is common, when rendering the frame at t2, to sample at [ t2-shutter/2, t2+shutter/2 ] for a shutter interval of *shutter*. The first sample falls between t1 and t2, but we must sample at t2 and apply velocity- based interpolation based on those samples to get a correct result. In such scenarios, one should provide a ``baseTime`` of t2 when querying *both* samples. If your application does not care about off-sample interpolation, it can supply the same value for ``baseTime`` that it does for ``time`` . When ``baseTime`` is less than or equal to ``time`` , we will choose the lower bracketing timeSample. Selecting sample times with respect to baseTime will be performed independently for positions and orientations. doProtoXforms \\- specifies whether to include the root transformation of each instance's prototype in the instance's transform. Default is to include it, but some clients may want to apply the proto transform as part of the prototype itself, so they can specify ``ExcludeProtoXform`` instead. applyMask \\- specifies whether to apply ApplyMaskToArray() to the computed result. The default is ``ApplyMask`` . Parameters ---------- xforms : VtArray[Matrix4d] time : TimeCode baseTime : TimeCode doProtoXforms : ProtoXformInclusion applyMask : MaskApplication ---------------------------------------------------------------------- ComputeInstanceTransformsAtTime(xforms, stage, time, protoIndices, positions, velocities, velocitiesSampleTime, accelerations, scales, orientations, angularVelocities, angularVelocitiesSampleTime, protoPaths, mask, velocityScale) -> bool This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Perform the per-instance transform computation as described in Computing an Instance Transform. This does the same computation as the non-static ComputeInstanceTransformsAtTime method, but takes all data as parameters rather than accessing authored data. xforms \\- the out parameter for the transformations. Its size will depend on the given data and ``applyMask`` stage \\- the UsdStage time \\- time at which we want to evaluate the transforms protoIndices \\- array containing all instance prototype indices. positions \\- array containing all instance positions. This array must be the same size as ``protoIndices`` . velocities \\- array containing all instance velocities. This array must be either the same size as ``protoIndices`` or empty. If it is empty, transforms are computed as if all velocities were zero in all dimensions. velocitiesSampleTime \\- time at which the samples from ``velocities`` were taken. accelerations \\- array containing all instance accelerations. This array must be either the same size as ``protoIndicesor`` empty. If it is empty, transforms are computed as if all accelerations were zero in all dimensions. scales \\- array containing all instance scales. This array must be either the same size as ``protoIndices`` or empty. If it is empty, transforms are computed with no change in scale. orientations \\- array containing all instance orientations. This array must be either the same size as ``protoIndices`` or empty. If it is empty, transforms are computed with no change in orientation angularVelocities \\- array containing all instance angular velocities. This array must be either the same size as ``protoIndices`` or empty. If it is empty, transforms are computed as if all angular velocities were zero in all dimensions. angularVelocitiesSampleTime \\- time at which the samples from ``angularVelocities`` were taken. protoPaths \\- array containing the paths for all instance prototypes. If this array is not empty, prototype transforms are applied to the instance transforms. mask \\- vector containing a mask to apply to the computed result. This vector must be either the same size as ``protoIndices`` or empty. If it is empty, no mask is applied. velocityScale \\- Deprecated Parameters ---------- xforms : VtArray[Matrix4d] stage : UsdStageWeak time : TimeCode protoIndices : IntArray positions : Vec3fArray velocities : Vec3fArray velocitiesSampleTime : TimeCode accelerations : Vec3fArray scales : Vec3fArray orientations : QuathArray angularVelocities : Vec3fArray angularVelocitiesSampleTime : TimeCode protoPaths : list[SdfPath] mask : list[bool] velocityScale : float """ result["PointInstancer"].ComputeInstanceTransformsAtTimes.func_doc = """ComputeInstanceTransformsAtTimes(xformsArray, times, baseTime, doProtoXforms, applyMask) -> bool Compute the per-instance transforms as in ComputeInstanceTransformsAtTime, but using multiple sample times. An array of matrix arrays is returned where each matrix array contains the instance transforms for the corresponding time in ``times`` . times \\- A vector containing the UsdTimeCodes at which we want to sample. Parameters ---------- xformsArray : list[VtArray[Matrix4d]] times : list[TimeCode] baseTime : TimeCode doProtoXforms : ProtoXformInclusion applyMask : MaskApplication """ result["PointInstancer"].ComputeExtentAtTime.func_doc = """ComputeExtentAtTime(extent, time, baseTime) -> bool Compute the extent of the point instancer based on the per- instance,"PointInstancer relative"transforms at ``time`` , as described in Computing an Instance Transform. If there is no error, we return ``true`` and ``extent`` will be the tightest bounds we can compute efficiently. If an error occurs, ``false`` will be returned and ``extent`` will be left untouched. For now, this uses a UsdGeomBBoxCache with the"default","proxy", and"render"purposes. extent \\- the out parameter for the extent. On success, it will contain two elements representing the min and max. time \\- UsdTimeCode at which we want to evaluate the extent baseTime \\- required for correct interpolation between samples when *velocities* or *angularVelocities* are present. If there are samples for *positions* and *velocities* at t1 and t2, normal value resolution would attempt to interpolate between the two samples, and if they could not be interpolated because they differ in size (common in cases where velocity is authored), will choose the sample at t1. When sampling for the purposes of motion-blur, for example, it is common, when rendering the frame at t2, to sample at [ t2-shutter/2, t2+shutter/2 ] for a shutter interval of *shutter*. The first sample falls between t1 and t2, but we must sample at t2 and apply velocity- based interpolation based on those samples to get a correct result. In such scenarios, one should provide a ``baseTime`` of t2 when querying *both* samples. If your application does not care about off-sample interpolation, it can supply the same value for ``baseTime`` that it does for ``time`` . When ``baseTime`` is less than or equal to ``time`` , we will choose the lower bracketing timeSample. Parameters ---------- extent : Vec3fArray time : TimeCode baseTime : TimeCode ---------------------------------------------------------------------- ComputeExtentAtTime(extent, time, baseTime, transform) -> bool This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Computes the extent as if the matrix ``transform`` was first applied. Parameters ---------- extent : Vec3fArray time : TimeCode baseTime : TimeCode transform : Matrix4d """ result["PointInstancer"].ComputeExtentAtTimes.func_doc = """ComputeExtentAtTimes(extents, times, baseTime) -> bool Compute the extent of the point instancer as in ComputeExtentAtTime, but across multiple ``times`` . This is equivalent to, but more efficient than, calling ComputeExtentAtTime several times. Each element in ``extents`` is the computed extent at the corresponding time in ``times`` . As in ComputeExtentAtTime, if there is no error, we return ``true`` and ``extents`` will be the tightest bounds we can compute efficiently. If an error occurs computing the extent at any time, ``false`` will be returned and ``extents`` will be left untouched. times \\- A vector containing the UsdTimeCodes at which we want to sample. Parameters ---------- extents : list[Vec3fArray] times : list[TimeCode] baseTime : TimeCode ---------------------------------------------------------------------- ComputeExtentAtTimes(extents, times, baseTime, transform) -> bool This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Computes the extent as if the matrix ``transform`` was first applied at each time. Parameters ---------- extents : list[Vec3fArray] times : list[TimeCode] baseTime : TimeCode transform : Matrix4d """ result["PointInstancer"].GetInstanceCount.func_doc = """GetInstanceCount(timeCode) -> int Returns the number of instances as defined by the size of the *protoIndices* array at *timeCode*. For most code, this check will be performant. When using file formats where the cost of attribute reading is high and the time sampled array will be read into memory later, it may be better to explicitly read the value once and check the size of the array directly. GetProtoIndicesAttr() Parameters ---------- timeCode : TimeCode """ result["PointInstancer"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ result["PointInstancer"].Get.func_doc = """**classmethod** Get(stage, path) -> PointInstancer Return a UsdGeomPointInstancer holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomPointInstancer(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ result["PointInstancer"].Define.func_doc = """**classmethod** Define(stage, path) -> PointInstancer Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ result["PointInstancer"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type """ result["Points"].__doc__ = """ Points are analogous to the RiPoints spec. Points can be an efficient means of storing and rendering particle effects comprised of thousands or millions of small particles. Points generally receive a single shading sample each, which should take *normals* into account, if present. While not technically UsdGeomPrimvars, the widths and normals also have interpolation metadata. It's common for authored widths and normals to have constant or varying interpolation. """ result["Points"].__init__.func_doc = """__init__(prim) Construct a UsdGeomPoints on UsdPrim ``prim`` . Equivalent to UsdGeomPoints::Get (prim.GetStage(), prim.GetPath()) for a *valid* ``prim`` , but will not immediately throw an error for an invalid ``prim`` Parameters ---------- prim : Prim ---------------------------------------------------------------------- __init__(schemaObj) Construct a UsdGeomPoints on the prim held by ``schemaObj`` . Should be preferred over UsdGeomPoints (schemaObj.GetPrim()), as it preserves SchemaBase state. Parameters ---------- schemaObj : SchemaBase """ result["Points"].GetWidthsAttr.func_doc = """GetWidthsAttr() -> Attribute Widths are defined as the *diameter* of the points, in object space. 'widths'is not a generic Primvar, but the number of elements in this attribute will be determined by its'interpolation'. See SetWidthsInterpolation() . If'widths'and'primvars:widths'are both specified, the latter has precedence. Declaration ``float[] widths`` C++ Type VtArray<float> Usd Type SdfValueTypeNames->FloatArray """ result["Points"].CreateWidthsAttr.func_doc = """CreateWidthsAttr(defaultValue, writeSparsely) -> Attribute See GetWidthsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Points"].GetIdsAttr.func_doc = """GetIdsAttr() -> Attribute Ids are optional; if authored, the ids array should be the same length as the points array, specifying (at each timesample if point identities are changing) the id of each point. The type is signed intentionally, so that clients can encode some binary state on Id'd points without adding a separate primvar. Declaration ``int64[] ids`` C++ Type VtArray<int64_t> Usd Type SdfValueTypeNames->Int64Array """ result["Points"].CreateIdsAttr.func_doc = """CreateIdsAttr(defaultValue, writeSparsely) -> Attribute See GetIdsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Points"].GetWidthsInterpolation.func_doc = """GetWidthsInterpolation() -> str Get the interpolation for the *widths* attribute. Although'widths'is not classified as a generic UsdGeomPrimvar (and will not be included in the results of UsdGeomPrimvarsAPI::GetPrimvars() ) it does require an interpolation specification. The fallback interpolation, if left unspecified, is UsdGeomTokens->vertex, which means a width value is specified for each point. """ result["Points"].SetWidthsInterpolation.func_doc = """SetWidthsInterpolation(interpolation) -> bool Set the interpolation for the *widths* attribute. true upon success, false if ``interpolation`` is not a legal value as defined by UsdPrimvar::IsValidInterpolation(), or if there was a problem setting the value. No attempt is made to validate that the widths attr's value contains the right number of elements to match its interpolation to its prim's topology. GetWidthsInterpolation() Parameters ---------- interpolation : str """ result["Points"].GetPointCount.func_doc = """GetPointCount(timeCode) -> int Returns the number of points as defined by the size of the *points* array at *timeCode*. For most code, this check will be performant. When using file formats where the cost of attribute reading is high and the time sampled array will be read into memory later, it may be better to explicitly read the value once and check the size of the array directly. GetPointsAttr() Parameters ---------- timeCode : TimeCode """ result["Points"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ result["Points"].Get.func_doc = """**classmethod** Get(stage, path) -> Points Return a UsdGeomPoints holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomPoints(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ result["Points"].Define.func_doc = """**classmethod** Define(stage, path) -> Points Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ result["Points"].ComputeExtent.func_doc = """**classmethod** ComputeExtent(points, widths, extent) -> bool Compute the extent for the point cloud defined by points and widths. true upon success, false if widths and points are different sized arrays. On success, extent will contain the axis-aligned bounding box of the point cloud defined by points with the given widths. This function is to provide easy authoring of extent for usd authoring tools, hence it is static and acts outside a specific prim (as in attribute based methods). Parameters ---------- points : Vec3fArray widths : FloatArray extent : Vec3fArray ---------------------------------------------------------------------- ComputeExtent(points, widths, transform, extent) -> bool This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Computes the extent as if the matrix ``transform`` was first applied. Parameters ---------- points : Vec3fArray widths : FloatArray transform : Matrix4d extent : Vec3fArray """ result["Points"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type """ result["Primvar"].__doc__ = """ Schema wrapper for UsdAttribute for authoring and introspecting attributes that are primvars. UsdGeomPrimvar provides API for authoring and retrieving the additional data required to encode an attribute as a"Primvar", which is a convenient contraction of RenderMan's"Primitive Variable"concept, which is represented in Alembic as"arbitrary geometry parameters"(arbGeomParams). This includes the attribute's interpolation across the primitive (which RenderMan refers to as its class specifier and Alembic as its "geometry scope" ); it also includes the attribute's elementSize, which states how many values in the value array must be aggregated for each element on the primitive. An attribute's TypeName also factors into the encoding of Primvar. What is the Purpose of a Primvar? ================================= There are three key aspects of Primvar identity: - Primvars define a value that can vary across the primitive on which they are defined, via prescribed interpolation rules - Taken collectively on a prim, its Primvars describe the"per- primitiveoverrides"to the material to which the prim is bound. Different renderers may communicate the variables to the shaders using different mechanisms over which Usd has no control; Primvars simply provide the classification that any renderer should use to locate potential overrides. Do please note that primvars override parameters on UsdShadeShader objects, *not* Interface Attributes on UsdShadeMaterial prims. - *Primvars inherit down scene namespace.* Regular USD attributes only apply to the prim on which they are specified, but primvars implicitly also apply to any child prims, unless those child prims have their own opinions about those primvars. This capability necessarily entails added cost to check for inherited values, but the benefit is that it allows concise encoding of certain opinions that broadly affect large amounts of geometry. See UsdGeomImageable::FindInheritedPrimvars(). Creating and Accessing Primvars =============================== The UsdGeomPrimvarsAPI schema provides a complete interface for creating and querying prims for primvars. The **only** way to create a new Primvar in scene description is by calling UsdGeomPrimvarsAPI::CreatePrimvar() . One cannot"enhance"or"promote"an already existing attribute into a Primvar, because doing so may require a namespace edit to rename the attribute, which cannot, in general, be done within a single UsdEditContext. Instead, create a new UsdGeomPrimvar of the desired name using UsdGeomPrimvarsAPI::CreatePrimvar() , and then copy the existing attribute onto the new UsdGeomPrimvar. Primvar names can contain arbitrary sub-namespaces. The behavior of UsdGeomImageable::GetPrimvar(TfToken const & name) is to prepend"primvars:"onto'name'if it is not already a prefix, and return the result, which means we do not have any ambiguity between the primvars"primvars:nsA:foo"and"primvars:nsB:foo". **There are reserved keywords that may not be used as the base names of primvars,** and attempting to create Primvars of these names will result in a coding error. The reserved keywords are tokens the Primvar uses internally to encode various features, such as the"indices"keyword used by Indexed Primvars. If a client wishes to access an already-extant attribute as a Primvar, (which may or may not actually be valid Primvar), they can use the speculative constructor; typically, a primvar is only"interesting"if it additionally provides a value. This might look like: .. code-block:: text UsdGeomPrimvar primvar = UsdGeomPrimvar(usdAttr); if (primvar.HasValue()) { VtValue values; primvar.Get(&values, timeCode); TfToken interpolation = primvar.GetInterpolation(); int elementSize = primvar.GetElementSize(); \\.\\.\\. } or, because Get() returns ``true`` if and only if it found a value: .. code-block:: text UsdGeomPrimvar primvar = UsdGeomPrimvar(usdAttr); VtValue values; if (primvar.Get(&values, timeCode)) { TfToken interpolation = primvar.GetInterpolation(); int elementSize = primvar.GetElementSize(); \\.\\.\\. } As discussed in greater detail in Indexed Primvars, primvars can optionally contain a (possibly time-varying) indexing attribute that establishes a sharing topology for elements of the primvar. Consumers can always chose to ignore the possibility of indexed data by exclusively using the ComputeFlattened() API. If a client wishes to preserve indexing in their processing of a primvar, we suggest a pattern like the following, which accounts for the fact that a stronger layer can block a primvar's indexing from a weaker layer, via UsdGeomPrimvar::BlockIndices() : .. code-block:: text VtValue values; VtIntArray indices; if (primvar.Get(&values, timeCode)){ if (primvar.GetIndices(&indices, timeCode)){ // primvar is indexed: validate/process values and indices together } else { // primvar is not indexed: validate/process values as flat array } } UsdGeomPrimvar presents a small slice of the UsdAttribute API - enough to extract the data that comprises the"Declaration info", and get/set of the attribute value. A UsdGeomPrimvar also auto-converts to UsdAttribute, so you can pass a UsdGeomPrimvar to any function that accepts a UsdAttribute or const-ref thereto. Primvar Allowed Scene Description Types and Plurality ===================================================== There are no limitations imposed on the allowable scene description types for Primvars; it is the responsibility of each consuming client to perform renderer-specific conversions, if need be (the USD distribution will include reference RenderMan conversion utilities). A note about type plurality of Primvars: It is legitimate for a Primvar to be of scalar or array type, and again, consuming clients must be prepared to accommodate both. However, while it is not possible, in all cases, for USD to *prevent* one from *changing* the type of an attribute in different layers or variants of an asset, it is never a good idea to do so. This is relevant because, except in a few special cases, it is not possible to encode an *interpolation* of any value greater than *constant* without providing multiple (i.e. array) data values. Therefore, if there is any possibility that downstream clients might need to change a Primvar's interpolation, the Primvar-creator should encode it as an array rather than a scalar. Why allow scalar values at all, then? First, sometimes it brings clarity to (use of) a shader's API to acknowledge that some parameters are meant to be single-valued over a shaded primitive. Second, many DCC's provide far richer affordances for editing scalars than they do array values, and we feel it is safer to let the content creator make the decision/tradeoff of which kind of flexibility is more relevant, rather than leaving it to an importer/exporter pair to interpret. Also, like all attributes, Primvars can be time-sampled, and values can be authored and consumed just as any other attribute. There is currently no validation that the length of value arrays matches to the size required by a gprim's topology, interpolation, and elementSize. For consumer convenience, we provide GetDeclarationInfo() , which returns all the type information (other than topology) needed to compute the required array size, which is also all the information required to prepare the Primvar's value for consumption by a renderer. Lifetime Management and Primvar Validity ======================================== UsdGeomPrimvar has an explicit bool operator that validates that the attribute IsDefined() and thus valid for querying and authoring values and metadata. This is a fairly expensive query that we do **not** cache, so if client code retains UsdGeomPrimvar objects, it should manage its object validity closely, for performance. An ideal pattern is to listen for UsdNotice::StageContentsChanged notifications, and revalidate/refetch its retained UsdGeomPrimvar s only then, and otherwise use them without validity checking. Interpolation of Geometric Primitive Variables ============================================== In the following explanation of the meaning of the various kinds/levels of Primvar interpolation, each bolded bullet gives the name of the token in UsdGeomTokens that provides the value. So to set a Primvar's interpolation to"varying", one would: .. code-block:: text primvar.SetInterpolation(UsdGeomTokens->varying); Reprinted and adapted from the RPS documentation, which contains further details, *interpolation* describes how the Primvar will be interpolated over the uv parameter space of a surface primitive (or curve or pointcloud). The possible values are: - **constant** One value remains constant over the entire surface primitive. - **uniform** One value remains constant for each uv patch segment of the surface primitive (which is a *face* for meshes). - **varying** Four values are interpolated over each uv patch segment of the surface. Bilinear interpolation is used for interpolation between the four values. - **vertex** Values are interpolated between each vertex in the surface primitive. The basis function of the surface is used for interpolation between vertices. - **faceVarying** For polygons and subdivision surfaces, four values are interpolated over each face of the mesh. Bilinear interpolation is used for interpolation between the four values. UsdGeomPrimvar As Example of Attribute Schema ============================================= Just as UsdSchemaBase and its subclasses provide the pattern for how to layer schema onto the generic UsdPrim object, UsdGeomPrimvar provides an example of how to layer schema onto a generic UsdAttribute object. In both cases, the schema object wraps and contains the UsdObject. Primvar Namespace Inheritance ============================= Constant interpolation primvar values can be inherited down namespace. That is, a primvar value set on a prim will also apply to any child prims, unless those children have their own opinions about those named primvars. For complete details on how primvars inherit, see usdGeom_PrimvarInheritance. UsdGeomImageable::FindInheritablePrimvars(). """ result["Primvar"].GetAttr.func_doc = """GetAttr() -> Attribute Explicit UsdAttribute extractor. """ result["Primvar"].IsDefined.func_doc = """IsDefined() -> bool Return true if the underlying UsdAttribute::IsDefined() , and in addition the attribute is identified as a Primvar. Does not imply that the primvar provides a value """ result["Primvar"].HasValue.func_doc = """HasValue() -> bool Return true if the underlying attribute has a value, either from authored scene description or a fallback. """ result["Primvar"].HasAuthoredValue.func_doc = """HasAuthoredValue() -> bool Return true if the underlying attribute has an unblocked, authored value. """ result["Primvar"].GetName.func_doc = """GetName() -> str UsdAttribute::GetName() """ result["Primvar"].GetPrimvarName.func_doc = """GetPrimvarName() -> str Returns the primvar's name, devoid of the"primvars:"namespace. This is the name by which clients should refer to the primvar, if not by its full attribute name - i.e. they should **not**, in general, use GetBaseName() . In the error condition in which this Primvar object is not backed by a properly namespaced UsdAttribute, return an empty TfToken. """ result["Primvar"].NameContainsNamespaces.func_doc = """NameContainsNamespaces() -> bool Does this primvar contain any namespaces other than the"primvars:"namespace? Some clients may only wish to consume primvars that have no extra namespaces in their names, for ease of translating to other systems that do not allow namespaces. """ result["Primvar"].GetBaseName.func_doc = """GetBaseName() -> str UsdAttribute::GetBaseName() """ result["Primvar"].GetNamespace.func_doc = """GetNamespace() -> str UsdAttribute::GetNamespace() """ result["Primvar"].SplitName.func_doc = """SplitName() -> list[str] UsdAttribute::SplitName() """ result["Primvar"].GetTypeName.func_doc = """GetTypeName() -> ValueTypeName UsdAttribute::GetTypeName() """ result["Primvar"].Get.func_doc = """Get(value, time) -> bool Get the attribute value of the Primvar at ``time`` . Usd_Handling_Indexed_Primvars for proper handling of indexed primvars Parameters ---------- value : T time : TimeCode ---------------------------------------------------------------------- Get(value, time) -> bool Parameters ---------- value : str time : TimeCode ---------------------------------------------------------------------- Get(value, time) -> bool Parameters ---------- value : StringArray time : TimeCode ---------------------------------------------------------------------- Get(value, time) -> bool Parameters ---------- value : VtValue time : TimeCode """ result["Primvar"].Set.func_doc = """Set(value, time) -> bool Set the attribute value of the Primvar at ``time`` . Parameters ---------- value : T time : TimeCode """ result["Primvar"].GetTimeSamples.func_doc = """GetTimeSamples(times) -> bool Populates a vector with authored sample times for this primvar. Returns false on error. This considers any timeSamples authored on the associated"indices"attribute if the primvar is indexed. UsdAttribute::GetTimeSamples Parameters ---------- times : list[float] """ result["Primvar"].GetTimeSamplesInInterval.func_doc = """GetTimeSamplesInInterval(interval, times) -> bool Populates a vector with authored sample times in ``interval`` . This considers any timeSamples authored on the associated"indices"attribute if the primvar is indexed. UsdAttribute::GetTimeSamplesInInterval Parameters ---------- interval : Interval times : list[float] """ result["Primvar"].ValueMightBeTimeVarying.func_doc = """ValueMightBeTimeVarying() -> bool Return true if it is possible, but not certain, that this primvar's value changes over time, false otherwise. This considers time-varyingness of the associated"indices"attribute if the primvar is indexed. UsdAttribute::ValueMightBeTimeVarying """ result["Primvar"].SetIndices.func_doc = """SetIndices(indices, time) -> bool Sets the indices value of the indexed primvar at ``time`` . The values in the indices array must be valid indices into the authored array returned by Get() . The element numerality of the primvar's'interpolation'metadata applies to the"indices"array, not the attribute value array (returned by Get() ). Parameters ---------- indices : IntArray time : TimeCode """ result["Primvar"].GetIndices.func_doc = """GetIndices(indices, time) -> bool Returns the value of the indices array associated with the indexed primvar at ``time`` . SetIndices() , Proper Client Handling of"Indexed"Primvars Parameters ---------- indices : IntArray time : TimeCode """ result["Primvar"].BlockIndices.func_doc = """BlockIndices() -> None Block the indices that were previously set. This effectively makes an indexed primvar no longer indexed. This is useful when overriding an existing primvar. """ result["Primvar"].IsIndexed.func_doc = """IsIndexed() -> bool Returns true if the primvar is indexed, i.e., if it has an associated"indices"attribute. If you are going to query the indices anyways, prefer to simply consult the return-value of GetIndices() , which will be more efficient. """ result["Primvar"].GetIndicesAttr.func_doc = """GetIndicesAttr() -> Attribute Returns a valid indices attribute if the primvar is indexed. Returns an invalid attribute otherwise. """ result["Primvar"].CreateIndicesAttr.func_doc = """CreateIndicesAttr() -> Attribute Returns the existing indices attribute if the primvar is indexed or creates a new one. """ result["Primvar"].SetUnauthoredValuesIndex.func_doc = """SetUnauthoredValuesIndex(unauthoredValuesIndex) -> bool Set the index that represents unauthored values in the indices array. Some apps (like Maya) allow you to author primvars sparsely over a surface. Since most apps can't handle sparse primvars, Maya needs to provide a value even for the elements it didn't author. This metadatum provides a way to recover the information in apps that do support sparse authoring / representation of primvars. The fallback value of unauthoredValuesIndex is -1, which indicates that there are no unauthored values. GetUnauthoredValuesIndex() Parameters ---------- unauthoredValuesIndex : int """ result["Primvar"].GetUnauthoredValuesIndex.func_doc = """GetUnauthoredValuesIndex() -> int Returns the index that represents unauthored values in the indices array. SetUnauthoredValuesIndex() """ result["Primvar"].ComputeFlattened.func_doc = """**classmethod** ComputeFlattened(value, time) -> bool Computes the flattened value of the primvar at ``time`` . If the primvar is not indexed or if the value type of this primvar is a scalar, this returns the authored value, which is the same as Get() . Hence, it's safe to call ComputeFlattened() on non-indexed primvars. Parameters ---------- value : VtArray[ScalarType] time : TimeCode ---------------------------------------------------------------------- ComputeFlattened(value, time) -> bool This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Computes the flattened value of the primvar at ``time`` as a VtValue. If the primvar is not indexed or if the value type of this primvar is a scalar, this returns the authored value, which is the same as Get() . Hence, it's safe to call ComputeFlattened() on non-indexed primvars. Parameters ---------- value : VtValue time : TimeCode ---------------------------------------------------------------------- ComputeFlattened(value, attrVal, indices, errString) -> bool Computes the flattened value of ``attrValue`` given ``indices`` . This method is a static convenience function that performs the main work of ComputeFlattened above without needing an instance of a UsdGeomPrimvar. Returns ``false`` if the value contained in ``attrVal`` is not a supported type for flattening. Otherwise returns ``true`` . The output ``errString`` variable may be populated with an error string if an error is encountered during flattening. Parameters ---------- value : VtValue attrVal : VtValue indices : IntArray errString : str """ result["Primvar"].IsIdTarget.func_doc = """IsIdTarget() -> bool Returns true if the primvar is an Id primvar. UsdGeomPrimvar_Id_primvars """ result["Primvar"].SetIdTarget.func_doc = """SetIdTarget(path) -> bool This primvar must be of String or StringArray type for this method to succeed. If not, a coding error is raised. UsdGeomPrimvar_Id_primvars Parameters ---------- path : Path """ result["Primvar"].__init__.func_doc = """__init__() ---------------------------------------------------------------------- __init__(other) Copy construct. Parameters ---------- other : Primvar ---------------------------------------------------------------------- __init__(attr) Speculative constructor that will produce a valid UsdGeomPrimvar when ``attr`` already represents an attribute that is Primvar, and produces an *invalid* Primvar otherwise (i.e. operator bool() will return false). Calling ``UsdGeomPrimvar::IsPrimvar(attr)`` will return the same truth value as this constructor, but if you plan to subsequently use the Primvar anyways, just use this constructor, as demonstrated in the class documentation. Parameters ---------- attr : Attribute ---------------------------------------------------------------------- __init__(prim, attrName, typeName) Factory for UsdGeomImageable 's use, so that we can encapsulate the logic of what discriminates Primvar in this class, while preserving the pattern that attributes can only be created via their container objects. The name of the created attribute may or may not be the specified ``attrName`` , due to the possible need to apply property namespacing for Primvar. The behavior with respect to the provided ``typeName`` is the same as for UsdAttributes::Create(). an invalid UsdGeomPrimvar if we failed to create a valid attribute, a valid UsdGeomPrimvar otherwise. It is not an error to create over an existing, compatible attribute. It is a failed verification for ``prim`` to be invalid/expired UsdPrim::CreateAttribute() Parameters ---------- prim : Prim attrName : str typeName : ValueTypeName """ result["Primvar"].GetInterpolation.func_doc = """GetInterpolation() -> str Return the Primvar's interpolation, which is UsdGeomTokens->constant if unauthored. Interpolation determines how the Primvar interpolates over a geometric primitive. See Interpolation of Geometric Primitive Variables """ result["Primvar"].SetInterpolation.func_doc = """SetInterpolation(interpolation) -> bool Set the Primvar's interpolation. Errors and returns false if ``interpolation`` is out of range as defined by IsValidInterpolation() . No attempt is made to validate that the Primvar's value contains the right number of elements to match its interpolation to its topology. GetInterpolation() , Interpolation of Geometric Primitive Variables Parameters ---------- interpolation : str """ result["Primvar"].HasAuthoredInterpolation.func_doc = """HasAuthoredInterpolation() -> bool Has interpolation been explicitly authored on this Primvar? GetInterpolationSize() """ result["Primvar"].GetElementSize.func_doc = """GetElementSize() -> int Return the"element size"for this Primvar, which is 1 if unauthored. If this Primvar's type is *not* an array type, (e.g."Vec3f[]"), then elementSize is irrelevant. ElementSize does *not* generally encode the length of an array-type primvar, and rarely needs to be authored. ElementSize can be thought of as a way to create an"aggregate interpolatable type", by dictating how many consecutive elements in the value array should be taken as an atomic element to be interpolated over a gprim. For example, spherical harmonics are often represented as a collection of nine floating-point coefficients, and the coefficients need to be sampled across a gprim's surface: a perfect case for primvars. However, USD has no ``float9`` datatype. But we can communicate the aggregation of nine floats successfully to renderers by declaring a simple float-array valued primvar, and setting its *elementSize* to 9. To author a *uniform* spherical harmonic primvar on a Mesh of 42 faces, the primvar's array value would contain 9\\*42 = 378 float elements. """ result["Primvar"].SetElementSize.func_doc = """SetElementSize(eltSize) -> bool Set the elementSize for this Primvar. Errors and returns false if ``eltSize`` less than 1. GetElementSize() Parameters ---------- eltSize : int """ result["Primvar"].HasAuthoredElementSize.func_doc = """HasAuthoredElementSize() -> bool Has elementSize been explicitly authored on this Primvar? GetElementSize() """ result["Primvar"].GetDeclarationInfo.func_doc = """GetDeclarationInfo(name, typeName, interpolation, elementSize) -> None Convenience function for fetching all information required to properly declare this Primvar. The ``name`` returned is the"client name", stripped of the"primvars"namespace, i.e. equivalent to GetPrimvarName() May also be more efficient than querying key individually. Parameters ---------- name : str typeName : ValueTypeName interpolation : str elementSize : int """ result["Primvar"].IsPrimvar.func_doc = """**classmethod** IsPrimvar(attr) -> bool Test whether a given UsdAttribute represents valid Primvar, which implies that creating a UsdGeomPrimvar from the attribute will succeed. Success implies that ``attr.IsDefined()`` is true. Parameters ---------- attr : Attribute """ result["Primvar"].IsValidPrimvarName.func_doc = """**classmethod** IsValidPrimvarName(name) -> bool Test whether a given ``name`` represents a valid name of a primvar, which implies that creating a UsdGeomPrimvar with the given name will succeed. Parameters ---------- name : str """ result["Primvar"].StripPrimvarsName.func_doc = """**classmethod** StripPrimvarsName(name) -> str Returns the ``name`` , devoid of the"primvars:"token if present, otherwise returns the ``name`` unchanged. Parameters ---------- name : str """ result["Primvar"].IsValidInterpolation.func_doc = """**classmethod** IsValidInterpolation(interpolation) -> bool Validate that the provided ``interpolation`` is a valid setting for interpolation as defined by Interpolation of Geometric Primitive Variables. Parameters ---------- interpolation : str """ result["PrimvarsAPI"].__doc__ = """ UsdGeomPrimvarsAPI encodes geometric"primitive variables", as UsdGeomPrimvar, which interpolate across a primitive's topology, can override shader inputs, and inherit down namespace. Which Method to Use to Retrieve Primvars ======================================== While creating primvars is unambiguous ( CreatePrimvar() ), there are quite a few methods available for retrieving primvars, making it potentially confusing knowing which one to use. Here are some guidelines: - If you are populating a GUI with the primvars already available for authoring values on a prim, use GetPrimvars() . - If you want all of the"useful"(e.g. to a renderer) primvars available at a prim, including those inherited from ancestor prims, use FindPrimvarsWithInheritance() . Note that doing so individually for many prims will be inefficient. - To find a particular primvar defined directly on a prim, which may or may not provide a value, use GetPrimvar() . - To find a particular primvar defined on a prim or inherited from ancestors, which may or may not provide a value, use FindPrimvarWithInheritance() . - To *efficiently* query for primvars using the overloads of FindPrimvarWithInheritance() and FindPrimvarsWithInheritance() , one must first cache the results of FindIncrementallyInheritablePrimvars() for each non-leaf prim on the stage. """ result["PrimvarsAPI"].__init__.func_doc = """__init__(prim) Construct a UsdGeomPrimvarsAPI on UsdPrim ``prim`` . Equivalent to UsdGeomPrimvarsAPI::Get (prim.GetStage(), prim.GetPath()) for a *valid* ``prim`` , but will not immediately throw an error for an invalid ``prim`` Parameters ---------- prim : Prim ---------------------------------------------------------------------- __init__(schemaObj) Construct a UsdGeomPrimvarsAPI on the prim held by ``schemaObj`` . Should be preferred over UsdGeomPrimvarsAPI (schemaObj.GetPrim()), as it preserves SchemaBase state. Parameters ---------- schemaObj : SchemaBase """ result["PrimvarsAPI"].CreatePrimvar.func_doc = """CreatePrimvar(name, typeName, interpolation, elementSize) -> Primvar Author scene description to create an attribute on this prim that will be recognized as Primvar (i.e. will present as a valid UsdGeomPrimvar). The name of the created attribute may or may not be the specified ``name`` , due to the possible need to apply property namespacing for primvars. See Creating and Accessing Primvars for more information. Creation may fail and return an invalid Primvar if ``name`` contains a reserved keyword, such as the"indices"suffix we use for indexed primvars. The behavior with respect to the provided ``typeName`` is the same as for UsdAttributes::Create(), and ``interpolation`` and ``elementSize`` are as described in UsdGeomPrimvar::GetInterpolation() and UsdGeomPrimvar::GetElementSize() . If ``interpolation`` and/or ``elementSize`` are left unspecified, we will author no opinions for them, which means any (strongest) opinion already authored in any contributing layer for these fields will become the Primvar's values, or the fallbacks if no opinions have been authored. an invalid UsdGeomPrimvar if we failed to create a valid attribute, a valid UsdGeomPrimvar otherwise. It is not an error to create over an existing, compatible attribute. UsdPrim::CreateAttribute() , UsdGeomPrimvar::IsPrimvar() Parameters ---------- name : str typeName : ValueTypeName interpolation : str elementSize : int """ result["PrimvarsAPI"].CreateNonIndexedPrimvar.func_doc = """CreateNonIndexedPrimvar(name, typeName, value, interpolation, elementSize, time) -> Primvar Author scene description to create an attribute and authoring a ``value`` on this prim that will be recognized as a Primvar (i.e. will present as a valid UsdGeomPrimvar). Note that unlike CreatePrimvar using this API explicitly authors a block for the indices attr associated with the primvar, thereby blocking any indices set in any weaker layers. an invalid UsdGeomPrimvar on error, a valid UsdGeomPrimvar otherwise. It is fine to call this method multiple times, and in different UsdEditTargets, even if there is an existing primvar of the same name, indexed or not. CreatePrimvar() , CreateIndexedPrimvar() , UsdPrim::CreateAttribute() , UsdGeomPrimvar::IsPrimvar() Parameters ---------- name : str typeName : ValueTypeName value : T interpolation : str elementSize : int time : TimeCode """ result["PrimvarsAPI"].CreateIndexedPrimvar.func_doc = """CreateIndexedPrimvar(name, typeName, value, indices, interpolation, elementSize, time) -> Primvar Author scene description to create an attribute and authoring a ``value`` on this prim that will be recognized as an indexed Primvar with ``indices`` appropriately set (i.e. will present as a valid UsdGeomPrimvar). an invalid UsdGeomPrimvar on error, a valid UsdGeomPrimvar otherwise. It is fine to call this method multiple times, and in different UsdEditTargets, even if there is an existing primvar of the same name, indexed or not. CreatePrimvar() , CreateNonIndexedPrimvar() , UsdPrim::CreateAttribute() , UsdGeomPrimvar::IsPrimvar() Parameters ---------- name : str typeName : ValueTypeName value : T indices : IntArray interpolation : str elementSize : int time : TimeCode """ result["PrimvarsAPI"].RemovePrimvar.func_doc = """RemovePrimvar(name) -> bool Author scene description to delete an attribute on this prim that was recognized as Primvar (i.e. will present as a valid UsdGeomPrimvar), *in the current UsdEditTarget*. Because this method can only remove opinions about the primvar from the current EditTarget, you may generally find it more useful to use BlockPrimvar() which will ensure that all values from the EditTarget and weaker layers for the primvar and its indices will be ignored. Removal may fail and return false if ``name`` contains a reserved keyword, such as the"indices"suffix we use for indexed primvars. Note this will also remove the indices attribute associated with an indiced primvar. true if UsdGeomPrimvar and indices attribute was successfully removed, false otherwise. UsdPrim::RemoveProperty() ) Parameters ---------- name : str """ result["PrimvarsAPI"].BlockPrimvar.func_doc = """BlockPrimvar(name) -> None Remove all time samples on the primvar and its associated indices attr, and author a *block* ``default`` value. This will cause authored opinions in weaker layers to be ignored. UsdAttribute::Block() , UsdGeomPrimvar::BlockIndices Parameters ---------- name : str """ result["PrimvarsAPI"].GetPrimvar.func_doc = """GetPrimvar(name) -> Primvar Return the Primvar object named by ``name`` , which will be valid if a Primvar attribute definition already exists. Name lookup will account for Primvar namespacing, which means that this method will succeed in some cases where .. code-block:: text UsdGeomPrimvar(prim->GetAttribute(name)) will not, unless ``name`` is properly namespace prefixed. Just because a Primvar is valid and defined, and *even if* its underlying UsdAttribute (GetAttr()) answers HasValue() affirmatively, one must still check the return value of Get() , due to the potential of time-varying value blocks (see Attribute Value Blocking). HasPrimvar() , Which Method to Use to Retrieve Primvars Parameters ---------- name : str """ result["PrimvarsAPI"].GetPrimvars.func_doc = """GetPrimvars() -> list[Primvar] Return valid UsdGeomPrimvar objects for all defined Primvars on this prim, similarly to UsdPrim::GetAttributes() . The returned primvars may not possess any values, and therefore not be useful to some clients. For the primvars useful for inheritance computations, see GetPrimvarsWithAuthoredValues() , and for primvars useful for direct consumption, see GetPrimvarsWithValues() . Which Method to Use to Retrieve Primvars """ result["PrimvarsAPI"].GetAuthoredPrimvars.func_doc = """GetAuthoredPrimvars() -> list[Primvar] Like GetPrimvars() , but include only primvars that have some authored scene description (though not necessarily a value). Which Method to Use to Retrieve Primvars """ result["PrimvarsAPI"].GetPrimvarsWithValues.func_doc = """GetPrimvarsWithValues() -> list[Primvar] Like GetPrimvars() , but include only primvars that have some value, whether it comes from authored scene description or a schema fallback. For most purposes, this method is more useful than GetPrimvars() . Which Method to Use to Retrieve Primvars """ result["PrimvarsAPI"].GetPrimvarsWithAuthoredValues.func_doc = """GetPrimvarsWithAuthoredValues() -> list[Primvar] Like GetPrimvars() , but include only primvars that have an **authored** value. This is the query used when computing inheritable primvars, and is generally more useful than GetAuthoredPrimvars() . Which Method to Use to Retrieve Primvars """ result["PrimvarsAPI"].FindInheritablePrimvars.func_doc = """FindInheritablePrimvars() -> list[Primvar] Compute the primvars that can be inherited from this prim by its child prims, including the primvars that **this** prim inherits from ancestor prims. Inherited primvars will be bound to attributes on the corresponding ancestor prims. Only primvars with **authored**, **non-blocked**, **constant interpolation** values are inheritable; fallback values are not inherited. The order of the returned primvars is undefined. It is not generally useful to call this method on UsdGeomGprim leaf prims, and furthermore likely to be expensive since *most* primvars are defined on Gprims. Which Method to Use to Retrieve Primvars """ result["PrimvarsAPI"].FindIncrementallyInheritablePrimvars.func_doc = """FindIncrementallyInheritablePrimvars(inheritedFromAncestors) -> list[Primvar] Compute the primvars that can be inherited from this prim by its child prims, starting from the set of primvars inherited from this prim's ancestors. If this method returns an empty vector, then this prim's children should inherit the same set of primvars available to this prim, i.e. the input ``inheritedFromAncestors`` . As opposed to FindInheritablePrimvars() , which always recurses up through all of the prim's ancestors, this method allows more efficient computation of inheritable primvars by starting with the list of primvars inherited from this prim's ancestors, and returning a newly allocated vector only when this prim makes a change to the set of inherited primvars. This enables O(n) inherited primvar computation for all prims on a Stage, with potential to share computed results that are identical (i.e. when this method returns an empty vector, its parent's result can (and must!) be reused for all of the prim's children. Which Method to Use to Retrieve Primvars Parameters ---------- inheritedFromAncestors : list[Primvar] """ result["PrimvarsAPI"].FindPrimvarWithInheritance.func_doc = """FindPrimvarWithInheritance(name) -> Primvar Like GetPrimvar() , but if the named primvar does not exist or has no authored value on this prim, search for the named, value-producing primvar on ancestor prims. The returned primvar will be bound to the attribute on the corresponding ancestor prim on which it was found (if any). If neither this prim nor any ancestor contains a value-producing primvar, then the returned primvar will be the same as that returned by GetPrimvar() . This is probably the method you want to call when needing to consume a primvar of a particular name. Which Method to Use to Retrieve Primvars Parameters ---------- name : str ---------------------------------------------------------------------- FindPrimvarWithInheritance(name, inheritedFromAncestors) -> Primvar This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. This version of FindPrimvarWithInheritance() takes the pre-computed set of primvars inherited from this prim's ancestors, as computed by FindInheritablePrimvars() or FindIncrementallyInheritablePrimvars() on the prim's parent. Which Method to Use to Retrieve Primvars Parameters ---------- name : str inheritedFromAncestors : list[Primvar] """ result["PrimvarsAPI"].FindPrimvarsWithInheritance.func_doc = """FindPrimvarsWithInheritance() -> list[Primvar] Find all of the value-producing primvars either defined on this prim, or inherited from ancestor prims. Which Method to Use to Retrieve Primvars ---------------------------------------------------------------------- FindPrimvarsWithInheritance(inheritedFromAncestors) -> list[Primvar] This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. This version of FindPrimvarsWithInheritance() takes the pre-computed set of primvars inherited from this prim's ancestors, as computed by FindInheritablePrimvars() or FindIncrementallyInheritablePrimvars() on the prim's parent. Which Method to Use to Retrieve Primvars Parameters ---------- inheritedFromAncestors : list[Primvar] """ result["PrimvarsAPI"].HasPrimvar.func_doc = """HasPrimvar(name) -> bool Is there a defined Primvar ``name`` on this prim? Name lookup will account for Primvar namespacing. Like GetPrimvar() , a return value of ``true`` for HasPrimvar() does not guarantee the primvar will produce a value. Parameters ---------- name : str """ result["PrimvarsAPI"].HasPossiblyInheritedPrimvar.func_doc = """HasPossiblyInheritedPrimvar(name) -> bool Is there a Primvar named ``name`` with an authored value on this prim or any of its ancestors? This is probably the method you want to call when wanting to know whether or not the prim"has"a primvar of a particular name. FindPrimvarWithInheritance() Parameters ---------- name : str """ result["PrimvarsAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ result["PrimvarsAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> PrimvarsAPI Return a UsdGeomPrimvarsAPI holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomPrimvarsAPI(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ result["PrimvarsAPI"].CanContainPropertyName.func_doc = """**classmethod** CanContainPropertyName(name) -> bool Test whether a given ``name`` contains the"primvars:"prefix. Parameters ---------- name : str """ result["PrimvarsAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type """ result["Scope"].__doc__ = """ Scope is the simplest grouping primitive, and does not carry the baggage of transformability. Note that transforms should inherit down through a Scope successfully - it is just a guaranteed no-op from a transformability perspective. """ result["Scope"].__init__.func_doc = """__init__(prim) Construct a UsdGeomScope on UsdPrim ``prim`` . Equivalent to UsdGeomScope::Get (prim.GetStage(), prim.GetPath()) for a *valid* ``prim`` , but will not immediately throw an error for an invalid ``prim`` Parameters ---------- prim : Prim ---------------------------------------------------------------------- __init__(schemaObj) Construct a UsdGeomScope on the prim held by ``schemaObj`` . Should be preferred over UsdGeomScope (schemaObj.GetPrim()), as it preserves SchemaBase state. Parameters ---------- schemaObj : SchemaBase """ result["Scope"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ result["Scope"].Get.func_doc = """**classmethod** Get(stage, path) -> Scope Return a UsdGeomScope holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomScope(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ result["Scope"].Define.func_doc = """**classmethod** Define(stage, path) -> Scope Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ result["Scope"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type """ result["Sphere"].__doc__ = """ Defines a primitive sphere centered at the origin. The fallback values for Cube, Sphere, Cone, and Cylinder are set so that they all pack into the same volume/bounds. """ result["Sphere"].__init__.func_doc = """__init__(prim) Construct a UsdGeomSphere on UsdPrim ``prim`` . Equivalent to UsdGeomSphere::Get (prim.GetStage(), prim.GetPath()) for a *valid* ``prim`` , but will not immediately throw an error for an invalid ``prim`` Parameters ---------- prim : Prim ---------------------------------------------------------------------- __init__(schemaObj) Construct a UsdGeomSphere on the prim held by ``schemaObj`` . Should be preferred over UsdGeomSphere (schemaObj.GetPrim()), as it preserves SchemaBase state. Parameters ---------- schemaObj : SchemaBase """ result["Sphere"].GetRadiusAttr.func_doc = """GetRadiusAttr() -> Attribute Indicates the sphere's radius. If you author *radius* you must also author *extent*. GetExtentAttr() Declaration ``double radius = 1`` C++ Type double Usd Type SdfValueTypeNames->Double """ result["Sphere"].CreateRadiusAttr.func_doc = """CreateRadiusAttr(defaultValue, writeSparsely) -> Attribute See GetRadiusAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Sphere"].GetExtentAttr.func_doc = """GetExtentAttr() -> Attribute Extent is re-defined on Sphere only to provide a fallback value. UsdGeomGprim::GetExtentAttr() . Declaration ``float3[] extent = [(-1, -1, -1), (1, 1, 1)]`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Float3Array """ result["Sphere"].CreateExtentAttr.func_doc = """CreateExtentAttr(defaultValue, writeSparsely) -> Attribute See GetExtentAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Sphere"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ result["Sphere"].Get.func_doc = """**classmethod** Get(stage, path) -> Sphere Return a UsdGeomSphere holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomSphere(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ result["Sphere"].Define.func_doc = """**classmethod** Define(stage, path) -> Sphere Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ result["Sphere"].ComputeExtent.func_doc = """**classmethod** ComputeExtent(radius, extent) -> bool Compute the extent for the sphere defined by the radius. true upon success, false if unable to calculate extent. On success, extent will contain an approximate axis-aligned bounding box of the sphere defined by the radius. This function is to provide easy authoring of extent for usd authoring tools, hence it is static and acts outside a specific prim (as in attribute based methods). Parameters ---------- radius : float extent : Vec3fArray ---------------------------------------------------------------------- ComputeExtent(radius, transform, extent) -> bool This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Computes the extent as if the matrix ``transform`` was first applied. Parameters ---------- radius : float transform : Matrix4d extent : Vec3fArray """ result["Sphere"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type """ result["Subset"].__doc__ = """ Encodes a subset of a piece of geometry (i.e. a UsdGeomImageable) as a set of indices. Currently only supports encoding of face-subsets, but could be extended in the future to support subsets representing edges, segments, points etc. To apply to a geometric prim, a GeomSubset prim must be the prim's direct child in namespace, and possess a concrete defining specifier (i.e. def). This restriction makes it easy and efficient to discover subsets of a prim. We might want to relax this restriction if it's common to have multiple **families** of subsets on a gprim and if it's useful to be able to organize subsets belonging to a family under a common scope. See'familyName'attribute for more info on defining a family of subsets. Note that a GeomSubset isn't an imageable (i.e. doesn't derive from UsdGeomImageable). So, you can't author **visibility** for it or override its **purpose**. Materials are bound to GeomSubsets just as they are for regular geometry using API available in UsdShade (UsdShadeMaterial::Bind). For any described attribute *Fallback* *Value* or *Allowed* *Values* below that are text/tokens, the actual token is published and defined in UsdGeomTokens. So to set an attribute to the value"rightHanded", use UsdGeomTokens->rightHanded as the value. """ result["Subset"].__init__.func_doc = """__init__(prim) Construct a UsdGeomSubset on UsdPrim ``prim`` . Equivalent to UsdGeomSubset::Get (prim.GetStage(), prim.GetPath()) for a *valid* ``prim`` , but will not immediately throw an error for an invalid ``prim`` Parameters ---------- prim : Prim ---------------------------------------------------------------------- __init__(schemaObj) Construct a UsdGeomSubset on the prim held by ``schemaObj`` . Should be preferred over UsdGeomSubset (schemaObj.GetPrim()), as it preserves SchemaBase state. Parameters ---------- schemaObj : SchemaBase """ result["Subset"].GetElementTypeAttr.func_doc = """GetElementTypeAttr() -> Attribute The type of element that the indices target. Currently only allows"face"and defaults to it. Declaration ``uniform token elementType ="face"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values face """ result["Subset"].CreateElementTypeAttr.func_doc = """CreateElementTypeAttr(defaultValue, writeSparsely) -> Attribute See GetElementTypeAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Subset"].GetIndicesAttr.func_doc = """GetIndicesAttr() -> Attribute The set of indices included in this subset. The indices need not be sorted, but the same index should not appear more than once. Declaration ``int[] indices = []`` C++ Type VtArray<int> Usd Type SdfValueTypeNames->IntArray """ result["Subset"].CreateIndicesAttr.func_doc = """CreateIndicesAttr(defaultValue, writeSparsely) -> Attribute See GetIndicesAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Subset"].GetFamilyNameAttr.func_doc = """GetFamilyNameAttr() -> Attribute The name of the family of subsets that this subset belongs to. This is optional and is primarily useful when there are multiple families of subsets under a geometric prim. In some cases, this could also be used for achieving proper roundtripping of subset data between DCC apps. When multiple subsets belonging to a prim have the same familyName, they are said to belong to the family. A *familyType* value can be encoded on the owner of a family of subsets as a token using the static method UsdGeomSubset::SetFamilyType() ."familyType"can have one of the following values: - **UsdGeomTokens->partition** : implies that every element of the whole geometry appears exactly once in only one of the subsets belonging to the family. - **UsdGeomTokens->nonOverlapping** : an element that appears in one subset may not appear in any other subset belonging to the family. - **UsdGeomTokens->unrestricted** : implies that there are no restrictions w.r.t. the membership of elements in the subsets. They could be overlapping and the union of all subsets in the family may not represent the whole. The validity of subset data is not enforced by the authoring APIs, however they can be checked using UsdGeomSubset::ValidateFamily() . Declaration ``uniform token familyName =""`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform """ result["Subset"].CreateFamilyNameAttr.func_doc = """CreateFamilyNameAttr(defaultValue, writeSparsely) -> Attribute See GetFamilyNameAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Subset"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ result["Subset"].Get.func_doc = """**classmethod** Get(stage, path) -> Subset Return a UsdGeomSubset holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomSubset(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ result["Subset"].Define.func_doc = """**classmethod** Define(stage, path) -> Subset Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ result["Subset"].CreateGeomSubset.func_doc = """**classmethod** CreateGeomSubset(geom, subsetName, elementType, indices, familyName, familyType) -> Subset Creates a new GeomSubset below the given ``geom`` with the given name, ``subsetName`` , element type, ``elementType`` and ``indices`` . If a subset named ``subsetName`` already exists below ``geom`` , then this updates its attributes with the values of the provided arguments (indices value at time'default'will be updated) and returns it. The family type is set / updated on ``geom`` only if a non-empty value is passed in for ``familyType`` and ``familyName`` . Parameters ---------- geom : Imageable subsetName : str elementType : str indices : IntArray familyName : str familyType : str """ result["Subset"].CreateUniqueGeomSubset.func_doc = """**classmethod** CreateUniqueGeomSubset(geom, subsetName, elementType, indices, familyName, familyType) -> Subset Creates a new GeomSubset below the given imageable, ``geom`` with the given name, ``subsetName`` , element type, ``elementType`` and ``indices`` . If a subset named ``subsetName`` already exists below ``geom`` , then this creates a new subset by appending a suitable index as suffix to ``subsetName`` (eg, subsetName_1) to avoid name collisions. The family type is set / updated on ``geom`` only if a non-empty value is passed in for ``familyType`` and ``familyName`` . Parameters ---------- geom : Imageable subsetName : str elementType : str indices : IntArray familyName : str familyType : str """ result["Subset"].GetAllGeomSubsets.func_doc = """**classmethod** GetAllGeomSubsets(geom) -> list[Subset] Returns all the GeomSubsets defined on the given imageable, ``geom`` . Parameters ---------- geom : Imageable """ result["Subset"].GetGeomSubsets.func_doc = """**classmethod** GetGeomSubsets(geom, elementType, familyName) -> list[Subset] Returns all the GeomSubsets of the given ``elementType`` belonging to the specified family, ``familyName`` on the given imageable, ``geom`` . If ``elementType`` is empty, then subsets containing all element types are returned. If ``familyName`` is left empty, then all subsets of the specified ``elementType`` will be returned. Parameters ---------- geom : Imageable elementType : str familyName : str """ result["Subset"].GetAllGeomSubsetFamilyNames.func_doc = """**classmethod** GetAllGeomSubsetFamilyNames(geom) -> str.Set Returns the names of all the families of GeomSubsets defined on the given imageable, ``geom`` . Parameters ---------- geom : Imageable """ result["Subset"].SetFamilyType.func_doc = """**classmethod** SetFamilyType(geom, familyName, familyType) -> bool This method is used to encode the type of family that the GeomSubsets on the given geometric prim ``geom`` , with the given family name, ``familyName`` belong to. See UsdGeomSubset::GetFamilyNameAttr for the possible values for ``familyType`` . When a family of GeomSubsets is tagged as a UsdGeomTokens->partition or UsdGeomTokens->nonOverlapping, the validity of the data (i.e. mutual exclusivity and/or wholeness) is not enforced by the authoring APIs. Use ValidateFamily() to validate the data in a family of GeomSubsets. Returns false upon failure to create or set the appropriate attribute on ``geom`` . Parameters ---------- geom : Imageable familyName : str familyType : str """ result["Subset"].GetFamilyType.func_doc = """**classmethod** GetFamilyType(geom, familyName) -> str Returns the type of family that the GeomSubsets on the given geometric prim ``geom`` , with the given family name, ``familyName`` belong to. This only returns the token that's encoded on ``geom`` and does not perform any actual validation on the family of GeomSubsets. Please use ValidateFamily() for such validation. When familyType is not set on ``geom`` , the fallback value UsdTokens->unrestricted is returned. Parameters ---------- geom : Imageable familyName : str """ result["Subset"].GetUnassignedIndices.func_doc = """**classmethod** GetUnassignedIndices(subsets, elementCount, time) -> IntArray Utility for getting the list of indices that are not assigned to any of the GeomSubsets in ``subsets`` at the timeCode, ``time`` , given the element count (total number of indices in the array being subdivided), ``elementCount`` . Parameters ---------- subsets : list[Subset] elementCount : int time : TimeCode """ result["Subset"].ValidateSubsets.func_doc = """**classmethod** ValidateSubsets(subsets, elementCount, familyType, reason) -> bool Validates the data in the given set of GeomSubsets, ``subsets`` , given the total number of elements in the array being subdivided, ``elementCount`` and the ``familyType`` that the subsets belong to. For proper validation of indices in ``subsets`` , all of the GeomSubsets must have the same'elementType'. If one or more subsets contain invalid data, then false is returned and ``reason`` is populated with a string explaining the reason why it is invalid. The python version of this method returns a tuple containing a (bool, string), where the bool has the validity of the subsets and the string contains the reason (if they're invalid). Parameters ---------- subsets : list[Subset] elementCount : int familyType : str reason : str """ result["Subset"].ValidateFamily.func_doc = """**classmethod** ValidateFamily(geom, elementType, familyName, reason) -> bool Validates whether the family of subsets identified by the given ``familyName`` and ``elementType`` on the given imageable, ``geom`` contain valid data. If the family is designated as a partition or as non-overlapping using SetFamilyType() , then the validity of the data is checked. If the familyType is"unrestricted", then this performs only bounds checking of the values in the"indices"arrays. If ``reason`` is not None, then it is populated with a string explaining why the family is invalid, if it is invalid. The python version of this method returns a tuple containing a (bool, string), where the bool has the validity of the family and the string contains the reason (if it's invalid). Parameters ---------- geom : Imageable elementType : str familyName : str reason : str """ result["Subset"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type """ result["VisibilityAPI"].__doc__ = """ UsdGeomVisibilityAPI introduces properties that can be used to author visibility opinions. Currently, this schema only introduces the attributes that are used to control purpose visibility. Later, this schema will define *all* visibility-related properties and UsdGeomImageable will no longer define those properties. The purpose visibility attributes added by this schema, *guideVisibility*, *proxyVisibility*, and *renderVisibility* can each be used to control visibility for geometry of the corresponding purpose values, with the overall *visibility* attribute acting as an override. I.e., if *visibility* evaluates to"invisible", purpose visibility is invisible; otherwise, purpose visibility is determined by the corresponding purpose visibility attribute. Note that the behavior of *guideVisibility* is subtly different from the *proxyVisibility* and *renderVisibility* attributes, in that"guide"purpose visibility always evaluates to either"invisible"or"visible", whereas the other attributes may yield computed values of"inherited"if there is no authored opinion on the attribute or inherited from an ancestor. This is motivated by the fact that, in Pixar"s user workflows, we have never found a need to have all guides visible in a scene by default, whereas we do find that flexibility useful for"proxy"and"render"geometry. This schema can only be applied to UsdGeomImageable prims. The UseGeomImageable schema provides API for computing the purpose visibility values that result from the attributes introduced by this schema. For any described attribute *Fallback* *Value* or *Allowed* *Values* below that are text/tokens, the actual token is published and defined in UsdGeomTokens. So to set an attribute to the value"rightHanded", use UsdGeomTokens->rightHanded as the value. """ result["VisibilityAPI"].__init__.func_doc = """__init__(prim) Construct a UsdGeomVisibilityAPI on UsdPrim ``prim`` . Equivalent to UsdGeomVisibilityAPI::Get (prim.GetStage(), prim.GetPath()) for a *valid* ``prim`` , but will not immediately throw an error for an invalid ``prim`` Parameters ---------- prim : Prim ---------------------------------------------------------------------- __init__(schemaObj) Construct a UsdGeomVisibilityAPI on the prim held by ``schemaObj`` . Should be preferred over UsdGeomVisibilityAPI (schemaObj.GetPrim()), as it preserves SchemaBase state. Parameters ---------- schemaObj : SchemaBase """ result["VisibilityAPI"].GetGuideVisibilityAttr.func_doc = """GetGuideVisibilityAttr() -> Attribute This attribute controls visibility for geometry with purpose"guide". Unlike overall *visibility*, *guideVisibility* is uniform, and therefore cannot be animated. Also unlike overall *visibility*, *guideVisibility* is tri-state, in that a descendant with an opinion of"visible"overrides an ancestor opinion of"invisible". The *guideVisibility* attribute works in concert with the overall *visibility* attribute: The visibility of a prim with purpose"guide"is determined by the inherited values it receives for the *visibility* and *guideVisibility* attributes. If *visibility* evaluates to"invisible", the prim is invisible. If *visibility* evaluates to"inherited"and *guideVisibility* evaluates to"visible", then the prim is visible. **Otherwise, it is invisible.** Declaration ``uniform token guideVisibility ="invisible"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values inherited, invisible, visible """ result["VisibilityAPI"].CreateGuideVisibilityAttr.func_doc = """CreateGuideVisibilityAttr(defaultValue, writeSparsely) -> Attribute See GetGuideVisibilityAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["VisibilityAPI"].GetProxyVisibilityAttr.func_doc = """GetProxyVisibilityAttr() -> Attribute This attribute controls visibility for geometry with purpose"proxy". Unlike overall *visibility*, *proxyVisibility* is uniform, and therefore cannot be animated. Also unlike overall *visibility*, *proxyVisibility* is tri-state, in that a descendant with an opinion of"visible"overrides an ancestor opinion of"invisible". The *proxyVisibility* attribute works in concert with the overall *visibility* attribute: The visibility of a prim with purpose"proxy"is determined by the inherited values it receives for the *visibility* and *proxyVisibility* attributes. If *visibility* evaluates to"invisible", the prim is invisible. If *visibility* evaluates to"inherited"then: If *proxyVisibility* evaluates to"visible", then the prim is visible; if *proxyVisibility* evaluates to"invisible", then the prim is invisible; if *proxyVisibility* evaluates to"inherited", then the prim may either be visible or invisible, depending on a fallback value determined by the calling context. Declaration ``uniform token proxyVisibility ="inherited"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values inherited, invisible, visible """ result["VisibilityAPI"].CreateProxyVisibilityAttr.func_doc = """CreateProxyVisibilityAttr(defaultValue, writeSparsely) -> Attribute See GetProxyVisibilityAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["VisibilityAPI"].GetRenderVisibilityAttr.func_doc = """GetRenderVisibilityAttr() -> Attribute This attribute controls visibility for geometry with purpose"render". Unlike overall *visibility*, *renderVisibility* is uniform, and therefore cannot be animated. Also unlike overall *visibility*, *renderVisibility* is tri-state, in that a descendant with an opinion of"visible"overrides an ancestor opinion of"invisible". The *renderVisibility* attribute works in concert with the overall *visibility* attribute: The visibility of a prim with purpose"render"is determined by the inherited values it receives for the *visibility* and *renderVisibility* attributes. If *visibility* evaluates to"invisible", the prim is invisible. If *visibility* evaluates to"inherited"then: If *renderVisibility* evaluates to"visible", then the prim is visible; if *renderVisibility* evaluates to"invisible", then the prim is invisible; if *renderVisibility* evaluates to"inherited", then the prim may either be visible or invisible, depending on a fallback value determined by the calling context. Declaration ``uniform token renderVisibility ="inherited"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values inherited, invisible, visible """ result["VisibilityAPI"].CreateRenderVisibilityAttr.func_doc = """CreateRenderVisibilityAttr(defaultValue, writeSparsely) -> Attribute See GetRenderVisibilityAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["VisibilityAPI"].GetPurposeVisibilityAttr.func_doc = """GetPurposeVisibilityAttr(purpose) -> Attribute Return the attribute that is used for expressing visibility opinions for the given ``purpose`` . The valid purpose tokens are"guide","proxy", and"render"which return the attributes *guideVisibility*, *proxyVisibility*, and *renderVisibility* respectively. Note that while"default"is a valid purpose token for UsdGeomImageable::GetPurposeVisibilityAttr, it is not a valid purpose for this function, as UsdGeomVisibilityAPI itself does not have a default visibility attribute. Calling this function with "default will result in a coding error. Parameters ---------- purpose : str """ result["VisibilityAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ result["VisibilityAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> VisibilityAPI Return a UsdGeomVisibilityAPI holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomVisibilityAPI(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ result["VisibilityAPI"].CanApply.func_doc = """**classmethod** CanApply(prim, whyNot) -> bool Returns true if this **single-apply** API schema can be applied to the given ``prim`` . If this schema can not be a applied to the prim, this returns false and, if provided, populates ``whyNot`` with the reason it can not be applied. Note that if CanApply returns false, that does not necessarily imply that calling Apply will fail. Callers are expected to call CanApply before calling Apply if they want to ensure that it is valid to apply a schema. UsdPrim::GetAppliedSchemas() UsdPrim::HasAPI() UsdPrim::CanApplyAPI() UsdPrim::ApplyAPI() UsdPrim::RemoveAPI() Parameters ---------- prim : Prim whyNot : str """ result["VisibilityAPI"].Apply.func_doc = """**classmethod** Apply(prim) -> VisibilityAPI Applies this **single-apply** API schema to the given ``prim`` . This information is stored by adding"VisibilityAPI"to the token- valued, listOp metadata *apiSchemas* on the prim. A valid UsdGeomVisibilityAPI object is returned upon success. An invalid (or empty) UsdGeomVisibilityAPI object is returned upon failure. See UsdPrim::ApplyAPI() for conditions resulting in failure. UsdPrim::GetAppliedSchemas() UsdPrim::HasAPI() UsdPrim::CanApplyAPI() UsdPrim::ApplyAPI() UsdPrim::RemoveAPI() Parameters ---------- prim : Prim """ result["VisibilityAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type """ result["Xform"].__doc__ = """ Concrete prim schema for a transform, which implements Xformable """ result["Xform"].__init__.func_doc = """__init__(prim) Construct a UsdGeomXform on UsdPrim ``prim`` . Equivalent to UsdGeomXform::Get (prim.GetStage(), prim.GetPath()) for a *valid* ``prim`` , but will not immediately throw an error for an invalid ``prim`` Parameters ---------- prim : Prim ---------------------------------------------------------------------- __init__(schemaObj) Construct a UsdGeomXform on the prim held by ``schemaObj`` . Should be preferred over UsdGeomXform (schemaObj.GetPrim()), as it preserves SchemaBase state. Parameters ---------- schemaObj : SchemaBase """ result["Xform"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ result["Xform"].Get.func_doc = """**classmethod** Get(stage, path) -> Xform Return a UsdGeomXform holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomXform(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ result["Xform"].Define.func_doc = """**classmethod** Define(stage, path) -> Xform Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ result["Xform"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type """ result["Xformable"].__doc__ = """ Base class for all transformable prims, which allows arbitrary sequences of component affine transformations to be encoded. You may find it useful to review Linear Algebra in UsdGeom while reading this class description. **Supported Component Transformation Operations** UsdGeomXformable currently supports arbitrary sequences of the following operations, each of which can be encoded in an attribute of the proper shape in any supported precision: - translate - 3D - scale - 3D - rotateX - 1D angle in degrees - rotateY - 1D angle in degrees - rotateZ - 1D angle in degrees - rotateABC - 3D where ABC can be any combination of the six principle Euler Angle sets: XYZ, XZY, YXZ, YZX, ZXY, ZYX. See note on rotation packing order - orient - 4D (quaternion) - transform - 4x4D **Creating a Component Transformation** To add components to a UsdGeomXformable prim, simply call AddXformOp() with the desired op type, as enumerated in UsdGeomXformOp::Type, and the desired precision, which is one of UsdGeomXformOp::Precision. Optionally, you can also provide an"op suffix"for the operator that disambiguates it from other components of the same type on the same prim. Application-specific transform schemas can use the suffixes to fill a role similar to that played by AbcGeom::XformOp's"Hint"enums for their own round-tripping logic. We also provide specific"Add"API for each type, for clarity and conciseness, e.g. AddTranslateOp() , AddRotateXYZOp() etc. AddXformOp() will return a UsdGeomXformOp object, which is a schema on a newly created UsdAttribute that provides convenience API for authoring and computing the component transformations. The UsdGeomXformOp can then be used to author any number of timesamples and default for the op. Each successive call to AddXformOp() adds an operator that will be applied"more locally"than the preceding operator, just as if we were pushing transforms onto a transformation stack - which is precisely what should happen when the operators are consumed by a reader. If you can, please try to use the UsdGeomXformCommonAPI, which wraps the UsdGeomXformable with an interface in which Op creation is taken care of for you, and there is a much higher chance that the data you author will be importable without flattening into other DCC's, as it conforms to a fixed set of Scale-Rotate-Translate Ops. Using the Authoring API **Data Encoding and Op Ordering** Because there is no"fixed schema"of operations, all of the attributes that encode transform operations are dynamic, and are scoped in the namespace"xformOp". The second component of an attribute's name provides the *type* of operation, as listed above. An"xformOp"attribute can have additional namespace components derived from the *opSuffix* argument to the AddXformOp() suite of methods, which provides a preferred way of naming the ops such that we can have multiple"translate"ops with unique attribute names. For example, in the attribute named"xformOp:translate:maya:pivot","translate"is the type of operation and"maya:pivot"is the suffix. The following ordered list of attribute declarations in usda define a basic Scale-Rotate-Translate with XYZ Euler angles, wherein the translation is double-precision, and the remainder of the ops are single, in which we will: - Scale by 2.0 in each dimension - Rotate about the X, Y, and Z axes by 30, 60, and 90 degrees, respectively - Translate by 100 units in the Y direction .. code-block:: text float3 xformOp:rotateXYZ = (30, 60, 90) float3 xformOp:scale = (2, 2, 2) double3 xformOp:translate = (0, 100, 0) uniform token[] xformOpOrder = [ "xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale" ] The attributes appear in the dictionary order in which USD, by default, sorts them. To ensure the ops are recovered and evaluated in the correct order, the schema introduces the **xformOpOrder** attribute, which contains the names of the op attributes, in the precise sequence in which they should be pushed onto a transform stack. **Note** that the order is opposite to what you might expect, given the matrix algebra described in Linear Algebra in UsdGeom. This also dictates order of op creation, since each call to AddXformOp() adds a new op to the end of the **xformOpOrder** array, as a new"most- local"operation. See Example 2 below for C++ code that could have produced this USD. If it were important for the prim's rotations to be independently overridable, we could equivalently (at some performance cost) encode the transformation also like so: .. code-block:: text float xformOp:rotateX = 30 float xformOp:rotateY = 60 float xformOp:rotateZ = 90 float3 xformOp:scale = (2, 2, 2) double3 xformOp:translate = (0, 100, 0) uniform token[] xformOpOrder = [ "xformOp:translate", "xformOp:rotateZ", "xformOp:rotateY", "xformOp:rotateX", "xformOp:scale" ] Again, note that although we are encoding an XYZ rotation, the three rotations appear in the **xformOpOrder** in the opposite order, with Z, followed, by Y, followed by X. Were we to add a Maya-style scalePivot to the above example, it might look like the following: .. code-block:: text float3 xformOp:rotateXYZ = (30, 60, 90) float3 xformOp:scale = (2, 2, 2) double3 xformOp:translate = (0, 100, 0) double3 xformOp:translate:scalePivot uniform token[] xformOpOrder = [ "xformOp:translate", "xformOp:rotateXYZ", "xformOp:translate:scalePivot", "xformOp:scale" ] **Paired"Inverted"Ops** We have been claiming that the ordered list of ops serves as a set of instructions to a transform stack, but you may have noticed in the last example that there is a missing operation - the pivot for the scale op needs to be applied in its inverse-form as a final (most local) op! In the AbcGeom::Xform schema, we would have encoded an actual"final"translation op whose value was authored by the exporter as the negation of the pivot's value. However, doing so would be brittle in USD, given that each op can be independently overridden, and the constraint that one attribute must be maintained as the negation of the other in order for successful re-importation of the schema cannot be expressed in USD. Our solution leverages the **xformOpOrder** member of the schema, which, in addition to ordering the ops, may also contain one of two special tokens that address the paired op and"stack resetting"behavior. The"paired op"behavior is encoded as an"!invert!"prefix in **xformOpOrder**, as the result of an AddXformOp(isInverseOp=True) call. The **xformOpOrder** for the last example would look like: .. code-block:: text uniform token[] xformOpOrder = [ "xformOp:translate", "xformOp:rotateXYZ", "xformOp:translate:scalePivot", "xformOp:scale", "!invert!xformOp:translate:scalePivot" ] When asked for its value via UsdGeomXformOp::GetOpTransform() , an"inverted"Op (i.e. the"inverted"half of a set of paired Ops) will fetch the value of its paired attribute and return its negation. This works for all op types - an error will be issued if a"transform"type op is singular and cannot be inverted. When getting the authored value of an inverted op via UsdGeomXformOp::Get() , the raw, uninverted value of the associated attribute is returned. For the sake of robustness, **setting a value on an inverted op is disallowed.** Attempting to set a value on an inverted op will result in a coding error and no value being set. **Resetting the Transform Stack** The other special op/token that can appear in *xformOpOrder* is *"!resetXformStack!"*, which, appearing as the first element of *xformOpOrder*, indicates this prim should not inherit the transformation of its namespace parent. See SetResetXformStack() **Expected Behavior for"Missing"Ops** If an importer expects Scale-Rotate-Translate operations, but a prim has only translate and rotate ops authored, the importer should assume an identity scale. This allows us to optimize the data a bit, if only a few components of a very rich schema (like Maya's) are authored in the app. **Using the C++ API** #1. Creating a simple transform matrix encoding .. code-block:: text #2. Creating the simple SRT from the example above .. code-block:: text #3. Creating a parameterized SRT with pivot using UsdGeomXformCommonAPI .. code-block:: text #4. Creating a rotate-only pivot transform with animated rotation and translation .. code-block:: text """ result["Xformable"].__init__.func_doc = """__init__(prim) Construct a UsdGeomXformable on UsdPrim ``prim`` . Equivalent to UsdGeomXformable::Get (prim.GetStage(), prim.GetPath()) for a *valid* ``prim`` , but will not immediately throw an error for an invalid ``prim`` Parameters ---------- prim : Prim ---------------------------------------------------------------------- __init__(schemaObj) Construct a UsdGeomXformable on the prim held by ``schemaObj`` . Should be preferred over UsdGeomXformable (schemaObj.GetPrim()), as it preserves SchemaBase state. Parameters ---------- schemaObj : SchemaBase """ result["Xformable"].GetXformOpOrderAttr.func_doc = """GetXformOpOrderAttr() -> Attribute Encodes the sequence of transformation operations in the order in which they should be pushed onto a transform stack while visiting a UsdStage 's prims in a graph traversal that will effect the desired positioning for this prim and its descendant prims. You should rarely, if ever, need to manipulate this attribute directly. It is managed by the AddXformOp() , SetResetXformStack() , and SetXformOpOrder() , and consulted by GetOrderedXformOps() and GetLocalTransformation() . Declaration ``uniform token[] xformOpOrder`` C++ Type VtArray<TfToken> Usd Type SdfValueTypeNames->TokenArray Variability SdfVariabilityUniform """ result["Xformable"].CreateXformOpOrderAttr.func_doc = """CreateXformOpOrderAttr(defaultValue, writeSparsely) -> Attribute See GetXformOpOrderAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["Xformable"].AddXformOp.func_doc = """AddXformOp(opType, precision, opSuffix, isInverseOp) -> XformOp Add an affine transformation to the local stack represented by this Xformable. This will fail if there is already a transform operation of the same name in the ordered ops on this prim (i.e. as returned by GetOrderedXformOps() ), or if an op of the same name exists at all on the prim with a different precision than that specified. The newly created operation will become the most-locally applied transformation on the prim, and will appear last in the list returned by GetOrderedXformOps() . It is OK to begin authoring values to the returned UsdGeomXformOp immediately, interspersed with subsequent calls to AddXformOp() - just note the order of application, which *can* be changed at any time (and in stronger layers) via SetXformOpOrder() . opType is the type of transform operation, one of UsdGeomXformOp::Type. precision allows you to specify the precision with which you desire to encode the data. This should be one of the values in the enum UsdGeomXformOp::Precision. opSuffix allows you to specify the purpose/meaning of the op in the stack. When opSuffix is specified, the associated attribute's name is set to"xformOp:<opType>:<opSuffix>". isInverseOp is used to indicate an inverse transformation operation. a UsdGeomXformOp that can be used to author to the operation. An error is issued and the returned object will be invalid (evaluate to false) if the op being added already exists in xformOpOrder or if the arguments supplied are invalid. If the attribute associated with the op already exists, but isn't of the requested precision, a coding error is issued, but a valid xformOp is returned with the existing attribute. Parameters ---------- opType : XformOp.Type precision : XformOp.Precision opSuffix : str isInverseOp : bool """ result["Xformable"].AddTranslateOp.func_doc = """AddTranslateOp(precision, opSuffix, isInverseOp) -> XformOp Add a translate operation to the local stack represented by this xformable. AddXformOp() Parameters ---------- precision : XformOp.Precision opSuffix : str isInverseOp : bool """ result["Xformable"].AddScaleOp.func_doc = """AddScaleOp(precision, opSuffix, isInverseOp) -> XformOp Add a scale operation to the local stack represented by this xformable. AddXformOp() Parameters ---------- precision : XformOp.Precision opSuffix : str isInverseOp : bool """ result["Xformable"].AddRotateXOp.func_doc = """AddRotateXOp(precision, opSuffix, isInverseOp) -> XformOp Add a rotation about the X-axis to the local stack represented by this xformable. Set the angle value of the resulting UsdGeomXformOp **in degrees** AddXformOp() Parameters ---------- precision : XformOp.Precision opSuffix : str isInverseOp : bool """ result["Xformable"].AddRotateYOp.func_doc = """AddRotateYOp(precision, opSuffix, isInverseOp) -> XformOp Add a rotation about the YX-axis to the local stack represented by this xformable. Set the angle value of the resulting UsdGeomXformOp **in degrees** AddXformOp() Parameters ---------- precision : XformOp.Precision opSuffix : str isInverseOp : bool """ result["Xformable"].AddRotateZOp.func_doc = """AddRotateZOp(precision, opSuffix, isInverseOp) -> XformOp Add a rotation about the Z-axis to the local stack represented by this xformable. AddXformOp() Parameters ---------- precision : XformOp.Precision opSuffix : str isInverseOp : bool """ result["Xformable"].AddRotateXYZOp.func_doc = """AddRotateXYZOp(precision, opSuffix, isInverseOp) -> XformOp Add a rotation op with XYZ rotation order to the local stack represented by this xformable. Set the angle value of the resulting UsdGeomXformOp **in degrees** AddXformOp() , note on angle packing order Parameters ---------- precision : XformOp.Precision opSuffix : str isInverseOp : bool """ result["Xformable"].AddRotateXZYOp.func_doc = """AddRotateXZYOp(precision, opSuffix, isInverseOp) -> XformOp Add a rotation op with XZY rotation order to the local stack represented by this xformable. Set the angle values of the resulting UsdGeomXformOp **in degrees** AddXformOp() , note on angle packing order Parameters ---------- precision : XformOp.Precision opSuffix : str isInverseOp : bool """ result["Xformable"].AddRotateYXZOp.func_doc = """AddRotateYXZOp(precision, opSuffix, isInverseOp) -> XformOp Add a rotation op with YXZ rotation order to the local stack represented by this xformable. Set the angle values of the resulting UsdGeomXformOp **in degrees** AddXformOp() , note on angle packing order Parameters ---------- precision : XformOp.Precision opSuffix : str isInverseOp : bool """ result["Xformable"].AddRotateYZXOp.func_doc = """AddRotateYZXOp(precision, opSuffix, isInverseOp) -> XformOp Add a rotation op with YZX rotation order to the local stack represented by this xformable. Set the angle values of the resulting UsdGeomXformOp **in degrees** AddXformOp() , note on angle packing order Parameters ---------- precision : XformOp.Precision opSuffix : str isInverseOp : bool """ result["Xformable"].AddRotateZXYOp.func_doc = """AddRotateZXYOp(precision, opSuffix, isInverseOp) -> XformOp Add a rotation op with ZXY rotation order to the local stack represented by this xformable. Set the angle values of the resulting UsdGeomXformOp **in degrees** AddXformOp() , note on angle packing order Parameters ---------- precision : XformOp.Precision opSuffix : str isInverseOp : bool """ result["Xformable"].AddRotateZYXOp.func_doc = """AddRotateZYXOp(precision, opSuffix, isInverseOp) -> XformOp Add a rotation op with ZYX rotation order to the local stack represented by this xformable. Set the angle values of the resulting UsdGeomXformOp **in degrees** AddXformOp() , note on angle packing order Parameters ---------- precision : XformOp.Precision opSuffix : str isInverseOp : bool """ result["Xformable"].AddOrientOp.func_doc = """AddOrientOp(precision, opSuffix, isInverseOp) -> XformOp Add a orient op (arbitrary axis/angle rotation) to the local stack represented by this xformable. AddXformOp() Parameters ---------- precision : XformOp.Precision opSuffix : str isInverseOp : bool """ result["Xformable"].AddTransformOp.func_doc = """AddTransformOp(precision, opSuffix, isInverseOp) -> XformOp Add a tranform op (4x4 matrix transformation) to the local stack represented by this xformable. AddXformOp() Note: This method takes a precision argument only to be consistent with the other types of xformOps. The only valid precision here is double since matrix values cannot be encoded in floating-pt precision in Sdf. Parameters ---------- precision : XformOp.Precision opSuffix : str isInverseOp : bool """ result["Xformable"].SetResetXformStack.func_doc = """SetResetXformStack(resetXform) -> bool Specify whether this prim's transform should reset the transformation stack inherited from its parent prim. By default, parent transforms are inherited. SetResetXformStack() can be called at any time during authoring, but will always add a'!resetXformStack!'op as the *first* op in the ordered list, if one does not exist already. If one already exists, and ``resetXform`` is false, it will remove all ops upto and including the last"!resetXformStack!"op. Parameters ---------- resetXform : bool """ result["Xformable"].GetResetXformStack.func_doc = """GetResetXformStack() -> bool Does this prim reset its parent's inherited transformation? Returns true if"!resetXformStack!"appears *anywhere* in xformOpOrder. When this returns true, all ops upto the last"!resetXformStack!"in xformOpOrder are ignored when computing the local transformation. """ result["Xformable"].SetXformOpOrder.func_doc = """SetXformOpOrder(orderedXformOps, resetXformStack) -> bool Reorder the already-existing transform ops on this prim. All elements in ``orderedXformOps`` must be valid and represent attributes on this prim. Note that it is *not* required that all the existing operations be present in ``orderedXformOps`` , so this method can be used to completely change the transformation structure applied to the prim. If ``resetXformStack`` is set to true, then "!resetXformOp! will be set as the first op in xformOpOrder, to indicate that the prim does not inherit its parent's transformation. If you wish to re-specify a prim's transformation completely in a stronger layer, you should first call this method with an *empty* ``orderedXformOps`` vector. From there you can call AddXformOp() just as if you were authoring to the prim from scratch. false if any of the elements of ``orderedXformOps`` are not extant on this prim, or if an error occurred while authoring the ordering metadata. Under either condition, no scene description is authored. GetOrderedXformOps() Parameters ---------- orderedXformOps : list[XformOp] resetXformStack : bool """ result["Xformable"].ClearXformOpOrder.func_doc = """ClearXformOpOrder() -> bool Clears the local transform stack. """ result["Xformable"].MakeMatrixXform.func_doc = """MakeMatrixXform() -> XformOp Clears the existing local transform stack and creates a new xform op of type'transform'. This API is provided for convenience since this is the most common xform authoring operation. ClearXformOpOrder() AddTransformOp() """ result["Xformable"].TransformMightBeTimeVarying.func_doc = """TransformMightBeTimeVarying() -> bool Determine whether there is any possibility that this prim's *local* transformation may vary over time. The determination is based on a snapshot of the authored state of the op attributes on the prim, and may become invalid in the face of further authoring. ---------------------------------------------------------------------- TransformMightBeTimeVarying(ops) -> bool This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Determine whether there is any possibility that this prim's *local* transformation may vary over time, using a pre-fetched (cached) list of ordered xform ops supplied by the client. The determination is based on a snapshot of the authored state of the op attributes on the prim, and may become invalid in the face of further authoring. Parameters ---------- ops : list[XformOp] """ result["Xformable"].GetTimeSamples.func_doc = """**classmethod** GetTimeSamples(times) -> bool Sets ``times`` to the union of all the timesamples at which xformOps that are included in the xformOpOrder attribute are authored. This clears the ``times`` vector before accumulating sample times from all the xformOps. UsdAttribute::GetTimeSamples Parameters ---------- times : list[float] ---------------------------------------------------------------------- GetTimeSamples(orderedXformOps, times) -> bool Returns the union of all the timesamples at which the attributes belonging to the given ``orderedXformOps`` are authored. This clears the ``times`` vector before accumulating sample times from ``orderedXformOps`` . UsdGeomXformable::GetTimeSamples Parameters ---------- orderedXformOps : list[XformOp] times : list[float] """ result["Xformable"].GetTimeSamplesInInterval.func_doc = """**classmethod** GetTimeSamplesInInterval(interval, times) -> bool Sets ``times`` to the union of all the timesamples in the interval, ``interval`` , at which xformOps that are included in the xformOpOrder attribute are authored. This clears the ``times`` vector before accumulating sample times from all the xformOps. UsdAttribute::GetTimeSamples Parameters ---------- interval : Interval times : list[float] ---------------------------------------------------------------------- GetTimeSamplesInInterval(orderedXformOps, interval, times) -> bool Returns the union of all the timesamples in the ``interval`` at which the attributes belonging to the given ``orderedXformOps`` are authored. This clears the ``times`` vector before accumulating sample times from ``orderedXformOps`` . UsdGeomXformable::GetTimeSamplesInInterval Parameters ---------- orderedXformOps : list[XformOp] interval : Interval times : list[float] """ result["Xformable"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ result["Xformable"].Get.func_doc = """**classmethod** Get(stage, path) -> Xformable Return a UsdGeomXformable holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomXformable(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ result["Xformable"].IsTransformationAffectedByAttrNamed.func_doc = """**classmethod** IsTransformationAffectedByAttrNamed(attrName) -> bool Returns true if the attribute named ``attrName`` could affect the local transformation of an xformable prim. Parameters ---------- attrName : str """ result["Xformable"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type """ result["XformCache"].__doc__ = """ A caching mechanism for transform matrices. For best performance, this object should be reused for multiple CTM queries. Instances of this type can be copied, though using Swap() may result in better performance. It is valid to cache prims from multiple stages in a single XformCache. WARNING: this class does not automatically invalidate cached values based on changes to the stage from which values were cached. Additionally, a separate instance of this class should be used per- thread, calling the Get\\* methods from multiple threads is not safe, as they mutate internal state. """ result["XformCache"].__init__.func_doc = """__init__(time) Construct a new XformCache for the specified ``time`` . Parameters ---------- time : TimeCode ---------------------------------------------------------------------- __init__() Construct a new XformCache for UsdTimeCode::Default() . """ result["XformCache"].GetLocalToWorldTransform.func_doc = """GetLocalToWorldTransform(prim) -> Matrix4d Compute the transformation matrix for the given ``prim`` , including the transform authored on the Prim itself, if present. This method may mutate internal cache state and is not thread safe. Parameters ---------- prim : Prim """ result["XformCache"].GetParentToWorldTransform.func_doc = """GetParentToWorldTransform(prim) -> Matrix4d Compute the transformation matrix for the given ``prim`` , but do NOT include the transform authored on the prim itself. This method may mutate internal cache state and is not thread safe. Parameters ---------- prim : Prim """ result["XformCache"].GetLocalTransformation.func_doc = """GetLocalTransformation(prim, resetsXformStack) -> Matrix4d Returns the local transformation of the prim. Uses the cached XformQuery to compute the result quickly. The ``resetsXformStack`` pointer must be valid. It will be set to true if ``prim`` resets the transform stack. The result of this call is cached. Parameters ---------- prim : Prim resetsXformStack : bool """ result["XformCache"].ComputeRelativeTransform.func_doc = """ComputeRelativeTransform(prim, ancestor, resetXformStack) -> Matrix4d Returns the result of concatenating all transforms beneath ``ancestor`` that affect ``prim`` . This includes the local transform of ``prim`` itself, but not the local transform of ``ancestor`` . If ``ancestor`` is not an ancestor of ``prim`` , the resulting transform is the local-to-world transformation of ``prim`` . The ``resetXformTsack`` pointer must be valid. If any intermediate prims reset the transform stack, ``resetXformStack`` will be set to true. Intermediate transforms are cached, but the result of this call itself is not cached. Parameters ---------- prim : Prim ancestor : Prim resetXformStack : bool """ result["XformCache"].Clear.func_doc = """Clear() -> None Clears all pre-cached values. """ result["XformCache"].SetTime.func_doc = """SetTime(time) -> None Use the new ``time`` when computing values and may clear any existing values cached for the previous time. Setting ``time`` to the current time is a no-op. Parameters ---------- time : TimeCode """ result["XformCache"].GetTime.func_doc = """GetTime() -> TimeCode Get the current time from which this cache is reading values. """ result["XformCache"].Swap.func_doc = """Swap(other) -> None Swap the contents of this XformCache with ``other`` . Parameters ---------- other : XformCache """ result["XformCommonAPI"].__doc__ = """ This class provides API for authoring and retrieving a standard set of component transformations which include a scale, a rotation, a scale- rotate pivot and a translation. The goal of the API is to enhance component-wise interchange. It achieves this by limiting the set of allowed basic ops and by specifying the order in which they are applied. In addition to the basic set of ops, the'resetXformStack'bit can also be set to indicate whether the underlying xformable resets the parent transformation (i.e. does not inherit it's parent's transformation). UsdGeomXformCommonAPI::GetResetXformStack() UsdGeomXformCommonAPI::SetResetXformStack() The operator-bool for the class will inform you whether an existing xformable is compatible with this API. The scale-rotate pivot is represented by a pair of (translate, inverse-translate) xformOps around the scale and rotate operations. The rotation operation can be any of the six allowed Euler angle sets. UsdGeomXformOp::Type. The xformOpOrder of an xformable that has all of the supported basic ops is as follows: ["xformOp:translate","xformOp:translate:pivot","xformOp:rotateXYZ","xformOp:scale","!invert!xformOp:translate:pivot"]. It is worth noting that all of the ops are optional. For example, an xformable may have only a translate or a rotate. It would still be considered as compatible with this API. Individual SetTranslate() , SetRotate() , SetScale() and SetPivot() methods are provided by this API to allow such sparse authoring. """ result["XformCommonAPI"].SetTranslate.func_doc = """SetTranslate(translation, time) -> bool Set translation at ``time`` to ``translation`` . Parameters ---------- translation : Vec3d time : TimeCode """ result["XformCommonAPI"].SetPivot.func_doc = """SetPivot(pivot, time) -> bool Set pivot position at ``time`` to ``pivot`` . Parameters ---------- pivot : Vec3f time : TimeCode """ result["XformCommonAPI"].SetRotate.func_doc = """SetRotate(rotation, rotOrder, time) -> bool Set rotation at ``time`` to ``rotation`` . Parameters ---------- rotation : Vec3f rotOrder : XformCommonAPI.RotationOrder time : TimeCode """ result["XformCommonAPI"].SetScale.func_doc = """SetScale(scale, time) -> bool Set scale at ``time`` to ``scale`` . Parameters ---------- scale : Vec3f time : TimeCode """ result["XformCommonAPI"].SetResetXformStack.func_doc = """SetResetXformStack(resetXformStack) -> bool Set whether the xformable resets the transform stack. i.e., does not inherit the parent transformation. Parameters ---------- resetXformStack : bool """ result["XformCommonAPI"].CreateXformOps.func_doc = """CreateXformOps(rotOrder, op1, op2, op3, op4) -> Ops Creates the specified XformCommonAPI-compatible xform ops, or returns the existing ops if they already exist. If successful, returns an Ops object with all the ops on this prim, identified by type. If the requested xform ops couldn't be created or the prim is not XformCommonAPI-compatible, returns an Ops object with all invalid ops. The ``rotOrder`` is only used if OpRotate is specified. Otherwise, it is ignored. (If you don't need to create a rotate op, you might find it helpful to use the other overload that takes no rotation order.) Parameters ---------- rotOrder : RotationOrder op1 : OpFlags op2 : OpFlags op3 : OpFlags op4 : OpFlags ---------------------------------------------------------------------- CreateXformOps(op1, op2, op3, op4) -> Ops This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. This overload does not take a rotation order. If you specify OpRotate, then this overload assumes RotationOrderXYZ or the previously-authored rotation order. (If you do need to create a rotate op, you might find it helpful to use the other overload that explicitly takes a rotation order.) Parameters ---------- op1 : OpFlags op2 : OpFlags op3 : OpFlags op4 : OpFlags """ result["XformCommonAPI"].GetRotationTransform.func_doc = """**classmethod** GetRotationTransform(rotation, rotationOrder) -> Matrix4d Return the 4x4 matrix that applies the rotation encoded by rotation vector ``rotation`` using the rotation order ``rotationOrder`` . Deprecated Please use the result of ConvertRotationOrderToOpType() along with UsdGeomXformOp::GetOpTransform() instead. Parameters ---------- rotation : Vec3f rotationOrder : XformCommonAPI.RotationOrder """ result["XformCommonAPI"].RotationOrder.__doc__ = """ Enumerates the rotation order of the 3-angle Euler rotation. """ result["XformCommonAPI"].OpFlags.__doc__ = """ Enumerates the categories of ops that can be handled by XformCommonAPI. For use with CreateXformOps() . """ result["XformCommonAPI"].__init__.func_doc = """__init__(prim) Construct a UsdGeomXformCommonAPI on UsdPrim ``prim`` . Equivalent to UsdGeomXformCommonAPI::Get (prim.GetStage(), prim.GetPath()) for a *valid* ``prim`` , but will not immediately throw an error for an invalid ``prim`` Parameters ---------- prim : Prim ---------------------------------------------------------------------- __init__(schemaObj) Construct a UsdGeomXformCommonAPI on the prim held by ``schemaObj`` . Should be preferred over UsdGeomXformCommonAPI (schemaObj.GetPrim()), as it preserves SchemaBase state. Parameters ---------- schemaObj : SchemaBase """ result["XformCommonAPI"].SetXformVectors.func_doc = """SetXformVectors(translation, rotation, scale, pivot, rotOrder, time) -> bool Set values for the various component xformOps at a given ``time`` . Calling this method will call all of the supported ops to be created, even if they only contain default (identity) values. To author individual operations selectively, use the Set[OpType]() API. Once the rotation order has been established for a given xformable (either because of an already defined (and compatible) rotate op or from calling SetXformVectors() or SetRotate() ), it cannot be changed. Parameters ---------- translation : Vec3d rotation : Vec3f scale : Vec3f pivot : Vec3f rotOrder : RotationOrder time : TimeCode """ result["XformCommonAPI"].GetXformVectors.func_doc = """GetXformVectors(translation, rotation, scale, pivot, rotOrder, time) -> bool Retrieve values of the various component xformOps at a given ``time`` . Identity values are filled in for the component xformOps that don't exist or don't have an authored value. This method works even on prims with an incompatible xform schema, i.e. when the bool operator returns false. When the underlying xformable has an incompatible xform schema, it performs a full-on matrix decomposition to XYZ rotation order. Parameters ---------- translation : Vec3d rotation : Vec3f scale : Vec3f pivot : Vec3f rotOrder : RotationOrder time : TimeCode """ result["XformCommonAPI"].GetXformVectorsByAccumulation.func_doc = """GetXformVectorsByAccumulation(translation, rotation, scale, pivot, rotOrder, time) -> bool Retrieve values of the various component xformOps at a given ``time`` . Identity values are filled in for the component xformOps that don't exist or don't have an authored value. This method allows some additional flexibility for xform schemas that do not strictly adhere to the xformCommonAPI. For incompatible schemas, this method will attempt to reduce the schema into one from which component vectors can be extracted by accumulating xformOp transforms of the common types. When the underlying xformable has a compatible xform schema, the usual component value extraction method is used instead. When the xform schema is incompatible and it cannot be reduced by accumulating transforms, it performs a full-on matrix decomposition to XYZ rotation order. Parameters ---------- translation : Vec3d rotation : Vec3f scale : Vec3f pivot : Vec3f rotOrder : XformCommonAPI.RotationOrder time : TimeCode """ result["XformCommonAPI"].GetResetXformStack.func_doc = """GetResetXformStack() -> bool Returns whether the xformable resets the transform stack. i.e., does not inherit the parent transformation. """ result["XformCommonAPI"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ result["XformCommonAPI"].Get.func_doc = """**classmethod** Get(stage, path) -> XformCommonAPI Return a UsdGeomXformCommonAPI holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomXformCommonAPI(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ result["XformCommonAPI"].ConvertRotationOrderToOpType.func_doc = """**classmethod** ConvertRotationOrderToOpType(rotOrder) -> XformOp.Type Converts the given ``rotOrder`` to the corresponding value in the UsdGeomXformOp::Type enum. For example, RotationOrderYZX corresponds to TypeRotateYZX. Raises a coding error if ``rotOrder`` is not one of the named enumerators of RotationOrder. Parameters ---------- rotOrder : RotationOrder """ result["XformCommonAPI"].ConvertOpTypeToRotationOrder.func_doc = """**classmethod** ConvertOpTypeToRotationOrder(opType) -> RotationOrder Converts the given ``opType`` to the corresponding value in the UsdGeomXformCommonAPI::RotationOrder enum. For example, TypeRotateYZX corresponds to RotationOrderYZX. Raises a coding error if ``opType`` is not convertible to RotationOrder (i.e., if it isn't a three-axis rotation) and returns the default RotationOrderXYZ instead. Parameters ---------- opType : XformOp.Type """ result["XformCommonAPI"].CanConvertOpTypeToRotationOrder.func_doc = """**classmethod** CanConvertOpTypeToRotationOrder(opType) -> bool Whether the given ``opType`` has a corresponding value in the UsdGeomXformCommonAPI::RotationOrder enum (i.e., whether it is a three-axis rotation). Parameters ---------- opType : XformOp.Type """ result["XformCommonAPI"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type """ result["XformOp"].__doc__ = """ Schema wrapper for UsdAttribute for authoring and computing transformation operations, as consumed by UsdGeomXformable schema. The semantics of an op are determined primarily by its name, which allows us to decode an op very efficiently. All ops are independent attributes, which must live in the"xformOp"property namespace. The op's primary name within the namespace must be one of UsdGeomXformOpTypes, which determines the type of transformation operation, and its secondary name (or suffix) within the namespace (which is not required to exist), can be any name that distinguishes it from other ops of the same type. Suffixes are generally imposed by higer level xform API schemas. **On packing order of rotateABC triples** The order in which the axis rotations are recorded in a Vec3\\* for the six *rotateABC* Euler triples **is always the same:** vec[0] = X, vec[1] = Y, vec[2] = Z. The *A*, *B*, *C* in the op name dictate the order in which their corresponding elements are consumed by the rotation, not how they are laid out. """ result["XformOp"].GetOpTypeToken.func_doc = """**classmethod** GetOpTypeToken(opType) -> str Returns the TfToken used to encode the given ``opType`` . Note that an empty TfToken is used to represent TypeInvalid Parameters ---------- opType : Type """ result["XformOp"].GetOpTypeEnum.func_doc = """**classmethod** GetOpTypeEnum(opTypeToken) -> Type Returns the Type enum associated with the given ``opTypeToken`` . Parameters ---------- opTypeToken : str """ result["XformOp"].GetOpName.func_doc = """**classmethod** GetOpName(opType, opSuffix, inverse) -> str Returns the xformOp's name as it appears in xformOpOrder, given the opType, the (optional) suffix and whether it is an inverse operation. Parameters ---------- opType : Type opSuffix : str inverse : bool ---------------------------------------------------------------------- GetOpName() -> str Returns the opName as it appears in the xformOpOrder attribute. This will begin with"!invert!:xformOp:"if it is an inverse xform operation. If it is not an inverse xformOp, it will begin with'xformOp:'. This will be empty for an invalid xformOp. """ result["XformOp"].GetOpType.func_doc = """GetOpType() -> Type Return the operation type of this op, one of UsdGeomXformOp::Type. """ result["XformOp"].GetPrecision.func_doc = """GetPrecision() -> Precision Returns the precision level of the xform op. """ result["XformOp"].IsInverseOp.func_doc = """IsInverseOp() -> bool Returns whether the xformOp represents an inverse operation. """ result["XformOp"].GetOpTransform.func_doc = """**classmethod** GetOpTransform(time) -> Matrix4d Return the 4x4 matrix that applies the transformation encoded in this op at ``time`` . Returns the identity matrix and issues a coding error if the op is invalid. If the op is valid, but has no authored value, the identity matrix is returned and no error is issued. Parameters ---------- time : TimeCode ---------------------------------------------------------------------- GetOpTransform(opType, opVal, isInverseOp) -> Matrix4d Return the 4x4 matrix that applies the transformation encoded by op ``opType`` and data value ``opVal`` . If ``isInverseOp`` is true, then the inverse of the tranformation represented by the op/value pair is returned. An error will be issued if ``opType`` is not one of the values in the enum UsdGeomXformOp::Type or if ``opVal`` cannot be converted to a suitable input to ``opType`` Parameters ---------- opType : Type opVal : VtValue isInverseOp : bool """ result["XformOp"].MightBeTimeVarying.func_doc = """MightBeTimeVarying() -> bool Determine whether there is any possibility that this op's value may vary over time. The determination is based on a snapshot of the authored state of the op, and may become invalid in the face of further authoring. """ result["XformOp"].GetAttr.func_doc = """GetAttr() -> Attribute Explicit UsdAttribute extractor. """ result["XformOp"].IsDefined.func_doc = """IsDefined() -> bool Return true if the wrapped UsdAttribute::IsDefined() , and in addition the attribute is identified as a XformOp. """ result["XformOp"].GetName.func_doc = """GetName() -> str UsdAttribute::GetName() """ result["XformOp"].GetBaseName.func_doc = """GetBaseName() -> str UsdAttribute::GetBaseName() """ result["XformOp"].GetNamespace.func_doc = """GetNamespace() -> str UsdAttribute::GetNamespace() """ result["XformOp"].SplitName.func_doc = """SplitName() -> list[str] UsdAttribute::SplitName() """ result["XformOp"].GetTypeName.func_doc = """GetTypeName() -> ValueTypeName UsdAttribute::GetTypeName() """ result["XformOp"].Get.func_doc = """Get(value, time) -> bool Get the attribute value of the XformOp at ``time`` . For inverted ops, this returns the raw, uninverted value. Parameters ---------- value : T time : TimeCode """ result["XformOp"].Set.func_doc = """Set(value, time) -> bool Set the attribute value of the XformOp at ``time`` . This only works on non-inverse operations. If invoked on an inverse xform operation, a coding error is issued and no value is authored. Parameters ---------- value : T time : TimeCode """ result["XformOp"].GetTimeSamples.func_doc = """GetTimeSamples(times) -> bool Populates the list of time samples at which the associated attribute is authored. Parameters ---------- times : list[float] """ result["XformOp"].GetTimeSamplesInInterval.func_doc = """GetTimeSamplesInInterval(interval, times) -> bool Populates the list of time samples within the given ``interval`` , at which the associated attribute is authored. Parameters ---------- interval : Interval times : list[float] """ result["XformOp"].GetNumTimeSamples.func_doc = """GetNumTimeSamples() -> int Returns the number of time samples authored for this xformOp. """ result["XformOp"].__init__.func_doc = """__init__(attr, isInverseOp, arg3) Parameters ---------- attr : Attribute isInverseOp : bool arg3 : _ValidAttributeTagType ---------------------------------------------------------------------- __init__(query, isInverseOp, arg3) Parameters ---------- query : AttributeQuery isInverseOp : bool arg3 : _ValidAttributeTagType ---------------------------------------------------------------------- __init__(prim, opType, precision, opSuffix, inverse) Parameters ---------- prim : Prim opType : Type precision : Precision opSuffix : str inverse : bool ---------------------------------------------------------------------- __init__() ---------------------------------------------------------------------- __init__(attr, isInverseOp) Speculative constructor that will produce a valid UsdGeomXformOp when ``attr`` already represents an attribute that is XformOp, and produces an *invalid* XformOp otherwise (i.e. explicit-bool conversion operator will return false). Calling ``UsdGeomXformOp::IsXformOp(attr)`` will return the same truth value as this constructor, but if you plan to subsequently use the XformOp anyways, just use this constructor. ``isInverseOp`` is set to true to indicate an inverse transformation op. This constructor exists mainly for internal use. Clients should use AddXformOp API (or one of Add\\*Op convenience API) to create and retain a copy of an UsdGeomXformOp object. Parameters ---------- attr : Attribute isInverseOp : bool """ result["XformOp"].Type.__doc__ = """ Enumerates the set of all transformation operation types. """ result["XformOp"].Precision.__doc__ = """ Precision with which the value of the tranformation operation is encoded. """ result["GetStageUpAxis"].func_doc = """GetStageUpAxis(stage) -> str Fetch and return ``stage`` 's upAxis. If unauthored, will return the value provided by UsdGeomGetFallbackUpAxis() . Exporters, however, are strongly encouraged to always set the upAxis for every USD file they create. one of: UsdGeomTokens->y or UsdGeomTokens->z, unless there was an error, in which case returns an empty TfToken Encoding Stage UpAxis Parameters ---------- stage : UsdStageWeak """ result["SetStageUpAxis"].func_doc = """SetStageUpAxis(stage, axis) -> bool Set ``stage`` 's upAxis to ``axis`` , which must be one of UsdGeomTokens->y or UsdGeomTokens->z. UpAxis is stage-level metadata, therefore see UsdStage::SetMetadata() . true if upAxis was successfully set. The stage's UsdEditTarget must be either its root layer or session layer. Encoding Stage UpAxis Parameters ---------- stage : UsdStageWeak axis : str """ result["GetFallbackUpAxis"].func_doc = """GetFallbackUpAxis() -> str Return the site-level fallback up axis as a TfToken. In a generic installation of USD, the fallback will be"Y". This can be changed to"Z"by adding, in a plugInfo.json file discoverable by USD's PlugPlugin mechanism: .. code-block:: text "UsdGeomMetrics": { "upAxis": "Z" } If more than one such entry is discovered and the values for upAxis differ, we will issue a warning during the first call to this function, and ignore all of them, so that we devolve to deterministic behavior of Y up axis until the problem is rectified. """ result["LinearUnits"].__doc__ = """""" result["GetStageMetersPerUnit"].func_doc = """GetStageMetersPerUnit(stage) -> float Return *stage* 's authored *metersPerUnit*, or 0.01 if unauthored. Encoding Stage Linear Units Parameters ---------- stage : UsdStageWeak """ result["StageHasAuthoredMetersPerUnit"].func_doc = """StageHasAuthoredMetersPerUnit(stage) -> bool Return whether *stage* has an authored *metersPerUnit*. Encoding Stage Linear Units Parameters ---------- stage : UsdStageWeak """ result["SetStageMetersPerUnit"].func_doc = """SetStageMetersPerUnit(stage, metersPerUnit) -> bool Author *stage* 's *metersPerUnit*. true if metersPerUnit was successfully set. The stage's UsdEditTarget must be either its root layer or session layer. Encoding Stage Linear Units Parameters ---------- stage : UsdStageWeak metersPerUnit : float """ result["LinearUnitsAre"].func_doc = """LinearUnitsAre(authoredUnits, standardUnits, epsilon) -> bool Return *true* if the two given metrics are within the provided relative *epsilon* of each other, when you need to know an absolute metric rather than a scaling factor. Use like so: .. code-block:: text double stageUnits = UsdGeomGetStageMetersPerUnit(stage); if (UsdGeomLinearUnitsAre(stageUnits, UsdGeomLinearUnits::meters)) // do something for meters else if (UsdGeomLinearUnitsAre(stageUnits, UsdGeomLinearUnits::feet)) // do something for feet *false* if either input is zero or negative, otherwise relative floating-point comparison between the two inputs. Encoding Stage Linear Units Parameters ---------- authoredUnits : float standardUnits : float epsilon : float """
403,670
Python
23.166128
237
0.737736
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdGeom/__init__.pyi
from __future__ import annotations import pxr.UsdGeom._usdGeom import typing import Boost.Python import pxr.Usd import pxr.UsdGeom __all__ = [ "BBoxCache", "BasisCurves", "Boundable", "Camera", "Capsule", "Cone", "ConstraintTarget", "Cube", "Curves", "Cylinder", "GetFallbackUpAxis", "GetStageMetersPerUnit", "GetStageUpAxis", "Gprim", "HermiteCurves", "Imageable", "LinearUnits", "LinearUnitsAre", "Mesh", "ModelAPI", "MotionAPI", "NurbsCurves", "NurbsPatch", "Plane", "PointBased", "PointInstancer", "Points", "Primvar", "PrimvarsAPI", "Scope", "SetStageMetersPerUnit", "SetStageUpAxis", "Sphere", "StageHasAuthoredMetersPerUnit", "Subset", "Tokens", "VisibilityAPI", "Xform", "XformCache", "XformCommonAPI", "XformOp", "XformOpTypes", "Xformable" ] class BBoxCache(Boost.Python.instance): """ Caches bounds by recursively computing and aggregating bounds of children in world space and aggregating the result back into local space. The cache is configured for a specific time and UsdGeomImageable::GetPurposeAttr() set of purposes. When querying a bound, transforms and extents are read either from the time specified or UsdTimeCode::Default() , following TimeSamples, Defaults, and Value Resolution standard time-sample value resolution. As noted in SetIncludedPurposes() , changing the included purposes does not invalidate the cache, because we cache purpose along with the geometric data. Child prims that are invisible at the requested time are excluded when computing a prim's bounds. However, if a bound is requested directly for an excluded prim, it will be computed. Additionally, only prims deriving from UsdGeomImageable are included in child bounds computations. Unlike standard UsdStage traversals, the traversal performed by the UsdGeomBBoxCache includesprims that are unloaded (see UsdPrim::IsLoaded() ). This makes it possible to fetch bounds for a UsdStage that has been opened without *forcePopulate*, provided the unloaded model prims have authored extent hints (see UsdGeomModelAPI::GetExtentsHint() ). This class is optimized for computing tight **untransformed"object"space** bounds for component-models. In the absence of component models, bounds are optimized for world-space, since there is no other easily identifiable space for which to optimize, and we cannot optimize for every prim's local space without performing quadratic work. The TfDebug flag, USDGEOM_BBOX, is provided for debugging. Warnings: - This class should only be used with valid UsdPrim objects. - This cache does not listen for change notifications; the user is responsible for clearing the cache when changes occur. - Thread safety: instances of this class may not be used concurrently. - Plugins may be loaded in order to compute extents for prim types provided by that plugin. See UsdGeomBoundable::ComputeExtentFromPlugins """ @staticmethod def Clear() -> None: """ Clear() -> None Clears all pre-cached values. """ @staticmethod def ClearBaseTime() -> None: """ ClearBaseTime() -> None Clear this cache's baseTime if one has been set. After calling this, the cache will use its time as the baseTime value. """ @staticmethod def ComputeLocalBound(prim) -> BBox3d: """ ComputeLocalBound(prim) -> BBox3d Computes the oriented bounding box of the given prim, leveraging any pre-existing, cached bounds. The computed bound includes the transform authored on the prim itself, but does not include any ancestor transforms (it does not include the local-to-world transform). See ComputeWorldBound() for notes on performance and error handling. Parameters ---------- prim : Prim """ @staticmethod def ComputePointInstanceLocalBound(instancer, instanceId) -> BBox3d: """ ComputePointInstanceLocalBound(instancer, instanceId) -> BBox3d Compute the oriented bounding boxes of the given point instances. Parameters ---------- instancer : PointInstancer instanceId : int """ @staticmethod def ComputePointInstanceLocalBounds(instancer, instanceIdBegin, numIds, result) -> bool: """ ComputePointInstanceLocalBounds(instancer, instanceIdBegin, numIds, result) -> bool Compute the oriented bounding boxes of the given point instances. The computed bounds include the transform authored on the instancer itself, but does not include any ancestor transforms (it does not include the local-to-world transform). The ``result`` pointer must point to ``numIds`` GfBBox3d instances to be filled. Parameters ---------- instancer : PointInstancer instanceIdBegin : int numIds : int result : BBox3d """ @staticmethod def ComputePointInstanceRelativeBound(instancer, instanceId, relativeToAncestorPrim) -> BBox3d: """ ComputePointInstanceRelativeBound(instancer, instanceId, relativeToAncestorPrim) -> BBox3d Compute the bound of the given point instance in the space of an ancestor prim ``relativeToAncestorPrim`` . Parameters ---------- instancer : PointInstancer instanceId : int relativeToAncestorPrim : Prim """ @staticmethod def ComputePointInstanceRelativeBounds(instancer, instanceIdBegin, numIds, relativeToAncestorPrim, result) -> bool: """ ComputePointInstanceRelativeBounds(instancer, instanceIdBegin, numIds, relativeToAncestorPrim, result) -> bool Compute the bounds of the given point instances in the space of an ancestor prim ``relativeToAncestorPrim`` . Write the results to ``result`` . The computed bound excludes the local transform at ``relativeToAncestorPrim`` . The computed bound may be incorrect if ``relativeToAncestorPrim`` is not an ancestor of ``prim`` . The ``result`` pointer must point to ``numIds`` GfBBox3d instances to be filled. Parameters ---------- instancer : PointInstancer instanceIdBegin : int numIds : int relativeToAncestorPrim : Prim result : BBox3d """ @staticmethod def ComputePointInstanceUntransformedBound(instancer, instanceId) -> BBox3d: """ ComputePointInstanceUntransformedBound(instancer, instanceId) -> BBox3d Computes the bound of the given point instances, but does not include the instancer's transform. Parameters ---------- instancer : PointInstancer instanceId : int """ @staticmethod def ComputePointInstanceUntransformedBounds(instancer, instanceIdBegin, numIds, result) -> bool: """ ComputePointInstanceUntransformedBounds(instancer, instanceIdBegin, numIds, result) -> bool Computes the bound of the given point instances, but does not include the transform (if any) authored on the instancer itself. **IMPORTANT:** while the BBox does not contain the local transformation, in general it may still contain a non-identity transformation matrix to put the bounds in the correct space. Therefore, to obtain the correct axis-aligned bounding box, the client must call ComputeAlignedRange(). The ``result`` pointer must point to ``numIds`` GfBBox3d instances to be filled. Parameters ---------- instancer : PointInstancer instanceIdBegin : int numIds : int result : BBox3d """ @staticmethod def ComputePointInstanceWorldBound(instancer, instanceId) -> BBox3d: """ ComputePointInstanceWorldBound(instancer, instanceId) -> BBox3d Compute the bound of the given point instance in world space. Parameters ---------- instancer : PointInstancer instanceId : int """ @staticmethod def ComputePointInstanceWorldBounds(instancer, instanceIdBegin, numIds, result) -> bool: """ ComputePointInstanceWorldBounds(instancer, instanceIdBegin, numIds, result) -> bool Compute the bound of the given point instances in world space. The bounds of each instance is computed and then transformed to world space. The ``result`` pointer must point to ``numIds`` GfBBox3d instances to be filled. Parameters ---------- instancer : PointInstancer instanceIdBegin : int numIds : int result : BBox3d """ @staticmethod def ComputeRelativeBound(prim, relativeToAncestorPrim) -> BBox3d: """ ComputeRelativeBound(prim, relativeToAncestorPrim) -> BBox3d Compute the bound of the given prim in the space of an ancestor prim, ``relativeToAncestorPrim`` , leveraging any pre-existing cached bounds. The computed bound excludes the local transform at ``relativeToAncestorPrim`` . The computed bound may be incorrect if ``relativeToAncestorPrim`` is not an ancestor of ``prim`` . Parameters ---------- prim : Prim relativeToAncestorPrim : Prim """ @staticmethod @typing.overload def ComputeUntransformedBound(prim) -> BBox3d: """ ComputeUntransformedBound(prim) -> BBox3d Computes the bound of the prim's children leveraging any pre-existing, cached bounds, but does not include the transform (if any) authored on the prim itself. **IMPORTANT:** while the BBox does not contain the local transformation, in general it may still contain a non-identity transformation matrix to put the bounds in the correct space. Therefore, to obtain the correct axis-aligned bounding box, the client must call ComputeAlignedRange(). See ComputeWorldBound() for notes on performance and error handling. Parameters ---------- prim : Prim ---------------------------------------------------------------------- This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Computes the bound of the prim's descendents while excluding the subtrees rooted at the paths in ``pathsToSkip`` . Additionally, the parameter ``ctmOverrides`` is used to specify overrides to the CTM values of certain paths underneath the prim. The CTM values in the ``ctmOverrides`` map are in the space of the given prim, ``prim`` . This leverages any pre-existing, cached bounds, but does not include the transform (if any) authored on the prim itself. **IMPORTANT:** while the BBox does not contain the local transformation, in general it may still contain a non-identity transformation matrix to put the bounds in the correct space. Therefore, to obtain the correct axis-aligned bounding box, the client must call ComputeAlignedRange(). See ComputeWorldBound() for notes on performance and error handling. Parameters ---------- prim : Prim pathsToSkip : SdfPathSet ctmOverrides : TfHashMap[Path, Matrix4d, Path.Hash] """ @staticmethod @typing.overload def ComputeUntransformedBound(prim, pathsToSkip, ctmOverrides) -> BBox3d: ... @staticmethod def ComputeWorldBound(prim) -> BBox3d: """ ComputeWorldBound(prim) -> BBox3d Compute the bound of the given prim in world space, leveraging any pre-existing, cached bounds. The bound of the prim is computed, including the transform (if any) authored on the node itself, and then transformed to world space. Error handling note: No checking of ``prim`` validity is performed. If ``prim`` is invalid, this method will abort the program; therefore it is the client's responsibility to ensure ``prim`` is valid. Parameters ---------- prim : Prim """ @staticmethod def ComputeWorldBoundWithOverrides(prim, pathsToSkip, primOverride, ctmOverrides) -> BBox3d: """ ComputeWorldBoundWithOverrides(prim, pathsToSkip, primOverride, ctmOverrides) -> BBox3d Computes the bound of the prim's descendents in world space while excluding the subtrees rooted at the paths in ``pathsToSkip`` . Additionally, the parameter ``primOverride`` overrides the local-to- world transform of the prim and ``ctmOverrides`` is used to specify overrides the local-to-world transforms of certain paths underneath the prim. This leverages any pre-existing, cached bounds, but does not include the transform (if any) authored on the prim itself. See ComputeWorldBound() for notes on performance and error handling. Parameters ---------- prim : Prim pathsToSkip : SdfPathSet primOverride : Matrix4d ctmOverrides : TfHashMap[Path, Matrix4d, Path.Hash] """ @staticmethod def GetBaseTime() -> TimeCode: """ GetBaseTime() -> TimeCode Return the base time if set, otherwise GetTime() . Use HasBaseTime() to observe if a base time has been set. """ @staticmethod def GetIncludedPurposes() -> list[TfToken]: """ GetIncludedPurposes() -> list[TfToken] Get the current set of included purposes. """ @staticmethod def GetTime() -> TimeCode: """ GetTime() -> TimeCode Get the current time from which this cache is reading values. """ @staticmethod def GetUseExtentsHint() -> bool: """ GetUseExtentsHint() -> bool Returns whether authored extent hints are used to compute bounding boxes. """ @staticmethod def HasBaseTime() -> bool: """ HasBaseTime() -> bool Return true if this cache has a baseTime that's been explicitly set, false otherwise. """ @staticmethod def SetBaseTime(baseTime) -> None: """ SetBaseTime(baseTime) -> None Set the base time value for this bbox cache. This value is used only when computing bboxes for point instancer instances (see ComputePointInstanceWorldBounds() , for example). See UsdGeomPointInstancer::ComputeExtentAtTime() for more information. If unset, the bbox cache uses its time ( GetTime() / SetTime() ) for this value. Note that setting the base time does not invalidate any cache entries. Parameters ---------- baseTime : TimeCode """ @staticmethod def SetIncludedPurposes(includedPurposes) -> None: """ SetIncludedPurposes(includedPurposes) -> None Indicate the set of ``includedPurposes`` to use when resolving child bounds. Each child's purpose must match one of the elements of this set to be included in the computation; if it does not, child is excluded. Note the use of *child* in the docs above, purpose is ignored for the prim for whose bounds are directly queried. Changing this value **does not invalidate existing caches**. Parameters ---------- includedPurposes : list[TfToken] """ @staticmethod def SetTime(time) -> None: """ SetTime(time) -> None Use the new ``time`` when computing values and may clear any existing values cached for the previous time. Setting ``time`` to the current time is a no-op. Parameters ---------- time : TimeCode """ __instance_size__ = 544 pass class BasisCurves(Curves, PointBased, Gprim, Boundable, Xformable, Imageable, pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): """ BasisCurves are a batched curve representation analogous to the classic RIB definition via Basis and Curves statements. BasisCurves are often used to render dense aggregate geometry like hair or grass. A'matrix'and'vstep'associated with the *basis* are used to interpolate the vertices of a cubic BasisCurves. (The basis attribute is unused for linear BasisCurves.) A single prim may have many curves whose count is determined implicitly by the length of the *curveVertexCounts* vector. Each individual curve is composed of one or more segments. Each segment is defined by four vertices for cubic curves and two vertices for linear curves. See the next section for more information on how to map curve vertex counts to segment counts. Segment Indexing ================ Interpolating a curve requires knowing how to decompose it into its individual segments. The segments of a cubic curve are determined by the vertex count, the *wrap* (periodicity), and the vstep of the basis. For linear curves, the basis token is ignored and only the vertex count and wrap are needed. cubic basis vstep bezier 3 catmullRom 1 bspline 1 The first segment of a cubic (nonperiodic) curve is always defined by its first four points. The vstep is the increment used to determine what vertex indices define the next segment. For a two segment (nonperiodic) bspline basis curve (vstep = 1), the first segment will be defined by interpolating vertices [0, 1, 2, 3] and the second segment will be defined by [1, 2, 3, 4]. For a two segment bezier basis curve (vstep = 3), the first segment will be defined by interpolating vertices [0, 1, 2, 3] and the second segment will be defined by [3, 4, 5, 6]. If the vstep is not one, then you must take special care to make sure that the number of cvs properly divides by your vstep. (The indices described are relative to the initial vertex index for a batched curve.) For periodic curves, at least one of the curve's initial vertices are repeated to close the curve. For cubic curves, the number of vertices repeated is'4 - vstep'. For linear curves, only one vertex is repeated to close the loop. Pinned curves are a special case of nonperiodic curves that only affects the behavior of cubic Bspline and Catmull-Rom curves. To evaluate or render pinned curves, a client must effectively add'phantom points'at the beginning and end of every curve in a batch. These phantom points are injected to ensure that the interpolated curve begins at P[0] and ends at P[n-1]. For a curve with initial point P[0] and last point P[n-1], the phantom points are defined as. P[-1] = 2 \* P[0] - P[1] P[n] = 2 \* P[n-1] - P[n-2] Pinned cubic curves will (usually) have to be unpacked into the standard nonperiodic representation before rendering. This unpacking can add some additional overhead. However, using pinned curves reduces the amount of data recorded in a scene and (more importantly) better records the authors'intent for interchange. The additional phantom points mean that the minimum curve vertex count for cubic bspline and catmullRom curves is 2. Linear curve segments are defined by two vertices. A two segment linear curve's first segment would be defined by interpolating vertices [0, 1]. The second segment would be defined by vertices [1, 2]. (Again, for a batched curve, indices are relative to the initial vertex index.) When validating curve topology, each renderable entry in the curveVertexCounts vector must pass this check. type wrap validitity linear nonperiodic curveVertexCounts[i]>2 linear periodic curveVertexCounts[i]>3 cubic nonperiodic (curveVertexCounts[i] - 4) % vstep == 0 cubic periodic (curveVertexCounts[i]) % vstep == 0 cubic pinned (catmullRom/bspline) (curveVertexCounts[i] - 2)>= 0 Cubic Vertex Interpolation ========================== Linear Vertex Interpolation =========================== Linear interpolation is always used on curves of type linear.'t'with domain [0, 1], the curve is defined by the equation P0 \* (1-t) + P1 \* t. t at 0 describes the first point and t at 1 describes the end point. Primvar Interpolation ===================== For cubic curves, primvar data can be either interpolated cubically between vertices or linearly across segments. The corresponding token for cubic interpolation is'vertex'and for linear interpolation is'varying'. Per vertex data should be the same size as the number of vertices in your curve. Segment varying data is dependent on the wrap (periodicity) and number of segments in your curve. For linear curves, varying and vertex data would be interpolated the same way. By convention varying is the preferred interpolation because of the association of varying with linear interpolation. To convert an entry in the curveVertexCounts vector into a segment count for an individual curve, apply these rules. Sum up all the results in order to compute how many total segments all curves have. The following tables describe the expected segment count for the'i'th curve in a curve batch as well as the entire batch. Python syntax like'[:]'(to describe all members of an array) and'len(\.\.\.)'(to describe the length of an array) are used. type wrap curve segment count batch segment count linear nonperiodic curveVertexCounts[i] - 1 sum(curveVertexCounts[:]) - len(curveVertexCounts) linear periodic curveVertexCounts[i] sum(curveVertexCounts[:]) cubic nonperiodic (curveVertexCounts[i] - 4) / vstep + 1 sum(curveVertexCounts[:] - 4) / vstep + len(curveVertexCounts) cubic periodic curveVertexCounts[i] / vstep sum(curveVertexCounts[:]) / vstep cubic pinned (catmullRom/bspline) (curveVertexCounts[i] - 2) + 1 sum(curveVertexCounts[:] - 2) + len(curveVertexCounts) The following table descrives the expected size of varying (linearly interpolated) data, derived from the segment counts computed above. wrap curve varying count batch varying count nonperiodic/pinned segmentCounts[i] + 1 sum(segmentCounts[:]) + len(curveVertexCounts) periodic segmentCounts[i] sum(segmentCounts[:]) Both curve types additionally define'constant'interpolation for the entire prim and'uniform'interpolation as per curve data. Take care when providing support for linearly interpolated data for cubic curves. Its shape doesn't provide a one to one mapping with either the number of curves (like'uniform') or the number of vertices (like'vertex') and so it is often overlooked. This is the only primitive in UsdGeom (as of this writing) where this is true. For meshes, while they use different interpolation methods,'varying'and'vertex'are both specified per point. It's common to assume that curves follow a similar pattern and build in structures and language for per primitive, per element, and per point data only to come upon these arrays that don't quite fit into either of those categories. It is also common to conflate'varying'with being per segment data and use the segmentCount rules table instead of its neighboring varying data table rules. We suspect that this is because for the common case of nonperiodic cubic curves, both the provided segment count and varying data size formula end with'+ 1'. While debugging, users may look at the double'+ 1'as a mistake and try to remove it. We take this time to enumerate these issues because we've fallen into them before and hope that we save others time in their own implementations. As an example of deriving per curve segment and varying primvar data counts from the wrap, type, basis, and curveVertexCount, the following table is provided. wrap type basis curveVertexCount curveSegmentCount varyingDataCount nonperiodic linear N/A [2 3 2 5] [1 2 1 4] [2 3 2 5] nonperiodic cubic bezier [4 7 10 4 7] [1 2 3 1 2] [2 3 4 2 3] nonperiodic cubic bspline [5 4 6 7] [2 1 3 4] [3 2 4 5] periodic cubic bezier [6 9 6] [2 3 2] [2 3 2] periodic linear N/A [3 7] [3 7] [3 7] Tubes and Ribbons ================= The strictest definition of a curve as an infinitely thin wire is not particularly useful for describing production scenes. The additional *widths* and *normals* attributes can be used to describe cylindrical tubes and or flat oriented ribbons. Curves with only widths defined are imaged as tubes with radius'width / 2'. Curves with both widths and normals are imaged as ribbons oriented in the direction of the interpolated normal vectors. While not technically UsdGeomPrimvars, widths and normals also have interpolation metadata. It's common for authored widths to have constant, varying, or vertex interpolation (see UsdGeomCurves::GetWidthsInterpolation() ). It's common for authored normals to have varying interpolation (see UsdGeomPointBased::GetNormalsInterpolation() ). The file used to generate these curves can be found in pxr/extras/examples/usdGeomExamples/basisCurves.usda. It's provided as a reference on how to properly image both tubes and ribbons. The first row of curves are linear; the second are cubic bezier. (We aim in future releases of HdSt to fix the discontinuity seen with broken tangents to better match offline renderers like RenderMan.) The yellow and violet cubic curves represent cubic vertex width interpolation for which there is no equivalent for linear curves. How did this prim type get its name? This prim is a portmanteau of two different statements in the original RenderMan specification:'Basis'and'Curves'. For any described attribute *Fallback* *Value* or *Allowed* *Values* below that are text/tokens, the actual token is published and defined in UsdGeomTokens. So to set an attribute to the value"rightHanded", use UsdGeomTokens->rightHanded as the value. """ @staticmethod def ComputeInterpolationForSize(n, timeCode, info) -> str: """ ComputeInterpolationForSize(n, timeCode, info) -> str Computes interpolation token for ``n`` . If this returns an empty token and ``info`` was non-None, it'll contain the expected value for each token. The topology is determined using ``timeCode`` . Parameters ---------- n : int timeCode : TimeCode info : ComputeInterpolationInfo """ @staticmethod def ComputeUniformDataSize(timeCode) -> int: """ ComputeUniformDataSize(timeCode) -> int Computes the expected size for data with"uniform"interpolation. If you're trying to determine what interpolation to use, it is more efficient to use ``ComputeInterpolationForSize`` Parameters ---------- timeCode : TimeCode """ @staticmethod def ComputeVaryingDataSize(timeCode) -> int: """ ComputeVaryingDataSize(timeCode) -> int Computes the expected size for data with"varying"interpolation. If you're trying to determine what interpolation to use, it is more efficient to use ``ComputeInterpolationForSize`` Parameters ---------- timeCode : TimeCode """ @staticmethod def ComputeVertexDataSize(timeCode) -> int: """ ComputeVertexDataSize(timeCode) -> int Computes the expected size for data with"vertex"interpolation. If you're trying to determine what interpolation to use, it is more efficient to use ``ComputeInterpolationForSize`` Parameters ---------- timeCode : TimeCode """ @staticmethod def CreateBasisAttr(defaultValue, writeSparsely) -> Attribute: """ CreateBasisAttr(defaultValue, writeSparsely) -> Attribute See GetBasisAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateTypeAttr(defaultValue, writeSparsely) -> Attribute: """ CreateTypeAttr(defaultValue, writeSparsely) -> Attribute See GetTypeAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateWrapAttr(defaultValue, writeSparsely) -> Attribute: """ CreateWrapAttr(defaultValue, writeSparsely) -> Attribute See GetWrapAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def Define(*args, **kwargs) -> None: """ **classmethod** Define(stage, path) -> BasisCurves Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ @staticmethod def Get(*args, **kwargs) -> None: """ **classmethod** Get(stage, path) -> BasisCurves Return a UsdGeomBasisCurves holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomBasisCurves(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ @staticmethod def GetBasisAttr() -> Attribute: """ GetBasisAttr() -> Attribute The basis specifies the vstep and matrix used for cubic interpolation. The'hermite'and'power'tokens have been removed. We've provided UsdGeomHermiteCurves as an alternative for the'hermite'basis. Declaration ``uniform token basis ="bezier"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values bezier, bspline, catmullRom """ @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: """ **classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ @staticmethod def GetTypeAttr() -> Attribute: """ GetTypeAttr() -> Attribute Linear curves interpolate linearly between two vertices. Cubic curves use a basis matrix with four vertices to interpolate a segment. Declaration ``uniform token type ="cubic"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values linear, cubic """ @staticmethod def GetWrapAttr() -> Attribute: """ GetWrapAttr() -> Attribute If wrap is set to periodic, the curve when rendered will repeat the initial vertices (dependent on the vstep) to close the curve. If wrap is set to'pinned', phantom points may be created to ensure that the curve interpolation starts at P[0] and ends at P[n-1]. Declaration ``uniform token wrap ="nonperiodic"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values nonperiodic, periodic, pinned """ @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: """ **classmethod** _GetStaticTfType() -> Type """ __instance_size__ = 40 pass class Boundable(Xformable, Imageable, pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): """ Boundable introduces the ability for a prim to persistently cache a rectilinear, local-space, extent. Why Extent and not Bounds ? =========================== Boundable introduces the notion of"extent", which is a cached computation of a prim's local-space 3D range for its resolved attributes **at the layer and time in which extent is authored**. We have found that with composed scene description, attempting to cache pre-computed bounds at interior prims in a scene graph is very fragile, given the ease with which one can author a single attribute in a stronger layer that can invalidate many authored caches - or with which a re-published, referenced asset can do the same. Therefore, we limit to precomputing (generally) leaf-prim extent, which avoids the need to read in large point arrays to compute bounds, and provides UsdGeomBBoxCache the means to efficiently compute and (session-only) cache intermediate bounds. You are free to compute and author intermediate bounds into your scenes, of course, which may work well if you have sufficient locks on your pipeline to guarantee that once authored, the geometry and transforms upon which they are based will remain unchanged, or if accuracy of the bounds is not an ironclad requisite. When intermediate bounds are authored on Boundable parents, the child prims will be pruned from BBox computation; the authored extent is expected to incorporate all child bounds. """ @staticmethod def ComputeExtent(radius, transform, extent) -> bool: """ **classmethod** ComputeExtent(radius, extent) -> bool Compute the extent for the sphere defined by the radius. true upon success, false if unable to calculate extent. On success, extent will contain an approximate axis-aligned bounding box of the sphere defined by the radius. This function is to provide easy authoring of extent for usd authoring tools, hence it is static and acts outside a specific prim (as in attribute based methods). Parameters ---------- radius : float extent : Vec3fArray ---------------------------------------------------------------------- This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Computes the extent as if the matrix ``transform`` was first applied. Parameters ---------- radius : float transform : Matrix4d extent : Vec3fArray """ @staticmethod def ComputeExtentFromPlugins(boundable, time, transform, extent) -> bool: """ **classmethod** ComputeExtentFromPlugins(boundable, time, extent) -> bool Compute the extent for the Boundable prim ``boundable`` at time ``time`` . If successful, populates ``extent`` with the result and returns ``true`` , otherwise returns ``false`` . The extent computation is based on the concrete type of the prim represented by ``boundable`` . Plugins that provide a Boundable prim type may implement and register an extent computation for that type using UsdGeomRegisterComputeExtentFunction. ComputeExtentFromPlugins will use this function to compute extents for all prims of that type. If no function has been registered for a prim type, but a function has been registered for one of its base types, that function will be used instead. This function may load plugins in order to access the extent computation for a prim type. Parameters ---------- boundable : Boundable time : TimeCode extent : Vec3fArray ---------------------------------------------------------------------- This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Computes the extent as if the matrix ``transform`` was first applied. Parameters ---------- boundable : Boundable time : TimeCode transform : Matrix4d extent : Vec3fArray """ @staticmethod def CreateExtentAttr(defaultValue, writeSparsely) -> Attribute: """ CreateExtentAttr(defaultValue, writeSparsely) -> Attribute See GetExtentAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def Get(*args, **kwargs) -> None: """ **classmethod** Get(stage, path) -> Boundable Return a UsdGeomBoundable holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomBoundable(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ @staticmethod def GetExtentAttr() -> Attribute: """ GetExtentAttr() -> Attribute Extent is a three dimensional range measuring the geometric extent of the authored gprim in its own local space (i.e. its own transform not applied), *without* accounting for any shader- induced displacement. If **any** extent value has been authored for a given Boundable, then it should be authored at every timeSample at which geometry-affecting properties are authored, to ensure correct evaluation via ComputeExtent() . If **no** extent value has been authored, then ComputeExtent() will call the Boundable's registered ComputeExtentFunction(), which may be expensive, which is why we strongly encourage proper authoring of extent. Why Extent and not Bounds? . An authored extent on a prim which has children is expected to include the extent of all children, as they will be pruned from BBox computation during traversal. Declaration ``float3[] extent`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Float3Array """ @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: """ **classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: """ **classmethod** _GetStaticTfType() -> Type """ __instance_size__ = 40 pass class Camera(Xformable, Imageable, pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): """ Transformable camera. Describes optical properties of a camera via a common set of attributes that provide control over the camera's frustum as well as its depth of field. For stereo, the left and right camera are individual prims tagged through the stereoRole attribute. There is a corresponding class GfCamera, which can hold the state of a camera (at a particular time). UsdGeomCamera::GetCamera() and UsdGeomCamera::SetFromCamera() convert between a USD camera prim and a GfCamera. To obtain the camera's location in world space, call the following on a UsdGeomCamera 'camera': .. code-block:: text GfMatrix4d camXform = camera.ComputeLocalToWorldTransform(time); **Cameras in USD are always"Y up", regardless of the stage's orientation (i.e. UsdGeomGetStageUpAxis() ).** This means that the inverse of'camXform'(the VIEW half of the MODELVIEW transform in OpenGL parlance) will transform the world such that the camera is at the origin, looking down the -Z axis, with +Y as the up axis, and +X pointing to the right. This describes a **right handed coordinate system**. Units of Measure for Camera Properties ====================================== Despite the familiarity of millimeters for specifying some physical camera properties, UsdGeomCamera opts for greater consistency with all other UsdGeom schemas, which measure geometric properties in scene units, as determined by UsdGeomGetStageMetersPerUnit() . We do make a concession, however, in that lens and filmback properties are measured in **tenths of a scene unit** rather than"raw"scene units. This means that with the fallback value of.01 for *metersPerUnit* - i.e. scene unit of centimeters - then these"tenth of scene unit"properties are effectively millimeters. If one adds a Camera prim to a UsdStage whose scene unit is not centimeters, the fallback values for filmback properties will be incorrect (or at the least, unexpected) in an absolute sense; however, proper imaging through a"default camera"with focusing disabled depends only on ratios of the other properties, so the camera is still usable. However, it follows that if even one property is authored in the correct scene units, then they all must be. Linear Algebra in UsdGeom For any described attribute *Fallback* *Value* or *Allowed* *Values* below that are text/tokens, the actual token is published and defined in UsdGeomTokens. So to set an attribute to the value"rightHanded", use UsdGeomTokens->rightHanded as the value. """ @staticmethod def CreateClippingPlanesAttr(defaultValue, writeSparsely) -> Attribute: """ CreateClippingPlanesAttr(defaultValue, writeSparsely) -> Attribute See GetClippingPlanesAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateClippingRangeAttr(defaultValue, writeSparsely) -> Attribute: """ CreateClippingRangeAttr(defaultValue, writeSparsely) -> Attribute See GetClippingRangeAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateExposureAttr(defaultValue, writeSparsely) -> Attribute: """ CreateExposureAttr(defaultValue, writeSparsely) -> Attribute See GetExposureAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateFStopAttr(defaultValue, writeSparsely) -> Attribute: """ CreateFStopAttr(defaultValue, writeSparsely) -> Attribute See GetFStopAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateFocalLengthAttr(defaultValue, writeSparsely) -> Attribute: """ CreateFocalLengthAttr(defaultValue, writeSparsely) -> Attribute See GetFocalLengthAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateFocusDistanceAttr(defaultValue, writeSparsely) -> Attribute: """ CreateFocusDistanceAttr(defaultValue, writeSparsely) -> Attribute See GetFocusDistanceAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateHorizontalApertureAttr(defaultValue, writeSparsely) -> Attribute: """ CreateHorizontalApertureAttr(defaultValue, writeSparsely) -> Attribute See GetHorizontalApertureAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateHorizontalApertureOffsetAttr(defaultValue, writeSparsely) -> Attribute: """ CreateHorizontalApertureOffsetAttr(defaultValue, writeSparsely) -> Attribute See GetHorizontalApertureOffsetAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateProjectionAttr(defaultValue, writeSparsely) -> Attribute: """ CreateProjectionAttr(defaultValue, writeSparsely) -> Attribute See GetProjectionAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateShutterCloseAttr(defaultValue, writeSparsely) -> Attribute: """ CreateShutterCloseAttr(defaultValue, writeSparsely) -> Attribute See GetShutterCloseAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateShutterOpenAttr(defaultValue, writeSparsely) -> Attribute: """ CreateShutterOpenAttr(defaultValue, writeSparsely) -> Attribute See GetShutterOpenAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateStereoRoleAttr(defaultValue, writeSparsely) -> Attribute: """ CreateStereoRoleAttr(defaultValue, writeSparsely) -> Attribute See GetStereoRoleAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateVerticalApertureAttr(defaultValue, writeSparsely) -> Attribute: """ CreateVerticalApertureAttr(defaultValue, writeSparsely) -> Attribute See GetVerticalApertureAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateVerticalApertureOffsetAttr(defaultValue, writeSparsely) -> Attribute: """ CreateVerticalApertureOffsetAttr(defaultValue, writeSparsely) -> Attribute See GetVerticalApertureOffsetAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def Define(*args, **kwargs) -> None: """ **classmethod** Define(stage, path) -> Camera Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ @staticmethod def Get(*args, **kwargs) -> None: """ **classmethod** Get(stage, path) -> Camera Return a UsdGeomCamera holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomCamera(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ @staticmethod def GetCamera(time) -> Camera: """ GetCamera(time) -> Camera Creates a GfCamera object from the attribute values at ``time`` . Parameters ---------- time : TimeCode """ @staticmethod def GetClippingPlanesAttr() -> Attribute: """ GetClippingPlanesAttr() -> Attribute Additional, arbitrarily oriented clipping planes. A vector (a,b,c,d) encodes a clipping plane that cuts off (x,y,z) with a \* x + b \* y + c \* z + d \* 1<0 where (x,y,z) are the coordinates in the camera's space. Declaration ``float4[] clippingPlanes = []`` C++ Type VtArray<GfVec4f> Usd Type SdfValueTypeNames->Float4Array """ @staticmethod def GetClippingRangeAttr() -> Attribute: """ GetClippingRangeAttr() -> Attribute Near and far clipping distances in scene units; see Units of Measure for Camera Properties. Declaration ``float2 clippingRange = (1, 1000000)`` C++ Type GfVec2f Usd Type SdfValueTypeNames->Float2 """ @staticmethod def GetExposureAttr() -> Attribute: """ GetExposureAttr() -> Attribute Exposure adjustment, as a log base-2 value. The default of 0.0 has no effect. A value of 1.0 will double the image-plane intensities in a rendered image; a value of -1.0 will halve them. Declaration ``float exposure = 0`` C++ Type float Usd Type SdfValueTypeNames->Float """ @staticmethod def GetFStopAttr() -> Attribute: """ GetFStopAttr() -> Attribute Lens aperture. Defaults to 0.0, which turns off focusing. Declaration ``float fStop = 0`` C++ Type float Usd Type SdfValueTypeNames->Float """ @staticmethod def GetFocalLengthAttr() -> Attribute: """ GetFocalLengthAttr() -> Attribute Perspective focal length in tenths of a scene unit; see Units of Measure for Camera Properties. Declaration ``float focalLength = 50`` C++ Type float Usd Type SdfValueTypeNames->Float """ @staticmethod def GetFocusDistanceAttr() -> Attribute: """ GetFocusDistanceAttr() -> Attribute Distance from the camera to the focus plane in scene units; see Units of Measure for Camera Properties. Declaration ``float focusDistance = 0`` C++ Type float Usd Type SdfValueTypeNames->Float """ @staticmethod def GetHorizontalApertureAttr() -> Attribute: """ GetHorizontalApertureAttr() -> Attribute Horizontal aperture in tenths of a scene unit; see Units of Measure for Camera Properties. Default is the equivalent of the standard 35mm spherical projector aperture. Declaration ``float horizontalAperture = 20.955`` C++ Type float Usd Type SdfValueTypeNames->Float """ @staticmethod def GetHorizontalApertureOffsetAttr() -> Attribute: """ GetHorizontalApertureOffsetAttr() -> Attribute Horizontal aperture offset in the same units as horizontalAperture. Defaults to 0. Declaration ``float horizontalApertureOffset = 0`` C++ Type float Usd Type SdfValueTypeNames->Float """ @staticmethod def GetProjectionAttr() -> Attribute: """ GetProjectionAttr() -> Attribute Declaration ``token projection ="perspective"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Allowed Values perspective, orthographic """ @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: """ **classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ @staticmethod def GetShutterCloseAttr() -> Attribute: """ GetShutterCloseAttr() -> Attribute Frame relative shutter close time, analogous comments from shutter:open apply. A value greater or equal to shutter:open should be authored, otherwise there is no exposure and a renderer should produce a black image. Declaration ``double shutter:close = 0`` C++ Type double Usd Type SdfValueTypeNames->Double """ @staticmethod def GetShutterOpenAttr() -> Attribute: """ GetShutterOpenAttr() -> Attribute Frame relative shutter open time in UsdTimeCode units (negative value indicates that the shutter opens before the current frame time). Used for motion blur. Declaration ``double shutter:open = 0`` C++ Type double Usd Type SdfValueTypeNames->Double """ @staticmethod def GetStereoRoleAttr() -> Attribute: """ GetStereoRoleAttr() -> Attribute If different from mono, the camera is intended to be the left or right camera of a stereo setup. Declaration ``uniform token stereoRole ="mono"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values mono, left, right """ @staticmethod def GetVerticalApertureAttr() -> Attribute: """ GetVerticalApertureAttr() -> Attribute Vertical aperture in tenths of a scene unit; see Units of Measure for Camera Properties. Default is the equivalent of the standard 35mm spherical projector aperture. Declaration ``float verticalAperture = 15.2908`` C++ Type float Usd Type SdfValueTypeNames->Float """ @staticmethod def GetVerticalApertureOffsetAttr() -> Attribute: """ GetVerticalApertureOffsetAttr() -> Attribute Vertical aperture offset in the same units as verticalAperture. Defaults to 0. Declaration ``float verticalApertureOffset = 0`` C++ Type float Usd Type SdfValueTypeNames->Float """ @staticmethod def SetFromCamera(camera, time) -> None: """ SetFromCamera(camera, time) -> None Write attribute values from ``camera`` for ``time`` . These attributes will be updated: - projection - horizontalAperture - horizontalApertureOffset - verticalAperture - verticalApertureOffset - focalLength - clippingRange - clippingPlanes - fStop - focalDistance - xformOpOrder and xformOp:transform This will clear any existing xformOpOrder and replace it with a single xformOp:transform entry. The xformOp:transform property is created or updated here to match the transform on ``camera`` . This operation will fail if there are stronger xform op opinions in the composed layer stack that are stronger than that of the current edit target. Parameters ---------- camera : Camera time : TimeCode """ @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: """ **classmethod** _GetStaticTfType() -> Type """ __instance_size__ = 40 pass class Capsule(Gprim, Boundable, Xformable, Imageable, pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): """ Defines a primitive capsule, i.e. a cylinder capped by two half spheres, centered at the origin, whose spine is along the specified *axis*. For any described attribute *Fallback* *Value* or *Allowed* *Values* below that are text/tokens, the actual token is published and defined in UsdGeomTokens. So to set an attribute to the value"rightHanded", use UsdGeomTokens->rightHanded as the value. """ @staticmethod def CreateAxisAttr(defaultValue, writeSparsely) -> Attribute: """ CreateAxisAttr(defaultValue, writeSparsely) -> Attribute See GetAxisAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateExtentAttr(defaultValue, writeSparsely) -> Attribute: """ CreateExtentAttr(defaultValue, writeSparsely) -> Attribute See GetExtentAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateHeightAttr(defaultValue, writeSparsely) -> Attribute: """ CreateHeightAttr(defaultValue, writeSparsely) -> Attribute See GetHeightAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateRadiusAttr(defaultValue, writeSparsely) -> Attribute: """ CreateRadiusAttr(defaultValue, writeSparsely) -> Attribute See GetRadiusAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def Define(*args, **kwargs) -> None: """ **classmethod** Define(stage, path) -> Capsule Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ @staticmethod def Get(*args, **kwargs) -> None: """ **classmethod** Get(stage, path) -> Capsule Return a UsdGeomCapsule holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomCapsule(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ @staticmethod def GetAxisAttr() -> Attribute: """ GetAxisAttr() -> Attribute The axis along which the spine of the capsule is aligned. Declaration ``uniform token axis ="Z"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values X, Y, Z """ @staticmethod def GetExtentAttr() -> Attribute: """ GetExtentAttr() -> Attribute Extent is re-defined on Capsule only to provide a fallback value. UsdGeomGprim::GetExtentAttr() . Declaration ``float3[] extent = [(-0.5, -0.5, -1), (0.5, 0.5, 1)]`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Float3Array """ @staticmethod def GetHeightAttr() -> Attribute: """ GetHeightAttr() -> Attribute The size of the capsule's spine along the specified *axis* excluding the size of the two half spheres, i.e. the size of the cylinder portion of the capsule. If you author *height* you must also author *extent*. Declaration ``double height = 1`` C++ Type double Usd Type SdfValueTypeNames->Double """ @staticmethod def GetRadiusAttr() -> Attribute: """ GetRadiusAttr() -> Attribute The radius of the capsule. If you author *radius* you must also author *extent*. Declaration ``double radius = 0.5`` C++ Type double Usd Type SdfValueTypeNames->Double """ @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: """ **classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: """ **classmethod** _GetStaticTfType() -> Type """ __instance_size__ = 40 pass class Cone(Gprim, Boundable, Xformable, Imageable, pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): """ Defines a primitive cone, centered at the origin, whose spine is along the specified *axis*, with the apex of the cone pointing in the direction of the positive axis. The fallback values for Cube, Sphere, Cone, and Cylinder are set so that they all pack into the same volume/bounds. For any described attribute *Fallback* *Value* or *Allowed* *Values* below that are text/tokens, the actual token is published and defined in UsdGeomTokens. So to set an attribute to the value"rightHanded", use UsdGeomTokens->rightHanded as the value. """ @staticmethod def CreateAxisAttr(defaultValue, writeSparsely) -> Attribute: """ CreateAxisAttr(defaultValue, writeSparsely) -> Attribute See GetAxisAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateExtentAttr(defaultValue, writeSparsely) -> Attribute: """ CreateExtentAttr(defaultValue, writeSparsely) -> Attribute See GetExtentAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateHeightAttr(defaultValue, writeSparsely) -> Attribute: """ CreateHeightAttr(defaultValue, writeSparsely) -> Attribute See GetHeightAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateRadiusAttr(defaultValue, writeSparsely) -> Attribute: """ CreateRadiusAttr(defaultValue, writeSparsely) -> Attribute See GetRadiusAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def Define(*args, **kwargs) -> None: """ **classmethod** Define(stage, path) -> Cone Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ @staticmethod def Get(*args, **kwargs) -> None: """ **classmethod** Get(stage, path) -> Cone Return a UsdGeomCone holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomCone(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ @staticmethod def GetAxisAttr() -> Attribute: """ GetAxisAttr() -> Attribute The axis along which the spine of the cone is aligned. Declaration ``uniform token axis ="Z"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values X, Y, Z """ @staticmethod def GetExtentAttr() -> Attribute: """ GetExtentAttr() -> Attribute Extent is re-defined on Cone only to provide a fallback value. UsdGeomGprim::GetExtentAttr() . Declaration ``float3[] extent = [(-1, -1, -1), (1, 1, 1)]`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Float3Array """ @staticmethod def GetHeightAttr() -> Attribute: """ GetHeightAttr() -> Attribute The size of the cone's spine along the specified *axis*. If you author *height* you must also author *extent*. Declaration ``double height = 2`` C++ Type double Usd Type SdfValueTypeNames->Double """ @staticmethod def GetRadiusAttr() -> Attribute: """ GetRadiusAttr() -> Attribute The radius of the cone. If you author *radius* you must also author *extent*. Declaration ``double radius = 1`` C++ Type double Usd Type SdfValueTypeNames->Double """ @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: """ **classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: """ **classmethod** _GetStaticTfType() -> Type """ __instance_size__ = 40 pass class ConstraintTarget(Boost.Python.instance): """ Schema wrapper for UsdAttribute for authoring and introspecting attributes that are constraint targets. Constraint targets correspond roughly to what some DCC's call locators. They are coordinate frames, represented as (animated or static) GfMatrix4d values. We represent them as attributes in USD rather than transformable prims because generally we require no other coordinated information about a constraint target other than its name and its matrix value, and because attributes are more concise than prims. Because consumer clients often care only about the identity and value of constraint targets and may be able to usefully consume them without caring about the actual geometry with which they may logically correspond, UsdGeom aggregates all constraint targets onto a model's root prim, assuming that an exporter will use property namespacing within the constraint target attribute's name to indicate a path to a prim within the model with which the constraint target may correspond. To facilitate instancing, and also position-tweaking of baked assets, we stipulate that constraint target values always be recorded in **model-relative transformation space**. In other words, to get the world-space value of a constraint target, transform it by the local- to-world transformation of the prim on which it is recorded. ComputeInWorldSpace() will perform this calculation. """ @staticmethod def ComputeInWorldSpace(time, xfCache) -> Matrix4d: """ ComputeInWorldSpace(time, xfCache) -> Matrix4d Computes the value of the constraint target in world space. If a valid UsdGeomXformCache is provided in the argument ``xfCache`` , it is used to evaluate the CTM of the model to which the constraint target belongs. To get the constraint value in model-space (or local space), simply use UsdGeomConstraintTarget::Get() , since the authored values must already be in model-space. Parameters ---------- time : TimeCode xfCache : XformCache """ @staticmethod def Get(value, time) -> bool: """ Get(value, time) -> bool Get the attribute value of the ConstraintTarget at ``time`` . Parameters ---------- value : Matrix4d time : TimeCode """ @staticmethod def GetAttr() -> Attribute: """ GetAttr() -> Attribute Explicit UsdAttribute extractor. """ @staticmethod def GetConstraintAttrName(*args, **kwargs) -> None: """ **classmethod** GetConstraintAttrName(constraintName) -> str Returns the fully namespaced constraint attribute name, given the constraint name. Parameters ---------- constraintName : str """ @staticmethod def GetIdentifier() -> str: """ GetIdentifier() -> str Get the stored identifier unique to the enclosing model's namespace for this constraint target. """ @staticmethod def IsDefined() -> bool: """ IsDefined() -> bool Return true if the wrapped UsdAttribute::IsDefined() , and in addition the attribute is identified as a ConstraintTarget. """ @staticmethod def IsValid(*args, **kwargs) -> None: """ **classmethod** IsValid(attr) -> bool Test whether a given UsdAttribute represents valid ConstraintTarget, which implies that creating a UsdGeomConstraintTarget from the attribute will succeed. Success implies that ``attr.IsDefined()`` is true. Parameters ---------- attr : Attribute """ @staticmethod def Set(value, time) -> bool: """ Set(value, time) -> bool Set the attribute value of the ConstraintTarget at ``time`` . Parameters ---------- value : Matrix4d time : TimeCode """ @staticmethod def SetIdentifier(identifier) -> None: """ SetIdentifier(identifier) -> None Explicitly sets the stored identifier to the given string. Clients are responsible for ensuring the uniqueness of this identifier within the enclosing model's namespace. Parameters ---------- identifier : str """ __instance_size__ = 48 pass class Cube(Gprim, Boundable, Xformable, Imageable, pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): """ Defines a primitive rectilinear cube centered at the origin. The fallback values for Cube, Sphere, Cone, and Cylinder are set so that they all pack into the same volume/bounds. """ @staticmethod def CreateExtentAttr(defaultValue, writeSparsely) -> Attribute: """ CreateExtentAttr(defaultValue, writeSparsely) -> Attribute See GetExtentAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateSizeAttr(defaultValue, writeSparsely) -> Attribute: """ CreateSizeAttr(defaultValue, writeSparsely) -> Attribute See GetSizeAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def Define(*args, **kwargs) -> None: """ **classmethod** Define(stage, path) -> Cube Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ @staticmethod def Get(*args, **kwargs) -> None: """ **classmethod** Get(stage, path) -> Cube Return a UsdGeomCube holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomCube(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ @staticmethod def GetExtentAttr() -> Attribute: """ GetExtentAttr() -> Attribute Extent is re-defined on Cube only to provide a fallback value. UsdGeomGprim::GetExtentAttr() . Declaration ``float3[] extent = [(-1, -1, -1), (1, 1, 1)]`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Float3Array """ @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: """ **classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ @staticmethod def GetSizeAttr() -> Attribute: """ GetSizeAttr() -> Attribute Indicates the length of each edge of the cube. If you author *size* you must also author *extent*. Declaration ``double size = 2`` C++ Type double Usd Type SdfValueTypeNames->Double """ @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: """ **classmethod** _GetStaticTfType() -> Type """ __instance_size__ = 40 pass class HermiteCurves(Curves, PointBased, Gprim, Boundable, Xformable, Imageable, pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): """ This schema specifies a cubic hermite interpolated curve batch as sometimes used for defining guides for animation. While hermite curves can be useful because they interpolate through their control points, they are not well supported by high-end renderers for imaging. Therefore, while we include this schema for interchange, we strongly recommend the use of UsdGeomBasisCurves as the representation of curves intended to be rendered (ie. hair or grass). Hermite curves can be converted to a Bezier representation (though not from Bezier back to Hermite in general). Point Interpolation =================== The initial cubic curve segment is defined by the first two points and first two tangents. Additional segments are defined by additional point / tangent pairs. The number of segments for each non-batched hermite curve would be len(curve.points) - 1. The total number of segments for the batched UsdGeomHermiteCurves representation is len(points) - len(curveVertexCounts). Primvar, Width, and Normal Interpolation ======================================== Primvar interpolation is not well specified for this type as it is not intended as a rendering representation. We suggest that per point primvars would be linearly interpolated across each segment and should be tagged as'varying'. It is not immediately clear how to specify cubic or'vertex'interpolation for this type, as we lack a specification for primvar tangents. This also means that width and normal interpolation should be restricted to varying (linear), uniform (per curve element), or constant (per prim). """ class PointAndTangentArrays(Boost.Python.instance): @staticmethod def GetPoints(*args, **kwargs) -> None: ... @staticmethod def GetTangents(*args, **kwargs) -> None: ... @staticmethod def Interleave(*args, **kwargs) -> None: ... @staticmethod def IsEmpty(*args, **kwargs) -> None: ... @staticmethod def Separate(*args, **kwargs) -> None: ... __instance_size__ = 96 pass @staticmethod def CreateTangentsAttr(defaultValue, writeSparsely) -> Attribute: """ CreateTangentsAttr(defaultValue, writeSparsely) -> Attribute See GetTangentsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def Define(*args, **kwargs) -> None: """ **classmethod** Define(stage, path) -> HermiteCurves Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ @staticmethod def Get(*args, **kwargs) -> None: """ **classmethod** Get(stage, path) -> HermiteCurves Return a UsdGeomHermiteCurves holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomHermiteCurves(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: """ **classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ @staticmethod def GetTangentsAttr() -> Attribute: """ GetTangentsAttr() -> Attribute Defines the outgoing trajectory tangent for each point. Tangents should be the same size as the points attribute. Declaration ``vector3f[] tangents = []`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Vector3fArray """ @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: """ **classmethod** _GetStaticTfType() -> Type """ __instance_size__ = 40 pass class Curves(PointBased, Gprim, Boundable, Xformable, Imageable, pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): """ Base class for UsdGeomBasisCurves, UsdGeomNurbsCurves, and UsdGeomHermiteCurves. The BasisCurves schema is designed to be analagous to offline renderers'notion of batched curves (such as the classical RIB definition via Basis and Curves statements), while the NurbsCurve schema is designed to be analgous to the NURBS curves found in packages like Maya and Houdini while retaining their consistency with the RenderMan specification for NURBS Patches. HermiteCurves are useful for the interchange of animation guides and paths. It is safe to use the length of the curve vertex count to derive the number of curves and the number and layout of curve vertices, but this schema should NOT be used to derive the number of curve points. While vertex indices are implicit in all shipped descendent types of this schema, one should not assume that all internal or future shipped schemas will follow this pattern. Be sure to key any indexing behavior off the concrete type, not this abstract type. """ @staticmethod def ComputeExtent(points, widths, transform, extent) -> bool: """ **classmethod** ComputeExtent(points, widths, extent) -> bool Compute the extent for the curves defined by points and widths. true upon success, false if unable to calculate extent. On success, extent will contain an approximate axis-aligned bounding box of the curve defined by points with the given widths. This function is to provide easy authoring of extent for usd authoring tools, hence it is static and acts outside a specific prim (as in attribute based methods). Parameters ---------- points : Vec3fArray widths : FloatArray extent : Vec3fArray ---------------------------------------------------------------------- This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Computes the extent as if the matrix ``transform`` was first applied. Parameters ---------- points : Vec3fArray widths : FloatArray transform : Matrix4d extent : Vec3fArray """ @staticmethod def CreateCurveVertexCountsAttr(defaultValue, writeSparsely) -> Attribute: """ CreateCurveVertexCountsAttr(defaultValue, writeSparsely) -> Attribute See GetCurveVertexCountsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateWidthsAttr(defaultValue, writeSparsely) -> Attribute: """ CreateWidthsAttr(defaultValue, writeSparsely) -> Attribute See GetWidthsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def Get(*args, **kwargs) -> None: """ **classmethod** Get(stage, path) -> Curves Return a UsdGeomCurves holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomCurves(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ @staticmethod def GetCurveCount(timeCode) -> int: """ GetCurveCount(timeCode) -> int Returns the number of curves as defined by the size of the *curveVertexCounts* array at *timeCode*. For most code, this check will be performant. When using file formats where the cost of attribute reading is high and the time sampled array will be read into memory later, it may be better to explicitly read the value once and check the size of the array directly. Parameters ---------- timeCode : TimeCode """ @staticmethod def GetCurveVertexCountsAttr() -> Attribute: """ GetCurveVertexCountsAttr() -> Attribute Curves-derived primitives can represent multiple distinct, potentially disconnected curves. The length of'curveVertexCounts'gives the number of such curves, and each element describes the number of vertices in the corresponding curve Declaration ``int[] curveVertexCounts`` C++ Type VtArray<int> Usd Type SdfValueTypeNames->IntArray """ @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: """ **classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ @staticmethod def GetWidthsAttr() -> Attribute: """ GetWidthsAttr() -> Attribute Provides width specification for the curves, whose application will depend on whether the curve is oriented (normals are defined for it), in which case widths are"ribbon width", or unoriented, in which case widths are cylinder width. 'widths'is not a generic Primvar, but the number of elements in this attribute will be determined by its'interpolation'. See SetWidthsInterpolation() . If'widths'and'primvars:widths'are both specified, the latter has precedence. Declaration ``float[] widths`` C++ Type VtArray<float> Usd Type SdfValueTypeNames->FloatArray """ @staticmethod def GetWidthsInterpolation() -> str: """ GetWidthsInterpolation() -> str Get the interpolation for the *widths* attribute. Although'widths'is not classified as a generic UsdGeomPrimvar (and will not be included in the results of UsdGeomPrimvarsAPI::GetPrimvars() ) it does require an interpolation specification. The fallback interpolation, if left unspecified, is UsdGeomTokens->vertex, which means a width value is specified at the end of each curve segment. """ @staticmethod def SetWidthsInterpolation(interpolation) -> bool: """ SetWidthsInterpolation(interpolation) -> bool Set the interpolation for the *widths* attribute. true upon success, false if ``interpolation`` is not a legal value as defined by UsdPrimvar::IsValidInterpolation(), or if there was a problem setting the value. No attempt is made to validate that the widths attr's value contains the right number of elements to match its interpolation to its prim's topology. Parameters ---------- interpolation : str """ @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: """ **classmethod** _GetStaticTfType() -> Type """ __instance_size__ = 40 pass class Cylinder(Gprim, Boundable, Xformable, Imageable, pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): """ Defines a primitive cylinder with closed ends, centered at the origin, whose spine is along the specified *axis*. The fallback values for Cube, Sphere, Cone, and Cylinder are set so that they all pack into the same volume/bounds. For any described attribute *Fallback* *Value* or *Allowed* *Values* below that are text/tokens, the actual token is published and defined in UsdGeomTokens. So to set an attribute to the value"rightHanded", use UsdGeomTokens->rightHanded as the value. """ @staticmethod def CreateAxisAttr(defaultValue, writeSparsely) -> Attribute: """ CreateAxisAttr(defaultValue, writeSparsely) -> Attribute See GetAxisAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateExtentAttr(defaultValue, writeSparsely) -> Attribute: """ CreateExtentAttr(defaultValue, writeSparsely) -> Attribute See GetExtentAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateHeightAttr(defaultValue, writeSparsely) -> Attribute: """ CreateHeightAttr(defaultValue, writeSparsely) -> Attribute See GetHeightAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateRadiusAttr(defaultValue, writeSparsely) -> Attribute: """ CreateRadiusAttr(defaultValue, writeSparsely) -> Attribute See GetRadiusAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def Define(*args, **kwargs) -> None: """ **classmethod** Define(stage, path) -> Cylinder Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ @staticmethod def Get(*args, **kwargs) -> None: """ **classmethod** Get(stage, path) -> Cylinder Return a UsdGeomCylinder holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomCylinder(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ @staticmethod def GetAxisAttr() -> Attribute: """ GetAxisAttr() -> Attribute The axis along which the spine of the cylinder is aligned. Declaration ``uniform token axis ="Z"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values X, Y, Z """ @staticmethod def GetExtentAttr() -> Attribute: """ GetExtentAttr() -> Attribute Extent is re-defined on Cylinder only to provide a fallback value. UsdGeomGprim::GetExtentAttr() . Declaration ``float3[] extent = [(-1, -1, -1), (1, 1, 1)]`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Float3Array """ @staticmethod def GetHeightAttr() -> Attribute: """ GetHeightAttr() -> Attribute The size of the cylinder's spine along the specified *axis*. If you author *height* you must also author *extent*. Declaration ``double height = 2`` C++ Type double Usd Type SdfValueTypeNames->Double """ @staticmethod def GetRadiusAttr() -> Attribute: """ GetRadiusAttr() -> Attribute The radius of the cylinder. If you author *radius* you must also author *extent*. Declaration ``double radius = 1`` C++ Type double Usd Type SdfValueTypeNames->Double """ @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: """ **classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: """ **classmethod** _GetStaticTfType() -> Type """ __instance_size__ = 40 pass class Mesh(PointBased, Gprim, Boundable, Xformable, Imageable, pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): """ Encodes a mesh with optional subdivision properties and features. As a point-based primitive, meshes are defined in terms of points that are connected into edges and faces. Many references to meshes use the term'vertex'in place of or interchangeably with'points', while some use'vertex'to refer to the'face-vertices'that define a face. To avoid confusion, the term'vertex'is intentionally avoided in favor of'points'or'face-vertices'. The connectivity between points, edges and faces is encoded using a common minimal topological description of the faces of the mesh. Each face is defined by a set of face-vertices using indices into the Mesh's *points* array (inherited from UsdGeomPointBased) and laid out in a single linear *faceVertexIndices* array for efficiency. A companion *faceVertexCounts* array provides, for each face, the number of consecutive face-vertices in *faceVertexIndices* that define the face. No additional connectivity information is required or constructed, so no adjacency or neighborhood queries are available. A key property of this mesh schema is that it encodes both subdivision surfaces and simpler polygonal meshes. This is achieved by varying the *subdivisionScheme* attribute, which is set to specify Catmull-Clark subdivision by default, so polygonal meshes must always be explicitly declared. The available subdivision schemes and additional subdivision features encoded in optional attributes conform to the feature set of OpenSubdiv ( https://graphics.pixar.com/opensubdiv/docs/subdivision_surfaces.html). **A Note About Primvars** The following list clarifies the number of elements for and the interpolation behavior of the different primvar interpolation types for meshes: - **constant** : One element for the entire mesh; no interpolation. - **uniform** : One element for each face of the mesh; elements are typically not interpolated but are inherited by other faces derived from a given face (via subdivision, tessellation, etc.). - **varying** : One element for each point of the mesh; interpolation of point data is always linear. - **vertex** : One element for each point of the mesh; interpolation of point data is applied according to the *subdivisionScheme* attribute. - **faceVarying** : One element for each of the face-vertices that define the mesh topology; interpolation of face-vertex data may be smooth or linear, according to the *subdivisionScheme* and *faceVaryingLinearInterpolation* attributes. Primvar interpolation types and related utilities are described more generally in Interpolation of Geometric Primitive Variables. **A Note About Normals** Normals should not be authored on a subdivision mesh, since subdivision algorithms define their own normals. They should only be authored for polygonal meshes ( *subdivisionScheme* ="none"). The *normals* attribute inherited from UsdGeomPointBased is not a generic primvar, but the number of elements in this attribute will be determined by its *interpolation*. See UsdGeomPointBased::GetNormalsInterpolation() . If *normals* and *primvars:normals* are both specified, the latter has precedence. If a polygonal mesh specifies **neither** *normals* nor *primvars:normals*, then it should be treated and rendered as faceted, with no attempt to compute smooth normals. The normals generated for smooth subdivision schemes, e.g. Catmull- Clark and Loop, will likewise be smooth, but others, e.g. Bilinear, may be discontinuous between faces and/or within non-planar irregular faces. For any described attribute *Fallback* *Value* or *Allowed* *Values* below that are text/tokens, the actual token is published and defined in UsdGeomTokens. So to set an attribute to the value"rightHanded", use UsdGeomTokens->rightHanded as the value. """ @staticmethod def CreateCornerIndicesAttr(defaultValue, writeSparsely) -> Attribute: """ CreateCornerIndicesAttr(defaultValue, writeSparsely) -> Attribute See GetCornerIndicesAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateCornerSharpnessesAttr(defaultValue, writeSparsely) -> Attribute: """ CreateCornerSharpnessesAttr(defaultValue, writeSparsely) -> Attribute See GetCornerSharpnessesAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateCreaseIndicesAttr(defaultValue, writeSparsely) -> Attribute: """ CreateCreaseIndicesAttr(defaultValue, writeSparsely) -> Attribute See GetCreaseIndicesAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateCreaseLengthsAttr(defaultValue, writeSparsely) -> Attribute: """ CreateCreaseLengthsAttr(defaultValue, writeSparsely) -> Attribute See GetCreaseLengthsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateCreaseSharpnessesAttr(defaultValue, writeSparsely) -> Attribute: """ CreateCreaseSharpnessesAttr(defaultValue, writeSparsely) -> Attribute See GetCreaseSharpnessesAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateFaceVaryingLinearInterpolationAttr(defaultValue, writeSparsely) -> Attribute: """ CreateFaceVaryingLinearInterpolationAttr(defaultValue, writeSparsely) -> Attribute See GetFaceVaryingLinearInterpolationAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateFaceVertexCountsAttr(defaultValue, writeSparsely) -> Attribute: """ CreateFaceVertexCountsAttr(defaultValue, writeSparsely) -> Attribute See GetFaceVertexCountsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateFaceVertexIndicesAttr(defaultValue, writeSparsely) -> Attribute: """ CreateFaceVertexIndicesAttr(defaultValue, writeSparsely) -> Attribute See GetFaceVertexIndicesAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateHoleIndicesAttr(defaultValue, writeSparsely) -> Attribute: """ CreateHoleIndicesAttr(defaultValue, writeSparsely) -> Attribute See GetHoleIndicesAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateInterpolateBoundaryAttr(defaultValue, writeSparsely) -> Attribute: """ CreateInterpolateBoundaryAttr(defaultValue, writeSparsely) -> Attribute See GetInterpolateBoundaryAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateSubdivisionSchemeAttr(defaultValue, writeSparsely) -> Attribute: """ CreateSubdivisionSchemeAttr(defaultValue, writeSparsely) -> Attribute See GetSubdivisionSchemeAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateTriangleSubdivisionRuleAttr(defaultValue, writeSparsely) -> Attribute: """ CreateTriangleSubdivisionRuleAttr(defaultValue, writeSparsely) -> Attribute See GetTriangleSubdivisionRuleAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def Define(*args, **kwargs) -> None: """ **classmethod** Define(stage, path) -> Mesh Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ @staticmethod def Get(*args, **kwargs) -> None: """ **classmethod** Get(stage, path) -> Mesh Return a UsdGeomMesh holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomMesh(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ @staticmethod def GetCornerIndicesAttr() -> Attribute: """ GetCornerIndicesAttr() -> Attribute The indices of points for which a corresponding sharpness value is specified in *cornerSharpnesses* (so the size of this array must match that of *cornerSharpnesses*). Declaration ``int[] cornerIndices = []`` C++ Type VtArray<int> Usd Type SdfValueTypeNames->IntArray """ @staticmethod def GetCornerSharpnessesAttr() -> Attribute: """ GetCornerSharpnessesAttr() -> Attribute The sharpness values associated with a corresponding set of points specified in *cornerIndices* (so the size of this array must match that of *cornerIndices*). Use the constant ``SHARPNESS_INFINITE`` for a perfectly sharp corner. Declaration ``float[] cornerSharpnesses = []`` C++ Type VtArray<float> Usd Type SdfValueTypeNames->FloatArray """ @staticmethod def GetCreaseIndicesAttr() -> Attribute: """ GetCreaseIndicesAttr() -> Attribute The indices of points grouped into sets of successive pairs that identify edges to be creased. The size of this array must be equal to the sum of all elements of the *creaseLengths* attribute. Declaration ``int[] creaseIndices = []`` C++ Type VtArray<int> Usd Type SdfValueTypeNames->IntArray """ @staticmethod def GetCreaseLengthsAttr() -> Attribute: """ GetCreaseLengthsAttr() -> Attribute The length of this array specifies the number of creases (sets of adjacent sharpened edges) on the mesh. Each element gives the number of points of each crease, whose indices are successively laid out in the *creaseIndices* attribute. Since each crease must be at least one edge long, each element of this array must be at least two. Declaration ``int[] creaseLengths = []`` C++ Type VtArray<int> Usd Type SdfValueTypeNames->IntArray """ @staticmethod def GetCreaseSharpnessesAttr() -> Attribute: """ GetCreaseSharpnessesAttr() -> Attribute The per-crease or per-edge sharpness values for all creases. Since *creaseLengths* encodes the number of points in each crease, the number of elements in this array will be either len(creaseLengths) or the sum over all X of (creaseLengths[X] - 1). Note that while the RI spec allows each crease to have either a single sharpness or a value per-edge, USD will encode either a single sharpness per crease on a mesh, or sharpnesses for all edges making up the creases on a mesh. Use the constant ``SHARPNESS_INFINITE`` for a perfectly sharp crease. Declaration ``float[] creaseSharpnesses = []`` C++ Type VtArray<float> Usd Type SdfValueTypeNames->FloatArray """ @staticmethod def GetFaceCount(timeCode) -> int: """ GetFaceCount(timeCode) -> int Returns the number of faces as defined by the size of the *faceVertexCounts* array at *timeCode*. For most code, this check will be performant. When using file formats where the cost of attribute reading is high and the time sampled array will be read into memory later, it may be better to explicitly read the value once and check the size of the array directly. Parameters ---------- timeCode : TimeCode """ @staticmethod def GetFaceVaryingLinearInterpolationAttr() -> Attribute: """ GetFaceVaryingLinearInterpolationAttr() -> Attribute Specifies how elements of a primvar of interpolation type"faceVarying"are interpolated for subdivision surfaces. Interpolation can be as smooth as a"vertex"primvar or constrained to be linear at features specified by several options. Valid values correspond to choices available in OpenSubdiv: - **none** : No linear constraints or sharpening, smooth everywhere - **cornersOnly** : Sharpen corners of discontinuous boundaries only, smooth everywhere else - **cornersPlus1** : The default, same as"cornersOnly"plus additional sharpening at points where three or more distinct face- varying values occur - **cornersPlus2** : Same as"cornersPlus1"plus additional sharpening at points with at least one discontinuous boundary corner or only one discontinuous boundary edge (a dart) - **boundaries** : Piecewise linear along discontinuous boundaries, smooth interior - **all** : Piecewise linear everywhere These are illustrated and described in more detail in the OpenSubdiv documentation: https://graphics.pixar.com/opensubdiv/docs/subdivision_surfaces.html#face- varying-interpolation-rules Declaration ``token faceVaryingLinearInterpolation ="cornersPlus1"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Allowed Values none, cornersOnly, cornersPlus1, cornersPlus2, boundaries, all """ @staticmethod def GetFaceVertexCountsAttr() -> Attribute: """ GetFaceVertexCountsAttr() -> Attribute Provides the number of vertices in each face of the mesh, which is also the number of consecutive indices in *faceVertexIndices* that define the face. The length of this attribute is the number of faces in the mesh. If this attribute has more than one timeSample, the mesh is considered to be topologically varying. Declaration ``int[] faceVertexCounts`` C++ Type VtArray<int> Usd Type SdfValueTypeNames->IntArray """ @staticmethod def GetFaceVertexIndicesAttr() -> Attribute: """ GetFaceVertexIndicesAttr() -> Attribute Flat list of the index (into the *points* attribute) of each vertex of each face in the mesh. If this attribute has more than one timeSample, the mesh is considered to be topologically varying. Declaration ``int[] faceVertexIndices`` C++ Type VtArray<int> Usd Type SdfValueTypeNames->IntArray """ @staticmethod def GetHoleIndicesAttr() -> Attribute: """ GetHoleIndicesAttr() -> Attribute The indices of all faces that should be treated as holes, i.e. made invisible. This is traditionally a feature of subdivision surfaces and not generally applied to polygonal meshes. Declaration ``int[] holeIndices = []`` C++ Type VtArray<int> Usd Type SdfValueTypeNames->IntArray """ @staticmethod def GetInterpolateBoundaryAttr() -> Attribute: """ GetInterpolateBoundaryAttr() -> Attribute Specifies how subdivision is applied for faces adjacent to boundary edges and boundary points. Valid values correspond to choices available in OpenSubdiv: - **none** : No boundary interpolation is applied and boundary faces are effectively treated as holes - **edgeOnly** : A sequence of boundary edges defines a smooth curve to which the edges of subdivided boundary faces converge - **edgeAndCorner** : The default, similar to"edgeOnly"but the smooth boundary curve is made sharp at corner points These are illustrated and described in more detail in the OpenSubdiv documentation: https://graphics.pixar.com/opensubdiv/docs/subdivision_surfaces.html#boundary- interpolation-rules Declaration ``token interpolateBoundary ="edgeAndCorner"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Allowed Values none, edgeOnly, edgeAndCorner """ @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: """ **classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ @staticmethod def GetSubdivisionSchemeAttr() -> Attribute: """ GetSubdivisionSchemeAttr() -> Attribute The subdivision scheme to be applied to the surface. Valid values are: - **catmullClark** : The default, Catmull-Clark subdivision; preferred for quad-dominant meshes (generalizes B-splines); interpolation of point data is smooth (non-linear) - **loop** : Loop subdivision; preferred for purely triangular meshes; interpolation of point data is smooth (non-linear) - **bilinear** : Subdivision reduces all faces to quads (topologically similar to"catmullClark"); interpolation of point data is bilinear - **none** : No subdivision, i.e. a simple polygonal mesh; interpolation of point data is linear Polygonal meshes are typically lighter weight and faster to render, depending on renderer and render mode. Use of"bilinear"will produce a similar shape to a polygonal mesh and may offer additional guarantees of watertightness and additional subdivision features (e.g. holes) but may also not respect authored normals. Declaration ``uniform token subdivisionScheme ="catmullClark"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values catmullClark, loop, bilinear, none """ @staticmethod def GetTriangleSubdivisionRuleAttr() -> Attribute: """ GetTriangleSubdivisionRuleAttr() -> Attribute Specifies an option to the subdivision rules for the Catmull-Clark scheme to try and improve undesirable artifacts when subdividing triangles. Valid values are"catmullClark"for the standard rules (the default) and"smooth"for the improvement. See https://graphics.pixar.com/opensubdiv/docs/subdivision_surfaces.html#triangle- subdivision-rule Declaration ``token triangleSubdivisionRule ="catmullClark"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Allowed Values catmullClark, smooth """ @staticmethod def ValidateTopology(*args, **kwargs) -> None: """ **classmethod** ValidateTopology(faceVertexIndices, faceVertexCounts, numPoints, reason) -> bool Validate the topology of a mesh. This validates that the sum of ``faceVertexCounts`` is equal to the size of the ``faceVertexIndices`` array, and that all face vertex indices in the ``faceVertexIndices`` array are in the range [0, numPoints). Returns true if the topology is valid, or false otherwise. If the topology is invalid and ``reason`` is non-null, an error message describing the validation error will be set. Parameters ---------- faceVertexIndices : IntArray faceVertexCounts : IntArray numPoints : int reason : str """ @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: """ **classmethod** _GetStaticTfType() -> Type """ SHARPNESS_INFINITE = 10.0 __instance_size__ = 40 pass class NurbsCurves(Curves, PointBased, Gprim, Boundable, Xformable, Imageable, pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): """ This schema is analagous to NURBS Curves in packages like Maya and Houdini, often used for interchange of rigging and modeling curves. Unlike Maya, this curve spec supports batching of multiple curves into a single prim, widths, and normals in the schema. Additionally, we require'numSegments + 2 \* degree + 1'knots (2 more than maya does). This is to be more consistent with RenderMan's NURBS patch specification. To express a periodic curve: - knot[0] = knot[1] - (knots[-2] - knots[-3]; - knot[-1] = knot[-2] + (knot[2] - knots[1]); To express a nonperiodic curve: - knot[0] = knot[1]; - knot[-1] = knot[-2]; In spite of these slight differences in the spec, curves generated in Maya should be preserved when roundtripping. *order* and *range*, when representing a batched NurbsCurve should be authored one value per curve. *knots* should be the concatentation of all batched curves. **NurbsCurve Form** **Form** is provided as an aid to interchange between modeling and animation applications so that they can robustly identify the intent with which the surface was modelled, and take measures (if they are able) to preserve the continuity/concidence constraints as the surface may be rigged or deformed. - An *open-form* NurbsCurve has no continuity constraints. - A *closed-form* NurbsCurve expects the first and last control points to overlap - A *periodic-form* NurbsCurve expects the first and last *order* - 1 control points to overlap. For any described attribute *Fallback* *Value* or *Allowed* *Values* below that are text/tokens, the actual token is published and defined in UsdGeomTokens. So to set an attribute to the value"rightHanded", use UsdGeomTokens->rightHanded as the value. """ @staticmethod def CreateFormAttr(defaultValue, writeSparsely) -> Attribute: """ CreateFormAttr(defaultValue, writeSparsely) -> Attribute See GetFormAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateKnotsAttr(defaultValue, writeSparsely) -> Attribute: """ CreateKnotsAttr(defaultValue, writeSparsely) -> Attribute See GetKnotsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateOrderAttr(defaultValue, writeSparsely) -> Attribute: """ CreateOrderAttr(defaultValue, writeSparsely) -> Attribute See GetOrderAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreatePointWeightsAttr(defaultValue, writeSparsely) -> Attribute: """ CreatePointWeightsAttr(defaultValue, writeSparsely) -> Attribute See GetPointWeightsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateRangesAttr(defaultValue, writeSparsely) -> Attribute: """ CreateRangesAttr(defaultValue, writeSparsely) -> Attribute See GetRangesAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def Define(*args, **kwargs) -> None: """ **classmethod** Define(stage, path) -> NurbsCurves Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ @staticmethod def Get(*args, **kwargs) -> None: """ **classmethod** Get(stage, path) -> NurbsCurves Return a UsdGeomNurbsCurves holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomNurbsCurves(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ @staticmethod def GetFormAttr() -> Attribute: """ GetFormAttr() -> Attribute Interpret the control grid and knot vectors as representing an open, geometrically closed, or geometrically closed and C2 continuous curve. NurbsCurve Form Declaration ``uniform token form ="open"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values open, closed, periodic """ @staticmethod def GetKnotsAttr() -> Attribute: """ GetKnotsAttr() -> Attribute Knot vector providing curve parameterization. The length of the slice of the array for the ith curve must be ( curveVertexCount[i] + order[i] ), and its entries must take on monotonically increasing values. Declaration ``double[] knots`` C++ Type VtArray<double> Usd Type SdfValueTypeNames->DoubleArray """ @staticmethod def GetOrderAttr() -> Attribute: """ GetOrderAttr() -> Attribute Order of the curve. Order must be positive and is equal to the degree of the polynomial basis to be evaluated, plus 1. Its value for the'i'th curve must be less than or equal to curveVertexCount[i] Declaration ``int[] order = []`` C++ Type VtArray<int> Usd Type SdfValueTypeNames->IntArray """ @staticmethod def GetPointWeightsAttr() -> Attribute: """ GetPointWeightsAttr() -> Attribute Optionally provides"w"components for each control point, thus must be the same length as the points attribute. If authored, the patch will be rational. If unauthored, the patch will be polynomial, i.e. weight for all points is 1.0. Some DCC's pre-weight the *points*, but in this schema, *points* are not pre-weighted. Declaration ``double[] pointWeights`` C++ Type VtArray<double> Usd Type SdfValueTypeNames->DoubleArray """ @staticmethod def GetRangesAttr() -> Attribute: """ GetRangesAttr() -> Attribute Provides the minimum and maximum parametric values (as defined by knots) over which the curve is actually defined. The minimum must be less than the maximum, and greater than or equal to the value of the knots['i'th curve slice][order[i]-1]. The maxium must be less than or equal to the last element's value in knots['i'th curve slice]. Range maps to (vmin, vmax) in the RenderMan spec. Declaration ``double2[] ranges`` C++ Type VtArray<GfVec2d> Usd Type SdfValueTypeNames->Double2Array """ @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: """ **classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: """ **classmethod** _GetStaticTfType() -> Type """ __instance_size__ = 40 pass class NurbsPatch(PointBased, Gprim, Boundable, Xformable, Imageable, pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): """ Encodes a rational or polynomial non-uniform B-spline surface, with optional trim curves. The encoding mostly follows that of RiNuPatch and RiTrimCurve: https://renderman.pixar.com/resources/current/RenderMan/geometricPrimitives.html#rinupatch, with some minor renaming and coalescing for clarity. The layout of control vertices in the *points* attribute inherited from UsdGeomPointBased is row-major with U considered rows, and V columns. **NurbsPatch Form** The authored points, orders, knots, weights, and ranges are all that is required to render the nurbs patch. However, the only way to model closed surfaces with nurbs is to ensure that the first and last control points along the given axis are coincident. Similarly, to ensure the surface is not only closed but also C2 continuous, the last *order* - 1 control points must be (correspondingly) coincident with the first *order* - 1 control points, and also the spacing of the last corresponding knots must be the same as the first corresponding knots. **Form** is provided as an aid to interchange between modeling and animation applications so that they can robustly identify the intent with which the surface was modelled, and take measures (if they are able) to preserve the continuity/concidence constraints as the surface may be rigged or deformed. - An *open-form* NurbsPatch has no continuity constraints. - A *closed-form* NurbsPatch expects the first and last control points to overlap - A *periodic-form* NurbsPatch expects the first and last *order* - 1 control points to overlap. **Nurbs vs Subdivision Surfaces** Nurbs are an important modeling primitive in CAD/CAM tools and early computer graphics DCC's. Because they have a natural UV parameterization they easily support"trim curves", which allow smooth shapes to be carved out of the surface. However, the topology of the patch is always rectangular, and joining two nurbs patches together (especially when they have differing numbers of spans) is difficult to do smoothly. Also, nurbs are not supported by the Ptex texturing technology ( http://ptex.us). Neither of these limitations are shared by subdivision surfaces; therefore, although they do not subscribe to trim-curve-based shaping, subdivs are often considered a more flexible modeling primitive. For any described attribute *Fallback* *Value* or *Allowed* *Values* below that are text/tokens, the actual token is published and defined in UsdGeomTokens. So to set an attribute to the value"rightHanded", use UsdGeomTokens->rightHanded as the value. """ @staticmethod def CreatePointWeightsAttr(defaultValue, writeSparsely) -> Attribute: """ CreatePointWeightsAttr(defaultValue, writeSparsely) -> Attribute See GetPointWeightsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateTrimCurveCountsAttr(defaultValue, writeSparsely) -> Attribute: """ CreateTrimCurveCountsAttr(defaultValue, writeSparsely) -> Attribute See GetTrimCurveCountsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateTrimCurveKnotsAttr(defaultValue, writeSparsely) -> Attribute: """ CreateTrimCurveKnotsAttr(defaultValue, writeSparsely) -> Attribute See GetTrimCurveKnotsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateTrimCurveOrdersAttr(defaultValue, writeSparsely) -> Attribute: """ CreateTrimCurveOrdersAttr(defaultValue, writeSparsely) -> Attribute See GetTrimCurveOrdersAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateTrimCurvePointsAttr(defaultValue, writeSparsely) -> Attribute: """ CreateTrimCurvePointsAttr(defaultValue, writeSparsely) -> Attribute See GetTrimCurvePointsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateTrimCurveRangesAttr(defaultValue, writeSparsely) -> Attribute: """ CreateTrimCurveRangesAttr(defaultValue, writeSparsely) -> Attribute See GetTrimCurveRangesAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateTrimCurveVertexCountsAttr(defaultValue, writeSparsely) -> Attribute: """ CreateTrimCurveVertexCountsAttr(defaultValue, writeSparsely) -> Attribute See GetTrimCurveVertexCountsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateUFormAttr(defaultValue, writeSparsely) -> Attribute: """ CreateUFormAttr(defaultValue, writeSparsely) -> Attribute See GetUFormAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateUKnotsAttr(defaultValue, writeSparsely) -> Attribute: """ CreateUKnotsAttr(defaultValue, writeSparsely) -> Attribute See GetUKnotsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateUOrderAttr(defaultValue, writeSparsely) -> Attribute: """ CreateUOrderAttr(defaultValue, writeSparsely) -> Attribute See GetUOrderAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateURangeAttr(defaultValue, writeSparsely) -> Attribute: """ CreateURangeAttr(defaultValue, writeSparsely) -> Attribute See GetURangeAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateUVertexCountAttr(defaultValue, writeSparsely) -> Attribute: """ CreateUVertexCountAttr(defaultValue, writeSparsely) -> Attribute See GetUVertexCountAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateVFormAttr(defaultValue, writeSparsely) -> Attribute: """ CreateVFormAttr(defaultValue, writeSparsely) -> Attribute See GetVFormAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateVKnotsAttr(defaultValue, writeSparsely) -> Attribute: """ CreateVKnotsAttr(defaultValue, writeSparsely) -> Attribute See GetVKnotsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateVOrderAttr(defaultValue, writeSparsely) -> Attribute: """ CreateVOrderAttr(defaultValue, writeSparsely) -> Attribute See GetVOrderAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateVRangeAttr(defaultValue, writeSparsely) -> Attribute: """ CreateVRangeAttr(defaultValue, writeSparsely) -> Attribute See GetVRangeAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateVVertexCountAttr(defaultValue, writeSparsely) -> Attribute: """ CreateVVertexCountAttr(defaultValue, writeSparsely) -> Attribute See GetVVertexCountAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def Define(*args, **kwargs) -> None: """ **classmethod** Define(stage, path) -> NurbsPatch Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ @staticmethod def Get(*args, **kwargs) -> None: """ **classmethod** Get(stage, path) -> NurbsPatch Return a UsdGeomNurbsPatch holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomNurbsPatch(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ @staticmethod def GetPointWeightsAttr() -> Attribute: """ GetPointWeightsAttr() -> Attribute Optionally provides"w"components for each control point, thus must be the same length as the points attribute. If authored, the patch will be rational. If unauthored, the patch will be polynomial, i.e. weight for all points is 1.0. Some DCC's pre-weight the *points*, but in this schema, *points* are not pre-weighted. Declaration ``double[] pointWeights`` C++ Type VtArray<double> Usd Type SdfValueTypeNames->DoubleArray """ @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: """ **classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ @staticmethod def GetTrimCurveCountsAttr() -> Attribute: """ GetTrimCurveCountsAttr() -> Attribute Each element specifies how many curves are present in each"loop"of the trimCurve, and the length of the array determines how many loops the trimCurve contains. The sum of all elements is the total nuber of curves in the trim, to which we will refer as *nCurves* in describing the other trim attributes. Declaration ``int[] trimCurve:counts`` C++ Type VtArray<int> Usd Type SdfValueTypeNames->IntArray """ @staticmethod def GetTrimCurveKnotsAttr() -> Attribute: """ GetTrimCurveKnotsAttr() -> Attribute Flat list of parametric values for each of the *nCurves* curves. There will be as many knots as the sum over all elements of *vertexCounts* plus the sum over all elements of *orders*. Declaration ``double[] trimCurve:knots`` C++ Type VtArray<double> Usd Type SdfValueTypeNames->DoubleArray """ @staticmethod def GetTrimCurveOrdersAttr() -> Attribute: """ GetTrimCurveOrdersAttr() -> Attribute Flat list of orders for each of the *nCurves* curves. Declaration ``int[] trimCurve:orders`` C++ Type VtArray<int> Usd Type SdfValueTypeNames->IntArray """ @staticmethod def GetTrimCurvePointsAttr() -> Attribute: """ GetTrimCurvePointsAttr() -> Attribute Flat list of homogeneous 2D points (u, v, w) that comprise the *nCurves* curves. The number of points should be equal to the um over all elements of *vertexCounts*. Declaration ``double3[] trimCurve:points`` C++ Type VtArray<GfVec3d> Usd Type SdfValueTypeNames->Double3Array """ @staticmethod def GetTrimCurveRangesAttr() -> Attribute: """ GetTrimCurveRangesAttr() -> Attribute Flat list of minimum and maximum parametric values (as defined by *knots*) for each of the *nCurves* curves. Declaration ``double2[] trimCurve:ranges`` C++ Type VtArray<GfVec2d> Usd Type SdfValueTypeNames->Double2Array """ @staticmethod def GetTrimCurveVertexCountsAttr() -> Attribute: """ GetTrimCurveVertexCountsAttr() -> Attribute Flat list of number of vertices for each of the *nCurves* curves. Declaration ``int[] trimCurve:vertexCounts`` C++ Type VtArray<int> Usd Type SdfValueTypeNames->IntArray """ @staticmethod def GetUFormAttr() -> Attribute: """ GetUFormAttr() -> Attribute Interpret the control grid and knot vectors as representing an open, geometrically closed, or geometrically closed and C2 continuous surface along the U dimension. NurbsPatch Form Declaration ``uniform token uForm ="open"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values open, closed, periodic """ @staticmethod def GetUKnotsAttr() -> Attribute: """ GetUKnotsAttr() -> Attribute Knot vector for U direction providing U parameterization. The length of this array must be ( uVertexCount + uOrder), and its entries must take on monotonically increasing values. Declaration ``double[] uKnots`` C++ Type VtArray<double> Usd Type SdfValueTypeNames->DoubleArray """ @staticmethod def GetUOrderAttr() -> Attribute: """ GetUOrderAttr() -> Attribute Order in the U direction. Order must be positive and is equal to the degree of the polynomial basis to be evaluated, plus 1. Declaration ``int uOrder`` C++ Type int Usd Type SdfValueTypeNames->Int """ @staticmethod def GetURangeAttr() -> Attribute: """ GetURangeAttr() -> Attribute Provides the minimum and maximum parametric values (as defined by uKnots) over which the surface is actually defined. The minimum must be less than the maximum, and greater than or equal to the value of uKnots[uOrder-1]. The maxium must be less than or equal to the last element's value in uKnots. Declaration ``double2 uRange`` C++ Type GfVec2d Usd Type SdfValueTypeNames->Double2 """ @staticmethod def GetUVertexCountAttr() -> Attribute: """ GetUVertexCountAttr() -> Attribute Number of vertices in the U direction. Should be at least as large as uOrder. Declaration ``int uVertexCount`` C++ Type int Usd Type SdfValueTypeNames->Int """ @staticmethod def GetVFormAttr() -> Attribute: """ GetVFormAttr() -> Attribute Interpret the control grid and knot vectors as representing an open, geometrically closed, or geometrically closed and C2 continuous surface along the V dimension. NurbsPatch Form Declaration ``uniform token vForm ="open"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values open, closed, periodic """ @staticmethod def GetVKnotsAttr() -> Attribute: """ GetVKnotsAttr() -> Attribute Knot vector for V direction providing U parameterization. The length of this array must be ( vVertexCount + vOrder), and its entries must take on monotonically increasing values. Declaration ``double[] vKnots`` C++ Type VtArray<double> Usd Type SdfValueTypeNames->DoubleArray """ @staticmethod def GetVOrderAttr() -> Attribute: """ GetVOrderAttr() -> Attribute Order in the V direction. Order must be positive and is equal to the degree of the polynomial basis to be evaluated, plus 1. Declaration ``int vOrder`` C++ Type int Usd Type SdfValueTypeNames->Int """ @staticmethod def GetVRangeAttr() -> Attribute: """ GetVRangeAttr() -> Attribute Provides the minimum and maximum parametric values (as defined by vKnots) over which the surface is actually defined. The minimum must be less than the maximum, and greater than or equal to the value of vKnots[vOrder-1]. The maxium must be less than or equal to the last element's value in vKnots. Declaration ``double2 vRange`` C++ Type GfVec2d Usd Type SdfValueTypeNames->Double2 """ @staticmethod def GetVVertexCountAttr() -> Attribute: """ GetVVertexCountAttr() -> Attribute Number of vertices in the V direction. Should be at least as large as vOrder. Declaration ``int vVertexCount`` C++ Type int Usd Type SdfValueTypeNames->Int """ @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: """ **classmethod** _GetStaticTfType() -> Type """ __instance_size__ = 40 pass class Plane(Gprim, Boundable, Xformable, Imageable, pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): """ Defines a primitive plane, centered at the origin, and is defined by a cardinal axis, width, and length. The plane is double-sided by default. The axis of width and length are perpendicular to the plane's *axis*: axis width length X z-axis y-axis Y x-axis z-axis Z x-axis y-axis For any described attribute *Fallback* *Value* or *Allowed* *Values* below that are text/tokens, the actual token is published and defined in UsdGeomTokens. So to set an attribute to the value"rightHanded", use UsdGeomTokens->rightHanded as the value. """ @staticmethod def CreateAxisAttr(defaultValue, writeSparsely) -> Attribute: """ CreateAxisAttr(defaultValue, writeSparsely) -> Attribute See GetAxisAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateDoubleSidedAttr(defaultValue, writeSparsely) -> Attribute: """ CreateDoubleSidedAttr(defaultValue, writeSparsely) -> Attribute See GetDoubleSidedAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateExtentAttr(defaultValue, writeSparsely) -> Attribute: """ CreateExtentAttr(defaultValue, writeSparsely) -> Attribute See GetExtentAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateLengthAttr(defaultValue, writeSparsely) -> Attribute: """ CreateLengthAttr(defaultValue, writeSparsely) -> Attribute See GetLengthAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateWidthAttr(defaultValue, writeSparsely) -> Attribute: """ CreateWidthAttr(defaultValue, writeSparsely) -> Attribute See GetWidthAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def Define(*args, **kwargs) -> None: """ **classmethod** Define(stage, path) -> Plane Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ @staticmethod def Get(*args, **kwargs) -> None: """ **classmethod** Get(stage, path) -> Plane Return a UsdGeomPlane holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomPlane(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ @staticmethod def GetAxisAttr() -> Attribute: """ GetAxisAttr() -> Attribute The axis along which the surface of the plane is aligned. When set to'Z'the plane is in the xy-plane; when *axis* is'X'the plane is in the yz-plane, and when *axis* is'Y'the plane is in the xz-plane. UsdGeomGprim::GetAxisAttr(). Declaration ``uniform token axis ="Z"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values X, Y, Z """ @staticmethod def GetDoubleSidedAttr() -> Attribute: """ GetDoubleSidedAttr() -> Attribute Planes are double-sided by default. Clients may also support single-sided planes. UsdGeomGprim::GetDoubleSidedAttr() Declaration ``uniform bool doubleSided = 1`` C++ Type bool Usd Type SdfValueTypeNames->Bool Variability SdfVariabilityUniform """ @staticmethod def GetExtentAttr() -> Attribute: """ GetExtentAttr() -> Attribute Extent is re-defined on Plane only to provide a fallback value. UsdGeomGprim::GetExtentAttr() . Declaration ``float3[] extent = [(-1, -1, 0), (1, 1, 0)]`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Float3Array """ @staticmethod def GetLengthAttr() -> Attribute: """ GetLengthAttr() -> Attribute The length of the plane, which aligns to the y-axis when *axis* is'Z'or'X', or to the z-axis when *axis* is'Y'. If you author *length* you must also author *extent*. UsdGeomGprim::GetExtentAttr() Declaration ``double length = 2`` C++ Type double Usd Type SdfValueTypeNames->Double """ @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: """ **classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ @staticmethod def GetWidthAttr() -> Attribute: """ GetWidthAttr() -> Attribute The width of the plane, which aligns to the x-axis when *axis* is'Z'or'Y', or to the z-axis when *axis* is'X'. If you author *width* you must also author *extent*. UsdGeomGprim::GetExtentAttr() Declaration ``double width = 2`` C++ Type double Usd Type SdfValueTypeNames->Double """ @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: """ **classmethod** _GetStaticTfType() -> Type """ __instance_size__ = 40 pass class Points(PointBased, Gprim, Boundable, Xformable, Imageable, pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): """ Points are analogous to the RiPoints spec. Points can be an efficient means of storing and rendering particle effects comprised of thousands or millions of small particles. Points generally receive a single shading sample each, which should take *normals* into account, if present. While not technically UsdGeomPrimvars, the widths and normals also have interpolation metadata. It's common for authored widths and normals to have constant or varying interpolation. """ @staticmethod def ComputeExtent(points, widths, transform, extent) -> bool: """ **classmethod** ComputeExtent(points, widths, extent) -> bool Compute the extent for the point cloud defined by points and widths. true upon success, false if widths and points are different sized arrays. On success, extent will contain the axis-aligned bounding box of the point cloud defined by points with the given widths. This function is to provide easy authoring of extent for usd authoring tools, hence it is static and acts outside a specific prim (as in attribute based methods). Parameters ---------- points : Vec3fArray widths : FloatArray extent : Vec3fArray ---------------------------------------------------------------------- This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Computes the extent as if the matrix ``transform`` was first applied. Parameters ---------- points : Vec3fArray widths : FloatArray transform : Matrix4d extent : Vec3fArray """ @staticmethod def CreateIdsAttr(defaultValue, writeSparsely) -> Attribute: """ CreateIdsAttr(defaultValue, writeSparsely) -> Attribute See GetIdsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateWidthsAttr(defaultValue, writeSparsely) -> Attribute: """ CreateWidthsAttr(defaultValue, writeSparsely) -> Attribute See GetWidthsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def Define(*args, **kwargs) -> None: """ **classmethod** Define(stage, path) -> Points Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ @staticmethod def Get(*args, **kwargs) -> None: """ **classmethod** Get(stage, path) -> Points Return a UsdGeomPoints holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomPoints(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ @staticmethod def GetIdsAttr() -> Attribute: """ GetIdsAttr() -> Attribute Ids are optional; if authored, the ids array should be the same length as the points array, specifying (at each timesample if point identities are changing) the id of each point. The type is signed intentionally, so that clients can encode some binary state on Id'd points without adding a separate primvar. Declaration ``int64[] ids`` C++ Type VtArray<int64_t> Usd Type SdfValueTypeNames->Int64Array """ @staticmethod def GetPointCount(timeCode) -> int: """ GetPointCount(timeCode) -> int Returns the number of points as defined by the size of the *points* array at *timeCode*. For most code, this check will be performant. When using file formats where the cost of attribute reading is high and the time sampled array will be read into memory later, it may be better to explicitly read the value once and check the size of the array directly. Parameters ---------- timeCode : TimeCode """ @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: """ **classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ @staticmethod def GetWidthsAttr() -> Attribute: """ GetWidthsAttr() -> Attribute Widths are defined as the *diameter* of the points, in object space. 'widths'is not a generic Primvar, but the number of elements in this attribute will be determined by its'interpolation'. See SetWidthsInterpolation() . If'widths'and'primvars:widths'are both specified, the latter has precedence. Declaration ``float[] widths`` C++ Type VtArray<float> Usd Type SdfValueTypeNames->FloatArray """ @staticmethod def GetWidthsInterpolation() -> str: """ GetWidthsInterpolation() -> str Get the interpolation for the *widths* attribute. Although'widths'is not classified as a generic UsdGeomPrimvar (and will not be included in the results of UsdGeomPrimvarsAPI::GetPrimvars() ) it does require an interpolation specification. The fallback interpolation, if left unspecified, is UsdGeomTokens->vertex, which means a width value is specified for each point. """ @staticmethod def SetWidthsInterpolation(interpolation) -> bool: """ SetWidthsInterpolation(interpolation) -> bool Set the interpolation for the *widths* attribute. true upon success, false if ``interpolation`` is not a legal value as defined by UsdPrimvar::IsValidInterpolation(), or if there was a problem setting the value. No attempt is made to validate that the widths attr's value contains the right number of elements to match its interpolation to its prim's topology. Parameters ---------- interpolation : str """ @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: """ **classmethod** _GetStaticTfType() -> Type """ __instance_size__ = 40 pass class PointBased(Gprim, Boundable, Xformable, Imageable, pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): """ Base class for all UsdGeomGprims that possess points, providing common attributes such as normals and velocities. """ @staticmethod def ComputeExtent(points, transform, extent) -> bool: """ **classmethod** ComputeExtent(points, extent) -> bool Compute the extent for the point cloud defined by points. true on success, false if extents was unable to be calculated. On success, extent will contain the axis-aligned bounding box of the point cloud defined by points. This function is to provide easy authoring of extent for usd authoring tools, hence it is static and acts outside a specific prim (as in attribute based methods). Parameters ---------- points : Vec3fArray extent : Vec3fArray ---------------------------------------------------------------------- This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Computes the extent as if the matrix ``transform`` was first applied. Parameters ---------- points : Vec3fArray transform : Matrix4d extent : Vec3fArray """ @staticmethod def ComputePointsAtTime(points, stage, time, positions, velocities, velocitiesSampleTime, accelerations, velocityScale) -> bool: """ **classmethod** ComputePointsAtTime(points, time, baseTime) -> bool Compute points given the positions, velocities and accelerations at ``time`` . This will return ``false`` and leave ``points`` untouched if: - ``points`` is None - one of ``time`` and ``baseTime`` is numeric and the other is UsdTimeCode::Default() (they must either both be numeric or both be default) - there is no authored points attribute If there is no error, we will return ``true`` and ``points`` will contain the computed points. points \- the out parameter for the new points. Its size will depend on the authored data. time \- UsdTimeCode at which we want to evaluate the transforms baseTime \- required for correct interpolation between samples when *velocities* or *accelerations* are present. If there are samples for *positions* and *velocities* at t1 and t2, normal value resolution would attempt to interpolate between the two samples, and if they could not be interpolated because they differ in size (common in cases where velocity is authored), will choose the sample at t1. When sampling for the purposes of motion-blur, for example, it is common, when rendering the frame at t2, to sample at [ t2-shutter/2, t2+shutter/2 ] for a shutter interval of *shutter*. The first sample falls between t1 and t2, but we must sample at t2 and apply velocity-based interpolation based on those samples to get a correct result. In such scenarios, one should provide a ``baseTime`` of t2 when querying *both* samples. If your application does not care about off-sample interpolation, it can supply the same value for ``baseTime`` that it does for ``time`` . When ``baseTime`` is less than or equal to ``time`` , we will choose the lower bracketing timeSample. Parameters ---------- points : VtArray[Vec3f] time : TimeCode baseTime : TimeCode ---------------------------------------------------------------------- This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Perform the point computation. This does the same computation as the non-static ComputePointsAtTime method, but takes all data as parameters rather than accessing authored data. points \- the out parameter for the computed points. Its size will depend on the given data. stage \- the UsdStage time \- time at which we want to evaluate the transforms positions \- array containing all current points. velocities \- array containing all velocities. This array must be either the same size as ``positions`` or empty. If it is empty, points are computed as if all velocities were zero in all dimensions. velocitiesSampleTime \- time at which the samples from ``velocities`` were taken. accelerations \- array containing all accelerations. This array must be either the same size as ``positions`` or empty. If it is empty, points are computed as if all accelerations were zero in all dimensions. velocityScale \- Deprecated Parameters ---------- points : VtArray[Vec3f] stage : UsdStageWeak time : TimeCode positions : Vec3fArray velocities : Vec3fArray velocitiesSampleTime : TimeCode accelerations : Vec3fArray velocityScale : float """ @staticmethod def ComputePointsAtTimes(pointsArray, times, baseTime) -> bool: """ ComputePointsAtTimes(pointsArray, times, baseTime) -> bool Compute points as in ComputePointsAtTime, but using multiple sample times. An array of vector arrays is returned where each vector array contains the points for the corresponding time in ``times`` . times \- A vector containing the UsdTimeCodes at which we want to sample. Parameters ---------- pointsArray : list[VtArray[Vec3f]] times : list[TimeCode] baseTime : TimeCode """ @staticmethod def CreateAccelerationsAttr(defaultValue, writeSparsely) -> Attribute: """ CreateAccelerationsAttr(defaultValue, writeSparsely) -> Attribute See GetAccelerationsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateNormalsAttr(defaultValue, writeSparsely) -> Attribute: """ CreateNormalsAttr(defaultValue, writeSparsely) -> Attribute See GetNormalsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreatePointsAttr(defaultValue, writeSparsely) -> Attribute: """ CreatePointsAttr(defaultValue, writeSparsely) -> Attribute See GetPointsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateVelocitiesAttr(defaultValue, writeSparsely) -> Attribute: """ CreateVelocitiesAttr(defaultValue, writeSparsely) -> Attribute See GetVelocitiesAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def Get(*args, **kwargs) -> None: """ **classmethod** Get(stage, path) -> PointBased Return a UsdGeomPointBased holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomPointBased(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ @staticmethod def GetAccelerationsAttr() -> Attribute: """ GetAccelerationsAttr() -> Attribute If provided,'accelerations'should be used with velocities to compute positions between samples for the'points'attribute rather than interpolating between neighboring'points'samples. Acceleration is measured in position units per second-squared. To convert to position units per squared UsdTimeCode, divide by the square of UsdStage::GetTimeCodesPerSecond() . Declaration ``vector3f[] accelerations`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Vector3fArray """ @staticmethod def GetNormalsAttr() -> Attribute: """ GetNormalsAttr() -> Attribute Provide an object-space orientation for individual points, which, depending on subclass, may define a surface, curve, or free points. Note that'normals'should not be authored on any Mesh that is subdivided, since the subdivision algorithm will define its own normals.'normals'is not a generic primvar, but the number of elements in this attribute will be determined by its'interpolation'. See SetNormalsInterpolation() . If'normals'and'primvars:normals'are both specified, the latter has precedence. Declaration ``normal3f[] normals`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Normal3fArray """ @staticmethod def GetNormalsInterpolation() -> str: """ GetNormalsInterpolation() -> str Get the interpolation for the *normals* attribute. Although'normals'is not classified as a generic UsdGeomPrimvar (and will not be included in the results of UsdGeomPrimvarsAPI::GetPrimvars() ) it does require an interpolation specification. The fallback interpolation, if left unspecified, is UsdGeomTokens->vertex, which will generally produce smooth shading on a polygonal mesh. To achieve partial or fully faceted shading of a polygonal mesh with normals, one should use UsdGeomTokens->faceVarying or UsdGeomTokens->uniform interpolation. """ @staticmethod def GetPointsAttr() -> Attribute: """ GetPointsAttr() -> Attribute The primary geometry attribute for all PointBased primitives, describes points in (local) space. Declaration ``point3f[] points`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Point3fArray """ @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: """ **classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ @staticmethod def GetVelocitiesAttr() -> Attribute: """ GetVelocitiesAttr() -> Attribute If provided,'velocities'should be used by renderers to. compute positions between samples for the'points'attribute, rather than interpolating between neighboring'points'samples. This is the only reasonable means of computing motion blur for topologically varying PointBased primitives. It follows that the length of each'velocities'sample must match the length of the corresponding'points'sample. Velocity is measured in position units per second, as per most simulation software. To convert to position units per UsdTimeCode, divide by UsdStage::GetTimeCodesPerSecond() . See also Applying Timesampled Velocities to Geometry. Declaration ``vector3f[] velocities`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Vector3fArray """ @staticmethod def SetNormalsInterpolation(interpolation) -> bool: """ SetNormalsInterpolation(interpolation) -> bool Set the interpolation for the *normals* attribute. true upon success, false if ``interpolation`` is not a legal value as defined by UsdGeomPrimvar::IsValidInterpolation() , or if there was a problem setting the value. No attempt is made to validate that the normals attr's value contains the right number of elements to match its interpolation to its prim's topology. Parameters ---------- interpolation : str """ @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: """ **classmethod** _GetStaticTfType() -> Type """ __instance_size__ = 40 pass class Gprim(Boundable, Xformable, Imageable, pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): """ Base class for all geometric primitives. Gprim encodes basic graphical properties such as *doubleSided* and *orientation*, and provides primvars for"display color"and"displayopacity"that travel with geometry to be used as shader overrides. For any described attribute *Fallback* *Value* or *Allowed* *Values* below that are text/tokens, the actual token is published and defined in UsdGeomTokens. So to set an attribute to the value"rightHanded", use UsdGeomTokens->rightHanded as the value. """ @staticmethod def CreateDisplayColorAttr(defaultValue, writeSparsely) -> Attribute: """ CreateDisplayColorAttr(defaultValue, writeSparsely) -> Attribute See GetDisplayColorAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateDisplayColorPrimvar(interpolation, elementSize) -> Primvar: """ CreateDisplayColorPrimvar(interpolation, elementSize) -> Primvar Convenience function to create the displayColor primvar, optionally specifying interpolation and elementSize. Parameters ---------- interpolation : str elementSize : int """ @staticmethod def CreateDisplayOpacityAttr(defaultValue, writeSparsely) -> Attribute: """ CreateDisplayOpacityAttr(defaultValue, writeSparsely) -> Attribute See GetDisplayOpacityAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateDisplayOpacityPrimvar(interpolation, elementSize) -> Primvar: """ CreateDisplayOpacityPrimvar(interpolation, elementSize) -> Primvar Convenience function to create the displayOpacity primvar, optionally specifying interpolation and elementSize. Parameters ---------- interpolation : str elementSize : int """ @staticmethod def CreateDoubleSidedAttr(defaultValue, writeSparsely) -> Attribute: """ CreateDoubleSidedAttr(defaultValue, writeSparsely) -> Attribute See GetDoubleSidedAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateOrientationAttr(defaultValue, writeSparsely) -> Attribute: """ CreateOrientationAttr(defaultValue, writeSparsely) -> Attribute See GetOrientationAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def Get(*args, **kwargs) -> None: """ **classmethod** Get(stage, path) -> Gprim Return a UsdGeomGprim holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomGprim(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ @staticmethod def GetDisplayColorAttr() -> Attribute: """ GetDisplayColorAttr() -> Attribute It is useful to have an"official"colorSet that can be used as a display or modeling color, even in the absence of any specified shader for a gprim. DisplayColor serves this role; because it is a UsdGeomPrimvar, it can also be used as a gprim override for any shader that consumes a *displayColor* parameter. Declaration ``color3f[] primvars:displayColor`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Color3fArray """ @staticmethod def GetDisplayColorPrimvar() -> Primvar: """ GetDisplayColorPrimvar() -> Primvar Convenience function to get the displayColor Attribute as a Primvar. """ @staticmethod def GetDisplayOpacityAttr() -> Attribute: """ GetDisplayOpacityAttr() -> Attribute Companion to *displayColor* that specifies opacity, broken out as an independent attribute rather than an rgba color, both so that each can be independently overridden, and because shaders rarely consume rgba parameters. Declaration ``float[] primvars:displayOpacity`` C++ Type VtArray<float> Usd Type SdfValueTypeNames->FloatArray """ @staticmethod def GetDisplayOpacityPrimvar() -> Primvar: """ GetDisplayOpacityPrimvar() -> Primvar Convenience function to get the displayOpacity Attribute as a Primvar. """ @staticmethod def GetDoubleSidedAttr() -> Attribute: """ GetDoubleSidedAttr() -> Attribute Although some renderers treat all parametric or polygonal surfaces as if they were effectively laminae with outward-facing normals on both sides, some renderers derive significant optimizations by considering these surfaces to have only a single outward side, typically determined by control-point winding order and/or *orientation*. By doing so they can perform"backface culling"to avoid drawing the many polygons of most closed surfaces that face away from the viewer. However, it is often advantageous to model thin objects such as paper and cloth as single, open surfaces that must be viewable from both sides, always. Setting a gprim's *doubleSided* attribute to ``true`` instructs all renderers to disable optimizations such as backface culling for the gprim, and attempt (not all renderers are able to do so, but the USD reference GL renderer always will) to provide forward- facing normals on each side of the surface for lighting calculations. Declaration ``uniform bool doubleSided = 0`` C++ Type bool Usd Type SdfValueTypeNames->Bool Variability SdfVariabilityUniform """ @staticmethod def GetOrientationAttr() -> Attribute: """ GetOrientationAttr() -> Attribute Orientation specifies whether the gprim's surface normal should be computed using the right hand rule, or the left hand rule. Please see Coordinate System, Winding Order, Orientation, and Surface Normals for a deeper explanation and generalization of orientation to composed scenes with transformation hierarchies. Declaration ``uniform token orientation ="rightHanded"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values rightHanded, leftHanded """ @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: """ **classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: """ **classmethod** _GetStaticTfType() -> Type """ __instance_size__ = 40 pass class Imageable(pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): """ Base class for all prims that may require rendering or visualization of some sort. The primary attributes of Imageable are *visibility* and *purpose*, which each provide instructions for what geometry should be included for processing by rendering and other computations. Deprecated Imageable also provides API for accessing primvars, which has been moved to the UsdGeomPrimvarsAPI schema, because primvars can now be applied on non-Imageable prim types. This API is planned to be removed, UsdGeomPrimvarsAPI should be used directly instead. For any described attribute *Fallback* *Value* or *Allowed* *Values* below that are text/tokens, the actual token is published and defined in UsdGeomTokens. So to set an attribute to the value"rightHanded", use UsdGeomTokens->rightHanded as the value. """ class PurposeInfo(Boost.Python.instance): @staticmethod def GetInheritablePurpose(*args, **kwargs) -> None: ... @property def isInheritable(self) -> None: """ :type: None """ @property def purpose(self) -> None: """ :type: None """ __instance_size__ = 32 pass @staticmethod def ComputeEffectiveVisibility(purpose, time) -> str: """ ComputeEffectiveVisibility(purpose, time) -> str Calculate the effective purpose visibility of this prim for the given ``purpose`` , taking into account opinions for the corresponding purpose attribute, along with overall visibility opinions. If ComputeVisibility() returns"invisible", then ComputeEffectiveVisibility() is"invisible"for all purpose values. Otherwise, ComputeEffectiveVisibility() returns the value of the nearest ancestral authored opinion for the corresponding purpose visibility attribute, as retured by GetPurposeVisibilityAttr(purpose). Note that the value returned here can be"invisible"(indicating the prim is invisible for the given purpose),"visible"(indicating that it's visible), or"inherited"(indicating that the purpose visibility is context-dependent and the fallback behavior must be determined by the caller. This function should be considered a reference implementation for correctness. **If called on each prim in the context of a traversal we will perform massive overcomputation, because sibling prims share sub- problems in the query that can be efficiently cached, but are not (cannot be) by this simple implementation.** If you have control of your traversal, it will be far more efficient to manage visibility on a stack as you traverse. UsdGeomVisibilityAPI Parameters ---------- purpose : str time : TimeCode """ @staticmethod def ComputeLocalBound(time, purpose1, purpose2, purpose3, purpose4) -> BBox3d: """ ComputeLocalBound(time, purpose1, purpose2, purpose3, purpose4) -> BBox3d Compute the bound of this prim in local space, at the specified ``time`` , and for the specified purposes. The bound of the prim is computed, including the transform (if any) authored on the node itself. It is an error to not specify any purposes, which will result in the return of an empty box. **If you need to compute bounds for multiple prims on a stage, it will be much, much more efficient to instantiate a UsdGeomBBoxCache and query it directly; doing so will reuse sub-computations shared by the prims.** Parameters ---------- time : TimeCode purpose1 : str purpose2 : str purpose3 : str purpose4 : str """ @staticmethod def ComputeLocalToWorldTransform(time) -> Matrix4d: """ ComputeLocalToWorldTransform(time) -> Matrix4d Compute the transformation matrix for this prim at the given time, including the transform authored on the Prim itself, if present. **If you need to compute the transform for multiple prims on a stage, it will be much, much more efficient to instantiate a UsdGeomXformCache and query it directly; doing so will reuse sub- computations shared by the prims.** Parameters ---------- time : TimeCode """ @staticmethod def ComputeParentToWorldTransform(time) -> Matrix4d: """ ComputeParentToWorldTransform(time) -> Matrix4d Compute the transformation matrix for this prim at the given time, *NOT* including the transform authored on the prim itself. **If you need to compute the transform for multiple prims on a stage, it will be much, much more efficient to instantiate a UsdGeomXformCache and query it directly; doing so will reuse sub- computations shared by the prims.** Parameters ---------- time : TimeCode """ @staticmethod def ComputeProxyPrim(*args, **kwargs) -> None: """ Returns None if neither this prim nor any of its ancestors has a valid renderProxy prim. Otherwise, returns a tuple of (proxyPrim, renderPrimWithAuthoredProxyPrimRel) """ @staticmethod def ComputePurpose() -> str: """ ComputePurpose() -> str Calculate the effective purpose information about this prim. This is equivalent to extracting the purpose from the value returned by ComputePurposeInfo() . This function should be considered a reference implementation for correctness. **If called on each prim in the context of a traversal we will perform massive overcomputation, because sibling prims share sub- problems in the query that can be efficiently cached, but are not (cannot be) by this simple implementation.** If you have control of your traversal, it will be far more efficient to manage purpose, along with visibility, on a stack as you traverse. """ @staticmethod @typing.overload def ComputePurposeInfo() -> PurposeInfo: """ ComputePurposeInfo() -> PurposeInfo Calculate the effective purpose information about this prim which includes final computed purpose value of the prim as well as whether the purpose value should be inherited by namespace children without their own purpose opinions. This function should be considered a reference implementation for correctness. **If called on each prim in the context of a traversal we will perform massive overcomputation, because sibling prims share sub- problems in the query that can be efficiently cached, but are not (cannot be) by this simple implementation.** If you have control of your traversal, it will be far more efficient to manage purpose, along with visibility, on a stack as you traverse. ---------------------------------------------------------------------- This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Calculates the effective purpose information about this prim, given the computed purpose information of its parent prim. This can be much more efficient than using CommputePurposeInfo() when PurposeInfo values are properly computed and cached for a hierarchy of prims using this function. Parameters ---------- parentPurposeInfo : PurposeInfo """ @staticmethod @typing.overload def ComputePurposeInfo(parentPurposeInfo) -> PurposeInfo: ... @staticmethod def ComputeUntransformedBound(time, purpose1, purpose2, purpose3, purpose4) -> BBox3d: """ ComputeUntransformedBound(time, purpose1, purpose2, purpose3, purpose4) -> BBox3d Compute the untransformed bound of this prim, at the specified ``time`` , and for the specified purposes. The bound of the prim is computed in its object space, ignoring any transforms authored on or above the prim. It is an error to not specify any purposes, which will result in the return of an empty box. **If you need to compute bounds for multiple prims on a stage, it will be much, much more efficient to instantiate a UsdGeomBBoxCache and query it directly; doing so will reuse sub-computations shared by the prims.** Parameters ---------- time : TimeCode purpose1 : str purpose2 : str purpose3 : str purpose4 : str """ @staticmethod def ComputeVisibility(time) -> str: """ ComputeVisibility(time) -> str Calculate the effective visibility of this prim, as defined by its most ancestral authored"invisible"opinion, if any. A prim is considered visible at the current ``time`` if none of its Imageable ancestors express an authored"invisible"opinion, which is what leads to the"simple pruning"behavior described in GetVisibilityAttr() . This function should be considered a reference implementation for correctness. **If called on each prim in the context of a traversal we will perform massive overcomputation, because sibling prims share sub- problems in the query that can be efficiently cached, but are not (cannot be) by this simple implementation.** If you have control of your traversal, it will be far more efficient to manage visibility on a stack as you traverse. Parameters ---------- time : TimeCode """ @staticmethod def ComputeWorldBound(time, purpose1, purpose2, purpose3, purpose4) -> BBox3d: """ ComputeWorldBound(time, purpose1, purpose2, purpose3, purpose4) -> BBox3d Compute the bound of this prim in world space, at the specified ``time`` , and for the specified purposes. The bound of the prim is computed, including the transform (if any) authored on the node itself, and then transformed to world space. It is an error to not specify any purposes, which will result in the return of an empty box. **If you need to compute bounds for multiple prims on a stage, it will be much, much more efficient to instantiate a UsdGeomBBoxCache and query it directly; doing so will reuse sub-computations shared by the prims.** Parameters ---------- time : TimeCode purpose1 : str purpose2 : str purpose3 : str purpose4 : str """ @staticmethod def CreateProxyPrimRel() -> Relationship: """ CreateProxyPrimRel() -> Relationship See GetProxyPrimRel() , and also Create vs Get Property Methods for when to use Get vs Create. """ @staticmethod def CreatePurposeAttr(defaultValue, writeSparsely) -> Attribute: """ CreatePurposeAttr(defaultValue, writeSparsely) -> Attribute See GetPurposeAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateVisibilityAttr(defaultValue, writeSparsely) -> Attribute: """ CreateVisibilityAttr(defaultValue, writeSparsely) -> Attribute See GetVisibilityAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def Get(*args, **kwargs) -> None: """ **classmethod** Get(stage, path) -> Imageable Return a UsdGeomImageable holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomImageable(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ @staticmethod def GetOrderedPurposeTokens(*args, **kwargs) -> None: """ **classmethod** GetOrderedPurposeTokens() -> list[TfToken] Returns an ordered list of allowed values of the purpose attribute. The ordering is important because it defines the protocol between UsdGeomModelAPI and UsdGeomBBoxCache for caching and retrieving extents hints by purpose. The order is: [default, render, proxy, guide] See UsdGeomModelAPI::GetExtentsHint() . """ @staticmethod def GetProxyPrimRel() -> Relationship: """ GetProxyPrimRel() -> Relationship The *proxyPrim* relationship allows us to link a prim whose *purpose* is"render"to its (single target) purpose="proxy"prim. This is entirely optional, but can be useful in several scenarios: - In a pipeline that does pruning (for complexity management) by deactivating prims composed from asset references, when we deactivate a purpose="render"prim, we will be able to discover and additionally deactivate its associated purpose="proxy"prim, so that preview renders reflect the pruning accurately. - DCC importers may be able to make more aggressive optimizations for interactive processing and display if they can discover the proxy for a given render prim. - With a little more work, a Hydra-based application will be able to map a picked proxy prim back to its render geometry for selection. It is only valid to author the proxyPrim relationship on prims whose purpose is"render". """ @staticmethod def GetPurposeAttr() -> Attribute: """ GetPurposeAttr() -> Attribute Purpose is a classification of geometry into categories that can each be independently included or excluded from traversals of prims on a stage, such as rendering or bounding-box computation traversals. See Imageable Purpose for more detail about how *purpose* is computed and used. Declaration ``uniform token purpose ="default"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values default, render, proxy, guide """ @staticmethod def GetPurposeVisibilityAttr(purpose) -> Attribute: """ GetPurposeVisibilityAttr(purpose) -> Attribute Return the attribute that is used for expressing visibility opinions for the given ``purpose`` . For"default"purpose, return the overall *visibility* attribute. For"guide","proxy", or"render"purpose, return *guideVisibility*, *proxyVisibility*, or *renderVisibility* if UsdGeomVisibilityAPI is applied to the prim. If UsdGeomvVisibiltyAPI is not applied, an empty attribute is returned for purposes other than default. UsdGeomVisibilityAPI::Apply UsdGeomVisibilityAPI::GetPurposeVisibilityAttr Parameters ---------- purpose : str """ @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: """ **classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ @staticmethod def GetVisibilityAttr() -> Attribute: """ GetVisibilityAttr() -> Attribute Visibility is meant to be the simplest form of"pruning"visibility that is supported by most DCC apps. Visibility is animatable, allowing a sub-tree of geometry to be present for some segment of a shot, and absent from others; unlike the action of deactivating geometry prims, invisible geometry is still available for inspection, for positioning, for defining volumes, etc. Declaration ``token visibility ="inherited"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Allowed Values inherited, invisible """ @staticmethod def MakeInvisible(time) -> None: """ MakeInvisible(time) -> None Makes the imageable invisible if it is visible at the given time. When visibility is animated, this only works when it is invoked sequentially at increasing time samples. If visibility is already authored and animated in the scene, calling MakeVisible() at an arbitrary (in-between) frame isn't guaranteed to work. Be sure to set the edit target to the layer containing the strongest visibility opinion or to a stronger layer. Parameters ---------- time : TimeCode """ @staticmethod def MakeVisible(time) -> None: """ MakeVisible(time) -> None Make the imageable visible if it is invisible at the given time. Since visibility is pruning, this may need to override some ancestor's visibility and all-but-one of the ancestor's children's visibility, for all the ancestors of this prim up to the highest ancestor that is explicitly invisible, to preserve the visibility state. If MakeVisible() (or MakeInvisible() ) is going to be applied to all the prims on a stage, ancestors must be processed prior to descendants to get the correct behavior. When visibility is animated, this only works when it is invoked sequentially at increasing time samples. If visibility is already authored and animated in the scene, calling MakeVisible() at an arbitrary (in-between) frame isn't guaranteed to work. This will only work properly if all ancestor prims of the imageable are **defined**, as the imageable schema is only valid on defined prims. Be sure to set the edit target to the layer containing the strongest visibility opinion or to a stronger layer. Parameters ---------- time : TimeCode """ @staticmethod def SetProxyPrim(proxy) -> bool: """ SetProxyPrim(proxy) -> bool Convenience function for authoring the *renderProxy* rel on this prim to target the given ``proxy`` prim. To facilitate authoring on sparse or unloaded stages, we do not perform any validation of this prim's purpose or the type or purpose of the specified prim. Parameters ---------- proxy : Prim ---------------------------------------------------------------------- Parameters ---------- proxy : SchemaBase """ @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: """ **classmethod** _GetStaticTfType() -> Type """ __instance_size__ = 40 pass class LinearUnits(Boost.Python.instance): centimeters = 0.01 feet = 0.3048 inches = 0.0254 kilometers = 1000.0 lightYears = 9460730472580800.0 meters = 1.0 micrometers = 1e-06 miles = 1609.344 millimeters = 0.001 nanometers = 1e-09 yards = 0.9144 pass class ModelAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): """ UsdGeomModelAPI extends the generic UsdModelAPI schema with geometry specific concepts such as cached extents for the entire model, constraint targets, and geometry-inspired extensions to the payload lofting process. As described in GetExtentsHint() below, it is useful to cache extents at the model level. UsdGeomModelAPI provides schema for computing and storing these cached extents, which can be consumed by UsdGeomBBoxCache to provide fast access to precomputed extents that will be used as the model's bounds ( see UsdGeomBBoxCache::UsdGeomBBoxCache() ). Draw Modes ========== Draw modes provide optional alternate imaging behavior for USD subtrees with kind model. *model:drawMode* (which is inheritable) and *model:applyDrawMode* (which is not) are resolved into a decision to stop traversing the scene graph at a certain point, and replace a USD subtree with proxy geometry. The value of *model:drawMode* determines the type of proxy geometry: - *origin* - Draw the model-space basis vectors of the replaced prim. - *bounds* - Draw the model-space bounding box of the replaced prim. - *cards* - Draw textured quads as a placeholder for the replaced prim. - *default* - An explicit opinion to draw the USD subtree as normal. - *inherited* - Defer to the parent opinion. *model:drawMode* falls back to *inherited* so that a whole scene, a large group, or all prototypes of a model hierarchy PointInstancer can be assigned a draw mode with a single attribute edit. If no draw mode is explicitly set in a hierarchy, the resolved value is *default*. *model:applyDrawMode* is meant to be written when an asset is authored, and provides flexibility for different asset types. For example, a character assembly (composed of character, clothes, etc) might have *model:applyDrawMode* set at the top of the subtree so the whole group can be drawn as a single card object. An effects subtree might have *model:applyDrawMode* set at a lower level so each particle group draws individually. Models of kind component are treated as if *model:applyDrawMode* were true. This means a prim is drawn with proxy geometry when: the prim has kind component, and/or *model:applyDrawMode* is set; and the prim's resolved value for *model:drawMode* is not *default*. Cards Geometry ============== The specific geometry used in cards mode is controlled by the *model:cardGeometry* attribute: - *cross* - Generate a quad normal to each basis direction and negative. Locate each quad so that it bisects the model extents. - *box* - Generate a quad normal to each basis direction and negative. Locate each quad on a face of the model extents, facing out. - *fromTexture* - Generate a quad for each supplied texture from attributes stored in that texture's metadata. For *cross* and *box* mode, the extents are calculated for purposes *default*, *proxy*, and *render*, at their earliest authored time. If the model has no textures, all six card faces are rendered using *model:drawModeColor*. If one or more textures are present, only axes with one or more textures assigned are drawn. For each axis, if both textures (positive and negative) are specified, they'll be used on the corresponding card faces; if only one texture is specified, it will be mapped to the opposite card face after being flipped on the texture's s-axis. Any card faces with invalid asset paths will be drawn with *model:drawModeColor*. Both *model:cardGeometry* and *model:drawModeColor* should be authored on the prim where the draw mode takes effect, since these attributes are not inherited. For *fromTexture* mode, only card faces with valid textures assigned are drawn. The geometry is generated by pulling the *worldtoscreen* attribute out of texture metadata. This is expected to be a 4x4 matrix mapping the model-space position of the card quad to the clip-space quad with corners (-1,-1,0) and (1,1,0). The card vertices are generated by transforming the clip-space corners by the inverse of *worldtoscreen*. Textures are mapped so that (s) and (t) map to (+x) and (+y) in clip space. If the metadata cannot be read in the right format, or the matrix can't be inverted, the card face is not drawn. All card faces are drawn and textured as single-sided. For any described attribute *Fallback* *Value* or *Allowed* *Values* below that are text/tokens, the actual token is published and defined in UsdGeomTokens. So to set an attribute to the value"rightHanded", use UsdGeomTokens->rightHanded as the value. """ @staticmethod def Apply(*args, **kwargs) -> None: """ **classmethod** Apply(prim) -> ModelAPI Applies this **single-apply** API schema to the given ``prim`` . This information is stored by adding"GeomModelAPI"to the token-valued, listOp metadata *apiSchemas* on the prim. A valid UsdGeomModelAPI object is returned upon success. An invalid (or empty) UsdGeomModelAPI object is returned upon failure. See UsdPrim::ApplyAPI() for conditions resulting in failure. UsdPrim::GetAppliedSchemas() UsdPrim::HasAPI() UsdPrim::CanApplyAPI() UsdPrim::ApplyAPI() UsdPrim::RemoveAPI() Parameters ---------- prim : Prim """ @staticmethod def CanApply(*args, **kwargs) -> None: """ **classmethod** CanApply(prim, whyNot) -> bool Returns true if this **single-apply** API schema can be applied to the given ``prim`` . If this schema can not be a applied to the prim, this returns false and, if provided, populates ``whyNot`` with the reason it can not be applied. Note that if CanApply returns false, that does not necessarily imply that calling Apply will fail. Callers are expected to call CanApply before calling Apply if they want to ensure that it is valid to apply a schema. UsdPrim::GetAppliedSchemas() UsdPrim::HasAPI() UsdPrim::CanApplyAPI() UsdPrim::ApplyAPI() UsdPrim::RemoveAPI() Parameters ---------- prim : Prim whyNot : str """ @staticmethod def ComputeExtentsHint(bboxCache) -> Vec3fArray: """ ComputeExtentsHint(bboxCache) -> Vec3fArray For the given model, compute the value for the extents hint with the given ``bboxCache`` . ``bboxCache`` should be setup with the appropriate time. After calling this function, the ``bboxCache`` may have it's included purposes changed. ``bboxCache`` should not be in use by any other thread while this method is using it in a thread. Parameters ---------- bboxCache : BBoxCache """ @staticmethod def ComputeModelDrawMode(parentDrawMode) -> str: """ ComputeModelDrawMode(parentDrawMode) -> str Calculate the effective model:drawMode of this prim. If the draw mode is authored on this prim, it's used. Otherwise, the fallback value is"inherited", which defers to the parent opinion. The first non-inherited opinion found walking from this prim towards the root is used. If the attribute isn't set on any ancestors, we return"default"(meaning, disable"drawMode"geometry). If this function is being called in a traversal context to compute the draw mode of an entire hierarchy of prims, it would be beneficial to cache and pass in the computed parent draw-mode via the ``parentDrawMode`` parameter. This avoids repeated upward traversal to look for ancestor opinions. When ``parentDrawMode`` is empty (or unspecified), this function does an upward traversal to find the closest ancestor with an authored model:drawMode. Parameters ---------- parentDrawMode : str """ @staticmethod def CreateConstraintTarget(constraintName) -> ConstraintTarget: """ CreateConstraintTarget(constraintName) -> ConstraintTarget Creates a new constraint target with the given name, ``constraintName`` . If the constraint target already exists, then the existing target is returned. If it does not exist, a new one is created and returned. Parameters ---------- constraintName : str """ @staticmethod def CreateModelApplyDrawModeAttr(defaultValue, writeSparsely) -> Attribute: """ CreateModelApplyDrawModeAttr(defaultValue, writeSparsely) -> Attribute See GetModelApplyDrawModeAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateModelCardGeometryAttr(defaultValue, writeSparsely) -> Attribute: """ CreateModelCardGeometryAttr(defaultValue, writeSparsely) -> Attribute See GetModelCardGeometryAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateModelCardTextureXNegAttr(defaultValue, writeSparsely) -> Attribute: """ CreateModelCardTextureXNegAttr(defaultValue, writeSparsely) -> Attribute See GetModelCardTextureXNegAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateModelCardTextureXPosAttr(defaultValue, writeSparsely) -> Attribute: """ CreateModelCardTextureXPosAttr(defaultValue, writeSparsely) -> Attribute See GetModelCardTextureXPosAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateModelCardTextureYNegAttr(defaultValue, writeSparsely) -> Attribute: """ CreateModelCardTextureYNegAttr(defaultValue, writeSparsely) -> Attribute See GetModelCardTextureYNegAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateModelCardTextureYPosAttr(defaultValue, writeSparsely) -> Attribute: """ CreateModelCardTextureYPosAttr(defaultValue, writeSparsely) -> Attribute See GetModelCardTextureYPosAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateModelCardTextureZNegAttr(defaultValue, writeSparsely) -> Attribute: """ CreateModelCardTextureZNegAttr(defaultValue, writeSparsely) -> Attribute See GetModelCardTextureZNegAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateModelCardTextureZPosAttr(defaultValue, writeSparsely) -> Attribute: """ CreateModelCardTextureZPosAttr(defaultValue, writeSparsely) -> Attribute See GetModelCardTextureZPosAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateModelDrawModeAttr(defaultValue, writeSparsely) -> Attribute: """ CreateModelDrawModeAttr(defaultValue, writeSparsely) -> Attribute See GetModelDrawModeAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateModelDrawModeColorAttr(defaultValue, writeSparsely) -> Attribute: """ CreateModelDrawModeColorAttr(defaultValue, writeSparsely) -> Attribute See GetModelDrawModeColorAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def Get(*args, **kwargs) -> None: """ **classmethod** Get(stage, path) -> ModelAPI Return a UsdGeomModelAPI holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomModelAPI(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ @staticmethod def GetConstraintTarget(constraintName) -> ConstraintTarget: """ GetConstraintTarget(constraintName) -> ConstraintTarget Get the constraint target with the given name, ``constraintName`` . If the requested constraint target does not exist, then an invalid UsdConstraintTarget object is returned. Parameters ---------- constraintName : str """ @staticmethod def GetConstraintTargets() -> list[ConstraintTarget]: """ GetConstraintTargets() -> list[ConstraintTarget] Returns all the constraint targets belonging to the model. Only valid constraint targets in the"constraintTargets"namespace are returned by this method. """ @staticmethod def GetExtentsHint(extents, time) -> bool: """ GetExtentsHint(extents, time) -> bool Retrieve the authored value (if any) of this model's"extentsHint". Persistent caching of bounds in USD is a potentially perilous endeavor, given that: - It is very easy to add overrides in new super-layers that invalidate the cached bounds, and no practical way to automatically detect when this happens - It is possible for references to be allowed to"float", so that asset updates can flow directly into cached scenes. Such changes in referenced scene description can also invalidate cached bounds in referencing layers. For these reasons, as a general rule, we only persistently cache leaf gprim extents in object space. However, even with cached gprim extents, computing bounds can be expensive. Since model-level bounds are so useful to many graphics applications, we make an exception, with some caveats. The"extentsHint"should be considered entirely optional (whereas gprim extent is not); if authored, it should contains the extents for various values of gprim purposes. The extents for different values of purpose are stored in a linear Vec3f array as pairs of GfVec3f values in the order specified by UsdGeomImageable::GetOrderedPurposeTokens() . This list is trimmed to only include non-empty extents. i.e., if a model has only default and render geoms, then it will only have 4 GfVec3f values in its extentsHint array. We do not skip over zero extents, so if a model has only default and proxy geom, we will author six GfVec3f 's, the middle two representing an zero extent for render geometry. A UsdGeomBBoxCache can be configured to first consult the cached extents when evaluating model roots, rather than descending into the models for the full computation. This is not the default behavior, and gives us a convenient way to validate that the cached extentsHint is still valid. ``true`` if a value was fetched; ``false`` if no value was authored, or on error. It is an error to make this query of a prim that is not a model root. UsdGeomImageable::GetPurposeAttr() , UsdGeomImageable::GetOrderedPurposeTokens() Parameters ---------- extents : Vec3fArray time : TimeCode """ @staticmethod def GetExtentsHintAttr() -> Attribute: """ GetExtentsHintAttr() -> Attribute Returns the custom'extentsHint'attribute if it exits. """ @staticmethod def GetModelApplyDrawModeAttr() -> Attribute: """ GetModelApplyDrawModeAttr() -> Attribute If true, and the resolved value of *model:drawMode* is non-default, apply an alternate imaging mode to this prim. See Draw Modes. Declaration ``uniform bool model:applyDrawMode = 0`` C++ Type bool Usd Type SdfValueTypeNames->Bool Variability SdfVariabilityUniform """ @staticmethod def GetModelCardGeometryAttr() -> Attribute: """ GetModelCardGeometryAttr() -> Attribute The geometry to generate for imaging prims inserted for *cards* imaging mode. See Cards Geometry for geometry descriptions. Declaration ``uniform token model:cardGeometry ="cross"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values cross, box, fromTexture """ @staticmethod def GetModelCardTextureXNegAttr() -> Attribute: """ GetModelCardTextureXNegAttr() -> Attribute In *cards* imaging mode, the texture applied to the X- quad. The texture axes (s,t) are mapped to model-space axes (y, -z). Declaration ``asset model:cardTextureXNeg`` C++ Type SdfAssetPath Usd Type SdfValueTypeNames->Asset """ @staticmethod def GetModelCardTextureXPosAttr() -> Attribute: """ GetModelCardTextureXPosAttr() -> Attribute In *cards* imaging mode, the texture applied to the X+ quad. The texture axes (s,t) are mapped to model-space axes (-y, -z). Declaration ``asset model:cardTextureXPos`` C++ Type SdfAssetPath Usd Type SdfValueTypeNames->Asset """ @staticmethod def GetModelCardTextureYNegAttr() -> Attribute: """ GetModelCardTextureYNegAttr() -> Attribute In *cards* imaging mode, the texture applied to the Y- quad. The texture axes (s,t) are mapped to model-space axes (-x, -z). Declaration ``asset model:cardTextureYNeg`` C++ Type SdfAssetPath Usd Type SdfValueTypeNames->Asset """ @staticmethod def GetModelCardTextureYPosAttr() -> Attribute: """ GetModelCardTextureYPosAttr() -> Attribute In *cards* imaging mode, the texture applied to the Y+ quad. The texture axes (s,t) are mapped to model-space axes (x, -z). Declaration ``asset model:cardTextureYPos`` C++ Type SdfAssetPath Usd Type SdfValueTypeNames->Asset """ @staticmethod def GetModelCardTextureZNegAttr() -> Attribute: """ GetModelCardTextureZNegAttr() -> Attribute In *cards* imaging mode, the texture applied to the Z- quad. The texture axes (s,t) are mapped to model-space axes (-x, -y). Declaration ``asset model:cardTextureZNeg`` C++ Type SdfAssetPath Usd Type SdfValueTypeNames->Asset """ @staticmethod def GetModelCardTextureZPosAttr() -> Attribute: """ GetModelCardTextureZPosAttr() -> Attribute In *cards* imaging mode, the texture applied to the Z+ quad. The texture axes (s,t) are mapped to model-space axes (x, -y). Declaration ``asset model:cardTextureZPos`` C++ Type SdfAssetPath Usd Type SdfValueTypeNames->Asset """ @staticmethod def GetModelDrawModeAttr() -> Attribute: """ GetModelDrawModeAttr() -> Attribute Alternate imaging mode; applied to this prim or child prims where *model:applyDrawMode* is true, or where the prim has kind *component*. See Draw Modes for mode descriptions. Declaration ``uniform token model:drawMode ="inherited"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values origin, bounds, cards, default, inherited """ @staticmethod def GetModelDrawModeColorAttr() -> Attribute: """ GetModelDrawModeColorAttr() -> Attribute The base color of imaging prims inserted for alternate imaging modes. For *origin* and *bounds* modes, this controls line color; for *cards* mode, this controls the fallback quad color. Declaration ``uniform float3 model:drawModeColor = (0.18, 0.18, 0.18)`` C++ Type GfVec3f Usd Type SdfValueTypeNames->Float3 Variability SdfVariabilityUniform """ @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: """ **classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ @staticmethod def SetExtentsHint(extents, time) -> bool: """ SetExtentsHint(extents, time) -> bool Authors the extentsHint array for this model at the given time. Parameters ---------- extents : Vec3fArray time : TimeCode """ @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: """ **classmethod** _GetStaticTfType() -> Type """ __instance_size__ = 48 pass class MotionAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): """ UsdGeomMotionAPI encodes data that can live on any prim that may affect computations involving: - computed motion for motion blur - sampling for motion blur The motion:blurScale attribute allows artists to scale the **amount** of motion blur to be rendered for parts of the scene without changing the recorded animation. See Effectively Applying motion:blurScale for use and implementation details. """ @staticmethod def Apply(*args, **kwargs) -> None: """ **classmethod** Apply(prim) -> MotionAPI Applies this **single-apply** API schema to the given ``prim`` . This information is stored by adding"MotionAPI"to the token-valued, listOp metadata *apiSchemas* on the prim. A valid UsdGeomMotionAPI object is returned upon success. An invalid (or empty) UsdGeomMotionAPI object is returned upon failure. See UsdPrim::ApplyAPI() for conditions resulting in failure. UsdPrim::GetAppliedSchemas() UsdPrim::HasAPI() UsdPrim::CanApplyAPI() UsdPrim::ApplyAPI() UsdPrim::RemoveAPI() Parameters ---------- prim : Prim """ @staticmethod def CanApply(*args, **kwargs) -> None: """ **classmethod** CanApply(prim, whyNot) -> bool Returns true if this **single-apply** API schema can be applied to the given ``prim`` . If this schema can not be a applied to the prim, this returns false and, if provided, populates ``whyNot`` with the reason it can not be applied. Note that if CanApply returns false, that does not necessarily imply that calling Apply will fail. Callers are expected to call CanApply before calling Apply if they want to ensure that it is valid to apply a schema. UsdPrim::GetAppliedSchemas() UsdPrim::HasAPI() UsdPrim::CanApplyAPI() UsdPrim::ApplyAPI() UsdPrim::RemoveAPI() Parameters ---------- prim : Prim whyNot : str """ @staticmethod def ComputeMotionBlurScale(time) -> float: """ ComputeMotionBlurScale(time) -> float Compute the inherited value of *motion:blurScale* at ``time`` , i.e. the authored value on the prim closest to this prim in namespace, resolved upwards through its ancestors in namespace. the inherited value, or 1.0 if neither the prim nor any of its ancestors possesses an authored value. this is a reference implementation that is not particularly efficient if evaluating over many prims, because it does not share inherited results. Parameters ---------- time : TimeCode """ @staticmethod def ComputeNonlinearSampleCount(time) -> int: """ ComputeNonlinearSampleCount(time) -> int Compute the inherited value of *nonlinearSampleCount* at ``time`` , i.e. the authored value on the prim closest to this prim in namespace, resolved upwards through its ancestors in namespace. the inherited value, or 3 if neither the prim nor any of its ancestors possesses an authored value. this is a reference implementation that is not particularly efficient if evaluating over many prims, because it does not share inherited results. Parameters ---------- time : TimeCode """ @staticmethod def ComputeVelocityScale(time) -> float: """ ComputeVelocityScale(time) -> float Deprecated Compute the inherited value of *velocityScale* at ``time`` , i.e. the authored value on the prim closest to this prim in namespace, resolved upwards through its ancestors in namespace. the inherited value, or 1.0 if neither the prim nor any of its ancestors possesses an authored value. this is a reference implementation that is not particularly efficient if evaluating over many prims, because it does not share inherited results. Parameters ---------- time : TimeCode """ @staticmethod def CreateMotionBlurScaleAttr(defaultValue, writeSparsely) -> Attribute: """ CreateMotionBlurScaleAttr(defaultValue, writeSparsely) -> Attribute See GetMotionBlurScaleAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateNonlinearSampleCountAttr(defaultValue, writeSparsely) -> Attribute: """ CreateNonlinearSampleCountAttr(defaultValue, writeSparsely) -> Attribute See GetNonlinearSampleCountAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateVelocityScaleAttr(defaultValue, writeSparsely) -> Attribute: """ CreateVelocityScaleAttr(defaultValue, writeSparsely) -> Attribute See GetVelocityScaleAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def Get(*args, **kwargs) -> None: """ **classmethod** Get(stage, path) -> MotionAPI Return a UsdGeomMotionAPI holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomMotionAPI(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ @staticmethod def GetMotionBlurScaleAttr() -> Attribute: """ GetMotionBlurScaleAttr() -> Attribute BlurScale is an **inherited** float attribute that stipulates the rendered motion blur (as typically specified via UsdGeomCamera 's *shutter:open* and *shutter:close* properties) should be scaled for **all objects** at and beneath the prim in namespace on which the *motion:blurScale* value is specified. Without changing any other data in the scene, *blurScale* allows artists to"dial in"the amount of blur on a per-object basis. A *blurScale* value of zero removes all blur, a value of 0.5 reduces blur by half, and a value of 2.0 doubles the blur. The legal range for *blurScale* is [0, inf), although very high values may result in extremely expensive renders, and may exceed the capabilities of some renderers. Although renderers are free to implement this feature however they see fit, see Effectively Applying motion:blurScale for our guidance on implementing the feature universally and efficiently. Declaration ``float motion:blurScale = 1`` C++ Type float Usd Type SdfValueTypeNames->Float """ @staticmethod def GetNonlinearSampleCountAttr() -> Attribute: """ GetNonlinearSampleCountAttr() -> Attribute Determines the number of position or transformation samples created when motion is described by attributes contributing non-linear terms. To give an example, imagine an application (such as a renderer) consuming'points'and the USD document also contains'accelerations'for the same prim. Unless the application can consume these'accelerations'itself, an intermediate layer has to compute samples within the sampling interval for the point positions based on the value of'points','velocities'and'accelerations'. The number of these samples is given by'nonlinearSampleCount'. The samples are equally spaced within the sampling interval. Another example involves the PointInstancer where'nonlinearSampleCount'is relevant when'angularVelocities'or'accelerations'are authored. 'nonlinearSampleCount'is an **inherited** attribute, also see ComputeNonlinearSampleCount() Declaration ``int motion:nonlinearSampleCount = 3`` C++ Type int Usd Type SdfValueTypeNames->Int """ @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: """ **classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ @staticmethod def GetVelocityScaleAttr() -> Attribute: """ GetVelocityScaleAttr() -> Attribute Deprecated VelocityScale is an **inherited** float attribute that velocity-based schemas (e.g. PointBased, PointInstancer) can consume to compute interpolated positions and orientations by applying velocity and angularVelocity, which is required for interpolating between samples when topology is varying over time. Although these quantities are generally physically computed by a simulator, sometimes we require more or less motion-blur to achieve the desired look. VelocityScale allows artists to dial-in, as a post-sim correction, a scale factor to be applied to the velocity prior to computing interpolated positions from it. Declaration ``float motion:velocityScale = 1`` C++ Type float Usd Type SdfValueTypeNames->Float """ @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: """ **classmethod** _GetStaticTfType() -> Type """ __instance_size__ = 48 pass class PointInstancer(Boundable, Xformable, Imageable, pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): """ Encodes vectorized instancing of multiple, potentially animated, prototypes (object/instance masters), which can be arbitrary prims/subtrees on a UsdStage. PointInstancer is a"multi instancer", as it allows multiple prototypes to be scattered among its"points". We use a UsdRelationship *prototypes* to identify and order all of the possible prototypes, by targeting the root prim of each prototype. The ordering imparted by relationships associates a zero-based integer with each prototype, and it is these integers we use to identify the prototype of each instance, compactly, and allowing prototypes to be swapped out without needing to reauthor all of the per-instance data. The PointInstancer schema is designed to scale to billions of instances, which motivates the choice to split the per-instance transformation into position, (quaternion) orientation, and scales, rather than a 4x4 matrix per-instance. In addition to requiring fewer bytes even if all elements are authored (32 bytes vs 64 for a single- precision 4x4 matrix), we can also be selective about which attributes need to animate over time, for substantial data reduction in many cases. Note that PointInstancer is *not* a Gprim, since it is not a graphical primitive by any stretch of the imagination. It *is*, however, Boundable, since we will sometimes want to treat the entire PointInstancer similarly to a procedural, from the perspective of inclusion or framing. Varying Instance Identity over Time =================================== PointInstancers originating from simulations often have the characteristic that points/instances are"born", move around for some time period, and then die (or leave the area of interest). In such cases, billions of instances may be birthed over time, while at any *specific* time, only a much smaller number are actually alive. To encode this situation efficiently, the simulator may re-use indices in the instance arrays, when a particle dies, its index will be taken over by a new particle that may be birthed in a much different location. This presents challenges both for identity-tracking, and for motion-blur. We facilitate identity tracking by providing an optional, animatable *ids* attribute, that specifies the 64 bit integer ID of the particle at each index, at each point in time. If the simulator keeps monotonically increasing a particle-count each time a new particle is birthed, it will serve perfectly as particle *ids*. We facilitate motion blur for varying-topology particle streams by optionally allowing per-instance *velocities* and *angularVelocities* to be authored. If instance transforms are requested at a time between samples and either of the velocity attributes is authored, then we will not attempt to interpolate samples of *positions* or *orientations*. If not authored, and the bracketing samples have the same length, then we will interpolate. Computing an Instance Transform =============================== Each instance's transformation is a combination of the SRT affine transform described by its scale, orientation, and position, applied *after* (i.e. less locally) than the transformation computed at the root of the prototype it is instancing. In other words, to put an instance of a PointInstancer into the space of the PointInstancer's parent prim: - Apply (most locally) the authored transformation for *prototypes[protoIndices[i]]* - If *scales* is authored, next apply the scaling matrix from *scales[i]* - If *orientations* is authored: **if *angularVelocities* is authored**, first multiply *orientations[i]* by the unit quaternion derived by scaling *angularVelocities[i]* by the time differential from the left-bracketing timeSample for *orientation* to the requested evaluation time *t*, storing the result in *R*, **else** assign *R* directly from *orientations[i]*. Apply the rotation matrix derived from *R*. - Apply the translation derived from *positions[i]*. If *velocities* is authored, apply the translation deriving from *velocities[i]* scaled by the time differential from the left- bracketing timeSample for *positions* to the requested evaluation time *t*. - Least locally, apply the transformation authored on the PointInstancer prim itself (or the UsdGeomImageable::ComputeLocalToWorldTransform() of the PointInstancer to put the instance directly into world space) If neither *velocities* nor *angularVelocities* are authored, we fallback to standard position and orientation computation logic (using linear interpolation between timeSamples) as described by Applying Timesampled Velocities to Geometry. **Scaling Velocities for Interpolation** When computing time-differentials by which to apply velocity or angularVelocity to positions or orientations, we must scale by ( 1.0 / UsdStage::GetTimeCodesPerSecond() ), because velocities are recorded in units/second, while we are interpolating in UsdTimeCode ordinates. We provide both high and low-level API's for dealing with the transformation as a matrix, both will compute the instance matrices using multiple threads; the low-level API allows the client to cache unvarying inputs so that they need not be read duplicately when computing over time. See also Applying Timesampled Velocities to Geometry. Primvars on PointInstancer ========================== Primvars authored on a PointInstancer prim should always be applied to each instance with *constant* interpolation at the root of the instance. When you are authoring primvars on a PointInstancer, think about it as if you were authoring them on a point-cloud (e.g. a UsdGeomPoints gprim). The same interpolation rules for points apply here, substituting"instance"for"point". In other words, the (constant) value extracted for each instance from the authored primvar value depends on the authored *interpolation* and *elementSize* of the primvar, as follows: - **constant** or **uniform** : the entire authored value of the primvar should be applied exactly to each instance. - **varying**, **vertex**, or **faceVarying** : the first *elementSize* elements of the authored primvar array should be assigned to instance zero, the second *elementSize* elements should be assigned to instance one, and so forth. Masking Instances:"Deactivating"and Invising ============================================ Often a PointInstancer is created"upstream"in a graphics pipeline, and the needs of"downstream"clients necessitate eliminating some of the instances from further consideration. Accomplishing this pruning by re-authoring all of the per-instance attributes is not very attractive, since it may mean destructively editing a large quantity of data. We therefore provide means of"masking"instances by ID, such that the instance data is unmolested, but per-instance transform and primvar data can be retrieved with the no-longer-desired instances eliminated from the (smaller) arrays. PointInstancer allows two independent means of masking instances by ID, each with different features that meet the needs of various clients in a pipeline. Both pruning features'lists of ID's are combined to produce the mask returned by ComputeMaskAtTime() . If a PointInstancer has no authored *ids* attribute, the masking features will still be available, with the integers specifying element position in the *protoIndices* array rather than ID. The first masking feature encodes a list of IDs in a list-editable metadatum called *inactiveIds*, which, although it does not have any similar impact to stage population as prim activation, it shares with that feature that its application is uniform over all time. Because it is list-editable, we can *sparsely* add and remove instances from it in many layers. This sparse application pattern makes *inactiveIds* a good choice when further downstream clients may need to reverse masking decisions made upstream, in a manner that is robust to many kinds of future changes to the upstream data. See ActivateId() , ActivateIds() , DeactivateId() , DeactivateIds() , ActivateAllIds() The second masking feature encodes a list of IDs in a time-varying Int64Array-valued UsdAttribute called *invisibleIds*, since it shares with Imageable visibility the ability to animate object visibility. Unlike *inactiveIds*, overriding a set of opinions for *invisibleIds* is not at all straightforward, because one will, in general need to reauthor (in the overriding layer) **all** timeSamples for the attribute just to change one Id's visibility state, so it cannot be authored sparsely. But it can be a very useful tool for situations like encoding pre-computed camera-frustum culling of geometry when either or both of the instances or the camera is animated. See VisId() , VisIds() , InvisId() , InvisIds() , VisAllIds() Processing and Not Processing Prototypes ======================================== Any prim in the scenegraph can be targeted as a prototype by the *prototypes* relationship. We do not, however, provide a specific mechanism for identifying prototypes as geometry that should not be drawn (or processed) in their own, local spaces in the scenegraph. We encourage organizing all prototypes as children of the PointInstancer prim that consumes them, and pruning"raw"processing and drawing traversals when they encounter a PointInstancer prim; this is what the UsdGeomBBoxCache and UsdImaging engines do. There *is* a pattern one can deploy for organizing the prototypes such that they will automatically be skipped by basic UsdPrim::GetChildren() or UsdPrimRange traversals. Usd prims each have a specifier of"def","over", or"class". The default traversals skip over prims that are"pure overs"or classes. So to protect prototypes from all generic traversals and processing, place them under a prim that is just an"over". For example, .. code-block:: text 01 def PointInstancer "Crowd_Mid" 02 { 03 rel prototypes = [ </Crowd_Mid/Prototypes/MaleThin_Business>, </Crowd_Mid/Prototypes/MaleThin_Casual> ] 04 05 over "Prototypes" 06 { 07 def "MaleThin_Business" ( 08 references = [@MaleGroupA/usd/MaleGroupA.usd@</MaleGroupA>] 09 variants = { 10 string modelingVariant = "Thin" 11 string costumeVariant = "BusinessAttire" 12 } 13 ) 14 { \.\.\. } 15 16 def "MaleThin_Casual" 17 \.\.\. 18 } 19 } """ class MaskApplication(pxr.Tf.Tf_PyEnumWrapper, pxr.Tf.Enum, Boost.Python.instance): """ Encodes whether to evaluate and apply the PointInstancer's mask to computed results. ComputeMaskAtTime() """ @staticmethod def GetValueFromName(*args, **kwargs) -> None: ... _baseName = 'PointInstancer' allValues: tuple # value = (UsdGeom.PointInstancer.ApplyMask, UsdGeom.PointInstancer.IgnoreMask) pass class ProtoXformInclusion(pxr.Tf.Tf_PyEnumWrapper, pxr.Tf.Enum, Boost.Python.instance): """ Encodes whether to include each prototype's root prim's transformation as the most-local component of computed instance transforms. """ @staticmethod def GetValueFromName(*args, **kwargs) -> None: ... _baseName = 'PointInstancer' allValues: tuple # value = (UsdGeom.PointInstancer.IncludeProtoXform, UsdGeom.PointInstancer.ExcludeProtoXform) pass @staticmethod def ActivateAllIds() -> bool: """ ActivateAllIds() -> bool Ensure that all instances are active over all time. This does not guarantee that the instances will be rendered, because each may still be"invisible"due to its presence in the *invisibleIds* attribute (see VisId() , InvisId() ) """ @staticmethod def ActivateId(id) -> bool: """ ActivateId(id) -> bool Ensure that the instance identified by ``id`` is active over all time. This activation is encoded sparsely, affecting no other instances. This does not guarantee that the instance will be rendered, because it may still be"invisible"due to ``id`` being present in the *invisibleIds* attribute (see VisId() , InvisId() ) Parameters ---------- id : int """ @staticmethod def ActivateIds(ids) -> bool: """ ActivateIds(ids) -> bool Ensure that the instances identified by ``ids`` are active over all time. This activation is encoded sparsely, affecting no other instances. This does not guarantee that the instances will be rendered, because each may still be"invisible"due to its presence in the *invisibleIds* attribute (see VisId() , InvisId() ) Parameters ---------- ids : Int64Array """ @staticmethod @typing.overload def ComputeExtentAtTime(extent, time, baseTime) -> bool: """ ComputeExtentAtTime(extent, time, baseTime) -> bool Compute the extent of the point instancer based on the per- instance,"PointInstancer relative"transforms at ``time`` , as described in Computing an Instance Transform. If there is no error, we return ``true`` and ``extent`` will be the tightest bounds we can compute efficiently. If an error occurs, ``false`` will be returned and ``extent`` will be left untouched. For now, this uses a UsdGeomBBoxCache with the"default","proxy", and"render"purposes. extent \- the out parameter for the extent. On success, it will contain two elements representing the min and max. time \- UsdTimeCode at which we want to evaluate the extent baseTime \- required for correct interpolation between samples when *velocities* or *angularVelocities* are present. If there are samples for *positions* and *velocities* at t1 and t2, normal value resolution would attempt to interpolate between the two samples, and if they could not be interpolated because they differ in size (common in cases where velocity is authored), will choose the sample at t1. When sampling for the purposes of motion-blur, for example, it is common, when rendering the frame at t2, to sample at [ t2-shutter/2, t2+shutter/2 ] for a shutter interval of *shutter*. The first sample falls between t1 and t2, but we must sample at t2 and apply velocity- based interpolation based on those samples to get a correct result. In such scenarios, one should provide a ``baseTime`` of t2 when querying *both* samples. If your application does not care about off-sample interpolation, it can supply the same value for ``baseTime`` that it does for ``time`` . When ``baseTime`` is less than or equal to ``time`` , we will choose the lower bracketing timeSample. Parameters ---------- extent : Vec3fArray time : TimeCode baseTime : TimeCode ---------------------------------------------------------------------- This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Computes the extent as if the matrix ``transform`` was first applied. Parameters ---------- extent : Vec3fArray time : TimeCode baseTime : TimeCode transform : Matrix4d """ @staticmethod @typing.overload def ComputeExtentAtTime(extent, time, baseTime, transform) -> bool: ... @staticmethod @typing.overload def ComputeExtentAtTimes(extents, times, baseTime) -> bool: """ ComputeExtentAtTimes(extents, times, baseTime) -> bool Compute the extent of the point instancer as in ComputeExtentAtTime, but across multiple ``times`` . This is equivalent to, but more efficient than, calling ComputeExtentAtTime several times. Each element in ``extents`` is the computed extent at the corresponding time in ``times`` . As in ComputeExtentAtTime, if there is no error, we return ``true`` and ``extents`` will be the tightest bounds we can compute efficiently. If an error occurs computing the extent at any time, ``false`` will be returned and ``extents`` will be left untouched. times \- A vector containing the UsdTimeCodes at which we want to sample. Parameters ---------- extents : list[Vec3fArray] times : list[TimeCode] baseTime : TimeCode ---------------------------------------------------------------------- This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Computes the extent as if the matrix ``transform`` was first applied at each time. Parameters ---------- extents : list[Vec3fArray] times : list[TimeCode] baseTime : TimeCode transform : Matrix4d """ @staticmethod @typing.overload def ComputeExtentAtTimes(extents, times, baseTime, transform) -> bool: ... @staticmethod def ComputeInstanceTransformsAtTime(xforms, stage, time, protoIndices, positions, velocities, velocitiesSampleTime, accelerations, scales, orientations, angularVelocities, angularVelocitiesSampleTime, protoPaths, mask, velocityScale) -> bool: """ **classmethod** ComputeInstanceTransformsAtTime(xforms, time, baseTime, doProtoXforms, applyMask) -> bool Compute the per-instance,"PointInstancer relative"transforms given the positions, scales, orientations, velocities and angularVelocities at ``time`` , as described in Computing an Instance Transform. This will return ``false`` and leave ``xforms`` untouched if: - ``xforms`` is None - one of ``time`` and ``baseTime`` is numeric and the other is UsdTimeCode::Default() (they must either both be numeric or both be default) - there is no authored *protoIndices* attribute or *positions* attribute - the size of any of the per-instance attributes does not match the size of *protoIndices* - ``doProtoXforms`` is ``IncludeProtoXform`` but an index value in *protoIndices* is outside the range [0, prototypes.size()) - ``applyMask`` is ``ApplyMask`` and a mask is set but the size of the mask does not match the size of *protoIndices*. If there is no error, we will return ``true`` and ``xforms`` will contain the computed transformations. xforms \- the out parameter for the transformations. Its size will depend on the authored data and ``applyMask`` time \- UsdTimeCode at which we want to evaluate the transforms baseTime \- required for correct interpolation between samples when *velocities* or *angularVelocities* are present. If there are samples for *positions* and *velocities* at t1 and t2, normal value resolution would attempt to interpolate between the two samples, and if they could not be interpolated because they differ in size (common in cases where velocity is authored), will choose the sample at t1. When sampling for the purposes of motion-blur, for example, it is common, when rendering the frame at t2, to sample at [ t2-shutter/2, t2+shutter/2 ] for a shutter interval of *shutter*. The first sample falls between t1 and t2, but we must sample at t2 and apply velocity- based interpolation based on those samples to get a correct result. In such scenarios, one should provide a ``baseTime`` of t2 when querying *both* samples. If your application does not care about off-sample interpolation, it can supply the same value for ``baseTime`` that it does for ``time`` . When ``baseTime`` is less than or equal to ``time`` , we will choose the lower bracketing timeSample. Selecting sample times with respect to baseTime will be performed independently for positions and orientations. doProtoXforms \- specifies whether to include the root transformation of each instance's prototype in the instance's transform. Default is to include it, but some clients may want to apply the proto transform as part of the prototype itself, so they can specify ``ExcludeProtoXform`` instead. applyMask \- specifies whether to apply ApplyMaskToArray() to the computed result. The default is ``ApplyMask`` . Parameters ---------- xforms : VtArray[Matrix4d] time : TimeCode baseTime : TimeCode doProtoXforms : ProtoXformInclusion applyMask : MaskApplication ---------------------------------------------------------------------- This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Perform the per-instance transform computation as described in Computing an Instance Transform. This does the same computation as the non-static ComputeInstanceTransformsAtTime method, but takes all data as parameters rather than accessing authored data. xforms \- the out parameter for the transformations. Its size will depend on the given data and ``applyMask`` stage \- the UsdStage time \- time at which we want to evaluate the transforms protoIndices \- array containing all instance prototype indices. positions \- array containing all instance positions. This array must be the same size as ``protoIndices`` . velocities \- array containing all instance velocities. This array must be either the same size as ``protoIndices`` or empty. If it is empty, transforms are computed as if all velocities were zero in all dimensions. velocitiesSampleTime \- time at which the samples from ``velocities`` were taken. accelerations \- array containing all instance accelerations. This array must be either the same size as ``protoIndicesor`` empty. If it is empty, transforms are computed as if all accelerations were zero in all dimensions. scales \- array containing all instance scales. This array must be either the same size as ``protoIndices`` or empty. If it is empty, transforms are computed with no change in scale. orientations \- array containing all instance orientations. This array must be either the same size as ``protoIndices`` or empty. If it is empty, transforms are computed with no change in orientation angularVelocities \- array containing all instance angular velocities. This array must be either the same size as ``protoIndices`` or empty. If it is empty, transforms are computed as if all angular velocities were zero in all dimensions. angularVelocitiesSampleTime \- time at which the samples from ``angularVelocities`` were taken. protoPaths \- array containing the paths for all instance prototypes. If this array is not empty, prototype transforms are applied to the instance transforms. mask \- vector containing a mask to apply to the computed result. This vector must be either the same size as ``protoIndices`` or empty. If it is empty, no mask is applied. velocityScale \- Deprecated Parameters ---------- xforms : VtArray[Matrix4d] stage : UsdStageWeak time : TimeCode protoIndices : IntArray positions : Vec3fArray velocities : Vec3fArray velocitiesSampleTime : TimeCode accelerations : Vec3fArray scales : Vec3fArray orientations : QuathArray angularVelocities : Vec3fArray angularVelocitiesSampleTime : TimeCode protoPaths : list[SdfPath] mask : list[bool] velocityScale : float """ @staticmethod def ComputeInstanceTransformsAtTimes(xformsArray, times, baseTime, doProtoXforms, applyMask) -> bool: """ ComputeInstanceTransformsAtTimes(xformsArray, times, baseTime, doProtoXforms, applyMask) -> bool Compute the per-instance transforms as in ComputeInstanceTransformsAtTime, but using multiple sample times. An array of matrix arrays is returned where each matrix array contains the instance transforms for the corresponding time in ``times`` . times \- A vector containing the UsdTimeCodes at which we want to sample. Parameters ---------- xformsArray : list[VtArray[Matrix4d]] times : list[TimeCode] baseTime : TimeCode doProtoXforms : ProtoXformInclusion applyMask : MaskApplication """ @staticmethod def ComputeMaskAtTime(time, ids) -> list[bool]: """ ComputeMaskAtTime(time, ids) -> list[bool] Computes a presence mask to be applied to per-instance data arrays based on authored *inactiveIds*, *invisibleIds*, and *ids*. If no *ids* attribute has been authored, then the values in *inactiveIds* and *invisibleIds* will be interpreted directly as indices of *protoIndices*. If ``ids`` is non-None, it is assumed to be the id-mapping to apply, and must match the length of *protoIndices* at ``time`` . If None, we will call GetIdsAttr() .Get(time) If all"live"instances at UsdTimeCode ``time`` pass the mask, we will return an **empty** mask so that clients can trivially recognize the common"no masking"case. The returned mask can be used with ApplyMaskToArray() , and will contain a ``true`` value for every element that should survive. Parameters ---------- time : TimeCode ids : Int64Array """ @staticmethod def CreateAccelerationsAttr(defaultValue, writeSparsely) -> Attribute: """ CreateAccelerationsAttr(defaultValue, writeSparsely) -> Attribute See GetAccelerationsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateAngularVelocitiesAttr(defaultValue, writeSparsely) -> Attribute: """ CreateAngularVelocitiesAttr(defaultValue, writeSparsely) -> Attribute See GetAngularVelocitiesAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateIdsAttr(defaultValue, writeSparsely) -> Attribute: """ CreateIdsAttr(defaultValue, writeSparsely) -> Attribute See GetIdsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateInvisibleIdsAttr(defaultValue, writeSparsely) -> Attribute: """ CreateInvisibleIdsAttr(defaultValue, writeSparsely) -> Attribute See GetInvisibleIdsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateOrientationsAttr(defaultValue, writeSparsely) -> Attribute: """ CreateOrientationsAttr(defaultValue, writeSparsely) -> Attribute See GetOrientationsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreatePositionsAttr(defaultValue, writeSparsely) -> Attribute: """ CreatePositionsAttr(defaultValue, writeSparsely) -> Attribute See GetPositionsAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateProtoIndicesAttr(defaultValue, writeSparsely) -> Attribute: """ CreateProtoIndicesAttr(defaultValue, writeSparsely) -> Attribute See GetProtoIndicesAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreatePrototypesRel() -> Relationship: """ CreatePrototypesRel() -> Relationship See GetPrototypesRel() , and also Create vs Get Property Methods for when to use Get vs Create. """ @staticmethod def CreateScalesAttr(defaultValue, writeSparsely) -> Attribute: """ CreateScalesAttr(defaultValue, writeSparsely) -> Attribute See GetScalesAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateVelocitiesAttr(defaultValue, writeSparsely) -> Attribute: """ CreateVelocitiesAttr(defaultValue, writeSparsely) -> Attribute See GetVelocitiesAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def DeactivateId(id) -> bool: """ DeactivateId(id) -> bool Ensure that the instance identified by ``id`` is inactive over all time. This deactivation is encoded sparsely, affecting no other instances. A deactivated instance is guaranteed not to render if the renderer honors masking. Parameters ---------- id : int """ @staticmethod def DeactivateIds(ids) -> bool: """ DeactivateIds(ids) -> bool Ensure that the instances identified by ``ids`` are inactive over all time. This deactivation is encoded sparsely, affecting no other instances. A deactivated instance is guaranteed not to render if the renderer honors masking. Parameters ---------- ids : Int64Array """ @staticmethod def Define(*args, **kwargs) -> None: """ **classmethod** Define(stage, path) -> PointInstancer Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ @staticmethod def Get(*args, **kwargs) -> None: """ **classmethod** Get(stage, path) -> PointInstancer Return a UsdGeomPointInstancer holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomPointInstancer(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ @staticmethod def GetAccelerationsAttr() -> Attribute: """ GetAccelerationsAttr() -> Attribute If authored, per-instance'accelerations'will be used with velocities to compute positions between samples for the'positions'attribute rather than interpolating between neighboring'positions'samples. Acceleration is measured in position units per second-squared. To convert to position units per squared UsdTimeCode, divide by the square of UsdStage::GetTimeCodesPerSecond() . Declaration ``vector3f[] accelerations`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Vector3fArray """ @staticmethod def GetAngularVelocitiesAttr() -> Attribute: """ GetAngularVelocitiesAttr() -> Attribute If authored, per-instance angular velocity vector to be used for interoplating orientations. Angular velocities should be considered mandatory if both *protoIndices* and *orientations* are animated. Angular velocity is measured in **degrees** per second. To convert to degrees per UsdTimeCode, divide by UsdStage::GetTimeCodesPerSecond() . See also Computing an Instance Transform. Declaration ``vector3f[] angularVelocities`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Vector3fArray """ @staticmethod def GetIdsAttr() -> Attribute: """ GetIdsAttr() -> Attribute Ids are optional; if authored, the ids array should be the same length as the *protoIndices* array, specifying (at each timeSample if instance identities are changing) the id of each instance. The type is signed intentionally, so that clients can encode some binary state on Id'd instances without adding a separate primvar. See also Varying Instance Identity over Time Declaration ``int64[] ids`` C++ Type VtArray<int64_t> Usd Type SdfValueTypeNames->Int64Array """ @staticmethod def GetInstanceCount(timeCode) -> int: """ GetInstanceCount(timeCode) -> int Returns the number of instances as defined by the size of the *protoIndices* array at *timeCode*. For most code, this check will be performant. When using file formats where the cost of attribute reading is high and the time sampled array will be read into memory later, it may be better to explicitly read the value once and check the size of the array directly. Parameters ---------- timeCode : TimeCode """ @staticmethod def GetInvisibleIdsAttr() -> Attribute: """ GetInvisibleIdsAttr() -> Attribute A list of id's to make invisible at the evaluation time. See invisibleIds: Animatable Masking. Declaration ``int64[] invisibleIds = []`` C++ Type VtArray<int64_t> Usd Type SdfValueTypeNames->Int64Array """ @staticmethod def GetOrientationsAttr() -> Attribute: """ GetOrientationsAttr() -> Attribute If authored, per-instance orientation of each instance about its prototype's origin, represented as a unit length quaternion, which allows us to encode it with sufficient precision in a compact GfQuath. It is client's responsibility to ensure that authored quaternions are unit length; the convenience API below for authoring orientations from rotation matrices will ensure that quaternions are unit length, though it will not make any attempt to select the"better (for interpolationwith respect to neighboring samples)"of the two possible quaternions that encode the rotation. See also Computing an Instance Transform. Declaration ``quath[] orientations`` C++ Type VtArray<GfQuath> Usd Type SdfValueTypeNames->QuathArray """ @staticmethod def GetPositionsAttr() -> Attribute: """ GetPositionsAttr() -> Attribute **Required property**. Per-instance position. See also Computing an Instance Transform. Declaration ``point3f[] positions`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Point3fArray """ @staticmethod def GetProtoIndicesAttr() -> Attribute: """ GetProtoIndicesAttr() -> Attribute **Required property**. Per-instance index into *prototypes* relationship that identifies what geometry should be drawn for each instance. **Topology attribute** - can be animated, but at a potential performance impact for streaming. Declaration ``int[] protoIndices`` C++ Type VtArray<int> Usd Type SdfValueTypeNames->IntArray """ @staticmethod def GetPrototypesRel() -> Relationship: """ GetPrototypesRel() -> Relationship **Required property**. Orders and targets the prototype root prims, which can be located anywhere in the scenegraph that is convenient, although we promote organizing prototypes as children of the PointInstancer. The position of a prototype in this relationship defines the value an instance would specify in the *protoIndices* attribute to instance that prototype. Since relationships are uniform, this property cannot be animated. """ @staticmethod def GetScalesAttr() -> Attribute: """ GetScalesAttr() -> Attribute If authored, per-instance scale to be applied to each instance, before any rotation is applied. See also Computing an Instance Transform. Declaration ``float3[] scales`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Float3Array """ @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: """ **classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ @staticmethod def GetVelocitiesAttr() -> Attribute: """ GetVelocitiesAttr() -> Attribute If provided, per-instance'velocities'will be used to compute positions between samples for the'positions'attribute, rather than interpolating between neighboring'positions'samples. Velocities should be considered mandatory if both *protoIndices* and *positions* are animated. Velocity is measured in position units per second, as per most simulation software. To convert to position units per UsdTimeCode, divide by UsdStage::GetTimeCodesPerSecond() . See also Computing an Instance Transform, Applying Timesampled Velocities to Geometry. Declaration ``vector3f[] velocities`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Vector3fArray """ @staticmethod def InvisId(id, time) -> bool: """ InvisId(id, time) -> bool Ensure that the instance identified by ``id`` is invisible at ``time`` . This will cause *invisibleIds* to first be broken down (keyed) at ``time`` , causing all animation in weaker layers that the current UsdEditTarget to be overridden. Has no effect on any timeSamples other than the one at ``time`` . An invised instance is guaranteed not to render if the renderer honors masking. Parameters ---------- id : int time : TimeCode """ @staticmethod def InvisIds(ids, time) -> bool: """ InvisIds(ids, time) -> bool Ensure that the instances identified by ``ids`` are invisible at ``time`` . This will cause *invisibleIds* to first be broken down (keyed) at ``time`` , causing all animation in weaker layers that the current UsdEditTarget to be overridden. Has no effect on any timeSamples other than the one at ``time`` . An invised instance is guaranteed not to render if the renderer honors masking. Parameters ---------- ids : Int64Array time : TimeCode """ @staticmethod def VisAllIds(time) -> bool: """ VisAllIds(time) -> bool Ensure that all instances are visible at ``time`` . Operates by authoring an empty array at ``time`` . This does not guarantee that the instances will be rendered, because each may still be"inactive"due to its id being present in the *inactivevIds* metadata (see ActivateId() , DeactivateId() ) Parameters ---------- time : TimeCode """ @staticmethod def VisId(id, time) -> bool: """ VisId(id, time) -> bool Ensure that the instance identified by ``id`` is visible at ``time`` . This will cause *invisibleIds* to first be broken down (keyed) at ``time`` , causing all animation in weaker layers that the current UsdEditTarget to be overridden. Has no effect on any timeSamples other than the one at ``time`` . If the *invisibleIds* attribute is not authored or is blocked, this operation is a no-op. This does not guarantee that the instance will be rendered, because it may still be"inactive"due to ``id`` being present in the *inactivevIds* metadata (see ActivateId() , DeactivateId() ) Parameters ---------- id : int time : TimeCode """ @staticmethod def VisIds(ids, time) -> bool: """ VisIds(ids, time) -> bool Ensure that the instances identified by ``ids`` are visible at ``time`` . This will cause *invisibleIds* to first be broken down (keyed) at ``time`` , causing all animation in weaker layers that the current UsdEditTarget to be overridden. Has no effect on any timeSamples other than the one at ``time`` . If the *invisibleIds* attribute is not authored or is blocked, this operation is a no-op. This does not guarantee that the instances will be rendered, because each may still be"inactive"due to ``id`` being present in the *inactivevIds* metadata (see ActivateId() , DeactivateId() ) Parameters ---------- ids : Int64Array time : TimeCode """ @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: """ **classmethod** _GetStaticTfType() -> Type """ ApplyMask: pxr.UsdGeom.MaskApplication # value = UsdGeom.PointInstancer.ApplyMask ExcludeProtoXform: pxr.UsdGeom.ProtoXformInclusion # value = UsdGeom.PointInstancer.ExcludeProtoXform IgnoreMask: pxr.UsdGeom.MaskApplication # value = UsdGeom.PointInstancer.IgnoreMask IncludeProtoXform: pxr.UsdGeom.ProtoXformInclusion # value = UsdGeom.PointInstancer.IncludeProtoXform __instance_size__ = 40 pass class Primvar(Boost.Python.instance): """ Schema wrapper for UsdAttribute for authoring and introspecting attributes that are primvars. UsdGeomPrimvar provides API for authoring and retrieving the additional data required to encode an attribute as a"Primvar", which is a convenient contraction of RenderMan's"Primitive Variable"concept, which is represented in Alembic as"arbitrary geometry parameters"(arbGeomParams). This includes the attribute's interpolation across the primitive (which RenderMan refers to as its class specifier and Alembic as its "geometry scope" ); it also includes the attribute's elementSize, which states how many values in the value array must be aggregated for each element on the primitive. An attribute's TypeName also factors into the encoding of Primvar. What is the Purpose of a Primvar? ================================= There are three key aspects of Primvar identity: - Primvars define a value that can vary across the primitive on which they are defined, via prescribed interpolation rules - Taken collectively on a prim, its Primvars describe the"per- primitiveoverrides"to the material to which the prim is bound. Different renderers may communicate the variables to the shaders using different mechanisms over which Usd has no control; Primvars simply provide the classification that any renderer should use to locate potential overrides. Do please note that primvars override parameters on UsdShadeShader objects, *not* Interface Attributes on UsdShadeMaterial prims. - *Primvars inherit down scene namespace.* Regular USD attributes only apply to the prim on which they are specified, but primvars implicitly also apply to any child prims, unless those child prims have their own opinions about those primvars. This capability necessarily entails added cost to check for inherited values, but the benefit is that it allows concise encoding of certain opinions that broadly affect large amounts of geometry. See UsdGeomImageable::FindInheritedPrimvars(). Creating and Accessing Primvars =============================== The UsdGeomPrimvarsAPI schema provides a complete interface for creating and querying prims for primvars. The **only** way to create a new Primvar in scene description is by calling UsdGeomPrimvarsAPI::CreatePrimvar() . One cannot"enhance"or"promote"an already existing attribute into a Primvar, because doing so may require a namespace edit to rename the attribute, which cannot, in general, be done within a single UsdEditContext. Instead, create a new UsdGeomPrimvar of the desired name using UsdGeomPrimvarsAPI::CreatePrimvar() , and then copy the existing attribute onto the new UsdGeomPrimvar. Primvar names can contain arbitrary sub-namespaces. The behavior of UsdGeomImageable::GetPrimvar(TfToken const & name) is to prepend"primvars:"onto'name'if it is not already a prefix, and return the result, which means we do not have any ambiguity between the primvars"primvars:nsA:foo"and"primvars:nsB:foo". **There are reserved keywords that may not be used as the base names of primvars,** and attempting to create Primvars of these names will result in a coding error. The reserved keywords are tokens the Primvar uses internally to encode various features, such as the"indices"keyword used by Indexed Primvars. If a client wishes to access an already-extant attribute as a Primvar, (which may or may not actually be valid Primvar), they can use the speculative constructor; typically, a primvar is only"interesting"if it additionally provides a value. This might look like: .. code-block:: text UsdGeomPrimvar primvar = UsdGeomPrimvar(usdAttr); if (primvar.HasValue()) { VtValue values; primvar.Get(&values, timeCode); TfToken interpolation = primvar.GetInterpolation(); int elementSize = primvar.GetElementSize(); \.\.\. } or, because Get() returns ``true`` if and only if it found a value: .. code-block:: text UsdGeomPrimvar primvar = UsdGeomPrimvar(usdAttr); VtValue values; if (primvar.Get(&values, timeCode)) { TfToken interpolation = primvar.GetInterpolation(); int elementSize = primvar.GetElementSize(); \.\.\. } As discussed in greater detail in Indexed Primvars, primvars can optionally contain a (possibly time-varying) indexing attribute that establishes a sharing topology for elements of the primvar. Consumers can always chose to ignore the possibility of indexed data by exclusively using the ComputeFlattened() API. If a client wishes to preserve indexing in their processing of a primvar, we suggest a pattern like the following, which accounts for the fact that a stronger layer can block a primvar's indexing from a weaker layer, via UsdGeomPrimvar::BlockIndices() : .. code-block:: text VtValue values; VtIntArray indices; if (primvar.Get(&values, timeCode)){ if (primvar.GetIndices(&indices, timeCode)){ // primvar is indexed: validate/process values and indices together } else { // primvar is not indexed: validate/process values as flat array } } UsdGeomPrimvar presents a small slice of the UsdAttribute API - enough to extract the data that comprises the"Declaration info", and get/set of the attribute value. A UsdGeomPrimvar also auto-converts to UsdAttribute, so you can pass a UsdGeomPrimvar to any function that accepts a UsdAttribute or const-ref thereto. Primvar Allowed Scene Description Types and Plurality ===================================================== There are no limitations imposed on the allowable scene description types for Primvars; it is the responsibility of each consuming client to perform renderer-specific conversions, if need be (the USD distribution will include reference RenderMan conversion utilities). A note about type plurality of Primvars: It is legitimate for a Primvar to be of scalar or array type, and again, consuming clients must be prepared to accommodate both. However, while it is not possible, in all cases, for USD to *prevent* one from *changing* the type of an attribute in different layers or variants of an asset, it is never a good idea to do so. This is relevant because, except in a few special cases, it is not possible to encode an *interpolation* of any value greater than *constant* without providing multiple (i.e. array) data values. Therefore, if there is any possibility that downstream clients might need to change a Primvar's interpolation, the Primvar-creator should encode it as an array rather than a scalar. Why allow scalar values at all, then? First, sometimes it brings clarity to (use of) a shader's API to acknowledge that some parameters are meant to be single-valued over a shaded primitive. Second, many DCC's provide far richer affordances for editing scalars than they do array values, and we feel it is safer to let the content creator make the decision/tradeoff of which kind of flexibility is more relevant, rather than leaving it to an importer/exporter pair to interpret. Also, like all attributes, Primvars can be time-sampled, and values can be authored and consumed just as any other attribute. There is currently no validation that the length of value arrays matches to the size required by a gprim's topology, interpolation, and elementSize. For consumer convenience, we provide GetDeclarationInfo() , which returns all the type information (other than topology) needed to compute the required array size, which is also all the information required to prepare the Primvar's value for consumption by a renderer. Lifetime Management and Primvar Validity ======================================== UsdGeomPrimvar has an explicit bool operator that validates that the attribute IsDefined() and thus valid for querying and authoring values and metadata. This is a fairly expensive query that we do **not** cache, so if client code retains UsdGeomPrimvar objects, it should manage its object validity closely, for performance. An ideal pattern is to listen for UsdNotice::StageContentsChanged notifications, and revalidate/refetch its retained UsdGeomPrimvar s only then, and otherwise use them without validity checking. Interpolation of Geometric Primitive Variables ============================================== In the following explanation of the meaning of the various kinds/levels of Primvar interpolation, each bolded bullet gives the name of the token in UsdGeomTokens that provides the value. So to set a Primvar's interpolation to"varying", one would: .. code-block:: text primvar.SetInterpolation(UsdGeomTokens->varying); Reprinted and adapted from the RPS documentation, which contains further details, *interpolation* describes how the Primvar will be interpolated over the uv parameter space of a surface primitive (or curve or pointcloud). The possible values are: - **constant** One value remains constant over the entire surface primitive. - **uniform** One value remains constant for each uv patch segment of the surface primitive (which is a *face* for meshes). - **varying** Four values are interpolated over each uv patch segment of the surface. Bilinear interpolation is used for interpolation between the four values. - **vertex** Values are interpolated between each vertex in the surface primitive. The basis function of the surface is used for interpolation between vertices. - **faceVarying** For polygons and subdivision surfaces, four values are interpolated over each face of the mesh. Bilinear interpolation is used for interpolation between the four values. UsdGeomPrimvar As Example of Attribute Schema ============================================= Just as UsdSchemaBase and its subclasses provide the pattern for how to layer schema onto the generic UsdPrim object, UsdGeomPrimvar provides an example of how to layer schema onto a generic UsdAttribute object. In both cases, the schema object wraps and contains the UsdObject. Primvar Namespace Inheritance ============================= Constant interpolation primvar values can be inherited down namespace. That is, a primvar value set on a prim will also apply to any child prims, unless those children have their own opinions about those named primvars. For complete details on how primvars inherit, see usdGeom_PrimvarInheritance. UsdGeomImageable::FindInheritablePrimvars(). """ @staticmethod def BlockIndices() -> None: """ BlockIndices() -> None Block the indices that were previously set. This effectively makes an indexed primvar no longer indexed. This is useful when overriding an existing primvar. """ @staticmethod @typing.overload def ComputeFlattened(value, time) -> bool: """ **classmethod** ComputeFlattened(value, time) -> bool Computes the flattened value of the primvar at ``time`` . If the primvar is not indexed or if the value type of this primvar is a scalar, this returns the authored value, which is the same as Get() . Hence, it's safe to call ComputeFlattened() on non-indexed primvars. Parameters ---------- value : VtArray[ScalarType] time : TimeCode ---------------------------------------------------------------------- This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Computes the flattened value of the primvar at ``time`` as a VtValue. If the primvar is not indexed or if the value type of this primvar is a scalar, this returns the authored value, which is the same as Get() . Hence, it's safe to call ComputeFlattened() on non-indexed primvars. Parameters ---------- value : VtValue time : TimeCode ---------------------------------------------------------------------- Computes the flattened value of ``attrValue`` given ``indices`` . This method is a static convenience function that performs the main work of ComputeFlattened above without needing an instance of a UsdGeomPrimvar. Returns ``false`` if the value contained in ``attrVal`` is not a supported type for flattening. Otherwise returns ``true`` . The output ``errString`` variable may be populated with an error string if an error is encountered during flattening. Parameters ---------- value : VtValue attrVal : VtValue indices : IntArray errString : str """ @staticmethod @typing.overload def ComputeFlattened(value, attrVal, indices, errString) -> bool: ... @staticmethod def CreateIndicesAttr() -> Attribute: """ CreateIndicesAttr() -> Attribute Returns the existing indices attribute if the primvar is indexed or creates a new one. """ @staticmethod def Get(value, time) -> bool: """ Get(value, time) -> bool Get the attribute value of the Primvar at ``time`` . Usd_Handling_Indexed_Primvars for proper handling of indexed primvars Parameters ---------- value : T time : TimeCode ---------------------------------------------------------------------- Parameters ---------- value : str time : TimeCode ---------------------------------------------------------------------- Parameters ---------- value : StringArray time : TimeCode ---------------------------------------------------------------------- Parameters ---------- value : VtValue time : TimeCode """ @staticmethod def GetAttr() -> Attribute: """ GetAttr() -> Attribute Explicit UsdAttribute extractor. """ @staticmethod def GetBaseName() -> str: """ GetBaseName() -> str UsdAttribute::GetBaseName() """ @staticmethod def GetDeclarationInfo(name, typeName, interpolation, elementSize) -> None: """ GetDeclarationInfo(name, typeName, interpolation, elementSize) -> None Convenience function for fetching all information required to properly declare this Primvar. The ``name`` returned is the"client name", stripped of the"primvars"namespace, i.e. equivalent to GetPrimvarName() May also be more efficient than querying key individually. Parameters ---------- name : str typeName : ValueTypeName interpolation : str elementSize : int """ @staticmethod def GetElementSize() -> int: """ GetElementSize() -> int Return the"element size"for this Primvar, which is 1 if unauthored. If this Primvar's type is *not* an array type, (e.g."Vec3f[]"), then elementSize is irrelevant. ElementSize does *not* generally encode the length of an array-type primvar, and rarely needs to be authored. ElementSize can be thought of as a way to create an"aggregate interpolatable type", by dictating how many consecutive elements in the value array should be taken as an atomic element to be interpolated over a gprim. For example, spherical harmonics are often represented as a collection of nine floating-point coefficients, and the coefficients need to be sampled across a gprim's surface: a perfect case for primvars. However, USD has no ``float9`` datatype. But we can communicate the aggregation of nine floats successfully to renderers by declaring a simple float-array valued primvar, and setting its *elementSize* to 9. To author a *uniform* spherical harmonic primvar on a Mesh of 42 faces, the primvar's array value would contain 9\*42 = 378 float elements. """ @staticmethod def GetIndices(indices, time) -> bool: """ GetIndices(indices, time) -> bool Returns the value of the indices array associated with the indexed primvar at ``time`` . Parameters ---------- indices : IntArray time : TimeCode """ @staticmethod def GetIndicesAttr() -> Attribute: """ GetIndicesAttr() -> Attribute Returns a valid indices attribute if the primvar is indexed. Returns an invalid attribute otherwise. """ @staticmethod def GetInterpolation() -> str: """ GetInterpolation() -> str Return the Primvar's interpolation, which is UsdGeomTokens->constant if unauthored. Interpolation determines how the Primvar interpolates over a geometric primitive. See Interpolation of Geometric Primitive Variables """ @staticmethod def GetName() -> str: """ GetName() -> str UsdAttribute::GetName() """ @staticmethod def GetNamespace() -> str: """ GetNamespace() -> str UsdAttribute::GetNamespace() """ @staticmethod def GetPrimvarName() -> str: """ GetPrimvarName() -> str Returns the primvar's name, devoid of the"primvars:"namespace. This is the name by which clients should refer to the primvar, if not by its full attribute name - i.e. they should **not**, in general, use GetBaseName() . In the error condition in which this Primvar object is not backed by a properly namespaced UsdAttribute, return an empty TfToken. """ @staticmethod def GetTimeSamples(times) -> bool: """ GetTimeSamples(times) -> bool Populates a vector with authored sample times for this primvar. Returns false on error. This considers any timeSamples authored on the associated"indices"attribute if the primvar is indexed. UsdAttribute::GetTimeSamples Parameters ---------- times : list[float] """ @staticmethod def GetTimeSamplesInInterval(interval, times) -> bool: """ GetTimeSamplesInInterval(interval, times) -> bool Populates a vector with authored sample times in ``interval`` . This considers any timeSamples authored on the associated"indices"attribute if the primvar is indexed. UsdAttribute::GetTimeSamplesInInterval Parameters ---------- interval : Interval times : list[float] """ @staticmethod def GetTypeName() -> ValueTypeName: """ GetTypeName() -> ValueTypeName UsdAttribute::GetTypeName() """ @staticmethod def GetUnauthoredValuesIndex() -> int: """ GetUnauthoredValuesIndex() -> int Returns the index that represents unauthored values in the indices array. """ @staticmethod def HasAuthoredElementSize() -> bool: """ HasAuthoredElementSize() -> bool Has elementSize been explicitly authored on this Primvar? """ @staticmethod def HasAuthoredInterpolation() -> bool: """ HasAuthoredInterpolation() -> bool Has interpolation been explicitly authored on this Primvar? """ @staticmethod def HasAuthoredValue() -> bool: """ HasAuthoredValue() -> bool Return true if the underlying attribute has an unblocked, authored value. """ @staticmethod def HasValue() -> bool: """ HasValue() -> bool Return true if the underlying attribute has a value, either from authored scene description or a fallback. """ @staticmethod def IsDefined() -> bool: """ IsDefined() -> bool Return true if the underlying UsdAttribute::IsDefined() , and in addition the attribute is identified as a Primvar. Does not imply that the primvar provides a value """ @staticmethod def IsIdTarget() -> bool: """ IsIdTarget() -> bool Returns true if the primvar is an Id primvar. UsdGeomPrimvar_Id_primvars """ @staticmethod def IsIndexed() -> bool: """ IsIndexed() -> bool Returns true if the primvar is indexed, i.e., if it has an associated"indices"attribute. If you are going to query the indices anyways, prefer to simply consult the return-value of GetIndices() , which will be more efficient. """ @staticmethod def IsPrimvar(*args, **kwargs) -> None: """ **classmethod** IsPrimvar(attr) -> bool Test whether a given UsdAttribute represents valid Primvar, which implies that creating a UsdGeomPrimvar from the attribute will succeed. Success implies that ``attr.IsDefined()`` is true. Parameters ---------- attr : Attribute """ @staticmethod def IsValidInterpolation(*args, **kwargs) -> None: """ **classmethod** IsValidInterpolation(interpolation) -> bool Validate that the provided ``interpolation`` is a valid setting for interpolation as defined by Interpolation of Geometric Primitive Variables. Parameters ---------- interpolation : str """ @staticmethod def IsValidPrimvarName(*args, **kwargs) -> None: """ **classmethod** IsValidPrimvarName(name) -> bool Test whether a given ``name`` represents a valid name of a primvar, which implies that creating a UsdGeomPrimvar with the given name will succeed. Parameters ---------- name : str """ @staticmethod def NameContainsNamespaces() -> bool: """ NameContainsNamespaces() -> bool Does this primvar contain any namespaces other than the"primvars:"namespace? Some clients may only wish to consume primvars that have no extra namespaces in their names, for ease of translating to other systems that do not allow namespaces. """ @staticmethod def Set(value, time) -> bool: """ Set(value, time) -> bool Set the attribute value of the Primvar at ``time`` . Parameters ---------- value : T time : TimeCode """ @staticmethod def SetElementSize(eltSize) -> bool: """ SetElementSize(eltSize) -> bool Set the elementSize for this Primvar. Errors and returns false if ``eltSize`` less than 1. Parameters ---------- eltSize : int """ @staticmethod def SetIdTarget(path) -> bool: """ SetIdTarget(path) -> bool This primvar must be of String or StringArray type for this method to succeed. If not, a coding error is raised. UsdGeomPrimvar_Id_primvars Parameters ---------- path : Path """ @staticmethod def SetIndices(indices, time) -> bool: """ SetIndices(indices, time) -> bool Sets the indices value of the indexed primvar at ``time`` . The values in the indices array must be valid indices into the authored array returned by Get() . The element numerality of the primvar's'interpolation'metadata applies to the"indices"array, not the attribute value array (returned by Get() ). Parameters ---------- indices : IntArray time : TimeCode """ @staticmethod def SetInterpolation(interpolation) -> bool: """ SetInterpolation(interpolation) -> bool Set the Primvar's interpolation. Errors and returns false if ``interpolation`` is out of range as defined by IsValidInterpolation() . No attempt is made to validate that the Primvar's value contains the right number of elements to match its interpolation to its topology. Parameters ---------- interpolation : str """ @staticmethod def SetUnauthoredValuesIndex(unauthoredValuesIndex) -> bool: """ SetUnauthoredValuesIndex(unauthoredValuesIndex) -> bool Set the index that represents unauthored values in the indices array. Some apps (like Maya) allow you to author primvars sparsely over a surface. Since most apps can't handle sparse primvars, Maya needs to provide a value even for the elements it didn't author. This metadatum provides a way to recover the information in apps that do support sparse authoring / representation of primvars. The fallback value of unauthoredValuesIndex is -1, which indicates that there are no unauthored values. Parameters ---------- unauthoredValuesIndex : int """ @staticmethod def SplitName() -> list[str]: """ SplitName() -> list[str] UsdAttribute::SplitName() """ @staticmethod def StripPrimvarsName(*args, **kwargs) -> None: """ **classmethod** StripPrimvarsName(name) -> str Returns the ``name`` , devoid of the"primvars:"token if present, otherwise returns the ``name`` unchanged. Parameters ---------- name : str """ @staticmethod def ValueMightBeTimeVarying() -> bool: """ ValueMightBeTimeVarying() -> bool Return true if it is possible, but not certain, that this primvar's value changes over time, false otherwise. This considers time-varyingness of the associated"indices"attribute if the primvar is indexed. UsdAttribute::ValueMightBeTimeVarying """ __instance_size__ = 64 pass class PrimvarsAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): """ UsdGeomPrimvarsAPI encodes geometric"primitive variables", as UsdGeomPrimvar, which interpolate across a primitive's topology, can override shader inputs, and inherit down namespace. Which Method to Use to Retrieve Primvars ======================================== While creating primvars is unambiguous ( CreatePrimvar() ), there are quite a few methods available for retrieving primvars, making it potentially confusing knowing which one to use. Here are some guidelines: - If you are populating a GUI with the primvars already available for authoring values on a prim, use GetPrimvars() . - If you want all of the"useful"(e.g. to a renderer) primvars available at a prim, including those inherited from ancestor prims, use FindPrimvarsWithInheritance() . Note that doing so individually for many prims will be inefficient. - To find a particular primvar defined directly on a prim, which may or may not provide a value, use GetPrimvar() . - To find a particular primvar defined on a prim or inherited from ancestors, which may or may not provide a value, use FindPrimvarWithInheritance() . - To *efficiently* query for primvars using the overloads of FindPrimvarWithInheritance() and FindPrimvarsWithInheritance() , one must first cache the results of FindIncrementallyInheritablePrimvars() for each non-leaf prim on the stage. """ @staticmethod def BlockPrimvar(name) -> None: """ BlockPrimvar(name) -> None Remove all time samples on the primvar and its associated indices attr, and author a *block* ``default`` value. This will cause authored opinions in weaker layers to be ignored. UsdAttribute::Block() , UsdGeomPrimvar::BlockIndices Parameters ---------- name : str """ @staticmethod def CanContainPropertyName(*args, **kwargs) -> None: """ **classmethod** CanContainPropertyName(name) -> bool Test whether a given ``name`` contains the"primvars:"prefix. Parameters ---------- name : str """ @staticmethod def CreateIndexedPrimvar(name, typeName, value, indices, interpolation, elementSize, time) -> Primvar: """ CreateIndexedPrimvar(name, typeName, value, indices, interpolation, elementSize, time) -> Primvar Author scene description to create an attribute and authoring a ``value`` on this prim that will be recognized as an indexed Primvar with ``indices`` appropriately set (i.e. will present as a valid UsdGeomPrimvar). an invalid UsdGeomPrimvar on error, a valid UsdGeomPrimvar otherwise. It is fine to call this method multiple times, and in different UsdEditTargets, even if there is an existing primvar of the same name, indexed or not. Parameters ---------- name : str typeName : ValueTypeName value : T indices : IntArray interpolation : str elementSize : int time : TimeCode """ @staticmethod def CreateNonIndexedPrimvar(name, typeName, value, interpolation, elementSize, time) -> Primvar: """ CreateNonIndexedPrimvar(name, typeName, value, interpolation, elementSize, time) -> Primvar Author scene description to create an attribute and authoring a ``value`` on this prim that will be recognized as a Primvar (i.e. will present as a valid UsdGeomPrimvar). Note that unlike CreatePrimvar using this API explicitly authors a block for the indices attr associated with the primvar, thereby blocking any indices set in any weaker layers. an invalid UsdGeomPrimvar on error, a valid UsdGeomPrimvar otherwise. It is fine to call this method multiple times, and in different UsdEditTargets, even if there is an existing primvar of the same name, indexed or not. Parameters ---------- name : str typeName : ValueTypeName value : T interpolation : str elementSize : int time : TimeCode """ @staticmethod def CreatePrimvar(name, typeName, interpolation, elementSize) -> Primvar: """ CreatePrimvar(name, typeName, interpolation, elementSize) -> Primvar Author scene description to create an attribute on this prim that will be recognized as Primvar (i.e. will present as a valid UsdGeomPrimvar). The name of the created attribute may or may not be the specified ``name`` , due to the possible need to apply property namespacing for primvars. See Creating and Accessing Primvars for more information. Creation may fail and return an invalid Primvar if ``name`` contains a reserved keyword, such as the"indices"suffix we use for indexed primvars. The behavior with respect to the provided ``typeName`` is the same as for UsdAttributes::Create(), and ``interpolation`` and ``elementSize`` are as described in UsdGeomPrimvar::GetInterpolation() and UsdGeomPrimvar::GetElementSize() . If ``interpolation`` and/or ``elementSize`` are left unspecified, we will author no opinions for them, which means any (strongest) opinion already authored in any contributing layer for these fields will become the Primvar's values, or the fallbacks if no opinions have been authored. an invalid UsdGeomPrimvar if we failed to create a valid attribute, a valid UsdGeomPrimvar otherwise. It is not an error to create over an existing, compatible attribute. UsdPrim::CreateAttribute() , UsdGeomPrimvar::IsPrimvar() Parameters ---------- name : str typeName : ValueTypeName interpolation : str elementSize : int """ @staticmethod def FindIncrementallyInheritablePrimvars(inheritedFromAncestors) -> list[Primvar]: """ FindIncrementallyInheritablePrimvars(inheritedFromAncestors) -> list[Primvar] Compute the primvars that can be inherited from this prim by its child prims, starting from the set of primvars inherited from this prim's ancestors. If this method returns an empty vector, then this prim's children should inherit the same set of primvars available to this prim, i.e. the input ``inheritedFromAncestors`` . As opposed to FindInheritablePrimvars() , which always recurses up through all of the prim's ancestors, this method allows more efficient computation of inheritable primvars by starting with the list of primvars inherited from this prim's ancestors, and returning a newly allocated vector only when this prim makes a change to the set of inherited primvars. This enables O(n) inherited primvar computation for all prims on a Stage, with potential to share computed results that are identical (i.e. when this method returns an empty vector, its parent's result can (and must!) be reused for all of the prim's children. Which Method to Use to Retrieve Primvars Parameters ---------- inheritedFromAncestors : list[Primvar] """ @staticmethod def FindInheritablePrimvars() -> list[Primvar]: """ FindInheritablePrimvars() -> list[Primvar] Compute the primvars that can be inherited from this prim by its child prims, including the primvars that **this** prim inherits from ancestor prims. Inherited primvars will be bound to attributes on the corresponding ancestor prims. Only primvars with **authored**, **non-blocked**, **constant interpolation** values are inheritable; fallback values are not inherited. The order of the returned primvars is undefined. It is not generally useful to call this method on UsdGeomGprim leaf prims, and furthermore likely to be expensive since *most* primvars are defined on Gprims. Which Method to Use to Retrieve Primvars """ @staticmethod @typing.overload def FindPrimvarWithInheritance(name) -> Primvar: """ FindPrimvarWithInheritance(name) -> Primvar Like GetPrimvar() , but if the named primvar does not exist or has no authored value on this prim, search for the named, value-producing primvar on ancestor prims. The returned primvar will be bound to the attribute on the corresponding ancestor prim on which it was found (if any). If neither this prim nor any ancestor contains a value-producing primvar, then the returned primvar will be the same as that returned by GetPrimvar() . This is probably the method you want to call when needing to consume a primvar of a particular name. Which Method to Use to Retrieve Primvars Parameters ---------- name : str ---------------------------------------------------------------------- This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. This version of FindPrimvarWithInheritance() takes the pre-computed set of primvars inherited from this prim's ancestors, as computed by FindInheritablePrimvars() or FindIncrementallyInheritablePrimvars() on the prim's parent. Which Method to Use to Retrieve Primvars Parameters ---------- name : str inheritedFromAncestors : list[Primvar] """ @staticmethod @typing.overload def FindPrimvarWithInheritance(name, inheritedFromAncestors) -> Primvar: ... @staticmethod @typing.overload def FindPrimvarsWithInheritance() -> list[Primvar]: """ FindPrimvarsWithInheritance() -> list[Primvar] Find all of the value-producing primvars either defined on this prim, or inherited from ancestor prims. Which Method to Use to Retrieve Primvars ---------------------------------------------------------------------- This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. This version of FindPrimvarsWithInheritance() takes the pre-computed set of primvars inherited from this prim's ancestors, as computed by FindInheritablePrimvars() or FindIncrementallyInheritablePrimvars() on the prim's parent. Which Method to Use to Retrieve Primvars Parameters ---------- inheritedFromAncestors : list[Primvar] """ @staticmethod @typing.overload def FindPrimvarsWithInheritance(inheritedFromAncestors) -> list[Primvar]: ... @staticmethod def Get(*args, **kwargs) -> None: """ **classmethod** Get(stage, path) -> PrimvarsAPI Return a UsdGeomPrimvarsAPI holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomPrimvarsAPI(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ @staticmethod def GetAuthoredPrimvars() -> list[Primvar]: """ GetAuthoredPrimvars() -> list[Primvar] Like GetPrimvars() , but include only primvars that have some authored scene description (though not necessarily a value). Which Method to Use to Retrieve Primvars """ @staticmethod def GetPrimvar(name) -> Primvar: """ GetPrimvar(name) -> Primvar Return the Primvar object named by ``name`` , which will be valid if a Primvar attribute definition already exists. Name lookup will account for Primvar namespacing, which means that this method will succeed in some cases where .. code-block:: text UsdGeomPrimvar(prim->GetAttribute(name)) will not, unless ``name`` is properly namespace prefixed. Just because a Primvar is valid and defined, and *even if* its underlying UsdAttribute (GetAttr()) answers HasValue() affirmatively, one must still check the return value of Get() , due to the potential of time-varying value blocks (see Attribute Value Blocking). Parameters ---------- name : str """ @staticmethod def GetPrimvars() -> list[Primvar]: """ GetPrimvars() -> list[Primvar] Return valid UsdGeomPrimvar objects for all defined Primvars on this prim, similarly to UsdPrim::GetAttributes() . The returned primvars may not possess any values, and therefore not be useful to some clients. For the primvars useful for inheritance computations, see GetPrimvarsWithAuthoredValues() , and for primvars useful for direct consumption, see GetPrimvarsWithValues() . Which Method to Use to Retrieve Primvars """ @staticmethod def GetPrimvarsWithAuthoredValues() -> list[Primvar]: """ GetPrimvarsWithAuthoredValues() -> list[Primvar] Like GetPrimvars() , but include only primvars that have an **authored** value. This is the query used when computing inheritable primvars, and is generally more useful than GetAuthoredPrimvars() . Which Method to Use to Retrieve Primvars """ @staticmethod def GetPrimvarsWithValues() -> list[Primvar]: """ GetPrimvarsWithValues() -> list[Primvar] Like GetPrimvars() , but include only primvars that have some value, whether it comes from authored scene description or a schema fallback. For most purposes, this method is more useful than GetPrimvars() . Which Method to Use to Retrieve Primvars """ @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: """ **classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ @staticmethod def HasPossiblyInheritedPrimvar(name) -> bool: """ HasPossiblyInheritedPrimvar(name) -> bool Is there a Primvar named ``name`` with an authored value on this prim or any of its ancestors? This is probably the method you want to call when wanting to know whether or not the prim"has"a primvar of a particular name. Parameters ---------- name : str """ @staticmethod def HasPrimvar(name) -> bool: """ HasPrimvar(name) -> bool Is there a defined Primvar ``name`` on this prim? Name lookup will account for Primvar namespacing. Like GetPrimvar() , a return value of ``true`` for HasPrimvar() does not guarantee the primvar will produce a value. Parameters ---------- name : str """ @staticmethod def RemovePrimvar(name) -> bool: """ RemovePrimvar(name) -> bool Author scene description to delete an attribute on this prim that was recognized as Primvar (i.e. will present as a valid UsdGeomPrimvar), *in the current UsdEditTarget*. Because this method can only remove opinions about the primvar from the current EditTarget, you may generally find it more useful to use BlockPrimvar() which will ensure that all values from the EditTarget and weaker layers for the primvar and its indices will be ignored. Removal may fail and return false if ``name`` contains a reserved keyword, such as the"indices"suffix we use for indexed primvars. Note this will also remove the indices attribute associated with an indiced primvar. true if UsdGeomPrimvar and indices attribute was successfully removed, false otherwise. UsdPrim::RemoveProperty() ) Parameters ---------- name : str """ @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: """ **classmethod** _GetStaticTfType() -> Type """ __instance_size__ = 48 pass class Scope(Imageable, pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): """ Scope is the simplest grouping primitive, and does not carry the baggage of transformability. Note that transforms should inherit down through a Scope successfully - it is just a guaranteed no-op from a transformability perspective. """ @staticmethod def Define(*args, **kwargs) -> None: """ **classmethod** Define(stage, path) -> Scope Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ @staticmethod def Get(*args, **kwargs) -> None: """ **classmethod** Get(stage, path) -> Scope Return a UsdGeomScope holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomScope(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: """ **classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: """ **classmethod** _GetStaticTfType() -> Type """ __instance_size__ = 40 pass class Sphere(Gprim, Boundable, Xformable, Imageable, pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): """ Defines a primitive sphere centered at the origin. The fallback values for Cube, Sphere, Cone, and Cylinder are set so that they all pack into the same volume/bounds. """ @staticmethod def CreateExtentAttr(defaultValue, writeSparsely) -> Attribute: """ CreateExtentAttr(defaultValue, writeSparsely) -> Attribute See GetExtentAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateRadiusAttr(defaultValue, writeSparsely) -> Attribute: """ CreateRadiusAttr(defaultValue, writeSparsely) -> Attribute See GetRadiusAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def Define(*args, **kwargs) -> None: """ **classmethod** Define(stage, path) -> Sphere Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ @staticmethod def Get(*args, **kwargs) -> None: """ **classmethod** Get(stage, path) -> Sphere Return a UsdGeomSphere holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomSphere(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ @staticmethod def GetExtentAttr() -> Attribute: """ GetExtentAttr() -> Attribute Extent is re-defined on Sphere only to provide a fallback value. UsdGeomGprim::GetExtentAttr() . Declaration ``float3[] extent = [(-1, -1, -1), (1, 1, 1)]`` C++ Type VtArray<GfVec3f> Usd Type SdfValueTypeNames->Float3Array """ @staticmethod def GetRadiusAttr() -> Attribute: """ GetRadiusAttr() -> Attribute Indicates the sphere's radius. If you author *radius* you must also author *extent*. Declaration ``double radius = 1`` C++ Type double Usd Type SdfValueTypeNames->Double """ @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: """ **classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: """ **classmethod** _GetStaticTfType() -> Type """ __instance_size__ = 40 pass class Subset(pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): """ Encodes a subset of a piece of geometry (i.e. a UsdGeomImageable) as a set of indices. Currently only supports encoding of face-subsets, but could be extended in the future to support subsets representing edges, segments, points etc. To apply to a geometric prim, a GeomSubset prim must be the prim's direct child in namespace, and possess a concrete defining specifier (i.e. def). This restriction makes it easy and efficient to discover subsets of a prim. We might want to relax this restriction if it's common to have multiple **families** of subsets on a gprim and if it's useful to be able to organize subsets belonging to a family under a common scope. See'familyName'attribute for more info on defining a family of subsets. Note that a GeomSubset isn't an imageable (i.e. doesn't derive from UsdGeomImageable). So, you can't author **visibility** for it or override its **purpose**. Materials are bound to GeomSubsets just as they are for regular geometry using API available in UsdShade (UsdShadeMaterial::Bind). For any described attribute *Fallback* *Value* or *Allowed* *Values* below that are text/tokens, the actual token is published and defined in UsdGeomTokens. So to set an attribute to the value"rightHanded", use UsdGeomTokens->rightHanded as the value. """ @staticmethod def CreateElementTypeAttr(defaultValue, writeSparsely) -> Attribute: """ CreateElementTypeAttr(defaultValue, writeSparsely) -> Attribute See GetElementTypeAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateFamilyNameAttr(defaultValue, writeSparsely) -> Attribute: """ CreateFamilyNameAttr(defaultValue, writeSparsely) -> Attribute See GetFamilyNameAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateGeomSubset(*args, **kwargs) -> None: """ **classmethod** CreateGeomSubset(geom, subsetName, elementType, indices, familyName, familyType) -> Subset Creates a new GeomSubset below the given ``geom`` with the given name, ``subsetName`` , element type, ``elementType`` and ``indices`` . If a subset named ``subsetName`` already exists below ``geom`` , then this updates its attributes with the values of the provided arguments (indices value at time'default'will be updated) and returns it. The family type is set / updated on ``geom`` only if a non-empty value is passed in for ``familyType`` and ``familyName`` . Parameters ---------- geom : Imageable subsetName : str elementType : str indices : IntArray familyName : str familyType : str """ @staticmethod def CreateIndicesAttr(defaultValue, writeSparsely) -> Attribute: """ CreateIndicesAttr(defaultValue, writeSparsely) -> Attribute See GetIndicesAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateUniqueGeomSubset(*args, **kwargs) -> None: """ **classmethod** CreateUniqueGeomSubset(geom, subsetName, elementType, indices, familyName, familyType) -> Subset Creates a new GeomSubset below the given imageable, ``geom`` with the given name, ``subsetName`` , element type, ``elementType`` and ``indices`` . If a subset named ``subsetName`` already exists below ``geom`` , then this creates a new subset by appending a suitable index as suffix to ``subsetName`` (eg, subsetName_1) to avoid name collisions. The family type is set / updated on ``geom`` only if a non-empty value is passed in for ``familyType`` and ``familyName`` . Parameters ---------- geom : Imageable subsetName : str elementType : str indices : IntArray familyName : str familyType : str """ @staticmethod def Define(*args, **kwargs) -> None: """ **classmethod** Define(stage, path) -> Subset Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ @staticmethod def Get(*args, **kwargs) -> None: """ **classmethod** Get(stage, path) -> Subset Return a UsdGeomSubset holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomSubset(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ @staticmethod def GetAllGeomSubsetFamilyNames(*args, **kwargs) -> None: """ **classmethod** GetAllGeomSubsetFamilyNames(geom) -> str.Set Returns the names of all the families of GeomSubsets defined on the given imageable, ``geom`` . Parameters ---------- geom : Imageable """ @staticmethod def GetAllGeomSubsets(*args, **kwargs) -> None: """ **classmethod** GetAllGeomSubsets(geom) -> list[Subset] Returns all the GeomSubsets defined on the given imageable, ``geom`` . Parameters ---------- geom : Imageable """ @staticmethod def GetElementTypeAttr() -> Attribute: """ GetElementTypeAttr() -> Attribute The type of element that the indices target. Currently only allows"face"and defaults to it. Declaration ``uniform token elementType ="face"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values face """ @staticmethod def GetFamilyNameAttr() -> Attribute: """ GetFamilyNameAttr() -> Attribute The name of the family of subsets that this subset belongs to. This is optional and is primarily useful when there are multiple families of subsets under a geometric prim. In some cases, this could also be used for achieving proper roundtripping of subset data between DCC apps. When multiple subsets belonging to a prim have the same familyName, they are said to belong to the family. A *familyType* value can be encoded on the owner of a family of subsets as a token using the static method UsdGeomSubset::SetFamilyType() ."familyType"can have one of the following values: - **UsdGeomTokens->partition** : implies that every element of the whole geometry appears exactly once in only one of the subsets belonging to the family. - **UsdGeomTokens->nonOverlapping** : an element that appears in one subset may not appear in any other subset belonging to the family. - **UsdGeomTokens->unrestricted** : implies that there are no restrictions w.r.t. the membership of elements in the subsets. They could be overlapping and the union of all subsets in the family may not represent the whole. The validity of subset data is not enforced by the authoring APIs, however they can be checked using UsdGeomSubset::ValidateFamily() . Declaration ``uniform token familyName =""`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform """ @staticmethod def GetFamilyType(*args, **kwargs) -> None: """ **classmethod** GetFamilyType(geom, familyName) -> str Returns the type of family that the GeomSubsets on the given geometric prim ``geom`` , with the given family name, ``familyName`` belong to. This only returns the token that's encoded on ``geom`` and does not perform any actual validation on the family of GeomSubsets. Please use ValidateFamily() for such validation. When familyType is not set on ``geom`` , the fallback value UsdTokens->unrestricted is returned. Parameters ---------- geom : Imageable familyName : str """ @staticmethod def GetGeomSubsets(*args, **kwargs) -> None: """ **classmethod** GetGeomSubsets(geom, elementType, familyName) -> list[Subset] Returns all the GeomSubsets of the given ``elementType`` belonging to the specified family, ``familyName`` on the given imageable, ``geom`` . If ``elementType`` is empty, then subsets containing all element types are returned. If ``familyName`` is left empty, then all subsets of the specified ``elementType`` will be returned. Parameters ---------- geom : Imageable elementType : str familyName : str """ @staticmethod def GetIndicesAttr() -> Attribute: """ GetIndicesAttr() -> Attribute The set of indices included in this subset. The indices need not be sorted, but the same index should not appear more than once. Declaration ``int[] indices = []`` C++ Type VtArray<int> Usd Type SdfValueTypeNames->IntArray """ @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: """ **classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ @staticmethod def GetUnassignedIndices(*args, **kwargs) -> None: """ **classmethod** GetUnassignedIndices(subsets, elementCount, time) -> IntArray Utility for getting the list of indices that are not assigned to any of the GeomSubsets in ``subsets`` at the timeCode, ``time`` , given the element count (total number of indices in the array being subdivided), ``elementCount`` . Parameters ---------- subsets : list[Subset] elementCount : int time : TimeCode """ @staticmethod def SetFamilyType(*args, **kwargs) -> None: """ **classmethod** SetFamilyType(geom, familyName, familyType) -> bool This method is used to encode the type of family that the GeomSubsets on the given geometric prim ``geom`` , with the given family name, ``familyName`` belong to. See UsdGeomSubset::GetFamilyNameAttr for the possible values for ``familyType`` . When a family of GeomSubsets is tagged as a UsdGeomTokens->partition or UsdGeomTokens->nonOverlapping, the validity of the data (i.e. mutual exclusivity and/or wholeness) is not enforced by the authoring APIs. Use ValidateFamily() to validate the data in a family of GeomSubsets. Returns false upon failure to create or set the appropriate attribute on ``geom`` . Parameters ---------- geom : Imageable familyName : str familyType : str """ @staticmethod def ValidateFamily(*args, **kwargs) -> None: """ **classmethod** ValidateFamily(geom, elementType, familyName, reason) -> bool Validates whether the family of subsets identified by the given ``familyName`` and ``elementType`` on the given imageable, ``geom`` contain valid data. If the family is designated as a partition or as non-overlapping using SetFamilyType() , then the validity of the data is checked. If the familyType is"unrestricted", then this performs only bounds checking of the values in the"indices"arrays. If ``reason`` is not None, then it is populated with a string explaining why the family is invalid, if it is invalid. The python version of this method returns a tuple containing a (bool, string), where the bool has the validity of the family and the string contains the reason (if it's invalid). Parameters ---------- geom : Imageable elementType : str familyName : str reason : str """ @staticmethod def ValidateSubsets(*args, **kwargs) -> None: """ **classmethod** ValidateSubsets(subsets, elementCount, familyType, reason) -> bool Validates the data in the given set of GeomSubsets, ``subsets`` , given the total number of elements in the array being subdivided, ``elementCount`` and the ``familyType`` that the subsets belong to. For proper validation of indices in ``subsets`` , all of the GeomSubsets must have the same'elementType'. If one or more subsets contain invalid data, then false is returned and ``reason`` is populated with a string explaining the reason why it is invalid. The python version of this method returns a tuple containing a (bool, string), where the bool has the validity of the subsets and the string contains the reason (if they're invalid). Parameters ---------- subsets : list[Subset] elementCount : int familyType : str reason : str """ @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: """ **classmethod** _GetStaticTfType() -> Type """ __instance_size__ = 40 pass class Tokens(Boost.Python.instance): accelerations = 'accelerations' all = 'all' angularVelocities = 'angularVelocities' axis = 'axis' basis = 'basis' bezier = 'bezier' bilinear = 'bilinear' boundaries = 'boundaries' bounds = 'bounds' box = 'box' bspline = 'bspline' cards = 'cards' catmullClark = 'catmullClark' catmullRom = 'catmullRom' clippingPlanes = 'clippingPlanes' clippingRange = 'clippingRange' closed = 'closed' constant = 'constant' cornerIndices = 'cornerIndices' cornerSharpnesses = 'cornerSharpnesses' cornersOnly = 'cornersOnly' cornersPlus1 = 'cornersPlus1' cornersPlus2 = 'cornersPlus2' creaseIndices = 'creaseIndices' creaseLengths = 'creaseLengths' creaseSharpnesses = 'creaseSharpnesses' cross = 'cross' cubic = 'cubic' curveVertexCounts = 'curveVertexCounts' default_ = 'default' doubleSided = 'doubleSided' edgeAndCorner = 'edgeAndCorner' edgeOnly = 'edgeOnly' elementSize = 'elementSize' elementType = 'elementType' exposure = 'exposure' extent = 'extent' extentsHint = 'extentsHint' fStop = 'fStop' face = 'face' faceVarying = 'faceVarying' faceVaryingLinearInterpolation = 'faceVaryingLinearInterpolation' faceVertexCounts = 'faceVertexCounts' faceVertexIndices = 'faceVertexIndices' familyName = 'familyName' focalLength = 'focalLength' focusDistance = 'focusDistance' form = 'form' fromTexture = 'fromTexture' guide = 'guide' guideVisibility = 'guideVisibility' height = 'height' hermite = 'hermite' holeIndices = 'holeIndices' horizontalAperture = 'horizontalAperture' horizontalApertureOffset = 'horizontalApertureOffset' ids = 'ids' inactiveIds = 'inactiveIds' indices = 'indices' inherited = 'inherited' interpolateBoundary = 'interpolateBoundary' interpolation = 'interpolation' invisible = 'invisible' invisibleIds = 'invisibleIds' knots = 'knots' left = 'left' leftHanded = 'leftHanded' length = 'length' linear = 'linear' loop = 'loop' metersPerUnit = 'metersPerUnit' modelApplyDrawMode = 'model:applyDrawMode' modelCardGeometry = 'model:cardGeometry' modelCardTextureXNeg = 'model:cardTextureXNeg' modelCardTextureXPos = 'model:cardTextureXPos' modelCardTextureYNeg = 'model:cardTextureYNeg' modelCardTextureYPos = 'model:cardTextureYPos' modelCardTextureZNeg = 'model:cardTextureZNeg' modelCardTextureZPos = 'model:cardTextureZPos' modelDrawMode = 'model:drawMode' modelDrawModeColor = 'model:drawModeColor' mono = 'mono' motionBlurScale = 'motion:blurScale' motionNonlinearSampleCount = 'motion:nonlinearSampleCount' motionVelocityScale = 'motion:velocityScale' nonOverlapping = 'nonOverlapping' none = 'none' nonperiodic = 'nonperiodic' normals = 'normals' open = 'open' order = 'order' orientation = 'orientation' orientations = 'orientations' origin = 'origin' orthographic = 'orthographic' partition = 'partition' periodic = 'periodic' perspective = 'perspective' pinned = 'pinned' pivot = 'pivot' pointWeights = 'pointWeights' points = 'points' positions = 'positions' power = 'power' primvarsDisplayColor = 'primvars:displayColor' primvarsDisplayOpacity = 'primvars:displayOpacity' projection = 'projection' protoIndices = 'protoIndices' prototypes = 'prototypes' proxy = 'proxy' proxyPrim = 'proxyPrim' proxyVisibility = 'proxyVisibility' purpose = 'purpose' radius = 'radius' ranges = 'ranges' render = 'render' renderVisibility = 'renderVisibility' right = 'right' rightHanded = 'rightHanded' scales = 'scales' shutterClose = 'shutter:close' shutterOpen = 'shutter:open' size = 'size' smooth = 'smooth' stereoRole = 'stereoRole' subdivisionScheme = 'subdivisionScheme' tangents = 'tangents' triangleSubdivisionRule = 'triangleSubdivisionRule' trimCurveCounts = 'trimCurve:counts' trimCurveKnots = 'trimCurve:knots' trimCurveOrders = 'trimCurve:orders' trimCurvePoints = 'trimCurve:points' trimCurveRanges = 'trimCurve:ranges' trimCurveVertexCounts = 'trimCurve:vertexCounts' type = 'type' uForm = 'uForm' uKnots = 'uKnots' uOrder = 'uOrder' uRange = 'uRange' uVertexCount = 'uVertexCount' unauthoredValuesIndex = 'unauthoredValuesIndex' uniform = 'uniform' unrestricted = 'unrestricted' upAxis = 'upAxis' vForm = 'vForm' vKnots = 'vKnots' vOrder = 'vOrder' vRange = 'vRange' vVertexCount = 'vVertexCount' varying = 'varying' velocities = 'velocities' vertex = 'vertex' verticalAperture = 'verticalAperture' verticalApertureOffset = 'verticalApertureOffset' visibility = 'visibility' visible = 'visible' width = 'width' widths = 'widths' wrap = 'wrap' x = 'X' xformOpOrder = 'xformOpOrder' y = 'Y' z = 'Z' pass class VisibilityAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): """ UsdGeomVisibilityAPI introduces properties that can be used to author visibility opinions. Currently, this schema only introduces the attributes that are used to control purpose visibility. Later, this schema will define *all* visibility-related properties and UsdGeomImageable will no longer define those properties. The purpose visibility attributes added by this schema, *guideVisibility*, *proxyVisibility*, and *renderVisibility* can each be used to control visibility for geometry of the corresponding purpose values, with the overall *visibility* attribute acting as an override. I.e., if *visibility* evaluates to"invisible", purpose visibility is invisible; otherwise, purpose visibility is determined by the corresponding purpose visibility attribute. Note that the behavior of *guideVisibility* is subtly different from the *proxyVisibility* and *renderVisibility* attributes, in that"guide"purpose visibility always evaluates to either"invisible"or"visible", whereas the other attributes may yield computed values of"inherited"if there is no authored opinion on the attribute or inherited from an ancestor. This is motivated by the fact that, in Pixar"s user workflows, we have never found a need to have all guides visible in a scene by default, whereas we do find that flexibility useful for"proxy"and"render"geometry. This schema can only be applied to UsdGeomImageable prims. The UseGeomImageable schema provides API for computing the purpose visibility values that result from the attributes introduced by this schema. For any described attribute *Fallback* *Value* or *Allowed* *Values* below that are text/tokens, the actual token is published and defined in UsdGeomTokens. So to set an attribute to the value"rightHanded", use UsdGeomTokens->rightHanded as the value. """ @staticmethod def Apply(*args, **kwargs) -> None: """ **classmethod** Apply(prim) -> VisibilityAPI Applies this **single-apply** API schema to the given ``prim`` . This information is stored by adding"VisibilityAPI"to the token- valued, listOp metadata *apiSchemas* on the prim. A valid UsdGeomVisibilityAPI object is returned upon success. An invalid (or empty) UsdGeomVisibilityAPI object is returned upon failure. See UsdPrim::ApplyAPI() for conditions resulting in failure. UsdPrim::GetAppliedSchemas() UsdPrim::HasAPI() UsdPrim::CanApplyAPI() UsdPrim::ApplyAPI() UsdPrim::RemoveAPI() Parameters ---------- prim : Prim """ @staticmethod def CanApply(*args, **kwargs) -> None: """ **classmethod** CanApply(prim, whyNot) -> bool Returns true if this **single-apply** API schema can be applied to the given ``prim`` . If this schema can not be a applied to the prim, this returns false and, if provided, populates ``whyNot`` with the reason it can not be applied. Note that if CanApply returns false, that does not necessarily imply that calling Apply will fail. Callers are expected to call CanApply before calling Apply if they want to ensure that it is valid to apply a schema. UsdPrim::GetAppliedSchemas() UsdPrim::HasAPI() UsdPrim::CanApplyAPI() UsdPrim::ApplyAPI() UsdPrim::RemoveAPI() Parameters ---------- prim : Prim whyNot : str """ @staticmethod def CreateGuideVisibilityAttr(defaultValue, writeSparsely) -> Attribute: """ CreateGuideVisibilityAttr(defaultValue, writeSparsely) -> Attribute See GetGuideVisibilityAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateProxyVisibilityAttr(defaultValue, writeSparsely) -> Attribute: """ CreateProxyVisibilityAttr(defaultValue, writeSparsely) -> Attribute See GetProxyVisibilityAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def CreateRenderVisibilityAttr(defaultValue, writeSparsely) -> Attribute: """ CreateRenderVisibilityAttr(defaultValue, writeSparsely) -> Attribute See GetRenderVisibilityAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def Get(*args, **kwargs) -> None: """ **classmethod** Get(stage, path) -> VisibilityAPI Return a UsdGeomVisibilityAPI holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomVisibilityAPI(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ @staticmethod def GetGuideVisibilityAttr() -> Attribute: """ GetGuideVisibilityAttr() -> Attribute This attribute controls visibility for geometry with purpose"guide". Unlike overall *visibility*, *guideVisibility* is uniform, and therefore cannot be animated. Also unlike overall *visibility*, *guideVisibility* is tri-state, in that a descendant with an opinion of"visible"overrides an ancestor opinion of"invisible". The *guideVisibility* attribute works in concert with the overall *visibility* attribute: The visibility of a prim with purpose"guide"is determined by the inherited values it receives for the *visibility* and *guideVisibility* attributes. If *visibility* evaluates to"invisible", the prim is invisible. If *visibility* evaluates to"inherited"and *guideVisibility* evaluates to"visible", then the prim is visible. **Otherwise, it is invisible.** Declaration ``uniform token guideVisibility ="invisible"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values inherited, invisible, visible """ @staticmethod def GetProxyVisibilityAttr() -> Attribute: """ GetProxyVisibilityAttr() -> Attribute This attribute controls visibility for geometry with purpose"proxy". Unlike overall *visibility*, *proxyVisibility* is uniform, and therefore cannot be animated. Also unlike overall *visibility*, *proxyVisibility* is tri-state, in that a descendant with an opinion of"visible"overrides an ancestor opinion of"invisible". The *proxyVisibility* attribute works in concert with the overall *visibility* attribute: The visibility of a prim with purpose"proxy"is determined by the inherited values it receives for the *visibility* and *proxyVisibility* attributes. If *visibility* evaluates to"invisible", the prim is invisible. If *visibility* evaluates to"inherited"then: If *proxyVisibility* evaluates to"visible", then the prim is visible; if *proxyVisibility* evaluates to"invisible", then the prim is invisible; if *proxyVisibility* evaluates to"inherited", then the prim may either be visible or invisible, depending on a fallback value determined by the calling context. Declaration ``uniform token proxyVisibility ="inherited"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values inherited, invisible, visible """ @staticmethod def GetPurposeVisibilityAttr(purpose) -> Attribute: """ GetPurposeVisibilityAttr(purpose) -> Attribute Return the attribute that is used for expressing visibility opinions for the given ``purpose`` . The valid purpose tokens are"guide","proxy", and"render"which return the attributes *guideVisibility*, *proxyVisibility*, and *renderVisibility* respectively. Note that while"default"is a valid purpose token for UsdGeomImageable::GetPurposeVisibilityAttr, it is not a valid purpose for this function, as UsdGeomVisibilityAPI itself does not have a default visibility attribute. Calling this function with "default will result in a coding error. Parameters ---------- purpose : str """ @staticmethod def GetRenderVisibilityAttr() -> Attribute: """ GetRenderVisibilityAttr() -> Attribute This attribute controls visibility for geometry with purpose"render". Unlike overall *visibility*, *renderVisibility* is uniform, and therefore cannot be animated. Also unlike overall *visibility*, *renderVisibility* is tri-state, in that a descendant with an opinion of"visible"overrides an ancestor opinion of"invisible". The *renderVisibility* attribute works in concert with the overall *visibility* attribute: The visibility of a prim with purpose"render"is determined by the inherited values it receives for the *visibility* and *renderVisibility* attributes. If *visibility* evaluates to"invisible", the prim is invisible. If *visibility* evaluates to"inherited"then: If *renderVisibility* evaluates to"visible", then the prim is visible; if *renderVisibility* evaluates to"invisible", then the prim is invisible; if *renderVisibility* evaluates to"inherited", then the prim may either be visible or invisible, depending on a fallback value determined by the calling context. Declaration ``uniform token renderVisibility ="inherited"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values inherited, invisible, visible """ @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: """ **classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: """ **classmethod** _GetStaticTfType() -> Type """ __instance_size__ = 48 pass class Xform(Xformable, Imageable, pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): """ Concrete prim schema for a transform, which implements Xformable """ @staticmethod def Define(*args, **kwargs) -> None: """ **classmethod** Define(stage, path) -> Xform Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ @staticmethod def Get(*args, **kwargs) -> None: """ **classmethod** Get(stage, path) -> Xform Return a UsdGeomXform holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomXform(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: """ **classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: """ **classmethod** _GetStaticTfType() -> Type """ __instance_size__ = 40 pass class XformCache(Boost.Python.instance): """ A caching mechanism for transform matrices. For best performance, this object should be reused for multiple CTM queries. Instances of this type can be copied, though using Swap() may result in better performance. It is valid to cache prims from multiple stages in a single XformCache. WARNING: this class does not automatically invalidate cached values based on changes to the stage from which values were cached. Additionally, a separate instance of this class should be used per- thread, calling the Get\* methods from multiple threads is not safe, as they mutate internal state. """ @staticmethod def Clear() -> None: """ Clear() -> None Clears all pre-cached values. """ @staticmethod def ComputeRelativeTransform(prim, ancestor, resetXformStack) -> Matrix4d: """ ComputeRelativeTransform(prim, ancestor, resetXformStack) -> Matrix4d Returns the result of concatenating all transforms beneath ``ancestor`` that affect ``prim`` . This includes the local transform of ``prim`` itself, but not the local transform of ``ancestor`` . If ``ancestor`` is not an ancestor of ``prim`` , the resulting transform is the local-to-world transformation of ``prim`` . The ``resetXformTsack`` pointer must be valid. If any intermediate prims reset the transform stack, ``resetXformStack`` will be set to true. Intermediate transforms are cached, but the result of this call itself is not cached. Parameters ---------- prim : Prim ancestor : Prim resetXformStack : bool """ @staticmethod def GetLocalToWorldTransform(prim) -> Matrix4d: """ GetLocalToWorldTransform(prim) -> Matrix4d Compute the transformation matrix for the given ``prim`` , including the transform authored on the Prim itself, if present. This method may mutate internal cache state and is not thread safe. Parameters ---------- prim : Prim """ @staticmethod def GetLocalTransformation(prim, resetsXformStack) -> Matrix4d: """ GetLocalTransformation(prim, resetsXformStack) -> Matrix4d Returns the local transformation of the prim. Uses the cached XformQuery to compute the result quickly. The ``resetsXformStack`` pointer must be valid. It will be set to true if ``prim`` resets the transform stack. The result of this call is cached. Parameters ---------- prim : Prim resetsXformStack : bool """ @staticmethod def GetParentToWorldTransform(prim) -> Matrix4d: """ GetParentToWorldTransform(prim) -> Matrix4d Compute the transformation matrix for the given ``prim`` , but do NOT include the transform authored on the prim itself. This method may mutate internal cache state and is not thread safe. Parameters ---------- prim : Prim """ @staticmethod def GetTime() -> TimeCode: """ GetTime() -> TimeCode Get the current time from which this cache is reading values. """ @staticmethod def SetTime(time) -> None: """ SetTime(time) -> None Use the new ``time`` when computing values and may clear any existing values cached for the previous time. Setting ``time`` to the current time is a no-op. Parameters ---------- time : TimeCode """ @staticmethod def Swap(other) -> None: """ Swap(other) -> None Swap the contents of this XformCache with ``other`` . Parameters ---------- other : XformCache """ __instance_size__ = 88 pass class XformCommonAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): """ This class provides API for authoring and retrieving a standard set of component transformations which include a scale, a rotation, a scale- rotate pivot and a translation. The goal of the API is to enhance component-wise interchange. It achieves this by limiting the set of allowed basic ops and by specifying the order in which they are applied. In addition to the basic set of ops, the'resetXformStack'bit can also be set to indicate whether the underlying xformable resets the parent transformation (i.e. does not inherit it's parent's transformation). UsdGeomXformCommonAPI::GetResetXformStack() UsdGeomXformCommonAPI::SetResetXformStack() The operator-bool for the class will inform you whether an existing xformable is compatible with this API. The scale-rotate pivot is represented by a pair of (translate, inverse-translate) xformOps around the scale and rotate operations. The rotation operation can be any of the six allowed Euler angle sets. UsdGeomXformOp::Type. The xformOpOrder of an xformable that has all of the supported basic ops is as follows: ["xformOp:translate","xformOp:translate:pivot","xformOp:rotateXYZ","xformOp:scale","!invert!xformOp:translate:pivot"]. It is worth noting that all of the ops are optional. For example, an xformable may have only a translate or a rotate. It would still be considered as compatible with this API. Individual SetTranslate() , SetRotate() , SetScale() and SetPivot() methods are provided by this API to allow such sparse authoring. """ class OpFlags(pxr.Tf.Tf_PyEnumWrapper, pxr.Tf.Enum, Boost.Python.instance): """ Enumerates the categories of ops that can be handled by XformCommonAPI. For use with CreateXformOps() . """ @staticmethod def GetValueFromName(*args, **kwargs) -> None: ... _baseName = 'XformCommonAPI' allValues: tuple # value = (UsdGeom.XformCommonAPI.OpTranslate, UsdGeom.XformCommonAPI.OpRotate, UsdGeom.XformCommonAPI.OpScale, UsdGeom.XformCommonAPI.OpPivot) pass class RotationOrder(pxr.Tf.Tf_PyEnumWrapper, pxr.Tf.Enum, Boost.Python.instance): """ Enumerates the rotation order of the 3-angle Euler rotation. """ @staticmethod def GetValueFromName(*args, **kwargs) -> None: ... _baseName = 'XformCommonAPI' allValues: tuple # value = (UsdGeom.XformCommonAPI.RotationOrderXYZ, UsdGeom.XformCommonAPI.RotationOrderXZY, UsdGeom.XformCommonAPI.RotationOrderYXZ, UsdGeom.XformCommonAPI.RotationOrderYZX, UsdGeom.XformCommonAPI.RotationOrderZXY, UsdGeom.XformCommonAPI.RotationOrderZYX) pass @staticmethod def CanConvertOpTypeToRotationOrder(*args, **kwargs) -> None: """ **classmethod** CanConvertOpTypeToRotationOrder(opType) -> bool Whether the given ``opType`` has a corresponding value in the UsdGeomXformCommonAPI::RotationOrder enum (i.e., whether it is a three-axis rotation). Parameters ---------- opType : XformOp.Type """ @staticmethod def ConvertOpTypeToRotationOrder(*args, **kwargs) -> None: """ **classmethod** ConvertOpTypeToRotationOrder(opType) -> RotationOrder Converts the given ``opType`` to the corresponding value in the UsdGeomXformCommonAPI::RotationOrder enum. For example, TypeRotateYZX corresponds to RotationOrderYZX. Raises a coding error if ``opType`` is not convertible to RotationOrder (i.e., if it isn't a three-axis rotation) and returns the default RotationOrderXYZ instead. Parameters ---------- opType : XformOp.Type """ @staticmethod def ConvertRotationOrderToOpType(*args, **kwargs) -> None: """ **classmethod** ConvertRotationOrderToOpType(rotOrder) -> XformOp.Type Converts the given ``rotOrder`` to the corresponding value in the UsdGeomXformOp::Type enum. For example, RotationOrderYZX corresponds to TypeRotateYZX. Raises a coding error if ``rotOrder`` is not one of the named enumerators of RotationOrder. Parameters ---------- rotOrder : RotationOrder """ @staticmethod @typing.overload def CreateXformOps(rotOrder, op1, op2, op3, op4) -> Ops: """ CreateXformOps(rotOrder, op1, op2, op3, op4) -> Ops Creates the specified XformCommonAPI-compatible xform ops, or returns the existing ops if they already exist. If successful, returns an Ops object with all the ops on this prim, identified by type. If the requested xform ops couldn't be created or the prim is not XformCommonAPI-compatible, returns an Ops object with all invalid ops. The ``rotOrder`` is only used if OpRotate is specified. Otherwise, it is ignored. (If you don't need to create a rotate op, you might find it helpful to use the other overload that takes no rotation order.) Parameters ---------- rotOrder : RotationOrder op1 : OpFlags op2 : OpFlags op3 : OpFlags op4 : OpFlags ---------------------------------------------------------------------- This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. This overload does not take a rotation order. If you specify OpRotate, then this overload assumes RotationOrderXYZ or the previously-authored rotation order. (If you do need to create a rotate op, you might find it helpful to use the other overload that explicitly takes a rotation order.) Parameters ---------- op1 : OpFlags op2 : OpFlags op3 : OpFlags op4 : OpFlags """ @staticmethod @typing.overload def CreateXformOps(op1, op2, op3, op4) -> Ops: ... @staticmethod def Get(*args, **kwargs) -> None: """ **classmethod** Get(stage, path) -> XformCommonAPI Return a UsdGeomXformCommonAPI holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomXformCommonAPI(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ @staticmethod def GetResetXformStack() -> bool: """ GetResetXformStack() -> bool Returns whether the xformable resets the transform stack. i.e., does not inherit the parent transformation. """ @staticmethod def GetRotationTransform(*args, **kwargs) -> None: """ **classmethod** GetRotationTransform(rotation, rotationOrder) -> Matrix4d Return the 4x4 matrix that applies the rotation encoded by rotation vector ``rotation`` using the rotation order ``rotationOrder`` . Deprecated Please use the result of ConvertRotationOrderToOpType() along with UsdGeomXformOp::GetOpTransform() instead. Parameters ---------- rotation : Vec3f rotationOrder : XformCommonAPI.RotationOrder """ @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: """ **classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ @staticmethod def GetXformVectors(translation, rotation, scale, pivot, rotOrder, time) -> bool: """ GetXformVectors(translation, rotation, scale, pivot, rotOrder, time) -> bool Retrieve values of the various component xformOps at a given ``time`` . Identity values are filled in for the component xformOps that don't exist or don't have an authored value. This method works even on prims with an incompatible xform schema, i.e. when the bool operator returns false. When the underlying xformable has an incompatible xform schema, it performs a full-on matrix decomposition to XYZ rotation order. Parameters ---------- translation : Vec3d rotation : Vec3f scale : Vec3f pivot : Vec3f rotOrder : RotationOrder time : TimeCode """ @staticmethod def GetXformVectorsByAccumulation(translation, rotation, scale, pivot, rotOrder, time) -> bool: """ GetXformVectorsByAccumulation(translation, rotation, scale, pivot, rotOrder, time) -> bool Retrieve values of the various component xformOps at a given ``time`` . Identity values are filled in for the component xformOps that don't exist or don't have an authored value. This method allows some additional flexibility for xform schemas that do not strictly adhere to the xformCommonAPI. For incompatible schemas, this method will attempt to reduce the schema into one from which component vectors can be extracted by accumulating xformOp transforms of the common types. When the underlying xformable has a compatible xform schema, the usual component value extraction method is used instead. When the xform schema is incompatible and it cannot be reduced by accumulating transforms, it performs a full-on matrix decomposition to XYZ rotation order. Parameters ---------- translation : Vec3d rotation : Vec3f scale : Vec3f pivot : Vec3f rotOrder : XformCommonAPI.RotationOrder time : TimeCode """ @staticmethod def SetPivot(pivot, time) -> bool: """ SetPivot(pivot, time) -> bool Set pivot position at ``time`` to ``pivot`` . Parameters ---------- pivot : Vec3f time : TimeCode """ @staticmethod def SetResetXformStack(resetXformStack) -> bool: """ SetResetXformStack(resetXformStack) -> bool Set whether the xformable resets the transform stack. i.e., does not inherit the parent transformation. Parameters ---------- resetXformStack : bool """ @staticmethod def SetRotate(rotation, rotOrder, time) -> bool: """ SetRotate(rotation, rotOrder, time) -> bool Set rotation at ``time`` to ``rotation`` . Parameters ---------- rotation : Vec3f rotOrder : XformCommonAPI.RotationOrder time : TimeCode """ @staticmethod def SetScale(scale, time) -> bool: """ SetScale(scale, time) -> bool Set scale at ``time`` to ``scale`` . Parameters ---------- scale : Vec3f time : TimeCode """ @staticmethod def SetTranslate(translation, time) -> bool: """ SetTranslate(translation, time) -> bool Set translation at ``time`` to ``translation`` . Parameters ---------- translation : Vec3d time : TimeCode """ @staticmethod def SetXformVectors(translation, rotation, scale, pivot, rotOrder, time) -> bool: """ SetXformVectors(translation, rotation, scale, pivot, rotOrder, time) -> bool Set values for the various component xformOps at a given ``time`` . Calling this method will call all of the supported ops to be created, even if they only contain default (identity) values. To author individual operations selectively, use the Set[OpType]() API. Once the rotation order has been established for a given xformable (either because of an already defined (and compatible) rotate op or from calling SetXformVectors() or SetRotate() ), it cannot be changed. Parameters ---------- translation : Vec3d rotation : Vec3f scale : Vec3f pivot : Vec3f rotOrder : RotationOrder time : TimeCode """ @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: """ **classmethod** _GetStaticTfType() -> Type """ OpPivot: pxr.UsdGeom.OpFlags # value = UsdGeom.XformCommonAPI.OpPivot OpRotate: pxr.UsdGeom.OpFlags # value = UsdGeom.XformCommonAPI.OpRotate OpScale: pxr.UsdGeom.OpFlags # value = UsdGeom.XformCommonAPI.OpScale OpTranslate: pxr.UsdGeom.OpFlags # value = UsdGeom.XformCommonAPI.OpTranslate RotationOrderXYZ: pxr.UsdGeom.RotationOrder # value = UsdGeom.XformCommonAPI.RotationOrderXYZ RotationOrderXZY: pxr.UsdGeom.RotationOrder # value = UsdGeom.XformCommonAPI.RotationOrderXZY RotationOrderYXZ: pxr.UsdGeom.RotationOrder # value = UsdGeom.XformCommonAPI.RotationOrderYXZ RotationOrderYZX: pxr.UsdGeom.RotationOrder # value = UsdGeom.XformCommonAPI.RotationOrderYZX RotationOrderZXY: pxr.UsdGeom.RotationOrder # value = UsdGeom.XformCommonAPI.RotationOrderZXY RotationOrderZYX: pxr.UsdGeom.RotationOrder # value = UsdGeom.XformCommonAPI.RotationOrderZYX __instance_size__ = 48 pass class XformOp(Boost.Python.instance): """ Schema wrapper for UsdAttribute for authoring and computing transformation operations, as consumed by UsdGeomXformable schema. The semantics of an op are determined primarily by its name, which allows us to decode an op very efficiently. All ops are independent attributes, which must live in the"xformOp"property namespace. The op's primary name within the namespace must be one of UsdGeomXformOpTypes, which determines the type of transformation operation, and its secondary name (or suffix) within the namespace (which is not required to exist), can be any name that distinguishes it from other ops of the same type. Suffixes are generally imposed by higer level xform API schemas. **On packing order of rotateABC triples** The order in which the axis rotations are recorded in a Vec3\* for the six *rotateABC* Euler triples **is always the same:** vec[0] = X, vec[1] = Y, vec[2] = Z. The *A*, *B*, *C* in the op name dictate the order in which their corresponding elements are consumed by the rotation, not how they are laid out. """ class Precision(pxr.Tf.Tf_PyEnumWrapper, pxr.Tf.Enum, Boost.Python.instance): """ Precision with which the value of the tranformation operation is encoded. """ @staticmethod def GetValueFromName(*args, **kwargs) -> None: ... _baseName = 'XformOp' allValues: tuple # value = (UsdGeom.XformOp.PrecisionDouble, UsdGeom.XformOp.PrecisionFloat, UsdGeom.XformOp.PrecisionHalf) pass class Type(pxr.Tf.Tf_PyEnumWrapper, pxr.Tf.Enum, Boost.Python.instance): """ Enumerates the set of all transformation operation types. """ @staticmethod def GetValueFromName(*args, **kwargs) -> None: ... _baseName = 'XformOp' allValues: tuple # value = (UsdGeom.XformOp.TypeInvalid, UsdGeom.XformOp.TypeTranslate, UsdGeom.XformOp.TypeScale, UsdGeom.XformOp.TypeRotateX, UsdGeom.XformOp.TypeRotateY, UsdGeom.XformOp.TypeRotateZ, UsdGeom.XformOp.TypeRotateXYZ, UsdGeom.XformOp.TypeRotateXZY, UsdGeom.XformOp.TypeRotateYXZ, UsdGeom.XformOp.TypeRotateYZX, UsdGeom.XformOp.TypeRotateZXY, UsdGeom.XformOp.TypeRotateZYX, UsdGeom.XformOp.TypeOrient, UsdGeom.XformOp.TypeTransform) pass @staticmethod def Get(value, time) -> bool: """ Get(value, time) -> bool Get the attribute value of the XformOp at ``time`` . For inverted ops, this returns the raw, uninverted value. Parameters ---------- value : T time : TimeCode """ @staticmethod def GetAttr() -> Attribute: """ GetAttr() -> Attribute Explicit UsdAttribute extractor. """ @staticmethod def GetBaseName() -> str: """ GetBaseName() -> str UsdAttribute::GetBaseName() """ @staticmethod def GetName() -> str: """ GetName() -> str UsdAttribute::GetName() """ @staticmethod def GetNamespace() -> str: """ GetNamespace() -> str UsdAttribute::GetNamespace() """ @staticmethod def GetNumTimeSamples() -> int: """ GetNumTimeSamples() -> int Returns the number of time samples authored for this xformOp. """ @staticmethod def GetOpName() -> str: """ **classmethod** GetOpName(opType, opSuffix, inverse) -> str Returns the xformOp's name as it appears in xformOpOrder, given the opType, the (optional) suffix and whether it is an inverse operation. Parameters ---------- opType : Type opSuffix : str inverse : bool ---------------------------------------------------------------------- Returns the opName as it appears in the xformOpOrder attribute. This will begin with"!invert!:xformOp:"if it is an inverse xform operation. If it is not an inverse xformOp, it will begin with'xformOp:'. This will be empty for an invalid xformOp. """ @staticmethod def GetOpTransform(opType, opVal, isInverseOp) -> Matrix4d: """ **classmethod** GetOpTransform(time) -> Matrix4d Return the 4x4 matrix that applies the transformation encoded in this op at ``time`` . Returns the identity matrix and issues a coding error if the op is invalid. If the op is valid, but has no authored value, the identity matrix is returned and no error is issued. Parameters ---------- time : TimeCode ---------------------------------------------------------------------- Return the 4x4 matrix that applies the transformation encoded by op ``opType`` and data value ``opVal`` . If ``isInverseOp`` is true, then the inverse of the tranformation represented by the op/value pair is returned. An error will be issued if ``opType`` is not one of the values in the enum UsdGeomXformOp::Type or if ``opVal`` cannot be converted to a suitable input to ``opType`` Parameters ---------- opType : Type opVal : VtValue isInverseOp : bool """ @staticmethod def GetOpType() -> Type: """ GetOpType() -> Type Return the operation type of this op, one of UsdGeomXformOp::Type. """ @staticmethod def GetOpTypeEnum(*args, **kwargs) -> None: """ **classmethod** GetOpTypeEnum(opTypeToken) -> Type Returns the Type enum associated with the given ``opTypeToken`` . Parameters ---------- opTypeToken : str """ @staticmethod def GetOpTypeToken(*args, **kwargs) -> None: """ **classmethod** GetOpTypeToken(opType) -> str Returns the TfToken used to encode the given ``opType`` . Note that an empty TfToken is used to represent TypeInvalid Parameters ---------- opType : Type """ @staticmethod def GetPrecision() -> Precision: """ GetPrecision() -> Precision Returns the precision level of the xform op. """ @staticmethod def GetTimeSamples(times) -> bool: """ GetTimeSamples(times) -> bool Populates the list of time samples at which the associated attribute is authored. Parameters ---------- times : list[float] """ @staticmethod def GetTimeSamplesInInterval(interval, times) -> bool: """ GetTimeSamplesInInterval(interval, times) -> bool Populates the list of time samples within the given ``interval`` , at which the associated attribute is authored. Parameters ---------- interval : Interval times : list[float] """ @staticmethod def GetTypeName() -> ValueTypeName: """ GetTypeName() -> ValueTypeName UsdAttribute::GetTypeName() """ @staticmethod def IsDefined() -> bool: """ IsDefined() -> bool Return true if the wrapped UsdAttribute::IsDefined() , and in addition the attribute is identified as a XformOp. """ @staticmethod def IsInverseOp() -> bool: """ IsInverseOp() -> bool Returns whether the xformOp represents an inverse operation. """ @staticmethod def MightBeTimeVarying() -> bool: """ MightBeTimeVarying() -> bool Determine whether there is any possibility that this op's value may vary over time. The determination is based on a snapshot of the authored state of the op, and may become invalid in the face of further authoring. """ @staticmethod def Set(value, time) -> bool: """ Set(value, time) -> bool Set the attribute value of the XformOp at ``time`` . This only works on non-inverse operations. If invoked on an inverse xform operation, a coding error is issued and no value is authored. Parameters ---------- value : T time : TimeCode """ @staticmethod def SplitName() -> list[str]: """ SplitName() -> list[str] UsdAttribute::SplitName() """ PrecisionDouble: pxr.UsdGeom.Precision # value = UsdGeom.XformOp.PrecisionDouble PrecisionFloat: pxr.UsdGeom.Precision # value = UsdGeom.XformOp.PrecisionFloat PrecisionHalf: pxr.UsdGeom.Precision # value = UsdGeom.XformOp.PrecisionHalf TypeInvalid: pxr.UsdGeom.Type # value = UsdGeom.XformOp.TypeInvalid TypeOrient: pxr.UsdGeom.Type # value = UsdGeom.XformOp.TypeOrient TypeRotateX: pxr.UsdGeom.Type # value = UsdGeom.XformOp.TypeRotateX TypeRotateXYZ: pxr.UsdGeom.Type # value = UsdGeom.XformOp.TypeRotateXYZ TypeRotateXZY: pxr.UsdGeom.Type # value = UsdGeom.XformOp.TypeRotateXZY TypeRotateY: pxr.UsdGeom.Type # value = UsdGeom.XformOp.TypeRotateY TypeRotateYXZ: pxr.UsdGeom.Type # value = UsdGeom.XformOp.TypeRotateYXZ TypeRotateYZX: pxr.UsdGeom.Type # value = UsdGeom.XformOp.TypeRotateYZX TypeRotateZ: pxr.UsdGeom.Type # value = UsdGeom.XformOp.TypeRotateZ TypeRotateZXY: pxr.UsdGeom.Type # value = UsdGeom.XformOp.TypeRotateZXY TypeRotateZYX: pxr.UsdGeom.Type # value = UsdGeom.XformOp.TypeRotateZYX TypeScale: pxr.UsdGeom.Type # value = UsdGeom.XformOp.TypeScale TypeTransform: pxr.UsdGeom.Type # value = UsdGeom.XformOp.TypeTransform TypeTranslate: pxr.UsdGeom.Type # value = UsdGeom.XformOp.TypeTranslate __instance_size__ = 152 pass class XformOpTypes(Boost.Python.instance): orient = 'orient' resetXformStack = '!resetXformStack!' rotateX = 'rotateX' rotateXYZ = 'rotateXYZ' rotateXZY = 'rotateXZY' rotateY = 'rotateY' rotateYXZ = 'rotateYXZ' rotateYZX = 'rotateYZX' rotateZ = 'rotateZ' rotateZXY = 'rotateZXY' rotateZYX = 'rotateZYX' scale = 'scale' transform = 'transform' translate = 'translate' pass class Xformable(Imageable, pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): """ Base class for all transformable prims, which allows arbitrary sequences of component affine transformations to be encoded. You may find it useful to review Linear Algebra in UsdGeom while reading this class description. **Supported Component Transformation Operations** UsdGeomXformable currently supports arbitrary sequences of the following operations, each of which can be encoded in an attribute of the proper shape in any supported precision: - translate - 3D - scale - 3D - rotateX - 1D angle in degrees - rotateY - 1D angle in degrees - rotateZ - 1D angle in degrees - rotateABC - 3D where ABC can be any combination of the six principle Euler Angle sets: XYZ, XZY, YXZ, YZX, ZXY, ZYX. See note on rotation packing order - orient - 4D (quaternion) - transform - 4x4D **Creating a Component Transformation** To add components to a UsdGeomXformable prim, simply call AddXformOp() with the desired op type, as enumerated in UsdGeomXformOp::Type, and the desired precision, which is one of UsdGeomXformOp::Precision. Optionally, you can also provide an"op suffix"for the operator that disambiguates it from other components of the same type on the same prim. Application-specific transform schemas can use the suffixes to fill a role similar to that played by AbcGeom::XformOp's"Hint"enums for their own round-tripping logic. We also provide specific"Add"API for each type, for clarity and conciseness, e.g. AddTranslateOp() , AddRotateXYZOp() etc. AddXformOp() will return a UsdGeomXformOp object, which is a schema on a newly created UsdAttribute that provides convenience API for authoring and computing the component transformations. The UsdGeomXformOp can then be used to author any number of timesamples and default for the op. Each successive call to AddXformOp() adds an operator that will be applied"more locally"than the preceding operator, just as if we were pushing transforms onto a transformation stack - which is precisely what should happen when the operators are consumed by a reader. If you can, please try to use the UsdGeomXformCommonAPI, which wraps the UsdGeomXformable with an interface in which Op creation is taken care of for you, and there is a much higher chance that the data you author will be importable without flattening into other DCC's, as it conforms to a fixed set of Scale-Rotate-Translate Ops. Using the Authoring API **Data Encoding and Op Ordering** Because there is no"fixed schema"of operations, all of the attributes that encode transform operations are dynamic, and are scoped in the namespace"xformOp". The second component of an attribute's name provides the *type* of operation, as listed above. An"xformOp"attribute can have additional namespace components derived from the *opSuffix* argument to the AddXformOp() suite of methods, which provides a preferred way of naming the ops such that we can have multiple"translate"ops with unique attribute names. For example, in the attribute named"xformOp:translate:maya:pivot","translate"is the type of operation and"maya:pivot"is the suffix. The following ordered list of attribute declarations in usda define a basic Scale-Rotate-Translate with XYZ Euler angles, wherein the translation is double-precision, and the remainder of the ops are single, in which we will: - Scale by 2.0 in each dimension - Rotate about the X, Y, and Z axes by 30, 60, and 90 degrees, respectively - Translate by 100 units in the Y direction .. code-block:: text float3 xformOp:rotateXYZ = (30, 60, 90) float3 xformOp:scale = (2, 2, 2) double3 xformOp:translate = (0, 100, 0) uniform token[] xformOpOrder = [ "xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale" ] The attributes appear in the dictionary order in which USD, by default, sorts them. To ensure the ops are recovered and evaluated in the correct order, the schema introduces the **xformOpOrder** attribute, which contains the names of the op attributes, in the precise sequence in which they should be pushed onto a transform stack. **Note** that the order is opposite to what you might expect, given the matrix algebra described in Linear Algebra in UsdGeom. This also dictates order of op creation, since each call to AddXformOp() adds a new op to the end of the **xformOpOrder** array, as a new"most- local"operation. See Example 2 below for C++ code that could have produced this USD. If it were important for the prim's rotations to be independently overridable, we could equivalently (at some performance cost) encode the transformation also like so: .. code-block:: text float xformOp:rotateX = 30 float xformOp:rotateY = 60 float xformOp:rotateZ = 90 float3 xformOp:scale = (2, 2, 2) double3 xformOp:translate = (0, 100, 0) uniform token[] xformOpOrder = [ "xformOp:translate", "xformOp:rotateZ", "xformOp:rotateY", "xformOp:rotateX", "xformOp:scale" ] Again, note that although we are encoding an XYZ rotation, the three rotations appear in the **xformOpOrder** in the opposite order, with Z, followed, by Y, followed by X. Were we to add a Maya-style scalePivot to the above example, it might look like the following: .. code-block:: text float3 xformOp:rotateXYZ = (30, 60, 90) float3 xformOp:scale = (2, 2, 2) double3 xformOp:translate = (0, 100, 0) double3 xformOp:translate:scalePivot uniform token[] xformOpOrder = [ "xformOp:translate", "xformOp:rotateXYZ", "xformOp:translate:scalePivot", "xformOp:scale" ] **Paired"Inverted"Ops** We have been claiming that the ordered list of ops serves as a set of instructions to a transform stack, but you may have noticed in the last example that there is a missing operation - the pivot for the scale op needs to be applied in its inverse-form as a final (most local) op! In the AbcGeom::Xform schema, we would have encoded an actual"final"translation op whose value was authored by the exporter as the negation of the pivot's value. However, doing so would be brittle in USD, given that each op can be independently overridden, and the constraint that one attribute must be maintained as the negation of the other in order for successful re-importation of the schema cannot be expressed in USD. Our solution leverages the **xformOpOrder** member of the schema, which, in addition to ordering the ops, may also contain one of two special tokens that address the paired op and"stack resetting"behavior. The"paired op"behavior is encoded as an"!invert!"prefix in **xformOpOrder**, as the result of an AddXformOp(isInverseOp=True) call. The **xformOpOrder** for the last example would look like: .. code-block:: text uniform token[] xformOpOrder = [ "xformOp:translate", "xformOp:rotateXYZ", "xformOp:translate:scalePivot", "xformOp:scale", "!invert!xformOp:translate:scalePivot" ] When asked for its value via UsdGeomXformOp::GetOpTransform() , an"inverted"Op (i.e. the"inverted"half of a set of paired Ops) will fetch the value of its paired attribute and return its negation. This works for all op types - an error will be issued if a"transform"type op is singular and cannot be inverted. When getting the authored value of an inverted op via UsdGeomXformOp::Get() , the raw, uninverted value of the associated attribute is returned. For the sake of robustness, **setting a value on an inverted op is disallowed.** Attempting to set a value on an inverted op will result in a coding error and no value being set. **Resetting the Transform Stack** The other special op/token that can appear in *xformOpOrder* is *"!resetXformStack!"*, which, appearing as the first element of *xformOpOrder*, indicates this prim should not inherit the transformation of its namespace parent. See SetResetXformStack() **Expected Behavior for"Missing"Ops** If an importer expects Scale-Rotate-Translate operations, but a prim has only translate and rotate ops authored, the importer should assume an identity scale. This allows us to optimize the data a bit, if only a few components of a very rich schema (like Maya's) are authored in the app. **Using the C++ API** #1. Creating a simple transform matrix encoding .. code-block:: text #2. Creating the simple SRT from the example above .. code-block:: text #3. Creating a parameterized SRT with pivot using UsdGeomXformCommonAPI .. code-block:: text #4. Creating a rotate-only pivot transform with animated rotation and translation .. code-block:: text """ @staticmethod def AddOrientOp(precision, opSuffix, isInverseOp) -> XformOp: """ AddOrientOp(precision, opSuffix, isInverseOp) -> XformOp Add a orient op (arbitrary axis/angle rotation) to the local stack represented by this xformable. Parameters ---------- precision : XformOp.Precision opSuffix : str isInverseOp : bool """ @staticmethod def AddRotateXOp(precision, opSuffix, isInverseOp) -> XformOp: """ AddRotateXOp(precision, opSuffix, isInverseOp) -> XformOp Add a rotation about the X-axis to the local stack represented by this xformable. Set the angle value of the resulting UsdGeomXformOp **in degrees** Parameters ---------- precision : XformOp.Precision opSuffix : str isInverseOp : bool """ @staticmethod def AddRotateXYZOp(precision, opSuffix, isInverseOp) -> XformOp: """ AddRotateXYZOp(precision, opSuffix, isInverseOp) -> XformOp Add a rotation op with XYZ rotation order to the local stack represented by this xformable. Set the angle value of the resulting UsdGeomXformOp **in degrees** Parameters ---------- precision : XformOp.Precision opSuffix : str isInverseOp : bool """ @staticmethod def AddRotateXZYOp(precision, opSuffix, isInverseOp) -> XformOp: """ AddRotateXZYOp(precision, opSuffix, isInverseOp) -> XformOp Add a rotation op with XZY rotation order to the local stack represented by this xformable. Set the angle values of the resulting UsdGeomXformOp **in degrees** Parameters ---------- precision : XformOp.Precision opSuffix : str isInverseOp : bool """ @staticmethod def AddRotateYOp(precision, opSuffix, isInverseOp) -> XformOp: """ AddRotateYOp(precision, opSuffix, isInverseOp) -> XformOp Add a rotation about the YX-axis to the local stack represented by this xformable. Set the angle value of the resulting UsdGeomXformOp **in degrees** Parameters ---------- precision : XformOp.Precision opSuffix : str isInverseOp : bool """ @staticmethod def AddRotateYXZOp(precision, opSuffix, isInverseOp) -> XformOp: """ AddRotateYXZOp(precision, opSuffix, isInverseOp) -> XformOp Add a rotation op with YXZ rotation order to the local stack represented by this xformable. Set the angle values of the resulting UsdGeomXformOp **in degrees** Parameters ---------- precision : XformOp.Precision opSuffix : str isInverseOp : bool """ @staticmethod def AddRotateYZXOp(precision, opSuffix, isInverseOp) -> XformOp: """ AddRotateYZXOp(precision, opSuffix, isInverseOp) -> XformOp Add a rotation op with YZX rotation order to the local stack represented by this xformable. Set the angle values of the resulting UsdGeomXformOp **in degrees** Parameters ---------- precision : XformOp.Precision opSuffix : str isInverseOp : bool """ @staticmethod def AddRotateZOp(precision, opSuffix, isInverseOp) -> XformOp: """ AddRotateZOp(precision, opSuffix, isInverseOp) -> XformOp Add a rotation about the Z-axis to the local stack represented by this xformable. Parameters ---------- precision : XformOp.Precision opSuffix : str isInverseOp : bool """ @staticmethod def AddRotateZXYOp(precision, opSuffix, isInverseOp) -> XformOp: """ AddRotateZXYOp(precision, opSuffix, isInverseOp) -> XformOp Add a rotation op with ZXY rotation order to the local stack represented by this xformable. Set the angle values of the resulting UsdGeomXformOp **in degrees** Parameters ---------- precision : XformOp.Precision opSuffix : str isInverseOp : bool """ @staticmethod def AddRotateZYXOp(precision, opSuffix, isInverseOp) -> XformOp: """ AddRotateZYXOp(precision, opSuffix, isInverseOp) -> XformOp Add a rotation op with ZYX rotation order to the local stack represented by this xformable. Set the angle values of the resulting UsdGeomXformOp **in degrees** Parameters ---------- precision : XformOp.Precision opSuffix : str isInverseOp : bool """ @staticmethod def AddScaleOp(precision, opSuffix, isInverseOp) -> XformOp: """ AddScaleOp(precision, opSuffix, isInverseOp) -> XformOp Add a scale operation to the local stack represented by this xformable. Parameters ---------- precision : XformOp.Precision opSuffix : str isInverseOp : bool """ @staticmethod def AddTransformOp(precision, opSuffix, isInverseOp) -> XformOp: """ AddTransformOp(precision, opSuffix, isInverseOp) -> XformOp Add a tranform op (4x4 matrix transformation) to the local stack represented by this xformable. Parameters ---------- precision : XformOp.Precision opSuffix : str isInverseOp : bool """ @staticmethod def AddTranslateOp(precision, opSuffix, isInverseOp) -> XformOp: """ AddTranslateOp(precision, opSuffix, isInverseOp) -> XformOp Add a translate operation to the local stack represented by this xformable. Parameters ---------- precision : XformOp.Precision opSuffix : str isInverseOp : bool """ @staticmethod def AddXformOp(opType, precision, opSuffix, isInverseOp) -> XformOp: """ AddXformOp(opType, precision, opSuffix, isInverseOp) -> XformOp Add an affine transformation to the local stack represented by this Xformable. This will fail if there is already a transform operation of the same name in the ordered ops on this prim (i.e. as returned by GetOrderedXformOps() ), or if an op of the same name exists at all on the prim with a different precision than that specified. The newly created operation will become the most-locally applied transformation on the prim, and will appear last in the list returned by GetOrderedXformOps() . It is OK to begin authoring values to the returned UsdGeomXformOp immediately, interspersed with subsequent calls to AddXformOp() - just note the order of application, which *can* be changed at any time (and in stronger layers) via SetXformOpOrder() . opType is the type of transform operation, one of UsdGeomXformOp::Type. precision allows you to specify the precision with which you desire to encode the data. This should be one of the values in the enum UsdGeomXformOp::Precision. opSuffix allows you to specify the purpose/meaning of the op in the stack. When opSuffix is specified, the associated attribute's name is set to"xformOp:<opType>:<opSuffix>". isInverseOp is used to indicate an inverse transformation operation. a UsdGeomXformOp that can be used to author to the operation. An error is issued and the returned object will be invalid (evaluate to false) if the op being added already exists in xformOpOrder or if the arguments supplied are invalid. If the attribute associated with the op already exists, but isn't of the requested precision, a coding error is issued, but a valid xformOp is returned with the existing attribute. Parameters ---------- opType : XformOp.Type precision : XformOp.Precision opSuffix : str isInverseOp : bool """ @staticmethod def ClearXformOpOrder() -> bool: """ ClearXformOpOrder() -> bool Clears the local transform stack. """ @staticmethod def CreateXformOpOrderAttr(defaultValue, writeSparsely) -> Attribute: """ CreateXformOpOrderAttr(defaultValue, writeSparsely) -> Attribute See GetXformOpOrderAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ @staticmethod def Get(*args, **kwargs) -> None: """ **classmethod** Get(stage, path) -> Xformable Return a UsdGeomXformable holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdGeomXformable(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ @staticmethod def GetLocalTransformation(*args, **kwargs) -> None: """ Compute the fully-combined, local-to-parent transformation for this prim. If a client does not need to manipulate the individual ops themselves, and requires only the combined transform on this prim, this method will take care of all the data marshalling and linear algebra needed to combine the ops into a 4x4 affine transformation matrix, in double-precision, regardless of the precision of the op inputs. The python version of this function only returns the computed local-to-parent transformation. Clients must independently call GetResetXformStack() to be able to construct the local-to-world transformation. Compute the fully-combined, local-to-parent transformation for this prim as efficiently as possible, using pre-fetched list of ordered xform ops supplied by the client. The python version of this function only returns the computed local-to-parent transformation. Clients must independently call GetResetXformStack() to be able to construct the local-to-world transformation. """ @staticmethod def GetOrderedXformOps(*args, **kwargs) -> None: """ Return the ordered list of transform operations to be applied to this prim, in least-to-most-local order. This is determined by the intersection of authored op-attributes and the explicit ordering of those attributes encoded in the "xformOpOrder" attribute on this prim. Any entries in "xformOpOrder" that do not correspond to valid attributes on the xformable prim are skipped and a warning is issued. A UsdGeomTransformable that has not had any ops added via AddXformOp() will return an empty vector. The python version of this function only returns the ordered list of xformOps. Clients must independently call GetResetXformStack() if they need the info. """ @staticmethod def GetResetXformStack() -> bool: """ GetResetXformStack() -> bool Does this prim reset its parent's inherited transformation? Returns true if"!resetXformStack!"appears *anywhere* in xformOpOrder. When this returns true, all ops upto the last"!resetXformStack!"in xformOpOrder are ignored when computing the local transformation. """ @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: """ **classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ @staticmethod def GetTimeSamples(orderedXformOps, times) -> bool: """ **classmethod** GetTimeSamples(times) -> bool Sets ``times`` to the union of all the timesamples at which xformOps that are included in the xformOpOrder attribute are authored. This clears the ``times`` vector before accumulating sample times from all the xformOps. UsdAttribute::GetTimeSamples Parameters ---------- times : list[float] ---------------------------------------------------------------------- Returns the union of all the timesamples at which the attributes belonging to the given ``orderedXformOps`` are authored. This clears the ``times`` vector before accumulating sample times from ``orderedXformOps`` . UsdGeomXformable::GetTimeSamples Parameters ---------- orderedXformOps : list[XformOp] times : list[float] """ @staticmethod def GetTimeSamplesInInterval(orderedXformOps, interval, times) -> bool: """ **classmethod** GetTimeSamplesInInterval(interval, times) -> bool Sets ``times`` to the union of all the timesamples in the interval, ``interval`` , at which xformOps that are included in the xformOpOrder attribute are authored. This clears the ``times`` vector before accumulating sample times from all the xformOps. UsdAttribute::GetTimeSamples Parameters ---------- interval : Interval times : list[float] ---------------------------------------------------------------------- Returns the union of all the timesamples in the ``interval`` at which the attributes belonging to the given ``orderedXformOps`` are authored. This clears the ``times`` vector before accumulating sample times from ``orderedXformOps`` . UsdGeomXformable::GetTimeSamplesInInterval Parameters ---------- orderedXformOps : list[XformOp] interval : Interval times : list[float] """ @staticmethod def GetXformOpOrderAttr() -> Attribute: """ GetXformOpOrderAttr() -> Attribute Encodes the sequence of transformation operations in the order in which they should be pushed onto a transform stack while visiting a UsdStage 's prims in a graph traversal that will effect the desired positioning for this prim and its descendant prims. You should rarely, if ever, need to manipulate this attribute directly. It is managed by the AddXformOp() , SetResetXformStack() , and SetXformOpOrder() , and consulted by GetOrderedXformOps() and GetLocalTransformation() . Declaration ``uniform token[] xformOpOrder`` C++ Type VtArray<TfToken> Usd Type SdfValueTypeNames->TokenArray Variability SdfVariabilityUniform """ @staticmethod def IsTransformationAffectedByAttrNamed(*args, **kwargs) -> None: """ **classmethod** IsTransformationAffectedByAttrNamed(attrName) -> bool Returns true if the attribute named ``attrName`` could affect the local transformation of an xformable prim. Parameters ---------- attrName : str """ @staticmethod def MakeMatrixXform() -> XformOp: """ MakeMatrixXform() -> XformOp Clears the existing local transform stack and creates a new xform op of type'transform'. This API is provided for convenience since this is the most common xform authoring operation. """ @staticmethod def SetResetXformStack(resetXform) -> bool: """ SetResetXformStack(resetXform) -> bool Specify whether this prim's transform should reset the transformation stack inherited from its parent prim. By default, parent transforms are inherited. SetResetXformStack() can be called at any time during authoring, but will always add a'!resetXformStack!'op as the *first* op in the ordered list, if one does not exist already. If one already exists, and ``resetXform`` is false, it will remove all ops upto and including the last"!resetXformStack!"op. Parameters ---------- resetXform : bool """ @staticmethod def SetXformOpOrder(orderedXformOps, resetXformStack) -> bool: """ SetXformOpOrder(orderedXformOps, resetXformStack) -> bool Reorder the already-existing transform ops on this prim. All elements in ``orderedXformOps`` must be valid and represent attributes on this prim. Note that it is *not* required that all the existing operations be present in ``orderedXformOps`` , so this method can be used to completely change the transformation structure applied to the prim. If ``resetXformStack`` is set to true, then "!resetXformOp! will be set as the first op in xformOpOrder, to indicate that the prim does not inherit its parent's transformation. If you wish to re-specify a prim's transformation completely in a stronger layer, you should first call this method with an *empty* ``orderedXformOps`` vector. From there you can call AddXformOp() just as if you were authoring to the prim from scratch. false if any of the elements of ``orderedXformOps`` are not extant on this prim, or if an error occurred while authoring the ordering metadata. Under either condition, no scene description is authored. Parameters ---------- orderedXformOps : list[XformOp] resetXformStack : bool """ @staticmethod @typing.overload def TransformMightBeTimeVarying() -> bool: """ TransformMightBeTimeVarying() -> bool Determine whether there is any possibility that this prim's *local* transformation may vary over time. The determination is based on a snapshot of the authored state of the op attributes on the prim, and may become invalid in the face of further authoring. ---------------------------------------------------------------------- This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Determine whether there is any possibility that this prim's *local* transformation may vary over time, using a pre-fetched (cached) list of ordered xform ops supplied by the client. The determination is based on a snapshot of the authored state of the op attributes on the prim, and may become invalid in the face of further authoring. Parameters ---------- ops : list[XformOp] """ @staticmethod @typing.overload def TransformMightBeTimeVarying(ops) -> bool: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: """ **classmethod** _GetStaticTfType() -> Type """ __instance_size__ = 40 pass class _CanApplyResult(Boost.Python.instance): @property def whyNot(self) -> None: """ :type: None """ __instance_size__ = 56 pass def GetFallbackUpAxis() -> str: """ GetFallbackUpAxis() -> str Return the site-level fallback up axis as a TfToken. In a generic installation of USD, the fallback will be"Y". This can be changed to"Z"by adding, in a plugInfo.json file discoverable by USD's PlugPlugin mechanism: .. code-block:: text "UsdGeomMetrics": { "upAxis": "Z" } If more than one such entry is discovered and the values for upAxis differ, we will issue a warning during the first call to this function, and ignore all of them, so that we devolve to deterministic behavior of Y up axis until the problem is rectified. """ def GetStageMetersPerUnit(stage) -> float: """ GetStageMetersPerUnit(stage) -> float Return *stage* 's authored *metersPerUnit*, or 0.01 if unauthored. Encoding Stage Linear Units Parameters ---------- stage : UsdStageWeak """ def GetStageUpAxis(stage) -> str: """ GetStageUpAxis(stage) -> str Fetch and return ``stage`` 's upAxis. If unauthored, will return the value provided by UsdGeomGetFallbackUpAxis() . Exporters, however, are strongly encouraged to always set the upAxis for every USD file they create. one of: UsdGeomTokens->y or UsdGeomTokens->z, unless there was an error, in which case returns an empty TfToken Encoding Stage UpAxis Parameters ---------- stage : UsdStageWeak """ def LinearUnitsAre(authoredUnits, standardUnits, epsilon) -> bool: """ LinearUnitsAre(authoredUnits, standardUnits, epsilon) -> bool Return *true* if the two given metrics are within the provided relative *epsilon* of each other, when you need to know an absolute metric rather than a scaling factor. Use like so: .. code-block:: text double stageUnits = UsdGeomGetStageMetersPerUnit(stage); if (UsdGeomLinearUnitsAre(stageUnits, UsdGeomLinearUnits::meters)) // do something for meters else if (UsdGeomLinearUnitsAre(stageUnits, UsdGeomLinearUnits::feet)) // do something for feet *false* if either input is zero or negative, otherwise relative floating-point comparison between the two inputs. Encoding Stage Linear Units Parameters ---------- authoredUnits : float standardUnits : float epsilon : float """ def SetStageMetersPerUnit(stage, metersPerUnit) -> bool: """ SetStageMetersPerUnit(stage, metersPerUnit) -> bool Author *stage* 's *metersPerUnit*. true if metersPerUnit was successfully set. The stage's UsdEditTarget must be either its root layer or session layer. Encoding Stage Linear Units Parameters ---------- stage : UsdStageWeak metersPerUnit : float """ def SetStageUpAxis(stage, axis) -> bool: """ SetStageUpAxis(stage, axis) -> bool Set ``stage`` 's upAxis to ``axis`` , which must be one of UsdGeomTokens->y or UsdGeomTokens->z. UpAxis is stage-level metadata, therefore see UsdStage::SetMetadata() . true if upAxis was successfully set. The stage's UsdEditTarget must be either its root layer or session layer. Encoding Stage UpAxis Parameters ---------- stage : UsdStageWeak axis : str """ def StageHasAuthoredMetersPerUnit(stage) -> bool: """ StageHasAuthoredMetersPerUnit(stage) -> bool Return whether *stage* has an authored *metersPerUnit*. Encoding Stage Linear Units Parameters ---------- stage : UsdStageWeak """ __MFB_FULL_PACKAGE_NAME = 'usdGeom'
467,493
unknown
28.567643
454
0.635622
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdMedia/__init__.py
# # 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. # from pxr import Tf Tf.PreparePythonModule() del Tf
1,111
Python
38.714284
74
0.765977
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdMedia/__DOC.py
def Execute(result): result["SpatialAudio"].__doc__ = """ The SpatialAudio primitive defines basic properties for encoding playback of an audio file or stream within a USD Stage. The SpatialAudio schema derives from UsdGeomXformable since it can support full spatial audio while also supporting non-spatial mono and stereo sounds. One or more SpatialAudio prims can be placed anywhere in the namespace, though it is advantageous to place truly spatial audio prims under/inside the models from which the sound emanates, so that the audio prim need only be transformed relative to the model, rather than copying its animation. Timecode Attributes and Time Scaling ==================================== *startTime* and *endTime* are timecode valued attributes which gives them the special behavior that layer offsets affecting the layer in which one of these values is authored are applied to the attribute's value itself during value resolution. This allows audio playback to be kept in sync with time sampled animation as the animation is affected by layer offsets in the composition. But this behavior brings with it some interesting edge cases and caveats when it comes to layer offsets that include scale. Although authored layer offsets may have a time scale which can scale the duration between an authored *startTime* and *endTime*, we make no attempt to infer any playback dilation of the actual audio media itself. Given that *startTime* and *endTime* can be independently authored in different layers with differing time scales, it is not possible, in general, to define an"original timeframe"from which we can compute a dilation to composed stage-time. Even if we could compute a composed dilation this way, it would still be impossible to flatten a stage or layer stack into a single layer and still retain the composed audio dilation using this schema. Although we do not expect it to be common, it is possible to apply a negative time scale to USD layers, which mostly has the effect of reversing animation in the affected composition. If a negative scale is applied to a composition that contains authored *startTime* and *endTime*, it will reverse their relative ordering in time. Therefore, we stipulate when *playbackMode* is"onceFromStartToEnd"or"loopFromStartToEnd", if *endTime* is less than *startTime*, then begin playback at *endTime*, and continue until *startTime*. When *startTime* and *endTime* are inverted, we do not, however, stipulate that playback of the audio media itself be inverted, since doing so"successfully"would require perfect knowledge of when, within the audio clip, relevant audio ends (so that we know how to offset the reversed audio to align it so that we reach the"beginning"at *startTime*), and sounds played in reverse are not likely to produce desirable results. For any described attribute *Fallback* *Value* or *Allowed* *Values* below that are text/tokens, the actual token is published and defined in UsdMediaTokens. So to set an attribute to the value"rightHanded", use UsdMediaTokens->rightHanded as the value. """ result["SpatialAudio"].__init__.func_doc = """__init__(prim) Construct a UsdMediaSpatialAudio on UsdPrim ``prim`` . Equivalent to UsdMediaSpatialAudio::Get (prim.GetStage(), prim.GetPath()) for a *valid* ``prim`` , but will not immediately throw an error for an invalid ``prim`` Parameters ---------- prim : Prim ---------------------------------------------------------------------- __init__(schemaObj) Construct a UsdMediaSpatialAudio on the prim held by ``schemaObj`` . Should be preferred over UsdMediaSpatialAudio (schemaObj.GetPrim()), as it preserves SchemaBase state. Parameters ---------- schemaObj : SchemaBase """ result["SpatialAudio"].GetFilePathAttr.func_doc = """GetFilePathAttr() -> Attribute Path to the audio file. In general, the formats allowed for audio files is no more constrained by USD than is image-type. As with images, however, usdz has stricter requirements based on DMA and format support in browsers and consumer devices. The allowed audio filetypes for usdz are M4A, MP3, WAV (in order of preference). Usdz Specification Declaration ``uniform asset filePath = @@`` C++ Type SdfAssetPath Usd Type SdfValueTypeNames->Asset Variability SdfVariabilityUniform """ result["SpatialAudio"].CreateFilePathAttr.func_doc = """CreateFilePathAttr(defaultValue, writeSparsely) -> Attribute See GetFilePathAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["SpatialAudio"].GetAuralModeAttr.func_doc = """GetAuralModeAttr() -> Attribute Determines how audio should be played. Valid values are: - spatial: Play the audio in 3D space if the device can support spatial audio. if not, fall back to mono. - nonSpatial: Play the audio without regard to the SpatialAudio prim's position. If the audio media contains any form of stereo or other multi-channel sound, it is left to the application to determine whether the listener's position should be taken into account. We expect nonSpatial to be the choice for ambient sounds and music sound- tracks. Declaration ``uniform token auralMode ="spatial"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values spatial, nonSpatial """ result["SpatialAudio"].CreateAuralModeAttr.func_doc = """CreateAuralModeAttr(defaultValue, writeSparsely) -> Attribute See GetAuralModeAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["SpatialAudio"].GetPlaybackModeAttr.func_doc = """GetPlaybackModeAttr() -> Attribute Along with *startTime* and *endTime*, determines when the audio playback should start and stop during the stage's animation playback and whether the audio should loop during its duration. Valid values are: - onceFromStart: Play the audio once, starting at *startTime*, continuing until the audio completes. - onceFromStartToEnd: Play the audio once beginning at *startTime*, continuing until *endTime* or until the audio completes, whichever comes first. - loopFromStart: Start playing the audio at *startTime* and continue looping through to the stage's authored *endTimeCode*. - loopFromStartToEnd: Start playing the audio at *startTime* and continue looping through, stopping the audio at *endTime*. - loopFromStage: Start playing the audio at the stage's authored *startTimeCode* and continue looping through to the stage's authored *endTimeCode*. This can be useful for ambient sounds that should always be active. Declaration ``uniform token playbackMode ="onceFromStart"`` C++ Type TfToken Usd Type SdfValueTypeNames->Token Variability SdfVariabilityUniform Allowed Values onceFromStart, onceFromStartToEnd, loopFromStart, loopFromStartToEnd, loopFromStage """ result["SpatialAudio"].CreatePlaybackModeAttr.func_doc = """CreatePlaybackModeAttr(defaultValue, writeSparsely) -> Attribute See GetPlaybackModeAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["SpatialAudio"].GetStartTimeAttr.func_doc = """GetStartTimeAttr() -> Attribute Expressed in the timeCodesPerSecond of the containing stage, *startTime* specifies when the audio stream will start playing during animation playback. This value is ignored when *playbackMode* is set to loopFromStage as, in this mode, the audio will always start at the stage's authored *startTimeCode*. Note that *startTime* is expressed as a timecode so that the stage can properly apply layer offsets when resolving its value. See Timecode Attributes and Time Scaling for more details and caveats. Declaration ``uniform timecode startTime = 0`` C++ Type SdfTimeCode Usd Type SdfValueTypeNames->TimeCode Variability SdfVariabilityUniform """ result["SpatialAudio"].CreateStartTimeAttr.func_doc = """CreateStartTimeAttr(defaultValue, writeSparsely) -> Attribute See GetStartTimeAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["SpatialAudio"].GetEndTimeAttr.func_doc = """GetEndTimeAttr() -> Attribute Expressed in the timeCodesPerSecond of the containing stage, *endTime* specifies when the audio stream will cease playing during animation playback if the length of the referenced audio clip is longer than desired. This only applies if *playbackMode* is set to onceFromStartToEnd or loopFromStartToEnd, otherwise the *endTimeCode* of the stage is used instead of *endTime*. If *endTime* is less than *startTime*, it is expected that the audio will instead be played from *endTime* to *startTime*. Note that *endTime* is expressed as a timecode so that the stage can properly apply layer offsets when resolving its value. See Timecode Attributes and Time Scaling for more details and caveats. Declaration ``uniform timecode endTime = 0`` C++ Type SdfTimeCode Usd Type SdfValueTypeNames->TimeCode Variability SdfVariabilityUniform """ result["SpatialAudio"].CreateEndTimeAttr.func_doc = """CreateEndTimeAttr(defaultValue, writeSparsely) -> Attribute See GetEndTimeAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["SpatialAudio"].GetMediaOffsetAttr.func_doc = """GetMediaOffsetAttr() -> Attribute Expressed in seconds, *mediaOffset* specifies the offset from the referenced audio file's beginning at which we should begin playback when stage playback reaches the time that prim's audio should start. If the prim's *playbackMode* is a looping mode, *mediaOffset* is applied only to the first run-through of the audio clip; the second and all other loops begin from the start of the audio clip. Declaration ``uniform double mediaOffset = 0`` C++ Type double Usd Type SdfValueTypeNames->Double Variability SdfVariabilityUniform """ result["SpatialAudio"].CreateMediaOffsetAttr.func_doc = """CreateMediaOffsetAttr(defaultValue, writeSparsely) -> Attribute See GetMediaOffsetAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["SpatialAudio"].GetGainAttr.func_doc = """GetGainAttr() -> Attribute Multiplier on the incoming audio signal. A value of 0"mutes"the signal. Negative values will be clamped to 0. Declaration ``double gain = 1`` C++ Type double Usd Type SdfValueTypeNames->Double """ result["SpatialAudio"].CreateGainAttr.func_doc = """CreateGainAttr(defaultValue, writeSparsely) -> Attribute See GetGainAttr() , and also Create vs Get Property Methods for when to use Get vs Create. If specified, author ``defaultValue`` as the attribute's default, sparsely (when it makes sense to do so) if ``writeSparsely`` is ``true`` - the default for ``writeSparsely`` is ``false`` . Parameters ---------- defaultValue : VtValue writeSparsely : bool """ result["SpatialAudio"].GetSchemaAttributeNames.func_doc = """**classmethod** GetSchemaAttributeNames(includeInherited) -> list[TfToken] Return a vector of names of all pre-declared attributes for this schema class and all its ancestor classes. Does not include attributes that may be authored by custom/extended methods of the schemas involved. Parameters ---------- includeInherited : bool """ result["SpatialAudio"].Get.func_doc = """**classmethod** Get(stage, path) -> SpatialAudio Return a UsdMediaSpatialAudio holding the prim adhering to this schema at ``path`` on ``stage`` . If no prim exists at ``path`` on ``stage`` , or if the prim at that path does not adhere to this schema, return an invalid schema object. This is shorthand for the following: .. code-block:: text UsdMediaSpatialAudio(stage->GetPrimAtPath(path)); Parameters ---------- stage : Stage path : Path """ result["SpatialAudio"].Define.func_doc = """**classmethod** Define(stage, path) -> SpatialAudio Attempt to ensure a *UsdPrim* adhering to this schema at ``path`` is defined (according to UsdPrim::IsDefined() ) on this stage. If a prim adhering to this schema at ``path`` is already defined on this stage, return that prim. Otherwise author an *SdfPrimSpec* with *specifier* == *SdfSpecifierDef* and this schema's prim type name for the prim at ``path`` at the current EditTarget. Author *SdfPrimSpec* s with ``specifier`` == *SdfSpecifierDef* and empty typeName at the current EditTarget for any nonexistent, or existing but not *Defined* ancestors. The given *path* must be an absolute prim path that does not contain any variant selections. If it is impossible to author any of the necessary PrimSpecs, (for example, in case *path* cannot map to the current UsdEditTarget 's namespace) issue an error and return an invalid *UsdPrim*. Note that this method may return a defined prim whose typeName does not specify this schema class, in case a stronger typeName opinion overrides the opinion at the current EditTarget. Parameters ---------- stage : Stage path : Path """ result["SpatialAudio"]._GetStaticTfType.func_doc = """**classmethod** _GetStaticTfType() -> Type """
14,690
Python
25.047872
138
0.752144
omniverse-code/kit/exts/omni.usd.libs/pxr/Glf/__init__.py
# # 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. # """ glf """ from pxr import Tf Tf.PreparePythonModule() del Tf
1,125
Python
33.121211
74
0.759111
omniverse-code/kit/exts/omni.usd.libs/pxr/Glf/__DOC.py
def Execute(result): result["DrawTarget"].__doc__ = """ A class representing a GL render target with mutliple image attachments. A DrawTarget is essentially a custom render pass into which several arbitrary variables can be output into. These can later be used as texture samplers by GLSL shaders. The DrawTarget maintains a map of named attachments that correspond to GL_TEXTURE_2D mages. By default, DrawTargets also create a depth component that is used both as a depth buffer during the draw pass, and can later be accessed as a regular GL_TEXTURE_2D data. Stencils are also available (by setting the format to GL_DEPTH_STENCIL and the internalFormat to GL_DEPTH24_STENCIL8) """ result["DrawTarget"].AddAttachment.func_doc = """AddAttachment(name, format, type, internalFormat) -> None Add an attachment to the DrawTarget. Parameters ---------- name : str format : GLenum type : GLenum internalFormat : GLenum """ result["DrawTarget"].WriteToFile.func_doc = """WriteToFile(name, filename, viewMatrix, projectionMatrix) -> bool Write the Attachment buffer to an image file (debugging). Parameters ---------- name : str filename : str viewMatrix : Matrix4d projectionMatrix : Matrix4d """ result["DrawTarget"].Bind.func_doc = """Bind() -> None Binds the framebuffer. """ result["DrawTarget"].Unbind.func_doc = """Unbind() -> None Unbinds the framebuffer. """ result["DrawTarget"].__init__.func_doc = """__init__(size, requestMSAA) Parameters ---------- size : Vec2i requestMSAA : bool ---------------------------------------------------------------------- __init__(drawtarget) Parameters ---------- drawtarget : DrawTarget """ result["GLQueryObject"].__doc__ = """ Represents a GL query object in Glf """ result["GLQueryObject"].__init__.func_doc = """__init__() ---------------------------------------------------------------------- __init__(arg1) Parameters ---------- arg1 : GLQueryObject """ result["GLQueryObject"].Begin.func_doc = """Begin(target) -> None Begin query for the given ``target`` target has to be one of GL_SAMPLES_PASSED, GL_ANY_SAMPLES_PASSED, GL_ANY_SAMPLES_PASSED_CONSERVATIVE, GL_PRIMITIVES_GENERATED GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN GL_TIME_ELAPSED, GL_TIMESTAMP. Parameters ---------- target : GLenum """ result["GLQueryObject"].BeginSamplesPassed.func_doc = """BeginSamplesPassed() -> None equivalent to Begin(GL_SAMPLES_PASSED). The number of samples that pass the depth test for all drawing commands within the scope of the query will be returned. """ result["GLQueryObject"].BeginPrimitivesGenerated.func_doc = """BeginPrimitivesGenerated() -> None equivalent to Begin(GL_PRIMITIVES_GENERATED). The number of primitives sent to the rasterizer by the scoped drawing command will be returned. """ result["GLQueryObject"].BeginTimeElapsed.func_doc = """BeginTimeElapsed() -> None equivalent to Begin(GL_TIME_ELAPSED). The time that it takes for the GPU to execute all of the scoped commands will be returned in nanoseconds. """ result["GLQueryObject"].End.func_doc = """End() -> None End query. """ result["GLQueryObject"].GetResult.func_doc = """GetResult() -> int Return the query result (synchronous) stalls CPU until the result becomes available. """ result["GLQueryObject"].GetResultNoWait.func_doc = """GetResultNoWait() -> int Return the query result (asynchronous) returns 0 if the result hasn't been available. """ result["SimpleLight"].__doc__ = """""" result["SimpleLight"].__init__.func_doc = """__init__(position) Parameters ---------- position : Vec4f """ result["SimpleMaterial"].__doc__ = """""" result["SimpleMaterial"].__init__.func_doc = """__init__() """ result["Texture"].__doc__ = """ Represents a texture object in Glf. A texture is typically defined by reading texture image data from an image file but a texture might also represent an attachment of a draw target. """ result["Texture"].GetTextureMemoryAllocated.func_doc = """**classmethod** GetTextureMemoryAllocated() -> int static reporting function """ result["SimpleLight"].transform = property(result["SimpleLight"].transform.fget, result["SimpleLight"].transform.fset, result["SimpleLight"].transform.fdel, """type : None ---------------------------------------------------------------------- type : Matrix4d """) result["SimpleLight"].ambient = property(result["SimpleLight"].ambient.fget, result["SimpleLight"].ambient.fset, result["SimpleLight"].ambient.fdel, """type : None ---------------------------------------------------------------------- type : Vec4f """) result["SimpleLight"].diffuse = property(result["SimpleLight"].diffuse.fget, result["SimpleLight"].diffuse.fset, result["SimpleLight"].diffuse.fdel, """type : None ---------------------------------------------------------------------- type : Vec4f """) result["SimpleLight"].specular = property(result["SimpleLight"].specular.fget, result["SimpleLight"].specular.fset, result["SimpleLight"].specular.fdel, """type : None ---------------------------------------------------------------------- type : Vec4f """) result["SimpleLight"].position = property(result["SimpleLight"].position.fget, result["SimpleLight"].position.fset, result["SimpleLight"].position.fdel, """type : None ---------------------------------------------------------------------- type : Vec4f """) result["SimpleLight"].spotDirection = property(result["SimpleLight"].spotDirection.fget, result["SimpleLight"].spotDirection.fset, result["SimpleLight"].spotDirection.fdel, """type : None ---------------------------------------------------------------------- type : Vec3f """) result["SimpleLight"].spotCutoff = property(result["SimpleLight"].spotCutoff.fget, result["SimpleLight"].spotCutoff.fset, result["SimpleLight"].spotCutoff.fdel, """type : None ---------------------------------------------------------------------- type : float """) result["SimpleLight"].spotFalloff = property(result["SimpleLight"].spotFalloff.fget, result["SimpleLight"].spotFalloff.fset, result["SimpleLight"].spotFalloff.fdel, """type : None ---------------------------------------------------------------------- type : float """) result["SimpleLight"].attenuation = property(result["SimpleLight"].attenuation.fget, result["SimpleLight"].attenuation.fset, result["SimpleLight"].attenuation.fdel, """type : None ---------------------------------------------------------------------- type : Vec3f """) result["SimpleLight"].shadowMatrices = property(result["SimpleLight"].shadowMatrices.fget, result["SimpleLight"].shadowMatrices.fset, result["SimpleLight"].shadowMatrices.fdel, """type : None ---------------------------------------------------------------------- type : list[Matrix4d] """) result["SimpleLight"].shadowResolution = property(result["SimpleLight"].shadowResolution.fget, result["SimpleLight"].shadowResolution.fset, result["SimpleLight"].shadowResolution.fdel, """type : None ---------------------------------------------------------------------- type : int """) result["SimpleLight"].shadowBias = property(result["SimpleLight"].shadowBias.fget, result["SimpleLight"].shadowBias.fset, result["SimpleLight"].shadowBias.fdel, """type : None ---------------------------------------------------------------------- type : float """) result["SimpleLight"].shadowBlur = property(result["SimpleLight"].shadowBlur.fget, result["SimpleLight"].shadowBlur.fset, result["SimpleLight"].shadowBlur.fdel, """type : None ---------------------------------------------------------------------- type : float """) result["SimpleLight"].shadowIndexStart = property(result["SimpleLight"].shadowIndexStart.fget, result["SimpleLight"].shadowIndexStart.fset, result["SimpleLight"].shadowIndexStart.fdel, """type : None ---------------------------------------------------------------------- type : int """) result["SimpleLight"].shadowIndexEnd = property(result["SimpleLight"].shadowIndexEnd.fget, result["SimpleLight"].shadowIndexEnd.fset, result["SimpleLight"].shadowIndexEnd.fdel, """type : None ---------------------------------------------------------------------- type : int """) result["SimpleLight"].hasShadow = property(result["SimpleLight"].hasShadow.fget, result["SimpleLight"].hasShadow.fset, result["SimpleLight"].hasShadow.fdel, """type : None """) result["SimpleLight"].isCameraSpaceLight = property(result["SimpleLight"].isCameraSpaceLight.fget, result["SimpleLight"].isCameraSpaceLight.fset, result["SimpleLight"].isCameraSpaceLight.fdel, """type : None ---------------------------------------------------------------------- type : bool """) result["SimpleLight"].isDomeLight = property(result["SimpleLight"].isDomeLight.fget, result["SimpleLight"].isDomeLight.fset, result["SimpleLight"].isDomeLight.fdel, """type : None ---------------------------------------------------------------------- type : bool """) result["SimpleMaterial"].ambient = property(result["SimpleMaterial"].ambient.fget, result["SimpleMaterial"].ambient.fset, result["SimpleMaterial"].ambient.fdel, """type : None ---------------------------------------------------------------------- type : Vec4f """) result["SimpleMaterial"].diffuse = property(result["SimpleMaterial"].diffuse.fget, result["SimpleMaterial"].diffuse.fset, result["SimpleMaterial"].diffuse.fdel, """type : None ---------------------------------------------------------------------- type : Vec4f """) result["SimpleMaterial"].specular = property(result["SimpleMaterial"].specular.fget, result["SimpleMaterial"].specular.fset, result["SimpleMaterial"].specular.fdel, """type : None ---------------------------------------------------------------------- type : Vec4f """) result["SimpleMaterial"].emission = property(result["SimpleMaterial"].emission.fget, result["SimpleMaterial"].emission.fset, result["SimpleMaterial"].emission.fdel, """type : None ---------------------------------------------------------------------- type : Vec4f """) result["SimpleMaterial"].shininess = property(result["SimpleMaterial"].shininess.fget, result["SimpleMaterial"].shininess.fset, result["SimpleMaterial"].shininess.fdel, """type : None ---------------------------------------------------------------------- type : float """) result["Texture"].memoryUsed = property(result["Texture"].memoryUsed.fget, result["Texture"].memoryUsed.fset, result["Texture"].memoryUsed.fdel, """type : int Amount of memory used to store the texture. """) result["Texture"].memoryRequested = property(result["Texture"].memoryRequested.fget, result["Texture"].memoryRequested.fset, result["Texture"].memoryRequested.fdel, """type : None Specify the amount of memory the user wishes to allocate to the texture. ---------------------------------------------------------------------- type : int Amount of memory the user wishes to allocate to the texture. """) result["Texture"].minFilterSupported = property(result["Texture"].minFilterSupported.fget, result["Texture"].minFilterSupported.fset, result["Texture"].minFilterSupported.fdel, """type : bool """) result["Texture"].magFilterSupported = property(result["Texture"].magFilterSupported.fget, result["Texture"].magFilterSupported.fset, result["Texture"].magFilterSupported.fdel, """type : bool """)
11,422
Python
27.274752
210
0.608125
omniverse-code/kit/exts/omni.usd.libs/pxr/Trace/__init__.py
# # Copyright 2018 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. # """ Trace -- Utilities for counting and recording events. """ from pxr import Tf Tf.PreparePythonModule() del Tf import contextlib @contextlib.contextmanager def TraceScope(label): """A context manager that calls BeginEvent on the global collector on enter and EndEvent on exit.""" try: collector = Collector() eventId = collector.BeginEvent(label) yield finally: collector.EndEvent(label) del contextlib def TraceFunction(obj): """A decorator that enables tracing the function that it decorates. If you decorate with 'TraceFunction' the function will be traced in the global collector.""" collector = Collector() def decorate(func): import inspect if inspect.ismethod(func): callableTypeLabel = 'method' classLabel = func.__self__.__class__.__name__+'.' else: callableTypeLabel = 'func' classLabel = '' module = inspect.getmodule(func) if module is not None: moduleLabel = module.__name__+'.' else: moduleLabel = '' label = 'Python {0}: {1}{2}{3}'.format( callableTypeLabel, moduleLabel, classLabel, func.__name__) def invoke(*args, **kwargs): with TraceScope(label): return func(*args, **kwargs) invoke.__name__ = func.__name__ # Make sure wrapper function gets attributes of wrapped function. import functools return functools.update_wrapper(invoke, func) return decorate(obj) def TraceMethod(obj): """A convenience. Same as TraceFunction but changes the recorded label to use the term 'method' rather than 'function'.""" return TraceFunction(obj)
2,861
Python
30.8
80
0.665851
omniverse-code/kit/exts/omni.usd.libs/pxr/Trace/__DOC.py
def Execute(result): result["AggregateNode"].__doc__ = """ A representation of a call tree. Each node represents one or more calls that occurred in the trace. Multiple calls to a child node are aggregated into one node. """ result["Collector"].__doc__ = """ This is a singleton class that records TraceEvent instances and populates TraceCollection instances. All public methods of TraceCollector are safe to call from any thread. """ result["Collector"].BeginEvent.func_doc = """BeginEvent(key) -> TimeStamp Record a begin event with *key* if ``Category`` is enabled. A matching end event is expected some time in the future. If the key is known at compile time ``BeginScope`` and ``Scope`` methods are preferred because they have lower overhead. The TimeStamp of the TraceEvent or 0 if the collector is disabled. BeginScope Scope Parameters ---------- key : Key """ result["Collector"].BeginEventAtTime.func_doc = """BeginEventAtTime(key, ms) -> None Record a begin event with *key* at a specified time if ``Category`` is enabled. This version of the method allows the passing of a specific number of elapsed milliseconds, *ms*, to use for this event. This method is used for testing and debugging code. Parameters ---------- key : Key ms : float """ result["Collector"].EndEvent.func_doc = """EndEvent(key) -> TimeStamp Record an end event with *key* if ``Category`` is enabled. A matching begin event must have preceded this end event. If the key is known at compile time EndScope and Scope methods are preferred because they have lower overhead. The TimeStamp of the TraceEvent or 0 if the collector is disabled. EndScope Scope Parameters ---------- key : Key """ result["Collector"].EndEventAtTime.func_doc = """EndEventAtTime(key, ms) -> None Record an end event with *key* at a specified time if ``Category`` is enabled. This version of the method allows the passing of a specific number of elapsed milliseconds, *ms*, to use for this event. This method is used for testing and debugging code. Parameters ---------- key : Key ms : float """ result["Collector"].Clear.func_doc = """Clear() -> None Clear all pending events from the collector. No TraceCollection will be made for these events. """ result["Collector"].GetLabel.func_doc = """GetLabel() -> str Return the label associated with this collector. """ result["Collector"].__init__.func_doc = """__init__() """ result["Reporter"].__doc__ = """ This class converts streams of TraceEvent objects into call trees which can then be used as a data source to a GUI or written out to a file. """ result["Reporter"].Report.func_doc = """Report(s, iterationCount) -> None Generates a report to the ostream *s*, dividing all times by *iterationCount*. Parameters ---------- s : ostream iterationCount : int """ result["Reporter"].ReportTimes.func_doc = """ReportTimes(s) -> None Generates a report of the times to the ostream *s*. Parameters ---------- s : ostream """ result["Reporter"].ReportChromeTracing.func_doc = """ReportChromeTracing(s) -> None Generates a timeline trace report suitable for viewing in Chrome's trace viewer. Parameters ---------- s : ostream """ result["Reporter"].GetLabel.func_doc = """GetLabel() -> str Return the label associated with this reporter. """ result["Reporter"].UpdateTraceTrees.func_doc = """UpdateTraceTrees() -> None This fully re-builds the event and aggregate trees from whatever the current collection holds. It is ok to call this multiple times in case the collection gets appended on inbetween. If we want to have multiple reporters per collector, this will need to be changed so that all reporters reporting on a collector update their respective trees. """ result["Reporter"].ClearTree.func_doc = """ClearTree() -> None Clears event tree and counters. """ result["Reporter"].__init__.func_doc = """__init__(label, dataSource) Parameters ---------- label : str dataSource : DataSource """ result["AggregateNode"].inclusiveTime = property(result["AggregateNode"].inclusiveTime.fget, result["AggregateNode"].inclusiveTime.fset, result["AggregateNode"].inclusiveTime.fdel, """type : TimeStamp Returns the total time of this node ands its children. """) result["AggregateNode"].exclusiveTime = property(result["AggregateNode"].exclusiveTime.fget, result["AggregateNode"].exclusiveTime.fset, result["AggregateNode"].exclusiveTime.fdel, """type : TimeStamp Returns the time spent in this node but not its children. """) result["AggregateNode"].count = property(result["AggregateNode"].count.fget, result["AggregateNode"].count.fset, result["AggregateNode"].count.fdel, """type : int Returns the call count of this node. ``recursive`` determines if recursive calls are counted. """) result["AggregateNode"].exclusiveCount = property(result["AggregateNode"].exclusiveCount.fget, result["AggregateNode"].exclusiveCount.fset, result["AggregateNode"].exclusiveCount.fdel, """type : int Returns the exclusive count. """) result["AggregateNode"].children = property(result["AggregateNode"].children.fget, result["AggregateNode"].children.fset, result["AggregateNode"].children.fdel, """type : list[TraceAggregateNodePtr] """) result["AggregateNode"].key = property(result["AggregateNode"].key.fget, result["AggregateNode"].key.fset, result["AggregateNode"].key.fdel, """type : str Returns the node's key. """) result["AggregateNode"].id = property(result["AggregateNode"].id.fget, result["AggregateNode"].id.fset, result["AggregateNode"].id.fdel, """type : Id Returns the node's id. """) result["AggregateNode"].expanded = property(result["AggregateNode"].expanded.fget, result["AggregateNode"].expanded.fset, result["AggregateNode"].expanded.fdel, """type : bool Returns whether this node is expanded in a gui. ---------------------------------------------------------------------- type : None Sets whether or not this node is expanded in a gui. """) result["Collector"].enabled = property(result["Collector"].enabled.fget, result["Collector"].enabled.fset, result["Collector"].enabled.fdel, """**classmethod** type : bool Returns whether collection of events is enabled for DefaultCategory. ---------------------------------------------------------------------- type : None Enables or disables collection of events for DefaultCategory. """) result["Collector"].pythonTracingEnabled = property(result["Collector"].pythonTracingEnabled.fget, result["Collector"].pythonTracingEnabled.fset, result["Collector"].pythonTracingEnabled.fdel, """type : None Set whether automatic tracing of all python scopes is enabled. ---------------------------------------------------------------------- type : bool Returns whether automatic tracing of all python scopes is enabled. """) result["Reporter"].groupByFunction = property(result["Reporter"].groupByFunction.fget, result["Reporter"].groupByFunction.fset, result["Reporter"].groupByFunction.fdel, """type : bool Returns the current group-by-function state. ---------------------------------------------------------------------- type : None This affects only stack trace event reporting. If ``true`` then all events in a function are grouped together otherwise events are split out by address. """) result["Reporter"].foldRecursiveCalls = property(result["Reporter"].foldRecursiveCalls.fget, result["Reporter"].foldRecursiveCalls.fset, result["Reporter"].foldRecursiveCalls.fdel, """type : bool Returns the current setting for recursion folding for stack trace event reporting. ---------------------------------------------------------------------- type : None When stack trace event reporting, this sets whether or not recursive calls are folded in the output. Recursion folding is useful when the stacks contain deep recursive structures. """) result["Reporter"].shouldAdjustForOverheadAndNoise = property(result["Reporter"].shouldAdjustForOverheadAndNoise.fget, result["Reporter"].shouldAdjustForOverheadAndNoise.fset, result["Reporter"].shouldAdjustForOverheadAndNoise.fdel, """type : None Set whether or not the reporter should adjust scope times for overhead and noise. """) result["Reporter"].aggregateTreeRoot = property(result["Reporter"].aggregateTreeRoot.fget, result["Reporter"].aggregateTreeRoot.fset, result["Reporter"].aggregateTreeRoot.fdel, """type : AggregateNode Returns the root node of the aggregated call tree. """) result["Reporter"].globalReporter.__doc__ = """**classmethod** globalReporter() -> Reporter Returns the global reporter. """
8,663
Python
23.474576
250
0.700681
omniverse-code/kit/exts/omni.usd.libs/pxr/Trace/__init__.pyi
from __future__ import annotations import pxr.Trace._trace import typing import Boost.Python import pxr.Trace __all__ = [ "AggregateNode", "Collector", "GetElapsedSeconds", "GetTestEventName", "Reporter", "TestAuto", "TestCreateEvents", "TestNesting" ] class AggregateNode(Boost.Python.instance): """ A representation of a call tree. Each node represents one or more calls that occurred in the trace. Multiple calls to a child node are aggregated into one node. """ @property def children(self) -> None: """ type : list[TraceAggregateNodePtr] :type: None """ @property def count(self) -> None: """ type : int Returns the call count of this node. ``recursive`` determines if recursive calls are counted. :type: None """ @property def exclusiveCount(self) -> None: """ type : int Returns the exclusive count. :type: None """ @property def exclusiveTime(self) -> None: """ type : TimeStamp Returns the time spent in this node but not its children. :type: None """ @property def expanded(self) -> None: """ type : bool Returns whether this node is expanded in a gui. ---------------------------------------------------------------------- type : None Sets whether or not this node is expanded in a gui. :type: None """ @property def expired(self) -> None: """ True if this object has expired, False otherwise. :type: None """ @property def id(self) -> None: """ type : Id Returns the node's id. :type: None """ @property def inclusiveTime(self) -> None: """ type : TimeStamp Returns the total time of this node ands its children. :type: None """ @property def key(self) -> None: """ type : str Returns the node's key. :type: None """ pass class Collector(Boost.Python.instance): """ This is a singleton class that records TraceEvent instances and populates TraceCollection instances. All public methods of TraceCollector are safe to call from any thread. """ @staticmethod def BeginEvent(key) -> TimeStamp: """ BeginEvent(key) -> TimeStamp Record a begin event with *key* if ``Category`` is enabled. A matching end event is expected some time in the future. If the key is known at compile time ``BeginScope`` and ``Scope`` methods are preferred because they have lower overhead. The TimeStamp of the TraceEvent or 0 if the collector is disabled. BeginScope Scope Parameters ---------- key : Key """ @staticmethod def BeginEventAtTime(key, ms) -> None: """ BeginEventAtTime(key, ms) -> None Record a begin event with *key* at a specified time if ``Category`` is enabled. This version of the method allows the passing of a specific number of elapsed milliseconds, *ms*, to use for this event. This method is used for testing and debugging code. Parameters ---------- key : Key ms : float """ @staticmethod def Clear() -> None: """ Clear() -> None Clear all pending events from the collector. No TraceCollection will be made for these events. """ @staticmethod def EndEvent(key) -> TimeStamp: """ EndEvent(key) -> TimeStamp Record an end event with *key* if ``Category`` is enabled. A matching begin event must have preceded this end event. If the key is known at compile time EndScope and Scope methods are preferred because they have lower overhead. The TimeStamp of the TraceEvent or 0 if the collector is disabled. EndScope Scope Parameters ---------- key : Key """ @staticmethod def EndEventAtTime(key, ms) -> None: """ EndEventAtTime(key, ms) -> None Record an end event with *key* at a specified time if ``Category`` is enabled. This version of the method allows the passing of a specific number of elapsed milliseconds, *ms*, to use for this event. This method is used for testing and debugging code. Parameters ---------- key : Key ms : float """ @staticmethod def GetLabel() -> str: """ GetLabel() -> str Return the label associated with this collector. """ @property def enabled(self) -> None: """ **classmethod** type : bool Returns whether collection of events is enabled for DefaultCategory. ---------------------------------------------------------------------- type : None Enables or disables collection of events for DefaultCategory. :type: None """ @property def expired(self) -> None: """ True if this object has expired, False otherwise. :type: None """ @property def pythonTracingEnabled(self) -> None: """ type : None Set whether automatic tracing of all python scopes is enabled. ---------------------------------------------------------------------- type : bool Returns whether automatic tracing of all python scopes is enabled. :type: None """ pass class Reporter(Boost.Python.instance): """ This class converts streams of TraceEvent objects into call trees which can then be used as a data source to a GUI or written out to a file. """ @staticmethod def ClearTree() -> None: """ ClearTree() -> None Clears event tree and counters. """ @staticmethod def GetLabel() -> str: """ GetLabel() -> str Return the label associated with this reporter. """ @staticmethod def Report(s, iterationCount) -> None: """ Report(s, iterationCount) -> None Generates a report to the ostream *s*, dividing all times by *iterationCount*. Parameters ---------- s : ostream iterationCount : int """ @staticmethod def ReportChromeTracing(s) -> None: """ ReportChromeTracing(s) -> None Generates a timeline trace report suitable for viewing in Chrome's trace viewer. Parameters ---------- s : ostream """ @staticmethod def ReportChromeTracingToFile(*args, **kwargs) -> None: ... @staticmethod def ReportTimes(s) -> None: """ ReportTimes(s) -> None Generates a report of the times to the ostream *s*. Parameters ---------- s : ostream """ @staticmethod def UpdateTraceTrees() -> None: """ UpdateTraceTrees() -> None This fully re-builds the event and aggregate trees from whatever the current collection holds. It is ok to call this multiple times in case the collection gets appended on inbetween. If we want to have multiple reporters per collector, this will need to be changed so that all reporters reporting on a collector update their respective trees. """ @property def aggregateTreeRoot(self) -> None: """ type : AggregateNode Returns the root node of the aggregated call tree. :type: None """ @property def expired(self) -> None: """ True if this object has expired, False otherwise. :type: None """ @property def foldRecursiveCalls(self) -> None: """ type : bool Returns the current setting for recursion folding for stack trace event reporting. ---------------------------------------------------------------------- type : None When stack trace event reporting, this sets whether or not recursive calls are folded in the output. Recursion folding is useful when the stacks contain deep recursive structures. :type: None """ @property def groupByFunction(self) -> None: """ type : bool Returns the current group-by-function state. ---------------------------------------------------------------------- type : None This affects only stack trace event reporting. If ``true`` then all events in a function are grouped together otherwise events are split out by address. :type: None """ @property def shouldAdjustForOverheadAndNoise(self) -> None: """ type : None Set whether or not the reporter should adjust scope times for overhead and noise. :type: None """ globalReporter: pxr.Trace.Reporter pass def GetElapsedSeconds(*args, **kwargs) -> None: pass def GetTestEventName(*args, **kwargs) -> None: pass def TestAuto(*args, **kwargs) -> None: pass def TestCreateEvents(*args, **kwargs) -> None: pass def TestNesting(*args, **kwargs) -> None: pass __MFB_FULL_PACKAGE_NAME = 'trace'
9,636
unknown
20.463252
78
0.543587
omniverse-code/kit/exts/omni.usd.libs/pxr/Trace/__main__.py
# # Copyright 2018 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. # # Execute a script with tracing enabled. # Usage: python -m pxr.Trace [-o OUTPUT] [-c "command" | FILE] from __future__ import print_function import argparse, sys parser = argparse.ArgumentParser(description='Trace script execution.') parser.add_argument('-o', dest='output', metavar='OUTPUT', type=str, default=None, help='trace output; defaults to stdout') parser.add_argument('-c', dest='cmd', type=str, help='trace <cmd> as a Python script') parser.add_argument('file', metavar="FILE", nargs='?', default=None, help='script to trace') args = parser.parse_args() if not args.cmd and not args.file: print("Must specify a command or script to trace", file=sys.stderr) sys.exit(1) if args.cmd and args.file: print("Only one of -c or FILE may be specified", file=sys.stderr) sys.exit(1) from pxr import Trace env = {} # Create a Main function that is traced so we always capture a useful # top-level scope. if args.file: @Trace.TraceFunction def Main(): exec(compile(open(args.file).read(), args.file, 'exec'), env) else: @Trace.TraceFunction def Main(): exec(args.cmd, env) try: Trace.Collector().enabled = True Main() finally: Trace.Collector().enabled = False if args.output is not None: Trace.Reporter.globalReporter.Report(args.output) else: Trace.Reporter.globalReporter.Report()
2,580
Python
31.670886
74
0.68062
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdAppUtils/cameraArgs.py
# # 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. # def AddCmdlineArgs(argsParser, defaultValue=None, altHelpText=''): """ Adds camera-related command line arguments to argsParser. The resulting 'camera' argument will be an Sdf.Path. If no value is given and defaultValue is not overridden, 'camera' will be a single-element path containing the primary camera name. """ from pxr import Sdf from pxr import UsdUtils if defaultValue is None: defaultValue = UsdUtils.GetPrimaryCameraName() helpText = altHelpText if not helpText: helpText = ( 'Which camera to use - may be given as either just the ' 'camera\'s prim name (i.e. just the last element in the prim ' 'path), or as a full prim path. Note that if only the prim name ' 'is used and more than one camera exists with that name, which ' 'one is used will effectively be random (default=%(default)s)') # This avoids an Sdf warning if an empty string is given, which someone # might do for example with usdview to open the app using the 'Free' camera # instead of the primary camera. def _ToSdfPath(inputArg): if not inputArg: return Sdf.Path.emptyPath return Sdf.Path(inputArg) argsParser.add_argument('--camera', '-cam', action='store', type=_ToSdfPath, default=defaultValue, help=helpText)
2,434
Python
40.982758
79
0.708299
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdAppUtils/colorArgs.py
# # 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. # def AddCmdlineArgs(argsParser, defaultValue='sRGB', altHelpText=''): """ Adds color-related command line arguments to argsParser. The resulting 'colorCorrectionMode' argument will be a Python string. """ helpText = altHelpText if not helpText: helpText = ( 'the color correction mode to use (default=%(default)s)') argsParser.add_argument('--colorCorrectionMode', '-color', action='store', type=str, default=defaultValue, choices=['disabled', 'sRGB', 'openColorIO'], help=helpText)
1,608
Python
40.256409
78
0.731343
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdAppUtils/complexityArgs.py
# # 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. # class RefinementComplexities(object): """ An enum-like container of standard complexity settings. """ class _RefinementComplexity(object): """ Class which represents a level of mesh refinement complexity. Each level has a string identifier, a display name, and a float complexity value. """ def __init__(self, compId, name, value): self._id = compId self._name = name self._value = value def __repr__(self): return self.id @property def id(self): return self._id @property def name(self): return self._name @property def value(self): return self._value LOW = _RefinementComplexity("low", "Low", 1.0) MEDIUM = _RefinementComplexity("medium", "Medium", 1.1) HIGH = _RefinementComplexity("high", "High", 1.2) VERY_HIGH = _RefinementComplexity("veryhigh", "Very High", 1.3) _ordered = (LOW, MEDIUM, HIGH, VERY_HIGH) @classmethod def ordered(cls): """ Get a tuple of all complexity levels in order. """ return cls._ordered @classmethod def fromId(cls, compId): """ Get a complexity from its identifier. """ matches = [comp for comp in cls._ordered if comp.id == compId] if len(matches) == 0: raise ValueError("No complexity with id '{}'".format(compId)) return matches[0] @classmethod def fromName(cls, name): """ Get a complexity from its display name. """ matches = [comp for comp in cls._ordered if comp.name == name] if len(matches) == 0: raise ValueError("No complexity with name '{}'".format(name)) return matches[0] @classmethod def next(cls, comp): """ Get the next highest level of complexity. If already at the highest level, return it. """ if comp not in cls._ordered: raise ValueError("Invalid complexity: {}".format(comp)) nextIndex = min( len(cls._ordered) - 1, cls._ordered.index(comp) + 1) return cls._ordered[nextIndex] @classmethod def prev(cls, comp): """ Get the next lowest level of complexity. If already at the lowest level, return it. """ if comp not in cls._ordered: raise ValueError("Invalid complexity: {}".format(comp)) prevIndex = max(0, cls._ordered.index(comp) - 1) return cls._ordered[prevIndex] def AddCmdlineArgs(argsParser, defaultValue=RefinementComplexities.LOW, altHelpText=''): """ Adds complexity-related command line arguments to argsParser. The resulting 'complexity' argument will be one of the standard RefinementComplexities. """ helpText = altHelpText if not helpText: helpText = ('level of refinement to use (default=%(default)s)') argsParser.add_argument('--complexity', '-c', action='store', type=RefinementComplexities.fromId, default=defaultValue, choices=[c for c in RefinementComplexities.ordered()], help=helpText)
4,297
Python
31.315789
77
0.62788
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdAppUtils/__init__.py
# # 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. # from pxr import Tf Tf.PreparePythonModule() del Tf from . import cameraArgs from . import colorArgs from . import complexityArgs from . import framesArgs from . import rendererArgs
1,242
Python
35.558822
74
0.769726
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdAppUtils/framesArgs.py
# # 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. # def _GetFloatStringPrecision(floatString): """ Gets the floating point precision specified by floatString. floatString can either contain an actual float in string form, or it can be a frame placeholder. We simply split the string on the dot (.) and return the length of the part after the dot, if any. If there is no dot in the string, a precision of zero is assumed. """ floatPrecision = 0 if not floatString: return floatPrecision floatStringParts = floatString.split('.') if len(floatStringParts) > 1: floatPrecision = len(floatStringParts[1]) return floatPrecision class FrameSpecIterator(object): """ A simple iterator object that handles splitting multiple comma-separated FrameSpecs into their equivalent UsdUtils.TimeCodeRanges, and then yields all of the time codes in all of those ranges sequentially when iterated. This object also stores the minimum floating point precision required to disambiguate any neighboring time codes in the FrameSpecs given. This can be used to validate that the frame placeholder in a frame format string has enough precision to uniquely identify every frame without collisions. """ from pxr import UsdUtils FRAMESPEC_SEPARATOR = ',' def __init__(self, frameSpec): from pxr import UsdUtils # Assume all frames are integral until we find a frame spec with a # non-integral stride. self._minFloatPrecision = 0 self._timeCodeRanges = [] subFrameSpecs = frameSpec.split(self.FRAMESPEC_SEPARATOR) for subFrameSpec in subFrameSpecs: timeCodeRange = UsdUtils.TimeCodeRange.CreateFromFrameSpec( subFrameSpec) self._timeCodeRanges.append(timeCodeRange) specParts = subFrameSpec.split( UsdUtils.TimeCodeRange.Tokens.StrideSeparator) if len(specParts) == 2: stride = specParts[1] stridePrecision = _GetFloatStringPrecision(stride) self._minFloatPrecision = max(self._minFloatPrecision, stridePrecision) def __iter__(self): for timeCodeRange in self._timeCodeRanges: for timeCode in timeCodeRange: yield timeCode @property def minFloatPrecision(self): return self._minFloatPrecision def AddCmdlineArgs(argsParser, altDefaultTimeHelpText='', altFramesHelpText=''): """ Adds frame-related command line arguments to argsParser. The resulting 'frames' argument will be an iterable of UsdTimeCodes. If no command-line arguments are given, 'frames' will be a list containing only Usd.TimeCode.EarliestTime(). If '--defaultTime' is given, 'frames' will be a list containing only Usd.TimeCode.Default(). Otherwise, '--frames' must be given a FrameSpec (or a comma-separated list of multiple FrameSpecs), and 'frames' will be a FrameSpecIterator which when iterated will yield the time codes specified by the FrameSpec(s). """ timeGroup = argsParser.add_mutually_exclusive_group() helpText = altDefaultTimeHelpText if not helpText: helpText = ( 'explicitly operate at the Default time code (the default ' 'behavior is to operate at the Earliest time code)') timeGroup.add_argument('--defaultTime', '-d', action='store_true', dest='defaultTime', help=helpText) helpText = altFramesHelpText if not helpText: helpText = ( 'specify FrameSpec(s) of the time codes to operate on - A ' 'FrameSpec consists of up to three floating point values for the ' 'start time code, end time code, and stride of a time code range. ' 'A single time code can be specified, or a start and end time ' 'code can be specified separated by a colon (:). When a start ' 'and end time code are specified, the stride may optionally be ' 'specified as well, separating it from the start and end time ' 'codes with (x). Multiple FrameSpecs can be combined as a ' 'comma-separated list. The following are examples of valid ' 'FrameSpecs: 123 - 101:105 - 105:101 - 101:109x2 - 101:110x2 - ' '101:104x0.5') timeGroup.add_argument('--frames', '-f', action='store', type=str, dest='frames', metavar='FRAMESPEC[,FRAMESPEC...]', help=helpText) def GetFramePlaceholder(frameFormat): """ Gets the frame placeholder in a frame format string. This function expects the input frameFormat string to contain exactly one frame placeholder. The placeholder must be composed of exactly one or two groups of one or more hashes ('#'), and if there are two, they must be separated by a dot ('.'). If no such placeholder exists in the frame format string, None is returned. """ if not frameFormat: return None import re PLACEHOLDER_PATTERN = r'^[^#]*(?P<placeholder>#+(\.#+)?)[^#]*$' matches = re.search(PLACEHOLDER_PATTERN, frameFormat) if not matches: return None placeholder = matches.group(1) return placeholder def ConvertFramePlaceholderToFloatSpec(frameFormat): """ Converts the frame placeholder in a frame format string to a Python {}-style float specifier for use with string.format(). This function expects the input frameFormat string to contain exactly one frame placeholder. The placeholder must be composed of exactly one or two groups of one or more hashes ('#'), and if there are two, they must be separated by a dot ('.'). The hashes after the dot indicate the floating point precision to use in the frame numbers inserted into the frame format string. If there is only a single group of hashes, the precision is zero and the inserted frame numbers will be integer values. The overall width of the frame placeholder specifies the minimum width to use when inserting frame numbers into the frame format string. Formatted frame numbers smaller than the minimum width will be zero-padded on the left until they reach the minimum width. If the input frame format string does not contain exactly one frame placeholder, this function will return None, indicating that this frame format string cannot be used when operating with a frame range. """ placeholder = GetFramePlaceholder(frameFormat) if not placeholder: return None # Frame numbers are zero-padded up to the field width. specFill = 0 # The full width of the placeholder determines the minimum field width. specWidth = len(placeholder) # The hashes after the dot, if any, determine the precision. If there are # none, integer frame numbers are used. specPrecision = 0 parts = placeholder.split('.') if len(parts) > 1: specPrecision = len(parts[1]) floatSpec = ('{frame:' + '{fill}{width}.{precision}f'.format(fill=specFill, width=specWidth, precision=specPrecision) + '}') return frameFormat.replace(placeholder, floatSpec) def ValidateCmdlineArgs(argsParser, args, frameFormatArgName=None): """ Validates the frame-related arguments in args parsed by argsParser. This populates 'frames' with the appropriate iterable based on the command-line arguments given, so it should be called after parse_args() is called on argsParser. When working with frame ranges, particularly when writing out images for each frame, it is common to also have command-line arguments such as an output image path for specifying where those images should be written. The value given to this argument should include a frame placeholder so that it can have the appropriate time code inserted. If the application has such an argument, its name can be specified using frameFormatArgName. That arg will be checked to ensure that it has a frame placeholder and it will be given a value with that placeholder replaced with a Python format specifier so that the value is ready to use with the str.format(frame=<timeCode>) method. If a frame range is not provided as an argument, then it is an error to include a frame placeholder in the frame format string. """ from pxr import Usd framePlaceholder = None frameFormat = None if frameFormatArgName is not None: frameFormat = getattr(args, frameFormatArgName) framePlaceholder = GetFramePlaceholder(frameFormat) frameFormat = ConvertFramePlaceholderToFloatSpec(frameFormat) if args.frames: args.frames = FrameSpecIterator(args.frames) if frameFormatArgName is not None: if not frameFormat: argsParser.error('%s must contain exactly one frame number ' 'placeholder of the form "###"" or "###.###". Note that ' 'the number of hash marks is variable in each group.' % frameFormatArgName) placeholderPrecision = _GetFloatStringPrecision(framePlaceholder) if placeholderPrecision < args.frames.minFloatPrecision: argsParser.error('The given FrameSpecs require a minimum ' 'floating point precision of %d, but the frame ' 'placeholder in %s only specified a precision of %d (%s). ' 'The precision of the frame placeholder must be equal to ' 'or greater than %d.' % (args.frames.minFloatPrecision, frameFormatArgName, placeholderPrecision, framePlaceholder,args.frames.minFloatPrecision)) setattr(args, frameFormatArgName, frameFormat) else: if frameFormat: argsParser.error('%s cannot contain a frame number placeholder ' 'when not operating on a frame range.' % frameFormatArgName) if args.defaultTime: args.frames = [Usd.TimeCode.Default()] else: args.frames = [Usd.TimeCode.EarliestTime()] return args
11,231
Python
40.6
80
0.685691
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdAppUtils/rendererArgs.py
# # 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. # def GetAllPluginArguments(): """ Returns argument strings for all the renderer plugins available. """ from pxr import UsdImagingGL return [ UsdImagingGL.Engine.GetRendererDisplayName(pluginId) for pluginId in UsdImagingGL.Engine.GetRendererPlugins() ] def GetPluginIdFromArgument(argumentString): """ Returns plugin id, if found, for the passed in argument string. Valid argument strings are returned by GetAllPluginArguments(). """ from pxr import UsdImagingGL for p in UsdImagingGL.Engine.GetRendererPlugins(): if argumentString == UsdImagingGL.Engine.GetRendererDisplayName(p): return p return None def AddCmdlineArgs(argsParser, altHelpText=''): """ Adds Hydra renderer-related command line arguments to argsParser. The resulting 'rendererPlugin' argument will be a _RendererPlugin instance representing one of the available Hydra renderer plugins. """ from pxr import UsdImagingGL helpText = altHelpText if not helpText: helpText = ( 'Hydra renderer plugin to use when generating images') renderers = GetAllPluginArguments() argsParser.add_argument('--renderer', '-r', action='store', dest='rendererPlugin', choices=renderers, help=helpText)
2,386
Python
33.594202
78
0.726739
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdAppUtils/__DOC.py
def Execute(result): result["FrameRecorder"].__doc__ = """ A utility class for recording images of USD stages. UsdAppUtilsFrameRecorder uses Hydra to produce recorded images of a USD stage looking through a particular UsdGeomCamera on that stage at a particular UsdTimeCode. The images generated will be effectively the same as what you would see in the viewer in usdview. Note that it is assumed that an OpenGL context has already been setup. """ result["FrameRecorder"].__init__.func_doc = """__init__() """ result["FrameRecorder"].GetCurrentRendererId.func_doc = """GetCurrentRendererId() -> str Gets the ID of the Hydra renderer plugin that will be used for recording. """ result["FrameRecorder"].SetRendererPlugin.func_doc = """SetRendererPlugin(id) -> bool Sets the Hydra renderer plugin to be used for recording. Parameters ---------- id : str """ result["FrameRecorder"].SetImageWidth.func_doc = """SetImageWidth(imageWidth) -> None Sets the width of the recorded image. The height of the recorded image will be computed using this value and the aspect ratio of the camera used for recording. The default image width is 960 pixels. Parameters ---------- imageWidth : int """ result["FrameRecorder"].SetComplexity.func_doc = """SetComplexity(complexity) -> None Sets the level of refinement complexity. The default complexity is"low"(1.0). Parameters ---------- complexity : float """ result["FrameRecorder"].SetColorCorrectionMode.func_doc = """SetColorCorrectionMode(colorCorrectionMode) -> None Sets the color correction mode to be used for recording. By default, color correction is disabled. Parameters ---------- colorCorrectionMode : str """ result["FrameRecorder"].SetIncludedPurposes.func_doc = """SetIncludedPurposes(purposes) -> None Sets the UsdGeomImageable purposes to be used for rendering. We will **always** include"default"purpose, and by default, we will also include UsdGeomTokens->proxy. Use this method to explicitly enumerate an alternate set of purposes to be included along with"default". Parameters ---------- purposes : list[TfToken] """ result["FrameRecorder"].Record.func_doc = """Record(stage, usdCamera, timeCode, outputImagePath) -> bool Records an image and writes the result to ``outputImagePath`` . The recorded image will represent the view from ``usdCamera`` looking at the imageable prims on USD stage ``stage`` at time ``timeCode`` . If ``usdCamera`` is not a valid camera, a camera will be computed to automatically frame the stage geometry. Returns true if the image was generated and written successfully, or false otherwise. Parameters ---------- stage : Stage usdCamera : Camera timeCode : TimeCode outputImagePath : str """
2,765
Python
19.954545
115
0.734177
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdMtlx/__init__.py
# # Copyright 2018 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. # from pxr import Tf Tf.PreparePythonModule() del Tf
1,110
Python
40.148147
74
0.766667
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdMtlx/__DOC.py
def Execute(result): pass
29
Python
13.999993
20
0.689655
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdResolverExample/__init__.py
# # Copyright 2021 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. # from pxr import Tf Tf.PreparePythonModule() del Tf
1,110
Python
40.148147
74
0.766667
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdResolverExample/__DOC.py
def Execute(result): pass
29
Python
13.999993
20
0.689655
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdDraco/__init__.py
# # 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. # from pxr import Tf Tf.PreparePythonModule() del Tf
1,110
Python
40.148147
74
0.766667
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdDraco/__DOC.py
def Execute(result): pass
29
Python
13.999993
20
0.689655
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdAbc/__init__.py
# # 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. # from pxr import Tf Tf.PreparePythonModule() del Tf
1,110
Python
40.148147
74
0.766667
omniverse-code/kit/exts/omni.usd.libs/pxr/UsdAbc/__DOC.py
def Execute(result): pass
29
Python
13.999993
20
0.689655
omniverse-code/kit/exts/omni.usd.libs/omni/usd_libs/package.py
import functools import os import typing import omni.kit.app import omni.log def _simple_yaml_load(file_path): # avoid bringing in a new dependency on PyYaml to parse a simple yaml file d = {} with open(file_path, "r", encoding="utf-8") as f: for line in f.readlines(): if ":" not in line: continue key, value = line.split(":", maxsplit=1) value = value.strip() if value.startswith("b'"): value = value[2:-1] d[key.strip()] = value return d def get_info_path() -> str: app = omni.kit.app.get_app_interface() manager = app.get_extension_manager() # get the usd build information that is currently being built against usd_libs_ext_id = manager.get_enabled_extension_id("omni.usd.libs") usd_libs_path = manager.get_extension_path(usd_libs_ext_id) return os.path.join(usd_libs_path, "PACKAGE-INFO.yaml") @functools.lru_cache() def get_info_data() -> typing.Optional[typing.Dict[str, object]]: # get the current usd build information package_info_path = get_info_path() try: yaml_data = _simple_yaml_load(package_info_path) except FileNotFoundError: omni.log.warn(f"{package_info_path} can not be found") except Exception as err: omni.log.warn(f"{package_info_path} can not be loaded: {err}") else: return yaml_data return None def get_name() -> str: package_info_data = get_info_data() return package_info_data.get("Package", "") def get_version() -> str: # get the current usd build information package_info_data = get_info_data() return package_info_data.get("Version", "")
1,707
Python
27
78
0.628588
omniverse-code/kit/exts/omni.usd.libs/omni/usd_libs/__init__.py
from .package import get_info_path, get_info_data, get_name, get_version
72
Python
71.999928
72
0.777778
omniverse-code/kit/exts/omni.kit.widget.nucleus_info/omni/kit/widget/nucleus_info/extension.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ext from .service_discovery import ServiceDiscovery g_singleton = None # Search Service is register name, it actually service name is NGSearch in server side # See the start up in omni.kit.search.service REGISTERED_NAME_TO_SERVCIE = { 'Search Service': 'NGSearch', } class NucleusInfoExtension(omni.ext.IExt): def __init__(self): super().__init__() self._discovery = None def on_startup(self, ext_id): self._discovery = ServiceDiscovery() # Save away this instance as singleton global g_singleton g_singleton = self def on_shutdown(self): if self._discovery: self._discovery.destory() global g_singleton g_singleton = None def is_service_available(self, service: str, nucleus_url: str): if not self._discovery: return False if service in REGISTERED_NAME_TO_SERVCIE: return self._discovery.is_service_supported_for_nucleus(nucleus_url, REGISTERED_NAME_TO_SERVCIE[service]) else: return self._discovery.is_service_supported_for_nucleus(nucleus_url, service) def get_nucleus_services(self, nucleus_url: str): if not self._discovery: return None return self._discovery.get_nucleus_services(nucleus_url) async def get_nucleus_services_async(self, nucleus_url: str): if not self._discovery: return None return await self._discovery.get_nucleus_services_async(nucleus_url) def get_instance(): return g_singleton
1,989
Python
32.728813
117
0.689794
omniverse-code/kit/exts/omni.kit.widget.nucleus_info/omni/kit/widget/nucleus_info/__init__.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import NucleusInfoExtension, get_instance def get_nucleus_info() -> NucleusInfoExtension: """Returns :class:`NucleusInfoExtension` interface""" return get_instance()
626
Python
38.187498
76
0.790735
omniverse-code/kit/exts/omni.kit.widget.nucleus_info/omni/kit/widget/nucleus_info/service_discovery.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ext import asyncio import omni.client from omni.kit.async_engine import run_coroutine class ServiceDiscovery(): def __init__(self): self._nucleus_services = {} self._connection_status_sub = omni.client.register_connection_status_callback(self._server_status_changed) def destory(self): self._connection_status_sub = None def _server_status_changed(self, url: str, status: omni.client.ConnectionStatus) -> None: """Collect signed in server's service information based upon server status changed.""" if status == omni.client.ConnectionStatus.CONNECTED: # must run on main thread as this one does not have async loop... run_coroutine(self.get_nucleus_services_async(url)) def _extract_server_from_url(self, url): client_url = omni.client.break_url(url) server_url = omni.client.make_url(scheme=client_url.scheme, host=client_url.host, port=client_url.port) return server_url def is_service_supported_for_nucleus(self, nucleus_url: str, service_name: str): if not nucleus_url: return False nucleus_url = self._extract_server_from_url(nucleus_url) if nucleus_url in self._nucleus_services: server_services =self._nucleus_services[nucleus_url] for service in server_services: if service.service_interface.name.startswith(service_name): return True return False else: self.get_nucleus_services(nucleus_url) scheme=omni.client.break_url(nucleus_url).scheme if scheme and scheme.startswith("omniverse"): return True return False def get_nucleus_services(self, nucleus_url: str): if not nucleus_url: return None nucleus_url = self._extract_server_from_url(nucleus_url) if nucleus_url in self._nucleus_services: return self._nucleus_services[nucleus_url] asyncio.ensure_future(self.get_nucleus_services_async(nucleus_url)) return None async def get_nucleus_services_async(self, nucleus_url: str): try: from idl.connection.transport.ws import WebSocketClient from omni.discovery.client import DiscoverySearch if not nucleus_url: return None nucleus_url = self._extract_server_from_url(nucleus_url) if nucleus_url in self._nucleus_services: return self._nucleus_services[nucleus_url] nucleus_services = [] client_url = omni.client.break_url(nucleus_url) transport = WebSocketClient(uri=f"ws://{client_url.host}:3333") discovery = DiscoverySearch(transport) async with discovery: async for service in discovery.find_all(): nucleus_services.append(service) self._nucleus_services[nucleus_url] = nucleus_services return self._nucleus_services[nucleus_url] except: return None
3,512
Python
40.821428
114
0.654613
omniverse-code/kit/exts/omni.kit.widget.nucleus_info/omni/kit/widget/nucleus_info/ui.py
# Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from typing import Callable from collections import namedtuple from omni.kit.window.popup_dialog import PopupDialog import omni.ui as ui class NucleusAboutDialog(PopupDialog): """Dialog to show the omniverse server info.""" FieldDef = namedtuple("AboutDialogFieldDef", "name version") _services_names = ["Discovery", "Auth", "Tagging", "NGSearch", "Search"] def __init__( self, nucleus_info, nucleus_services, ): """ Args: nucleus_info ([ServerInfo]): nucleus server's information. nucleus_services ([ServicesData]): nucleus server's services Note: AboutDialog.FieldDef: A namedtuple of (name, version) for describing the service's info, """ super().__init__( width=400, title="About", ok_handler=lambda self: self.hide(), ok_label="Close", modal=True, ) self._nucleus_info = nucleus_info self._nucleus_services = self._parse_services(nucleus_services) self._build_ui() def _parse_services(self, nucleus_services): parse_res = set() if nucleus_services: for service in nucleus_services: parse_res.add( NucleusAboutDialog.FieldDef( service.service_interface.name, service.meta.get('version','unknown') ) ) return parse_res def _build_ui(self) -> None: with self._window.frame: with ui.ZStack(spacing=6): ui.Rectangle(style_type_name_override="Background") with ui.VStack(style_type_name_override="Dialog", spacing=6): ui.Spacer(height=25) with ui.HStack(style_type_name_override="Dialog", spacing=6, height=60): ui.Spacer(width=15) ui.Image( "resources/glyphs/omniverse_logo.svg", width=50, height=50, alignment=ui.Alignment.CENTER ) ui.Spacer(width=5) with ui.VStack(style_type_name_override="Dialog"): ui.Spacer(height=10) ui.Label("Nucleus", style={"font_size": 20}) ui.Label(self._nucleus_info.version) ui.Spacer(height=5) with ui.HStack(style_type_name_override="Dialog"): ui.Spacer(width=15) with ui.VStack(style_type_name_override="Dialog"): ui.Label("Services", style={"font_size": 20}) for service_name in NucleusAboutDialog._services_names: self._build_service_item(service_name) ui.Label("Features", style={"font_size": 20}) self._build_info_item(True, "Versioning") self._build_info_item(self._nucleus_info.checkpoints_enabled, "Atomic checkpoints") self._build_info_item(self._nucleus_info.omniojects_enabled, "Omni-objects V2") self._build_ok_cancel_buttons(disable_cancel_button=True) def _build_service_item(self, service_name: str): supported = False version = "unknown" for service in self._nucleus_services: if service.name.startswith(service_name): supported = True version = service.version break self._build_info_item(supported, service_name + " " + version) def _build_info_item(self, supported: bool, info: str): with ui.HStack(style_type_name_override="Dialog", spacing=6): ui.Spacer(width=5) image_url = "resources/icons/Ok_64.png" if supported else "resources/icons/Cancel_64.png" ui.Image(image_url, width=20, height=20, alignment=ui.Alignment.CENTER) ui.Label(info) ui.Spacer() def destroy(self) -> None: """Destructor.""" self._window = None
4,739
Python
42.888888
111
0.546529
omniverse-code/kit/exts/omni.kit.widget.nucleus_info/omni/kit/widget/nucleus_info/tests/test_discovery.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## from functools import partial from unittest.mock import patch from omni.kit.test.async_unittest import AsyncTestCase from ..service_discovery import ServiceDiscovery from ..ui import NucleusAboutDialog from .. import get_nucleus_info class MockServiceInterface: def __init__(self, name): self.name = name class MockService: def __init__(self, name): self.service_interface = MockServiceInterface(name) self.meta = {"version": "test_version"} class MockInfo: def __init__(self): self.version = "test_nucleus_version" self.checkpoints_enabled = True self.omniojects_enabled = True class TestDiscovery(AsyncTestCase): # Before running each test async def setUp(self): self._mock_service_content= [MockService("NGSearch"),MockService("Object"),MockService("Search")] self._mock_service_localhost= [MockService("Object"),MockService("Otherservice")] # After running each test async def tearDown(self): pass async def _mock_get_nucleus_services_async(self, discovery, url: str): if url == "omniverse://content": discovery._nucleus_services["omniverse://content"] = self._mock_service_content return discovery._nucleus_services["omniverse://content"] if url == "omniverse://localhost": discovery._nucleus_services["omniverse://localhost"] = self._mock_service_localhost return discovery._nucleus_services["omniverse://localhost"] async def test_service_discovery(self): discovery = ServiceDiscovery() test_unknow = await discovery.get_nucleus_services_async("unknow://unknow") self.assertIsNone(test_unknow) with patch.object(discovery, "get_nucleus_services_async", side_effect=partial(self._mock_get_nucleus_services_async,discovery)): content_services = await discovery.get_nucleus_services_async("omniverse://content") await discovery.get_nucleus_services_async("omniverse://localhost") self.assertIsNone(discovery.get_nucleus_services("unknow://unknow")) self.assertTrue(discovery.is_service_supported_for_nucleus("omniverse://content", "NGSearch")) self.assertFalse(discovery.is_service_supported_for_nucleus("omniverse://localhost", "NGSearch")) self.assertFalse(discovery.is_service_supported_for_nucleus("l://other", "other")) self.assertTrue(discovery.is_service_supported_for_nucleus("omniverse://localhost", "Otherservice")) self.assertEqual(discovery.get_nucleus_services("omniverse://content"), self._mock_service_content) self.assertEqual(discovery.get_nucleus_services("omniverse://localhost"), self._mock_service_localhost) dialog = NucleusAboutDialog(MockInfo(), content_services) dialog.show() self.assertTrue(dialog._window.visible) dialog.hide() self.assertFalse(dialog._window.visible) dialog.destroy() discovery.destory() async def test_interface(self): inst = get_nucleus_info() test_unknow = await inst.get_nucleus_services_async("unknow://unknow") self.assertIsNone(test_unknow) discovery = ServiceDiscovery() with patch.object(discovery, "get_nucleus_services_async", side_effect=partial(self._mock_get_nucleus_services_async,discovery)),\ patch.object(discovery, "get_nucleus_services", side_effect=partial(self._mock_get_nucleus_services_async,discovery)),\ patch.object(inst, "_discovery", side_effect=discovery): await discovery.get_nucleus_services_async("omniverse://content") await discovery.get_nucleus_services_async("omniverse://localhost") self.assertTrue(inst.is_service_available("omniverse://content", "NGSearch")) self.assertTrue(inst.is_service_available("omniverse://localhost", "Otherservice")) discovery.destory() inst._discovery = None self.assertIsNone(inst.get_nucleus_services("omniverse://content")) self.assertIsNone(inst.get_nucleus_services("omniverse://localhost"))
4,619
Python
49.76923
139
0.68976
omniverse-code/kit/exts/omni.kit.widget.nucleus_info/omni/kit/widget/nucleus_info/tests/__init__.py
from .test_discovery import *
30
Python
14.499993
29
0.766667
omniverse-code/kit/exts/omni.kit.widget.nucleus_info/docs/index.rst
omni.kit.widget.nucleus_info ############################# .. toctree:: :maxdepth: 1 CHANGELOG nucleus info Widgets ========================== .. automodule:: omni.kit.widget.nucleus_info :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :show-inheritance:
298
reStructuredText
17.687499
44
0.553691
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/event.py
import carb.events HOTKEY_REGISTER_EVENT: int = carb.events.type_from_string("omni.kit.hotkeys.core.HOTKEY_REGISTER") HOTKEY_DEREGISTER_EVENT: int = carb.events.type_from_string("omni.kit.hotkeys.core.HOTKEY_DEREGISTER") HOTKEY_CHANGED_EVENT: int = carb.events.type_from_string("omni.kit.hotkeys.core.HOTKEY_CHANGED")
319
Python
52.333325
102
0.789969
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/registry.py
__all__ = ["HotkeyRegistry"] from typing import List, Optional, Union, Dict, Tuple import carb import carb.settings import omni.kit.app from .hotkey import Hotkey from .key_combination import KeyCombination from .filter import HotkeyFilter from .storage import HotkeyStorage from .event import HOTKEY_REGISTER_EVENT, HOTKEY_DEREGISTER_EVENT, HOTKEY_CHANGED_EVENT from .keyboard_layout import KeyboardLayoutDelegate # Extension who register hotkey for menu items HOTKEY_EXT_ID_MENU_UTILS = "omni.kit.menu.utils" SETTING_DEFAULT_KEYBOARD_LAYOUT = "/exts/omni.kit.hotkeys.core/default_keyboard_layout" class HotkeyRegistry: """ Registry of hotkeys. """ class Result: OK = "OK" ERROR_NO_ACTION = "No action defined" ERROR_ACTION_DUPLICATED = "Duplicated action definition" ERROR_KEY_INVALID = "Invaid key definition" ERROR_KEY_DUPLICATED = "Duplicated key definition" def __init__(self): """ Define hotkey registry object. """ self._hotkeys: List[Hotkey] = [] self._hotkeys_by_key_and_context: Dict[KeyCombination, Dict[str, Hotkey]] = {} self._hotkeys_by_key_and_window: Dict[KeyCombination, Dict[str, Hotkey]] = {} self._global_hotkeys_by_key: Dict[KeyCombination, Hotkey] = {} self._event_stream = omni.kit.app.get_app().get_message_bus_event_stream() self.__hotkey_storage = HotkeyStorage() self.__default_key_combinations: Dict[str, str] = {} self.__default_filters: Dict[str, HotkeyFilter] = {} self.__last_error = HotkeyRegistry.Result.OK self.__settings = carb.settings.get_settings() keyboard_layout = self.__settings.get("/persistent" + SETTING_DEFAULT_KEYBOARD_LAYOUT) if keyboard_layout is None: keyboard_layout = self.__settings.get(SETTING_DEFAULT_KEYBOARD_LAYOUT) self.__keyboard_layout = KeyboardLayoutDelegate.get_instance(keyboard_layout) # Here we only append user hotkeys. # For system hotkeys which is changed, update when registering. self.__append_user_hotkeys() @property def last_error(self) -> "HotkeyRegistry.Result": """ Error code for last hotkey command. """ return self.__last_error @property def keyboard_layout(self) -> Optional[KeyboardLayoutDelegate]: """ Current keyboard layout object in using. """ return self.__keyboard_layout def switch_layout(self, layout_name: str) -> None: """ Change keyboard layout. Args: layout_name (str): Name of keyboard layout to use. """ def __get_layout_keys() -> List[Hotkey]: # Ignore user hotkeys and modified hotkeys return [hotkey for hotkey in self._hotkeys if not self.is_user_hotkey(hotkey) and self.get_hotkey_default(hotkey)[0] == hotkey.key_combination.id] layout = KeyboardLayoutDelegate.get_instance(layout_name) if not layout or layout == self.__keyboard_layout: return carb.log_info(f"Change keyboard layout to {layout_name}") refresh_menu = False # Restore hotkey key combination to default for hotkey in __get_layout_keys(): # Restore key combination if self.__keyboard_layout: restore_key_combination = self.__keyboard_layout.restore_key(hotkey.key_combination) if restore_key_combination: self.__edit_hotkey_internal(hotkey, restore_key_combination, filter=hotkey.filter) # Map to new key combination new_key_combination = layout.map_key(hotkey.key_combination) if new_key_combination: self.__edit_hotkey_internal(hotkey, new_key_combination, filter=hotkey.filter) self.__default_key_combinations[hotkey.id] = new_key_combination.id if (restore_key_combination or new_key_combination) and hotkey.hotkey_ext_id == HOTKEY_EXT_ID_MENU_UTILS: refresh_menu = True self.__keyboard_layout = layout self.__settings.set("/persistent" + SETTING_DEFAULT_KEYBOARD_LAYOUT, layout_name) if refresh_menu: # Refresh menu items for new hotkey text try: import omni.kit.menu.utils # pylint: disable=redefined-outer-name omni.kit.menu.utils.rebuild_menus() except ImportError: pass def register_hotkey(self, *args, **kwargs) -> Optional[Hotkey]: """ Register hotkey by hotkey object or arguments. Args could be: .. code:: python register_hotkey(hotkey: Hotkey) or .. code:: python register_hotkey( hotkey_ext_id: str, key: Union[str, KeyCombination], action_ext_id: str, action_id: str, filter: Optional[HotkeyFilter] = None ) Returns: Created hotkey object if register succeeded. Otherwise return None. """ return self._register_hotkey_obj(args[0]) if len(args) == 1 else self._register_hotkey_args(*args, **kwargs) def edit_hotkey( self, hotkey: Hotkey, key: Union[str, KeyCombination], filter: Optional[HotkeyFilter] # noqa: A002 # pylint: disable=redefined-builtin ) -> "HotkeyRegistry.Result": """ Change key combination of hotkey object. Args: hotkey (Hotkey): Hotkey object to change. key (Union[str, KeyCombination]): New key combination. filter (Optional[HotkeyFiler]): New filter. Returns: Result code. """ key_combination = KeyCombination(key) if isinstance(key, str) else key self.__last_error = self.verify_hotkey(hotkey, key_combination=key_combination, hotkey_filter=filter) if self.__last_error != HotkeyRegistry.Result.OK: return self.__last_error self.__edit_hotkey_internal(hotkey, key_combination, filter) self.__hotkey_storage.edit_hotkey(hotkey) if hotkey.hotkey_ext_id == HOTKEY_EXT_ID_MENU_UTILS: # Refresh menu items for new hotkey text try: import omni.kit.menu.utils # pylint: disable=redefined-outer-name omni.kit.menu.utils.rebuild_menus() except ImportError: pass return HotkeyRegistry.Result.OK def __edit_hotkey_internal( self, hotkey: Hotkey, key_combination: KeyCombination, filter: Optional[HotkeyFilter] # noqa: A002 # pylint: disable=redefined-builtin ) -> None: self.__deregister_hotkey_maps(hotkey) hotkey.key_combination = key_combination hotkey.filter = filter self.__register_hotkey_maps(hotkey) self._send_event(HOTKEY_CHANGED_EVENT, hotkey) def deregister_hotkey(self, *args, **kwargs) -> bool: """ Deregister hotkey by hotkey object or arguments. Args could be: .. code:: python deregister_hotkey(hotkey: Hotkey) or .. code:: python deregister_hotkey( hotkey_ext_id: str, key: Union[str, KeyCombination], filter: Optional[HotkeyFilter] = None ) Returns: True if hotkey found. Otherwise return False. """ return self._deregister_hotkey_obj(args[0]) if len(args) == 1 else self._deregister_hotkey_args(*args, **kwargs) def deregister_hotkeys(self, hotkey_ext_id: str, key: Union[str, KeyCombination]) -> None: """ Deregister hotkeys registered from a special extension with speicial key combination. Args: hotkey_ext_id (str): Extension id that hotkeys belongs to. key (Union[str, KeyCombination]): Key combination. """ discovered_hotkeys = self.get_hotkeys(hotkey_ext_id, key) for hotkey in discovered_hotkeys: self._deregister_hotkey_obj(hotkey) def deregister_all_hotkeys_for_extension(self, hotkey_ext_id: Optional[str]) -> None: """ Deregister hotkeys registered from a special extension. Args: hotkey_ext_id (Optional[str]): Extension id that hotkeys belongs to. If None, discover all global hotkeys """ discovered_hotkeys = self.get_all_hotkeys_for_extension(hotkey_ext_id) for hotkey in discovered_hotkeys: self._deregister_hotkey_obj(hotkey) def deregister_all_hotkeys_for_filter(self, filter: HotkeyFilter) -> None: # noqa: A002 # pylint: disable=redefined-builtin """ Deregister hotkeys registered with speicial filter. Args: filter (HotkeyFilter): Hotkey HotkeyFilter. """ discovered_hotkeys = self.get_all_hotkeys_for_filter(filter) for hotkey in discovered_hotkeys: self._deregister_hotkey_obj(hotkey) def get_hotkey(self, hotkey_ext_id: str, key: Union[str, KeyCombination], filter: Optional[HotkeyFilter] = None) -> Optional[Hotkey]: # noqa: A002 # pylint: disable=redefined-builtin """ Discover a registered hotkey. Args: hotkey_ext_id (str): Extension id which owns the hotkey. key (Union[str, KeyCombination]): Key combination. Keyword Args: filter (Optional[HotkeyFilter]): Hotkey filter. Default None Returns: Hotkey object if discovered. Otherwise None. """ key_combination = KeyCombination(key) if isinstance(key, str) else key for hotkey in self._hotkeys: if hotkey.hotkey_ext_id == hotkey_ext_id and hotkey.key_combination == key_combination and hotkey.filter == filter: return hotkey return None def get_hotkey_for_trigger(self, key: Union[str, KeyCombination], context: Optional[str] = None, window: Optional[str] = None) -> Optional[Hotkey]: """ Discover hotkey for trigger from key combination and filter. Args: key (Union[str, KeyCombination]): Key combination. Keyword Args: context (str): Context assigned to Hotkey window (str): Window assigned to Hotkey Returns: Hotkey object if discovered. Otherwise None. """ key_combination = KeyCombination(key) if isinstance(key, str) else key if context: return ( self._hotkeys_by_key_and_context[key_combination][context] if key_combination in self._hotkeys_by_key_and_context and context in self._hotkeys_by_key_and_context[key_combination] else None ) if window: return ( self._hotkeys_by_key_and_window[key_combination][window] if key_combination in self._hotkeys_by_key_and_window and window in self._hotkeys_by_key_and_window[key_combination] else None ) return self._global_hotkeys_by_key[key_combination] if key_combination in self._global_hotkeys_by_key else None def get_hotkey_for_filter(self, key: Union[str, KeyCombination], filter: HotkeyFilter) -> Optional[Hotkey]: # noqa: A002 # pylint: disable=redefined-builtin """ Discover hotkey registered with special key combination and filter Args: key (Union[str, KeyCombination]): Key combination. filter (HotkeyFilter): Hotkey filter. Returns: First discovered hotkey. None if nothing found. """ if filter: if filter.context: return self.get_hotkey_for_trigger(key, context=filter.context) if filter.windows: for window in filter.windows: found = self.get_hotkey_for_trigger(key, window=window) if found: return found return None return self.get_hotkey_for_trigger(key) def get_hotkeys(self, hotkey_ext_id: str, key: Union[str, KeyCombination]) -> List[Hotkey]: """ Discover hotkeys registered from a special extension with special key combination. Args: hotkey_ext_id (str): Extension id that hotkeys belongs to. key (Union[str, KeyCombination]): Key combination. Returns: List of discovered hotkeys. """ key_combination = KeyCombination(key) if isinstance(key, str) else key return [hotkey for hotkey in self._hotkeys if hotkey.hotkey_ext_id == hotkey_ext_id and hotkey.key_combination == key_combination] def get_all_hotkeys(self) -> List[Hotkey]: """ Discover all registered hotkeys. Returns: List of all registered hotkeys. """ return self._hotkeys def get_all_hotkeys_for_extension(self, hotkey_ext_id: Optional[str]) -> List[Hotkey]: """ Discover hotkeys registered from a special extension. Args: hotkey_ext_id (Optional[str]): Extension id that hotkeys belongs to. If None, discover all global hotkeys Returns: List of discovered hotkeys. """ return [hotkey for hotkey in self._hotkeys if hotkey.filter is None] if hotkey_ext_id is None \ else [hotkey for hotkey in self._hotkeys if hotkey.hotkey_ext_id == hotkey_ext_id] def get_all_hotkeys_for_key(self, key: Union[str, KeyCombination]) -> List[Hotkey]: """ Discover hotkeys registered from a special key. Args: key (Union[str, KeyCombination]): Key combination. Returns: List of discovered hotkeys. """ key_combination = KeyCombination(key) if isinstance(key, str) else key return [hotkey for hotkey in self._hotkeys if hotkey.key_combination == key_combination] def get_all_hotkeys_for_filter(self, filter: HotkeyFilter) -> List[Hotkey]: # noqa: A002 # pylint: disable=redefined-builtin """ Discover hotkeys registered with speicial filter. Args: filter (HotkeyFilter): Hotkey HotkeyFilter. Returns: List of discovered hotkeys. """ return [hotkey for hotkey in self._hotkeys if hotkey.filter == filter] def _register_hotkey_obj(self, hotkey: Hotkey) -> Optional[Hotkey]: self.__last_error = self.has_duplicated_hotkey(hotkey) if self.__last_error != HotkeyRegistry.Result.OK: carb.log_warn(f"[Hotkey] Cannot register {hotkey}, error code: {self.__last_error}") return None # Record default key binding and filter default_key_combination = hotkey.key_combination default_filter = hotkey.filter # Update key binding from keyboard layout if self.__keyboard_layout and not self.is_user_hotkey(hotkey): new_key_combination = self.__keyboard_layout.map_key(hotkey.key_combination) if new_key_combination: hotkey.key_combination = new_key_combination default_key_combination = new_key_combination # Update key binding/filter definition from storage user_hotkey = self.__hotkey_storage.get_hotkey(hotkey) if user_hotkey: if hotkey.key_combination != user_hotkey.key_combination: carb.log_info(f"[Hotkey] Replace {hotkey.action_text}.{hotkey.key_text} with {user_hotkey.key_text}") hotkey.key_combination = user_hotkey.key_combination if hotkey.filter != user_hotkey.filter: carb.log_info(f"[Hotkey] Replace {hotkey.action_text}.{hotkey.filter_text} with {user_hotkey.filter_text}") hotkey.filter = user_hotkey.filter self.__last_error = self.verify_hotkey(hotkey) if self.__last_error != HotkeyRegistry.Result.OK: carb.log_warn(f"[Hotkey] Cannot register {hotkey}, error code: {self.__last_error}") return None # Append hotkey self._hotkeys.append(hotkey) self.__default_key_combinations[hotkey.id] = default_key_combination.id self.__default_filters[hotkey.id] = default_filter self.__register_hotkey_maps(hotkey) # Save to storage self.__hotkey_storage.register_user_hotkey(hotkey) self._send_event(HOTKEY_REGISTER_EVENT, hotkey) return hotkey def _register_hotkey_args( self, hotkey_ext_id: str, key: Union[str, KeyCombination], action_ext_id: str, action_id: str, filter: Optional[HotkeyFilter] = None # noqa: A002 # pylint: disable=redefined-builtin ) -> Optional[Hotkey]: hotkey = Hotkey(hotkey_ext_id, key, action_ext_id, action_id, filter=filter) return self._register_hotkey_obj(hotkey) def _deregister_hotkey_obj(self, hotkey: Hotkey) -> bool: if hotkey in self._hotkeys: self._hotkeys.remove(hotkey) self.__deregister_hotkey_maps(hotkey) self.__default_key_combinations.pop(hotkey.id) self.__default_filters.pop(hotkey.id) self.__hotkey_storage.deregister_hotkey(hotkey) self._send_event(HOTKEY_DEREGISTER_EVENT, hotkey) return True return False def _deregister_hotkey_args( self, hotkey_ext_id: str, key: Union[str, KeyCombination], filter: Optional[HotkeyFilter] = None # noqa: A002 # pylint: disable=redefined-builtin ) -> bool: hotkey = self.get_hotkey(hotkey_ext_id, key, filter=filter) return self._deregister_hotkey_obj(hotkey) if hotkey else False def _send_event(self, event: int, hotkey: Hotkey): self._event_stream.push( event, payload={ "hotkey_ext_id": hotkey.hotkey_ext_id, "key": hotkey.key_combination.as_string, "trigger_press": hotkey.key_combination.trigger_press, "action_ext_id": hotkey.action.extension_id if hotkey.action else "", "action_id": hotkey.action.id if hotkey.action else "" } ) def __register_hotkey_maps(self, hotkey: Hotkey) -> None: if hotkey.key_combination.key == "": return if hotkey.filter is None: self._global_hotkeys_by_key[hotkey.key_combination] = hotkey else: if hotkey.filter.context: if hotkey.key_combination not in self._hotkeys_by_key_and_context: self._hotkeys_by_key_and_context[hotkey.key_combination] = {} if hotkey.filter.context in self._hotkeys_by_key_and_context[hotkey.key_combination]: carb.log_warn(f"Hotkey {hotkey.key_combination.as_string} to context {hotkey.filter.context} already exists: ") old_hotkey = self._hotkeys_by_key_and_context[hotkey.key_combination][hotkey.filter.context] carb.log_warn(f" existing from {old_hotkey.hotkey_ext_id}") carb.log_warn(f" replace with the one from {hotkey.hotkey_ext_id}") self._hotkeys_by_key_and_context[hotkey.key_combination][hotkey.filter.context] = hotkey if hotkey.filter.windows: if hotkey.key_combination not in self._hotkeys_by_key_and_window: self._hotkeys_by_key_and_window[hotkey.key_combination] = {} for window in hotkey.filter.windows: if window in self._hotkeys_by_key_and_window[hotkey.key_combination]: carb.log_warn(f"Hotkey {hotkey.key_combination.as_string} to window {window} already exists: ") old_hotkey = self._hotkeys_by_key_and_window[hotkey.key_combination][window] carb.log_warn(f" existing from {old_hotkey.hotkey_ext_id}") carb.log_warn(f" replace with the one from {hotkey.hotkey_ext_id}") self._hotkeys_by_key_and_window[hotkey.key_combination][window] = hotkey def __deregister_hotkey_maps(self, hotkey: Hotkey) -> bool: if hotkey.key_combination.key == "": return if hotkey.filter: if hotkey.filter.context \ and hotkey.filter.context in self._hotkeys_by_key_and_context[hotkey.key_combination] \ and self._hotkeys_by_key_and_context[hotkey.key_combination][hotkey.filter.context] == hotkey: self._hotkeys_by_key_and_context[hotkey.key_combination].pop(hotkey.filter.context) if hotkey.filter.windows: for window in hotkey.filter.windows: if window in self._hotkeys_by_key_and_window[hotkey.key_combination] \ and self._hotkeys_by_key_and_window[hotkey.key_combination][window] == hotkey: self._hotkeys_by_key_and_window[hotkey.key_combination].pop(window) else: if hotkey.key_combination in self._global_hotkeys_by_key: self._global_hotkeys_by_key.pop(hotkey.key_combination) def __append_user_hotkeys(self): user_hotkeys = self.__hotkey_storage.get_user_hotkeys() for hotkey in user_hotkeys: self._hotkeys.append(hotkey) self.__default_key_combinations[hotkey.id] = hotkey.key_combination.id self.__default_filters[hotkey.id] = hotkey.filter self.__register_hotkey_maps(hotkey) def clear_storage(self) -> None: """ Clear user defined hotkeys. """ user_hotkeys = self.__hotkey_storage.get_user_hotkeys() for hotkey in user_hotkeys: if hotkey in self._hotkeys: self._hotkeys.remove(hotkey) self.__deregister_hotkey_maps(hotkey) self.__default_key_combinations.pop(hotkey.id) self.__default_filters.pop(hotkey.id) self.__hotkey_storage.clear_hotkeys() def export_storage(self, url: str) -> None: """ Export user defined hotkeys to file. Args: url (str): File path to export user defined hotkeys. """ self.__hotkey_storage.save_preset(url) def import_storage(self, url: str) -> bool: """ Import user defined hotkeys from file. Args: url (str): File path to import user defined hotkeys. """ preset = self.__hotkey_storage.preload_preset(url) if preset is None: return False # First we need to restore all hotkeys self.restore_defaults() self.__hotkey_storage.load_preset(preset) # For system hotkeys, change to new definition in preset for hotkey in self._hotkeys: user_hotkey = self.__hotkey_storage.get_hotkey(hotkey) if user_hotkey: self.__deregister_hotkey_maps(hotkey) if hotkey.key_combination != user_hotkey.key_combination: carb.log_info(f"[Hotkey] Replace {hotkey.action_text}.{hotkey.key_text} with {user_hotkey.key_text}") hotkey.key_combination = user_hotkey.key_combination if hotkey.filter != user_hotkey.filter: carb.log_info(f"[Hotkey] Replace {hotkey.action_text}.{hotkey.filter_text} with {user_hotkey.filter_text}") hotkey.filter = user_hotkey.filter self.__register_hotkey_maps(hotkey) # Apppend user hotkeys self.__append_user_hotkeys() return True def has_duplicated_hotkey(self, hotkey: Hotkey) -> "HotkeyRegistry.Result": """ Check if already have hotkey registered. Args: hotkey (Hotkey): Hotkey object to check. Returns: Result code. """ exist_hotkey = self.__default_key_combinations.get(hotkey.id, None) if exist_hotkey: carb.log_warn(f"[Hotkey] duplicated action as {exist_hotkey} with {hotkey.id}!") return HotkeyRegistry.Result.ERROR_ACTION_DUPLICATED return HotkeyRegistry.Result.OK def verify_hotkey(self, hotkey: Hotkey, key_combination: Optional[KeyCombination] = None, hotkey_filter: Optional[HotkeyFilter] = None) -> "HotkeyRegistry.Result": """ Verify hotkey. """ if not hotkey.action_text: return HotkeyRegistry.Result.ERROR_NO_ACTION if key_combination is None: key_combination = hotkey.key_combination if not key_combination.is_valid: return HotkeyRegistry.Result.ERROR_KEY_INVALID if key_combination.key != "": hotkey_filter = hotkey.filter if hotkey_filter is None else hotkey_filter found = self.get_hotkey_for_filter(key_combination, hotkey_filter) if found and found.id != hotkey.id: carb.log_warn(f"[Hotkey] duplicated key:'{key_combination}'") carb.log_warn(f" -- {hotkey}") carb.log_warn(f" -- {found}") return HotkeyRegistry.Result.ERROR_KEY_DUPLICATED return HotkeyRegistry.Result.OK def get_hotkey_default(self, hotkey: Hotkey) -> Tuple[str, HotkeyFilter]: """ Discover hotkey default key binding and filter. Args: hotkey (Hotkey): Hotkey object. Returns: Tuple of key binding string and hotkey filter object. """ return ( self.__default_key_combinations.get(hotkey.id, None), self.__default_filters.get(hotkey.id, None) ) def restore_defaults(self) -> None: """ Clean user defined hotkeys and restore system hotkey to default """ to_remove_hotkeys = [] for hotkey in self._hotkeys: saved_hotkey = self.__hotkey_storage.get_hotkey(hotkey) if saved_hotkey: if self.__hotkey_storage.is_user_hotkey(hotkey): # User-defined hotkey, remove later self.__deregister_hotkey_maps(hotkey) self.__default_key_combinations.pop(hotkey.id, None) self.__default_filters.pop(hotkey.id, None) to_remove_hotkeys.append(hotkey) else: # System hotkey, restore key-bindings and filter self.__deregister_hotkey_maps(hotkey) if hotkey.id in self.__default_key_combinations: hotkey.key_combination = KeyCombination(self.__default_key_combinations[hotkey.id]) if hotkey.id in self.__default_filters: hotkey.filter = self.__default_filters[hotkey.id] self.__register_hotkey_maps(hotkey) for hotkey in to_remove_hotkeys: self._hotkeys.remove(hotkey) self.__hotkey_storage.clear_hotkeys() def is_user_hotkey(self, hotkey: Hotkey) -> bool: """ If a user defined hotkey. Args: hotkey (Hotkey): Hotkey object. Returns: True if user defined. Otherwise False. """ return self.__hotkey_storage.is_user_hotkey(hotkey)
27,402
Python
40.207519
187
0.605613
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/trigger.py
__all__ = ["HotkeyTrigger"] import asyncio import carb import carb.input import omni.appwindow import omni.kit.app from .registry import HotkeyRegistry from .context import HotkeyContext from .key_combination import KeyCombination from .hovered_window import get_hovered_window SETTING_ALLOW_LIST = "/exts/omni.kit.hotkeys.core/allow_list" class HotkeyTrigger: def __init__(self, registry: HotkeyRegistry, context: HotkeyContext): """ Trigger hotkey on keyboard input. Args: registry (HotkeyRegistry): Hotkey registry. context (HotkeyContext): Hotkey context. """ self._registry = registry self._context = context self._input = carb.input.acquire_input_interface() self._input_sub_id = self._input.subscribe_to_input_events(self._on_input_event, order=0) self.__app_window = omni.appwindow.get_default_app_window() self._stop_event = asyncio.Event() self._work_queue = asyncio.Queue() self.__run_future = asyncio.ensure_future(self._run()) self.__settings = carb.settings.get_settings() self._allow_list = self.__settings.get(SETTING_ALLOW_LIST) def __on_allow_list_change(value, event_type) -> None: self._allow_list = self.__settings.get(SETTING_ALLOW_LIST) self._sub_allow_list = omni.kit.app.SettingChangeSubscription(SETTING_ALLOW_LIST, __on_allow_list_change) def destroy(self): self._stop_event.set() self._work_queue.put_nowait((None, None, None)) self.__run_future.cancel() self._input.unsubscribe_to_input_events(self._input_sub_id) self._input_sub_id = None self._input = None self._sub_allow_list = None def _on_input_event(self, event, *_): if event.deviceType == carb.input.DeviceType.KEYBOARD \ and event.event.type in [carb.input.KeyboardEventType.KEY_PRESS, carb.input.KeyboardEventType.KEY_RELEASE]: is_down = event.event.type == carb.input.KeyboardEventType.KEY_PRESS if event.deviceType == carb.input.DeviceType.KEYBOARD: key_combination = KeyCombination(event.event.input, modifiers=event.event.modifiers, trigger_press=is_down) if not self._allow_list or key_combination.as_string in self._allow_list and self._registry.get_all_hotkeys_for_key(key_combination): (mouse_pos_x, mouse_pos_y) = self._input.get_mouse_coords_pixel(self.__app_window.get_mouse()) self._work_queue.put_nowait((key_combination, mouse_pos_x, mouse_pos_y)) return True def __trigger(self, key_combination: KeyCombination, pos_x: float, pos_y: float): hotkey = None # First: find hotkey assigned to current context current_context = self._context.get() if current_context: hotkey = self._registry.get_hotkey_for_trigger(key_combination, context=current_context) if not hotkey: current_window = get_hovered_window(pos_x, pos_y) if current_window: hotkey = self._registry.get_hotkey_for_trigger(key_combination, window=current_window.title) if not hotkey: # Finally: No context/window hotkey found, find global hotkey hotkey = self._registry.get_hotkey_for_trigger(key_combination) if hotkey: hotkey.execute() async def _run(self): while not self._stop_event.is_set(): (key_combination, pos_x, pos_y) = await self._work_queue.get() self.__trigger(key_combination, pos_x, pos_y)
3,635
Python
38.956044
149
0.644567
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/extension.py
# pylint: disable=attribute-defined-outside-init __all__ = ["get_hotkey_context", "get_hotkey_registry", "HotkeysExtension"] import omni.ext import carb from .context import HotkeyContext from .registry import HotkeyRegistry from .trigger import HotkeyTrigger from .keyboard_layout import USKeyboardLayout, GermanKeyboardLayout, FrenchKeyboardLayout _hotkey_context = None _hotkey_registry = None # public API def get_hotkey_context() -> HotkeyContext: """ Get the hotkey context. Return: HotkeyContext object which implements the hotkey context interface. """ return _hotkey_context def get_hotkey_registry() -> HotkeyRegistry: """ Get the hotkey registry. Return: HotkeyRegistry object which implements the hotkey registry interface. """ return _hotkey_registry class HotkeysExtension(omni.ext.IExt): """ Hotkeys extension. """ def on_startup(self, ext_id): """ Extension startup entrypoint. """ self._us_keyboard_layout = USKeyboardLayout() self._german_keyboard_layput = GermanKeyboardLayout() self._french_keyboard_layout = FrenchKeyboardLayout() global _hotkey_context, _hotkey_registry _hotkey_context = HotkeyContext() _hotkey_registry = HotkeyRegistry() self._hotkey_trigger = None _settings = carb.settings.get_settings() enabled = _settings.get("/exts/omni.kit.hotkeys.core/hotkeys_enabled") if enabled: self._hotkey_trigger = HotkeyTrigger(_hotkey_registry, _hotkey_context) else: carb.log_info("All Hotkeys disabled via carb setting /exts/omni.kit.hotkeys.core/hotkeys_enabled=false") def on_shutdown(self): if self._hotkey_trigger: self._hotkey_trigger.destroy() self._us_keyboard_layout = None self._german_keyboard_layput = None self._french_keyboard_layout = None global _hotkey_context, _hotkey_registry _hotkey_context = None _hotkey_registry = None
2,066
Python
27.315068
116
0.668441
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/__init__.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # """ Omni Kit Hotkeys Core --------------------- Omni Kit Hotkeys Core is a framework for creating, registering, and discovering hotkeys. Here is an example of registering an hokey from Python that execute action "omni.kit.window.file::new" to create a new file when CTRL + N pressed: .. code-block:: hotkey_registry = omni.kit.hotkeys.core.get_hotkey_registry() hotkey_registry.register_hotkey( "your_extension_id", "CTRL + N", "omni.kit.window.file", "new", filter=None, ) For more examples, please consult the Usage Examples page. """ from .key_combination import KeyCombination from .hotkey import Hotkey from .registry import HotkeyRegistry from .filter import HotkeyFilter from .extension import HotkeysExtension, get_hotkey_context, get_hotkey_registry from .event import HOTKEY_REGISTER_EVENT, HOTKEY_DEREGISTER_EVENT, HOTKEY_CHANGED_EVENT from .keyboard_layout import KeyboardLayoutDelegate __all__ = [ "KeyCombination", "Hotkey", "HotkeyRegistry", "HotkeyFilter", "HotkeysExtension", "get_hotkey_context", "get_hotkey_registry", "HOTKEY_REGISTER_EVENT", "HOTKEY_DEREGISTER_EVENT", "HOTKEY_CHANGED_EVENT", ]
1,645
Python
30.056603
146
0.728267
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/storage.py
__all__ = ["HotkeyDescription", "HotkeyStorage"] import json from dataclasses import dataclass, asdict from typing import List, Optional, Dict, Tuple import carb.settings from .hotkey import Hotkey from .filter import HotkeyFilter from .key_combination import KeyCombination # Hotkey ext id for all hotkeys created from here USER_HOTKEY_EXT_ID = "omni.kit.hotkeys.window" SETTING_USER_HOTKEYS = "/persistent/omni.kit.hotkeys.core/userHotkeys" @dataclass class HotkeyDescription: hotkey_ext_id: str = "" action_ext_id: str = "" action_id: str = "" key: str = "" trigger_press: bool = True context: str = None windows: str = None @staticmethod def from_hotkey(hotkey: Hotkey): (context, windows) = HotkeyDescription.get_filter_string(hotkey) return HotkeyDescription( hotkey_ext_id=hotkey.hotkey_ext_id, action_ext_id=hotkey.action_ext_id, action_id=hotkey.action_id, key=hotkey.key_combination.as_string, trigger_press=hotkey.key_combination.trigger_press, context=context, windows=windows, ) @property def id(self) -> str: # noqa: A003 return self.to_hotkey().id def to_hotkey(self) -> Hotkey: if self.context or self.windows: hotkey_filter = HotkeyFilter(context=self.context if self.context else None, windows=self.windows.split(",") if self.windows else None) else: hotkey_filter = None key = KeyCombination(self.key, trigger_press=self.trigger_press) return Hotkey(self.hotkey_ext_id, key, self.action_ext_id, self.action_id, filter=hotkey_filter) def update(self, hotkey: Hotkey) -> None: self.key = hotkey.key_combination.as_string self.trigger_press = hotkey.key_combination.trigger_press (self.context, self.windows) = HotkeyDescription.get_filter_string(hotkey) @staticmethod def get_filter_string(hotkey: Hotkey) -> Tuple[str, str]: return ( hotkey.filter.context if hotkey.filter and hotkey.filter else "", ",".join(hotkey.filter.windows) if hotkey.filter and hotkey.filter.windows else "" ) class HotkeyStorage: def __init__(self): self.__settings = carb.settings.get_settings() self.__hotkey_descs: List[HotkeyDescription] = [HotkeyDescription(**desc) for desc in self.__settings.get(SETTING_USER_HOTKEYS) or []] carb.log_info(f"[Hotkey] {len(self.__hotkey_descs)} user defined hotkeys") def get_hotkey(self, hotkey: Hotkey) -> Optional[Hotkey]: """ Get hotkey definition in storage. """ hotkey_desc = self.__find_hotkey_desc(hotkey) return hotkey_desc.to_hotkey() if hotkey_desc else None def get_user_hotkeys(self) -> List[Hotkey]: """ Get all user-defined hotkeys. """ user_hotkeys: List[Hotkey] = [] for hotkey_desc in self.__hotkey_descs: hotkey = hotkey_desc.to_hotkey() if self.is_user_hotkey(hotkey): user_hotkeys.append(hotkey) return user_hotkeys def get_hotkeys(self) -> List[Hotkey]: """ Discover all hotkey definitions in this storage. """ return [desc.to_hotkey() for desc in self.__hotkey_descs] def register_user_hotkey(self, hotkey: Hotkey): """ Register user hotkey. """ if self.is_user_hotkey(hotkey): # This is user defined hotkey hotkey_desc = HotkeyDescription().from_hotkey(hotkey) self.__hotkey_descs.append(hotkey_desc) self.__settings.set(SETTING_USER_HOTKEYS, [asdict(desc) for desc in self.__hotkey_descs]) def edit_hotkey(self, hotkey: Hotkey): """ Edit hotkey. This could be a user-defined hotkey or system hotkey but changed by user. """ # This is system hotkey but user changed key bindings, etc. hotkey_desc = self.__find_hotkey_desc(hotkey) if hotkey_desc: hotkey_desc.update(hotkey) else: hotkey_desc = HotkeyDescription().from_hotkey(hotkey) self.__hotkey_descs.append(hotkey_desc) self.__settings.set(SETTING_USER_HOTKEYS, [asdict(desc) for desc in self.__hotkey_descs]) def deregister_hotkey(self, hotkey: Hotkey): """ Deregister user hotkey from storage. For system hotkey, keep in storage to reload when register again """ if self.is_user_hotkey(hotkey): hotkey_desc = HotkeyDescription().from_hotkey(hotkey) if hotkey_desc in self.__hotkey_descs: self.__hotkey_descs.remove(hotkey_desc) self.__settings.set(SETTING_USER_HOTKEYS, [asdict(desc) for desc in self.__hotkey_descs]) def __find_hotkey_desc(self, hotkey: Hotkey) -> Optional[HotkeyDescription]: """ Find if there is user-defined hotkey """ for hotkey_desc in self.__hotkey_descs: if hotkey_desc.id == hotkey.id: return hotkey_desc return None def clear_hotkeys(self) -> None: """ Clear all hotkeys in storage """ self.__hotkey_descs = [] self.__settings.set(SETTING_USER_HOTKEYS, []) def is_user_hotkey(self, hotkey: Hotkey) -> bool: """ If a user-defined hotkey """ return hotkey.hotkey_ext_id == USER_HOTKEY_EXT_ID def save_preset(self, url: str) -> bool: """ Save storage to file. """ output = { "Type": "Hotkey Preset", "Keys": [asdict(desc) for desc in self.__hotkey_descs] } try: with open(url, "w", encoding="utf8") as json_file: json.dump(output, json_file, indent=4) json_file.close() carb.log_info(f"Saved hotkeys preset to {url}!") except FileNotFoundError: carb.log_warn(f"Failed to open {url}!") return False except PermissionError: carb.log_warn(f"Cannot write to {url}: permission denied!") return False except Exception as e: # pylint: disable=broad-except carb.log_warn(f"Unknown failure to write to {url}: {e}") return False finally: if json_file: json_file.close() return bool(json_file) def load_preset(self, preset: List[Dict]) -> None: """ Load hotkey preset. """ self.clear_hotkeys() self.__hotkey_descs = [HotkeyDescription(**desc) for desc in preset] self.__settings.set(SETTING_USER_HOTKEYS, [asdict(desc) for desc in self.__hotkey_descs]) def preload_preset(self, url: str) -> Optional[Dict]: """ Preload hotkey preset from file. """ keys_json = None try: with open(url, "r", encoding="utf8") as json_file: keys_json = json.load(json_file) except FileNotFoundError: carb.log_error(f"Failed to open {url}!") except PermissionError: carb.log_error(f"Cannot read {url}: permission denied!") except Exception as exc: # pylint: disable=broad-except carb.log_error(f"Unknown failure to read {url}: {exc}") if keys_json is None: return None if keys_json.get("Type", None) != "Hotkey Preset": carb.log_error(f"{url} is not a valid hotkey preset file!") return None if "Keys" not in keys_json: carb.log_error(f"{url} is not a valid hotkey preset: No key found!") return None return keys_json["Keys"]
7,763
Python
34.452055
147
0.595904
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/keyboard_layout.py
import abc from typing import Dict, List, Optional import weakref import carb.input from .key_combination import KeyCombination class KeyboardLayoutDelegate(abc.ABC): """Base class for keyboard layout delegates and registry of these same delegate instances. Whenever an instance of this class is created, it is automatically registered. """ __g_registered = [] @classmethod def get_instances(cls) -> List["KeyboardLayoutDelegate"]: remove = [] for wref in KeyboardLayoutDelegate.__g_registered: obj = wref() if obj: yield obj else: remove.append(wref) for wref in remove: KeyboardLayoutDelegate.__g_registered.remove(wref) @classmethod def get_instance(cls, name: str) -> Optional["KeyboardLayoutDelegate"]: for inst in KeyboardLayoutDelegate.get_instances(): if inst.get_name() == name: return inst return None def __init__(self): self.__g_registered.append(weakref.ref(self, lambda r: KeyboardLayoutDelegate.__g_registered.remove(r))) # noqa: PLW0108 # pylint: disable=unnecessary-lambda self._maps = self.get_maps() self._restore_maps = {value: key for (key, value) in self._maps.items()} def __del__(self): self.destroy() def destroy(self): for wref in KeyboardLayoutDelegate.__g_registered: if wref() == self: KeyboardLayoutDelegate.__g_registered.remove(wref) break @abc.abstractmethod def get_name(self) -> str: return "" @abc.abstractmethod def get_maps(self) -> dict: return {} def map_key(self, key: KeyCombination) -> Optional[KeyCombination]: return KeyCombination(self._maps[key.key], modifiers=key.modifiers, trigger_press=key.trigger_press) if key.key in self._maps else None def restore_key(self, key: KeyCombination) -> Optional[KeyCombination]: return KeyCombination(self._restore_maps[key.key], modifiers=key.modifiers, trigger_press=key.trigger_press) if key.key in self._restore_maps else None class USKeyboardLayout(KeyboardLayoutDelegate): def get_name(self) -> str: return "U.S. QWERTY" def get_maps(self) -> Dict[carb.input.KeyboardInput, carb.input.KeyboardInput]: return {} class GermanKeyboardLayout(KeyboardLayoutDelegate): def get_name(self) -> str: return "German QWERTZ" def get_maps(self) -> Dict[carb.input.KeyboardInput, carb.input.KeyboardInput]: return { carb.input.KeyboardInput.Z: carb.input.KeyboardInput.Y, carb.input.KeyboardInput.Y: carb.input.KeyboardInput.Z, } class FrenchKeyboardLayout(KeyboardLayoutDelegate): def get_name(self) -> str: return "French AZERTY" def get_maps(self) -> Dict[carb.input.KeyboardInput, carb.input.KeyboardInput]: return { carb.input.KeyboardInput.Q: carb.input.KeyboardInput.A, carb.input.KeyboardInput.W: carb.input.KeyboardInput.Z, carb.input.KeyboardInput.A: carb.input.KeyboardInput.Q, carb.input.KeyboardInput.Z: carb.input.KeyboardInput.W, }
3,239
Python
33.105263
166
0.651436
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/filter.py
__all__ = ["HotkeyFilter"] from typing import List, Optional class HotkeyFilter: """ Hotkey filter class. """ def __init__(self, context: Optional[str] = None, windows: Optional[List[str]] = None): """ Define a hotkey filter object. Keyword Args: context (Optional[str]): Name of context to filter. Default None. windows (Optional[List[str]]): List of window names to filter. Default None Returns: The hotkey filter object that was created. """ self.context = context self.windows = windows @property def windows_text(self): """ String of windows defined in this filter. """ return ",".join(self.windows) if self.windows else "" def __eq__(self, other): return isinstance(other, HotkeyFilter) and self.context == other.context and self.windows == other.windows def __str__(self): info = "" if self.context: info += f"[Context] {self.context}" if self.windows: info += "[Windows] " + (",".join(self.windows)) return info
1,148
Python
27.02439
114
0.569686
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/hotkey.py
from typing import Optional, Union import carb from omni.kit.actions.core import get_action_registry, Action from .key_combination import KeyCombination from .filter import HotkeyFilter class Hotkey: """ Hotkey object class. """ def __init__( self, hotkey_ext_id: str, key: Union[str, KeyCombination], action_ext_id: str, action_id: str, filter: Optional[HotkeyFilter] = None # noqa: A002 # pylint: disable=redefined-builtin ): """ Define a hotkey object. Args: hotkey_ext_id (str): Extension id which owns the hotkey. key (Union[str, KeyCombination]): Key combination. action_ext_id (str): Extension id which owns the action assigned to the hotkey. action_id (str): Action id assigned to the hotkey. Keyword Args: filter (Optional[HotkeyFilter]): Hotkey filter. Default None Returns: The hotkey object that was created. """ self.hotkey_ext_id = hotkey_ext_id if key: self.key_combination = KeyCombination(key) if isinstance(key, str) else key else: self.key_combination = None # For user defined action, the extension may not loaded yet # So only save action id instead get real action here self.action_ext_id = action_ext_id self.action_id = action_id self.filter = filter @property def id(self) -> str: # noqa: A003 """ Identifier string of this hotkey. """ hotkey_id = f"{self.hotkey_ext_id}.{self.action_text}" if self.filter: hotkey_id += "." + str(self.filter) return hotkey_id @property def key_text(self) -> str: """ String of key bindings assigned to this hotkey. """ return self.key_combination.as_string if self.key_combination else "" @property def action_text(self) -> str: """ String of action object assigned to this hotkey. """ return self.action_ext_id + "::" + self.action_id if self.action_ext_id or self.action_id else "" @property def filter_text(self) -> str: """ String of filter object assigned to this hotkey. """ return str(self.filter) if self.filter else "" @property def action(self) -> Action: """ Action object assigned to this hotkey. """ if self.action_ext_id and self.action_id: action = get_action_registry().get_action(self.action_ext_id, self.action_id) if action is None: carb.log_warn(f"[Hotkey] Action '{self.action_ext_id}::{self.action_id}' not FOUND!") return action return None def execute(self) -> None: """ Execute action assigned to the hotkey """ if self.action: self.action.execute() def __eq__(self, other) -> bool: return isinstance(other, Hotkey)\ and self.hotkey_ext_id == other.hotkey_ext_id \ and self.key_combination == other.key_combination \ and self.action_ext_id == other.action_ext_id \ and self.action_id == other.action_id \ and self.filter == other.filter def __repr__(self): basic_info = f"[{self.hotkey_ext_id}] {self.action_text}.{self.key_text}" if self.filter is None: return f"Global {basic_info}" return f"Local {basic_info} for {self.filter}"
3,558
Python
30.776785
105
0.578696
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/context.py
__all__ = ["HotkeyContext"] from typing import List, Optional import carb.settings SETTING_HOTKEY_CURRENT_CONTEXT = "/exts/omni.kit.hotkeys.core/context" class HotkeyContext: def __init__(self): """Represent hotkey context.""" self._queue: List[str] = [] self._settings = carb.settings.get_settings() def push(self, name: str) -> None: """ Push a context. Args: name (str): name of context """ self._queue.append(name) self._update_settings() def pop(self) -> Optional[str]: """Remove and return last context.""" poped = self._queue.pop() if self._queue else None self._update_settings() return poped def get(self) -> Optional[str]: """Get last context.""" return self._queue[-1] if self._queue else None def clean(self) -> None: """Clean all contexts""" self._queue.clear() self._update_settings() def _update_settings(self): current = self.get() self._settings.set(SETTING_HOTKEY_CURRENT_CONTEXT, current if current else "")
1,132
Python
25.97619
86
0.581272
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/key_combination.py
__all__ = ["KeyCombination"] from typing import Union, Optional, Dict, Tuple import re import carb import carb.input PREDEFINED_STRING_TO_KEYS: Dict[str, carb.input.Keyboard] = carb.input.KeyboardInput.__members__ class KeyCombination: """ Key binding class. """ def __init__(self, key: Union[str, carb.input.KeyboardInput], modifiers: int = 0, trigger_press: bool = True): """ Create a key binding object. Args: key (Union[str, carb.input.KeyboardInput]): could be string or carb.input.KeyboardInput. if string, use "+" to join carb.input.KeyboardInput and modifiers, for example: "CTRL+D" or "CTRL+SHIFT+D" Keyword Args: modifiers (int): Represent combination of keyboard modifier flags, which could be: carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT carb.input.KEYBOARD_MODIFIER_FLAG_ALT carb.input.KEYBOARD_MODIFIER_FLAG_SUPER trigger_press (bool): Trigger when key pressed if True. Otherwise trigger when key released. Default True. """ self.key: Optional[carb.input.Keyboard] = None self.modifiers = 0 if isinstance(key, str): (self.key, self.modifiers, self.trigger_press) = KeyCombination.from_string(key) else: self.modifiers = modifiers if key in [ carb.input.KeyboardInput.LEFT_CONTROL, carb.input.KeyboardInput.RIGHT_CONTROL, carb.input.KeyboardInput.LEFT_SHIFT, carb.input.KeyboardInput.RIGHT_SHIFT, carb.input.KeyboardInput.LEFT_ALT, carb.input.KeyboardInput.RIGHT_ALT, carb.input.KeyboardInput.LEFT_SUPER, carb.input.KeyboardInput.RIGHT_SUPER, ]: self.key = "" else: self.key = key self.trigger_press = trigger_press @property def as_string(self) -> str: """ Get string to describe key combination """ if self.key is None: return "" descs = [] if self.modifiers & carb.input.KEYBOARD_MODIFIER_FLAG_SUPER: descs.append("SUPER") if self.modifiers & carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT: descs.append("SHIFT") if self.modifiers & carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL: descs.append("CTRL") if self.modifiers & carb.input.KEYBOARD_MODIFIER_FLAG_ALT: descs.append("ALT") if self.key in PREDEFINED_STRING_TO_KEYS.values(): key = list(PREDEFINED_STRING_TO_KEYS.keys())[list(PREDEFINED_STRING_TO_KEYS.values()).index(self.key)] # OM-67426: Remove "KEY_". For example, "KEY_1" to "1". if key.startswith("KEY_"): key = key[4:] descs.append(key) return " + ".join(descs) @property def id(self) -> str: # noqa: A003 """ Identifier string of this key binding object. """ return f"{self.as_string} (On " + ("Press" if self.trigger_press else "Release") + ")" @property def is_valid(self) -> bool: """ If a valid key binding object. """ return self.key is not None def __repr__(self) -> str: return self.id def __eq__(self, other) -> bool: return isinstance(other, KeyCombination) and self.id == other.id def __hash__(self): return hash(self.id) @staticmethod def from_string(key_string: str) -> Tuple[carb.input.KeyboardInput, int, bool]: """ Get key binding information from a string. Args: key_string (str): String represent a key binding. Returns: Tuple of carb.input.KeyboardInput, modifiers and flag for press/release. """ if key_string is None: carb.log_error("No key defined!") return (None, None, None) key_string = key_string.strip() if key_string == "": # Empty key string means no key return ("", 0, True) modifiers = 0 key = None trigger_press = True m = re.search(r"(.*)\(on (press|release)\)", key_string, flags=re.IGNORECASE) if m: trigger = m.groups()[1] trigger_press = trigger.upper() == "PRESS" key_string = m.groups()[0] else: trigger_press = True key_descs = key_string.split("+") for desc in key_descs: desc = desc.strip().upper() if desc in ["CTRL", "CTL", "CONTROL"]: modifiers += carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL elif desc in ["SHIFT"]: modifiers += carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT elif desc in ["ALT"]: modifiers += carb.input.KEYBOARD_MODIFIER_FLAG_ALT elif desc in ["SUPER"]: modifiers += carb.input.KEYBOARD_MODIFIER_FLAG_SUPER elif desc in ["PRESS", "RELEASE"]: trigger_press = desc == "PRESS" elif desc in PREDEFINED_STRING_TO_KEYS: key = PREDEFINED_STRING_TO_KEYS[desc] elif desc in [str(i) for i in range(0, 10)]: # OM-67426: for numbers, convert to original key definition key = PREDEFINED_STRING_TO_KEYS["KEY_" + desc] elif desc == "": key = "" else: carb.log_warn(f"Unknown key definition '{desc}' in '{key_string}'") return (None, None, None) return (key, modifiers, trigger_press) @staticmethod def is_valid_key_string(key: str) -> bool: """ If key string valid. Args: key (str): Key string to check. Returns: True if key string is valid. Otherwise False. """ (key, modifiers, press) = KeyCombination.from_string(key) if key is None or modifiers is None or press is None: return False return True
6,158
Python
34.194286
122
0.556999
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/hovered_window.py
__all__ = ["is_window_hovered", "get_hovered_window"] from typing import Optional, List import omni.ui as ui def is_window_hovered(pos_x: float, pos_y: float, window: ui.Window) -> bool: """ Check if window under mouse position. Args: pos_x (flaot): X position. pos_y (flaot): Y position. window (ui.Window): Window to check. """ # if window hasn't been drawn yet docked may not be valid, so check dock_id also # OM-65505: For ui.ToolBar, is_selected_in_dock always return False if docked. if not window or not window.visible or ((window.docked or window.dock_id != 0) and (not isinstance(window, ui.ToolBar) and not window.is_selected_in_dock())): return False if (window.position_x + window.width > pos_x > window.position_x and window.position_y + window.height > pos_y > window.position_y): return True return False def get_hovered_window(pos_x: float, pos_y: float) -> Optional[str]: """ Get first window under mouse. Args: pos_x (flaot): X position. pos_y (flaot): Y position. Return None if nothing found. If muliple window found, float window first. If multiple float window, just first result """ hovered_float_windows: List[ui.Window] = [] hovered_doced_windows: List[ui.Window] = [] dpi = ui.Workspace.get_dpi_scale() pos_x /= dpi pos_y /= dpi windows = ui.Workspace.get_windows() for window in windows: if is_window_hovered(pos_x, pos_y, window): if window.docked: hovered_doced_windows.append(window) else: hovered_float_windows.append(window) if hovered_float_windows: return hovered_float_windows[0] if hovered_doced_windows: return hovered_doced_windows[0] return None
1,841
Python
33.11111
162
0.633351
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/tests/test_registry.py
# pylint: disable=attribute-defined-outside-init import omni.kit.test import carb.events from omni.kit.hotkeys.core import get_hotkey_registry, HotkeyFilter, Hotkey, HotkeyRegistry, HOTKEY_CHANGED_EVENT, HOTKEY_REGISTER_EVENT, HOTKEY_DEREGISTER_EVENT from omni.kit.actions.core import get_action_registry TEST_HOTKEY_EXT_ID = "omni.kit.hotkey.test.hotkey" TEST_ACTION_EXT_ID = "omni.kit.hotkey.test.action" TEST_ACTION_ID = "hotkey_test_action" TEST_ANOTHER_ACTION_ID = "hotkey_test_action_another" TEST_CONTEXT_NAME = "[email protected]" TEST_HOTKEY = "CTRL + T" TEST_ANOTHER_HOTKEY = "SHIFT + T" TEST_EDIT_HOTKEY = "T" CHANGE_HOTKEY = "SHIFT + CTRL + T" class TestRegistry(omni.kit.test.AsyncTestCase): async def setUp(self): self._hotkey_registry = get_hotkey_registry() self._hotkey_registry.clear_storage() self._action_registry = get_action_registry() self._filter = HotkeyFilter(context=TEST_CONTEXT_NAME) self._register_payload = {} self._action = self._action_registry.register_action(TEST_ACTION_EXT_ID, TEST_ACTION_ID, lambda: print("this is a hotkey test")) self._another_action = self._action_registry.register_action(TEST_ACTION_EXT_ID, TEST_ANOTHER_ACTION_ID, lambda: print("this is another hotkey test")) # After running each test async def tearDown(self): self._hotkey_registry.deregister_all_hotkeys_for_extension(TEST_HOTKEY_EXT_ID) self._hotkey_registry.clear_storage() self._hotkey_registry = None self._action_registry.deregister_action(self._action) self._action_registry = None async def test_register_global_hotkey(self): hotkey = self._hotkey_registry.get_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY) self.assertIsNone(hotkey) # Register a global hotkey self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_ACTION_ID) hotkey = self._hotkey_registry.get_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY) self.assertEqual(hotkey.hotkey_ext_id, TEST_HOTKEY_EXT_ID) self.assertEqual(hotkey.action, self._action) self.assertEqual(hotkey.key_combination.as_string, TEST_HOTKEY) # Deregister the global hotkey self._hotkey_registry.deregister_hotkey(hotkey) hotkey = self._hotkey_registry.get_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY) self.assertIsNone(hotkey) async def test_register_local_hotkey(self): global_hotkey = self._hotkey_registry.get_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY) self.assertIsNone(global_hotkey) local_hotkey = self._hotkey_registry.get_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, filter=self._filter) self.assertIsNone(local_hotkey) # Register a local hotkey self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_ACTION_ID, filter=self._filter) global_hotkey = self._hotkey_registry.get_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY) self.assertIsNone(global_hotkey) local_hotkey = self._hotkey_registry.get_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, filter=self._filter) self.assertEqual(local_hotkey.hotkey_ext_id, TEST_HOTKEY_EXT_ID) self.assertEqual(local_hotkey.action, self._action) self.assertEqual(local_hotkey.key_combination.as_string, TEST_HOTKEY) # Deregister the local hotkey self._hotkey_registry.deregister_hotkey(local_hotkey) hotkey = self._hotkey_registry.get_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, filter=self._filter) self.assertIsNone(hotkey) async def test_mixed_hotkey(self): # Register a global hotkey global_hotkey = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_ACTION_ID) # Register a local hotkey local_hotkey = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_ACTION_ID, filter=self._filter) self.assertNotEqual(global_hotkey, local_hotkey) discovered_global_hotkey = self._hotkey_registry.get_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY) self.assertEqual(global_hotkey, discovered_global_hotkey) discovered_local_hotkey = self._hotkey_registry.get_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, filter=self._filter) self.assertEqual(local_hotkey, discovered_local_hotkey) # Deregister the hotkeys self._hotkey_registry.deregister_hotkey(global_hotkey) self._hotkey_registry.deregister_hotkey(local_hotkey) async def test_deregister(self): # Register a global hotkey hotkey_1 = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_ACTION_ID) self.assertIsNotNone(hotkey_1) # Register a local hotkey hotkey_2 = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_ACTION_ID, filter=self._filter) self.assertIsNotNone(hotkey_2) # Register with another key, should since already action already defined hotkey_3 = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, "SHIFT+D", TEST_ACTION_EXT_ID, TEST_ACTION_ID) self.assertIsNone(hotkey_3) # Register with another extension id hotkey_4 = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID + "_another", TEST_ANOTHER_HOTKEY, TEST_ACTION_EXT_ID, TEST_ANOTHER_ACTION_ID, filter=self._filter) self.assertIsNotNone(hotkey_4) hotkeys = self._hotkey_registry.get_all_hotkeys_for_extension(TEST_HOTKEY_EXT_ID + "_another") self.assertEqual(len(hotkeys), 1) # Deregister hotkey_4 self._hotkey_registry.deregister_all_hotkeys_for_extension(TEST_HOTKEY_EXT_ID + "_another") hotkeys = self._hotkey_registry.get_all_hotkeys_for_extension(TEST_HOTKEY_EXT_ID + "_another") self.assertEqual(len(hotkeys), 0) # Deregister hotkey_1 hotkeys = self._hotkey_registry.get_all_hotkeys_for_extension(None) self.assertEqual(len(hotkeys), 1) self._hotkey_registry.deregister_all_hotkeys_for_extension(None) hotkeys = self._hotkey_registry.get_all_hotkeys_for_extension(None) self.assertEqual(len(hotkeys), 0) # Deregister hotkey_2 hotkeys = self._hotkey_registry.get_all_hotkeys_for_filter(self._filter) self.assertEqual(len(hotkeys), 1) self._hotkey_registry.deregister_all_hotkeys_for_filter(self._filter) hotkeys = self._hotkey_registry.get_all_hotkeys_for_filter(self._filter) self.assertEqual(len(hotkeys), 0) async def test_discover_hotkeys(self): hotkeys = self._hotkey_registry.get_all_hotkeys_for_extension(TEST_HOTKEY_EXT_ID) self.assertEqual(len(hotkeys), 0) hotkeys = self._hotkey_registry.get_all_hotkeys_for_key(TEST_HOTKEY) self.assertEqual(len(hotkeys), 0) hotkeys = self._hotkey_registry.get_hotkeys(TEST_ACTION_EXT_ID, TEST_HOTKEY) self.assertEqual(len(hotkeys), 0) # Register a global hotkey global_hotkey = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_ACTION_ID) self.assertIsNotNone(global_hotkey) # Register a local hotkey local_hotkey = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_ACTION_ID, filter=self._filter) self.assertIsNotNone(local_hotkey) # Register with another key hotkey_1 = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, "SHIFT+D", TEST_ACTION_EXT_ID, TEST_ANOTHER_ACTION_ID) self.assertIsNotNone(hotkey_1) # Register with another extension id (should be failed since key + filter is same) hotkey_2 = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID + "_another", TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_ANOTHER_ACTION_ID, filter=self._filter) self.assertIsNone(hotkey_2) hotkeys = self._hotkey_registry.get_all_hotkeys_for_extension(TEST_HOTKEY_EXT_ID) self.assertEqual(len(hotkeys), 3) hotkeys = self._hotkey_registry.get_all_hotkeys_for_extension(None) self.assertEqual(len(hotkeys), 2) hotkeys = self._hotkey_registry.get_all_hotkeys_for_key(TEST_HOTKEY) self.assertEqual(len(hotkeys), 2) hotkeys = self._hotkey_registry.get_hotkeys(TEST_HOTKEY_EXT_ID, TEST_HOTKEY) self.assertEqual(len(hotkeys), 2) self._hotkey_registry.deregister_hotkey(global_hotkey) self._hotkey_registry.deregister_hotkey(local_hotkey) self._hotkey_registry.deregister_hotkey(hotkey_1) self._hotkey_registry.deregister_hotkey(hotkey_2) async def test_event(self): event_stream = omni.kit.app.get_app().get_message_bus_event_stream() self._register_event_sub = event_stream.create_subscription_to_pop_by_type( HOTKEY_REGISTER_EVENT, self._on_hotkey_register) self._deregister_event_sub = event_stream.create_subscription_to_pop_by_type( HOTKEY_DEREGISTER_EVENT, self._on_hotkey_deregister) self._change_event_sub = event_stream.create_subscription_to_pop_by_type( HOTKEY_CHANGED_EVENT, self._on_hotkey_changed) # Register hotkey event test_hotkey = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_ACTION_ID) for _ in range(2): await omni.kit.app.get_app().next_update_async() self.assertEqual(self._register_payload["hotkey_ext_id"], TEST_HOTKEY_EXT_ID) self.assertEqual(self._register_payload["key"], TEST_HOTKEY) self.assertEqual(self._register_payload["action_ext_id"], TEST_ACTION_EXT_ID) self.assertEqual(self._register_payload["action_id"], TEST_ACTION_ID) # Change hotkey error_code = self._hotkey_registry.edit_hotkey(test_hotkey, CHANGE_HOTKEY, None) self.assertEqual(error_code, HotkeyRegistry.Result.OK) for _ in range(2): await omni.kit.app.get_app().next_update_async() self.assertEqual(self._changed_payload["hotkey_ext_id"], TEST_HOTKEY_EXT_ID) self.assertEqual(self._changed_payload["key"], CHANGE_HOTKEY) self.assertEqual(self._changed_payload["action_ext_id"], TEST_ACTION_EXT_ID) self.assertEqual(self._changed_payload["action_id"], TEST_ACTION_ID) # Change hotkey back self._hotkey_registry.edit_hotkey(test_hotkey, TEST_HOTKEY, None) for _ in range(2): await omni.kit.app.get_app().next_update_async() self.assertEqual(self._changed_payload["key"], TEST_HOTKEY) # Deregister hotkey event self._hotkey_registry.deregister_hotkey(test_hotkey) for _ in range(2): await omni.kit.app.get_app().next_update_async() self.assertEqual(self._deregister_payload["hotkey_ext_id"], TEST_HOTKEY_EXT_ID) self.assertEqual(self._deregister_payload["key"], TEST_HOTKEY) self.assertEqual(self._deregister_payload["action_ext_id"], TEST_ACTION_EXT_ID) self.assertEqual(self._deregister_payload["action_id"], TEST_ACTION_ID) self._register_event_sub = None self._deregister_event_sub = None self._change_event_sub = None async def test_error_code_global(self): hotkey = Hotkey(TEST_HOTKEY_EXT_ID, "CBL", TEST_ACTION_EXT_ID, TEST_ACTION_ID) registered_hotkey = self._hotkey_registry.register_hotkey(hotkey) self.assertIsNone(registered_hotkey) self.assertEqual(self._hotkey_registry.last_error, HotkeyRegistry.Result.ERROR_KEY_INVALID) registered_hotkey = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, "T", "", "") self.assertIsNone(registered_hotkey) self.assertEqual(self._hotkey_registry.last_error, HotkeyRegistry.Result.ERROR_NO_ACTION) registered_hotkey = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_ACTION_ID) self.assertIsNotNone(registered_hotkey) self.assertEqual(self._hotkey_registry.last_error, HotkeyRegistry.Result.OK) registered_another = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_ANOTHER_ACTION_ID) self.assertIsNone(registered_another) self.assertEqual(self._hotkey_registry.last_error, HotkeyRegistry.Result.ERROR_KEY_DUPLICATED) # Edit global hotkey registered_another = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_ANOTHER_HOTKEY, TEST_ACTION_EXT_ID, TEST_ANOTHER_ACTION_ID) self.assertIsNotNone(registered_another) error_code = self._hotkey_registry.edit_hotkey(registered_another, "CBL", None) self.assertEqual(error_code, HotkeyRegistry.Result.ERROR_KEY_INVALID) error_code = self._hotkey_registry.edit_hotkey(registered_another, TEST_HOTKEY, None) self.assertEqual(error_code, HotkeyRegistry.Result.ERROR_KEY_DUPLICATED) duplicated = self._hotkey_registry.get_hotkey_for_filter(TEST_HOTKEY, None) self.assertEqual(duplicated.action_ext_id, TEST_ACTION_EXT_ID) self.assertEqual(duplicated.action_id, TEST_ACTION_ID) error_code = self._hotkey_registry.edit_hotkey(registered_another, TEST_EDIT_HOTKEY, None) self.assertEqual(error_code, HotkeyRegistry.Result.OK) error_code = self._hotkey_registry.edit_hotkey(registered_another, "", None) self.assertEqual(error_code, HotkeyRegistry.Result.OK) async def test_error_code_window(self): # Edit hotkey in window hotkey_filter = HotkeyFilter(windows=["Test Window"]) registered_hotkey = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_ACTION_ID, filter=hotkey_filter) self.assertIsNotNone(registered_hotkey) self.assertEqual(self._hotkey_registry.last_error, HotkeyRegistry.Result.OK) registered_another = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_ANOTHER_ACTION_ID, filter=hotkey_filter) self.assertIsNone(registered_another) self.assertEqual(self._hotkey_registry.last_error, HotkeyRegistry.Result.ERROR_KEY_DUPLICATED) registered_another = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_ANOTHER_HOTKEY, TEST_ACTION_EXT_ID, TEST_ANOTHER_ACTION_ID, filter=hotkey_filter) self.assertEqual(self._hotkey_registry.last_error, HotkeyRegistry.Result.OK) self.assertIsNotNone(registered_another) error_code = self._hotkey_registry.edit_hotkey(registered_another, "CBL", hotkey_filter) self.assertEqual(error_code, HotkeyRegistry.Result.ERROR_KEY_INVALID) error_code = self._hotkey_registry.edit_hotkey(registered_another, TEST_HOTKEY, hotkey_filter) self.assertEqual(error_code, HotkeyRegistry.Result.ERROR_KEY_DUPLICATED) duplicated = self._hotkey_registry.get_hotkey_for_filter(TEST_HOTKEY, hotkey_filter) self.assertEqual(duplicated.action_ext_id, TEST_ACTION_EXT_ID) self.assertEqual(duplicated.action_id, TEST_ACTION_ID) error_code = self._hotkey_registry.edit_hotkey(registered_another, TEST_EDIT_HOTKEY, hotkey_filter) self.assertEqual(error_code, HotkeyRegistry.Result.OK) error_code = self._hotkey_registry.edit_hotkey(registered_another, "", hotkey_filter) self.assertEqual(error_code, HotkeyRegistry.Result.OK) def _on_hotkey_register(self, event: carb.events.IEvent): self._register_payload = event.payload def _on_hotkey_deregister(self, event: carb.events.IEvent): self._deregister_payload = event.payload def _on_hotkey_changed(self, event: carb.events.IEvent): self._changed_payload = event.payload
15,929
Python
54.3125
175
0.7013
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/tests/test_context.py
from typing import List import omni.kit.test # Import extension python module we are testing with absolute import path, as if we are external user (other extension) from omni.kit.hotkeys.core import get_hotkey_context import carb.settings SETTING_HOTKEY_CURRENT_CONTEXT = "/exts/omni.kit.hotkeys.core/context" # Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test class TestContext(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): self._settings = carb.settings.get_settings() # After running each test async def tearDown(self): pass async def test_empty(self): context = get_hotkey_context() self.assertEqual(self._settings.get(SETTING_HOTKEY_CURRENT_CONTEXT), "") self.assertIsNone(context.get()) self.assertIsNone(context.pop()) async def test_push_pop(self): max_contexts = 10 context_names: List[str] = [f"context_{i}" for i in range(max_contexts)] context = get_hotkey_context() for name in context_names: context.push(name) self.assertEqual(self._settings.get(SETTING_HOTKEY_CURRENT_CONTEXT), name) self.assertEqual(context.get(), name) for i in range(max_contexts): self.assertEqual(context.pop(), context_names[-(i + 1)]) if i == max_contexts - 1: current = None else: current = context_names[-(i + 2)] self.assertEqual(context.get(), current) self.assertEqual(self._settings.get(SETTING_HOTKEY_CURRENT_CONTEXT), current if current else "") self.assertIsNone(context.pop()) async def test_clean(self): max_contexts = 10 context_names: List[str] = [f"context_{i}" for i in range(max_contexts)] context = get_hotkey_context() for name in context_names: context.push(name) context.clean() self.assertEqual(self._settings.get(SETTING_HOTKEY_CURRENT_CONTEXT), "") self.assertIsNone(context.get()) self.assertIsNone(context.pop())
2,195
Python
35.599999
142
0.648292
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/tests/__init__.py
from .test_key_combination import * from .test_context import * from .test_registry import * from .test_trigger import * from .test_keyboard_layout import *
157
Python
25.333329
35
0.764331
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/tests/test_keyboard_layout.py
import omni.kit.test import omni.kit.ui_test as ui_test import carb.input from omni.kit.hotkeys.core import get_hotkey_context, get_hotkey_registry, HotkeyFilter from omni.kit.actions.core import get_action_registry TEST_HOTKEY_EXT_ID = "omni.kit.hotkey.test.hotkey" TEST_ACTION_EXT_ID = "omni.kit.hotkey.test.action" TEST_CONTEXT_PRESS_ACTION_ID = "hotkey_test_context_press_action" TEST_CONTEXT_RELEASE_ACTION_ID = "hotkey_test_context_release_action" TEST_GLOBAL_PRESS_ACTION_ID = "hotkey_test_global_press_action" TEST_GLOBAL_RELEASE_ACTION_ID = "hotkey_test_global_release_action" TEST_CONTEXT_NAME = "[email protected]" TEST_HOTKEY = "CTRL+Z" _global_press_action_count = 0 def global_press_action_func(): global _global_press_action_count _global_press_action_count += 1 class TestKeyboardLayout(omni.kit.test.AsyncTestCase): async def setUp(self): self._hotkey_registry = get_hotkey_registry() self._hotkey_context = get_hotkey_context() self._action_registry = get_action_registry() self._filter = HotkeyFilter(context=TEST_CONTEXT_NAME) self._action_registry.register_action(TEST_ACTION_EXT_ID, TEST_GLOBAL_PRESS_ACTION_ID, global_press_action_func) self._hotkey_registry.clear_storage() await ui_test.emulate_keyboard_press(carb.input.KeyboardInput.Z, carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL) await ui_test.human_delay() # After running each test async def tearDown(self): self._hotkey_context = None self._hotkey_registry.deregister_all_hotkeys_for_extension(TEST_HOTKEY_EXT_ID) self._hotkey_registry = None self._action_registry.deregister_all_actions_for_extension(TEST_ACTION_EXT_ID) self._action_registry = None async def test_hotkey_register_with_new_layout(self): self._hotkey_registry.switch_layout("German QWERTZ") # With new keyboard layout, key combination should be changed when register hotkey = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_GLOBAL_PRESS_ACTION_ID) self.assertIsNotNone(hotkey) self.assertEqual(hotkey.key_combination.as_string, "CTRL + Y") await self.__verify_trigger(carb.input.KeyboardInput.Z, False) await self.__verify_trigger(carb.input.KeyboardInput.Y, True) async def test_hotkey_switch_layout(self): self._hotkey_registry.switch_layout("U.S. QWERTY") # Global pressed hotkey hotkey = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_GLOBAL_PRESS_ACTION_ID) self.assertIsNotNone(hotkey) # Trigger hotkey in global, default layout, should trigger await self.__verify_trigger(carb.input.KeyboardInput.Z, True) # Switch layout self._hotkey_registry.switch_layout("German QWERTZ") self.assertEqual(hotkey.key_combination.as_string, "CTRL + Y") # Default key, nothing triggered await self.__verify_trigger(carb.input.KeyboardInput.Z, False) # Trigger with new key mapping await self.__verify_trigger(carb.input.KeyboardInput.Y, True) # Switch layout back to default self._hotkey_registry.switch_layout("U.S. QWERTY") self.assertEqual(hotkey.key_combination.as_string, "CTRL + Z") # New key, nothing triggered await self.__verify_trigger(carb.input.KeyboardInput.Y, False) # Trigger with default key mapping await self.__verify_trigger(carb.input.KeyboardInput.Z, True) async def test_user_hotkey(self): self._hotkey_registry.switch_layout("U.S. QWERTY") hotkey = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, "CTRL + M", TEST_ACTION_EXT_ID, TEST_GLOBAL_PRESS_ACTION_ID) self.assertIsNotNone(hotkey) self._hotkey_registry.edit_hotkey(hotkey, "CTRL + Z", None) self.assertEqual(hotkey.key_combination.as_string, "CTRL + Z") self._hotkey_registry.switch_layout("German QWERTZ") self.assertEqual(hotkey.key_combination.as_string, "CTRL + Z") async def __verify_trigger(self, key, should_trigger): saved_count = _global_press_action_count await ui_test.emulate_keyboard_press(key, carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL) await ui_test.human_delay() if should_trigger: self.assertEqual(_global_press_action_count, saved_count + 1) else: self.assertEqual(_global_press_action_count, saved_count)
4,565
Python
42.075471
136
0.698138
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/tests/test_trigger.py
import omni.kit.test import omni.kit.ui_test as ui_test import carb.input from omni.kit.hotkeys.core import get_hotkey_context, get_hotkey_registry, HotkeyFilter, KeyCombination from omni.kit.actions.core import get_action_registry SETTING_ALLOW_LIST = "/exts/omni.kit.hotkeys.core/allow_list" TEST_HOTKEY_EXT_ID = "omni.kit.hotkey.test.hotkey" TEST_ACTION_EXT_ID = "omni.kit.hotkey.test.action" TEST_CONTEXT_PRESS_ACTION_ID = "hotkey_test_context_press_action" TEST_CONTEXT_RELEASE_ACTION_ID = "hotkey_test_context_release_action" TEST_GLOBAL_PRESS_ACTION_ID = "hotkey_test_global_press_action" TEST_GLOBAL_RELEASE_ACTION_ID = "hotkey_test_global_release_action" TEST_CONTEXT_NAME = "[email protected]" TEST_HOTKEY = "CTRL+T" _context_press_action_count = 0 _context_release_action_count = 0 _global_press_action_count = 0 _global_release_action_count = 0 def context_press_action_func(): global _context_press_action_count _context_press_action_count += 1 def context_release_action_func(): global _context_release_action_count _context_release_action_count += 1 def global_press_action_func(): global _global_press_action_count _global_press_action_count += 1 def global_release_action_func(): global _global_release_action_count _global_release_action_count += 1 class TestTrigger(omni.kit.test.AsyncTestCase): async def setUp(self): self._hotkey_registry = get_hotkey_registry() self._hotkey_context = get_hotkey_context() self._action_registry = get_action_registry() self._filter = HotkeyFilter(context=TEST_CONTEXT_NAME) await ui_test.emulate_keyboard_press(carb.input.KeyboardInput.T, carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL) await ui_test.human_delay() self.assertEqual(_context_press_action_count, 0) self.assertEqual(_context_release_action_count, 0) self.assertEqual(_global_press_action_count, 0) self.assertEqual(_global_release_action_count, 0) # Hotkey with context self._action_registry.register_action(TEST_ACTION_EXT_ID, TEST_CONTEXT_PRESS_ACTION_ID, context_press_action_func) hotkey = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_CONTEXT_PRESS_ACTION_ID, filter=self._filter) self.assertIsNotNone(hotkey) # Hotkey with context with key released self._action_registry.register_action(TEST_ACTION_EXT_ID, TEST_CONTEXT_RELEASE_ACTION_ID, context_release_action_func) hotkey = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, KeyCombination(TEST_HOTKEY, trigger_press=False), TEST_ACTION_EXT_ID, TEST_CONTEXT_RELEASE_ACTION_ID, filter=self._filter) self.assertIsNotNone(hotkey) # Global pressed hotkey self._action_registry.register_action(TEST_ACTION_EXT_ID, TEST_GLOBAL_PRESS_ACTION_ID, global_press_action_func) hotkey = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_GLOBAL_PRESS_ACTION_ID) self.assertIsNotNone(hotkey) # Global released hotkey self._action_registry.register_action(TEST_ACTION_EXT_ID, TEST_GLOBAL_RELEASE_ACTION_ID, global_release_action_func) hotkey = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, KeyCombination(TEST_HOTKEY, trigger_press=False), TEST_ACTION_EXT_ID, TEST_GLOBAL_RELEASE_ACTION_ID) self.assertIsNotNone(hotkey) # After running each test async def tearDown(self): self._hotkey_context = None self._hotkey_registry.deregister_all_hotkeys_for_extension(TEST_HOTKEY_EXT_ID) self._hotkey_registry = None self._action_registry.deregister_all_actions_for_extension(TEST_ACTION_EXT_ID) self._action_registry = None async def test_hotkey_in_context(self): # Trigger hotkey in context self._hotkey_context.push(TEST_CONTEXT_NAME) await ui_test.emulate_keyboard_press(carb.input.KeyboardInput.T, carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL) await ui_test.human_delay() self.assertEqual(_context_press_action_count, 1) self.assertEqual(_context_release_action_count, 1) self.assertEqual(_global_press_action_count, 0) self.assertEqual(_global_release_action_count, 0) self._hotkey_context.pop() # Trigger hotkey in global await ui_test.emulate_keyboard_press(carb.input.KeyboardInput.T, carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL) await ui_test.human_delay() self.assertEqual(_context_press_action_count, 1) self.assertEqual(_context_release_action_count, 1) self.assertEqual(_global_press_action_count, 1) self.assertEqual(_global_release_action_count, 1) async def test_allow_list(self): global _global_press_action_count, _global_release_action_count settings = carb.settings.get_settings() try: # Do not trigger since key not in allow list settings.set(SETTING_ALLOW_LIST, ["F1"]) await ui_test.emulate_keyboard_press(carb.input.KeyboardInput.T, carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL) await ui_test.human_delay() self.assertEqual(_global_press_action_count, 0) self.assertEqual(_global_release_action_count, 0) # Trigger since key in allow list settings.set(SETTING_ALLOW_LIST, ["CTRL + T"]) await ui_test.emulate_keyboard_press(carb.input.KeyboardInput.T, carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL) await ui_test.human_delay() self.assertEqual(_global_press_action_count, 1) self.assertEqual(_global_release_action_count, 1) # Trigger since no allow list settings.set(SETTING_ALLOW_LIST, []) await ui_test.emulate_keyboard_press(carb.input.KeyboardInput.T, carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL) await ui_test.human_delay() self.assertEqual(_global_press_action_count, 2) self.assertEqual(_global_release_action_count, 2) finally: settings.set(SETTING_ALLOW_LIST, []) _global_press_action_count = 0 _global_release_action_count = 0
6,265
Python
45.414814
197
0.698324
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/tests/test_key_combination.py
# NOTE: # omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests # For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html import omni.kit.test # Import extension python module we are testing with absolute import path, as if we are external user (other extension) from omni.kit.hotkeys.core import KeyCombination import carb.input # Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test class TestKeyCombination(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): pass # After running each test async def tearDown(self): pass # Actual test, notice it is "async" function, so "await" can be used if needed async def test_key_define_function(self): key_comb = KeyCombination(carb.input.KeyboardInput.D) self.assertEqual(key_comb.as_string, "D") self.assertEqual(key_comb.trigger_press, True) key_comb = KeyCombination(carb.input.KeyboardInput.D, trigger_press=False) self.assertEqual(key_comb.as_string, "D") self.assertEqual(key_comb.trigger_press, False) key_comb = KeyCombination(carb.input.KeyboardInput.D, modifiers=carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL) self.assertEqual(key_comb.as_string, "CTRL + D") key_comb = KeyCombination(carb.input.KeyboardInput.D, modifiers=carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT) self.assertEqual(key_comb.as_string, "SHIFT + D") key_comb = KeyCombination(carb.input.KeyboardInput.D, modifiers=carb.input.KEYBOARD_MODIFIER_FLAG_ALT) self.assertEqual(key_comb.as_string, "ALT + D") key_comb = KeyCombination(carb.input.KeyboardInput.A, modifiers=carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL + carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT) self.assertEqual(key_comb.as_string, "SHIFT + CTRL + A") key_comb = KeyCombination(carb.input.KeyboardInput.A, modifiers=carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL + carb.input.KEYBOARD_MODIFIER_FLAG_ALT) self.assertEqual(key_comb.as_string, "CTRL + ALT + A") key_comb = KeyCombination(carb.input.KeyboardInput.A, modifiers=carb.input.KEYBOARD_MODIFIER_FLAG_ALT + carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT) self.assertEqual(key_comb.as_string, "SHIFT + ALT + A") key_comb = KeyCombination(carb.input.KeyboardInput.B, modifiers=carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL + carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT + carb.input.KEYBOARD_MODIFIER_FLAG_ALT) self.assertEqual(key_comb.as_string, "SHIFT + CTRL + ALT + B") async def test_key_string_function(self): key_comb = KeyCombination("d") self.assertEqual(key_comb.as_string, "D") key_comb = KeyCombination("D") self.assertEqual(key_comb.as_string, "D") self.assertTrue(key_comb.trigger_press) key_comb = KeyCombination("D", trigger_press=False) self.assertEqual(key_comb.as_string, "D") self.assertFalse(key_comb.trigger_press) key_comb = KeyCombination("ctrl+d") self.assertEqual(key_comb.as_string, "CTRL + D") key_comb = KeyCombination("ctl+d") self.assertEqual(key_comb.as_string, "CTRL + D") key_comb = KeyCombination("control+d") self.assertEqual(key_comb.as_string, "CTRL + D") key_comb = KeyCombination("shift+d") self.assertEqual(key_comb.as_string, "SHIFT + D") key_comb = KeyCombination("alt+d") self.assertEqual(key_comb.as_string, "ALT + D") key_comb = KeyCombination("ctrl+shift+a") self.assertEqual(key_comb.as_string, "SHIFT + CTRL + A") key_comb = KeyCombination("shift+ctrl+A") self.assertEqual(key_comb.as_string, "SHIFT + CTRL + A") key_comb = KeyCombination("ctrl+ALT+a") self.assertEqual(key_comb.as_string, "CTRL + ALT + A") key_comb = KeyCombination("alt+CTRL+a") self.assertEqual(key_comb.as_string, "CTRL + ALT + A") key_comb = KeyCombination("ALT+shift+a") self.assertEqual(key_comb.as_string, "SHIFT + ALT + A") key_comb = KeyCombination("SHIFT+alt+a") self.assertEqual(key_comb.as_string, "SHIFT + ALT + A") key_comb = KeyCombination("Ctrl+shift+alt+b") self.assertEqual(key_comb.as_string, "SHIFT + CTRL + ALT + B") key_comb = KeyCombination("Ctrl+alt+shift+b") self.assertEqual(key_comb.as_string, "SHIFT + CTRL + ALT + B")
4,567
Python
47.595744
196
0.680534
omniverse-code/kit/exts/omni.kit.hotkeys.core/docs/index.rst
omni.kit.hotkeys.core ########################### omni.kit.hotkeys.core .. toctree:: :maxdepth: 1 CHANGELOG USAGE
125
reStructuredText
11.599999
27
0.528
omniverse-code/kit/exts/omni.gpu_foundation/omni/gpu_foundation_factory/__init__.py
from ._gpu_foundation_factory import * from .impl.foundation_extension import GpuFoundationConfig # Cached interface instance pointer def get_gpu_foundation_factory_interface() -> IGpuFoundationFactory: """Returns cached :class:`omni.gpu_foundation.IGpuFoundationFactory` interface""" if not hasattr(get_gpu_foundation_factory_interface, "gpu_foundation_factory"): get_gpu_foundation_factory_interface.gpu_foundation_factory = acquire_gpu_foundation_factory_interface() return get_gpu_foundation_factory_interface.gpu_foundation_factory
559
Python
49.909086
112
0.792487
omniverse-code/kit/exts/omni.kit.property.material/PACKAGE-LICENSES/omni.kit.property.material-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
412
Markdown
57.999992
74
0.839806
omniverse-code/kit/exts/omni.kit.property.material/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.8.19" category = "Internal" feature = true # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarly for displaying extension info in UI title = "Material Property Widget" description="View and Edit Material Property Values" # URL of the extension source repository. repository = "" # Preview image. Folder named "data" automatically goes in git lfs (see .gitattributes file). preview_image = "data/preview.png" # Icon is shown in Extensions window, it is recommended to be square, of size 256x256. icon = "data/icon.png" # Keywords for the extension keywords = ["kit", "usd", "property", "material"] # Location of change log file in target (final) folder of extension, relative to the root. # More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog="docs/CHANGELOG.md" # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" [dependencies] "omni.usd" = {} "omni.ui" = {} "omni.kit.window.property" = {} "omni.kit.material.library" = {} "omni.kit.property.usd" = {} "omni.client" = {} "omni.kit.window.quicksearch" = { optional = true } [[python.module]] name = "omni.kit.property.material" [[test]] args = [ "--/renderer/enabled=pxr", "--/renderer/active=pxr", "--/renderer/multiGpu/enabled=false", "--/renderer/multiGpu/autoEnable=false", # Disable mGPU with PXR due to OM-51026, OM-53611 "--/renderer/multiGpu/maxGpuCount=1", "--/app/asyncRendering=false", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--/persistent/app/stage/dragDropImport='reference'", "--/persistent/app/material/dragDropMaterialPath='absolute'", "--/persistent/app/omniverse/filepicker/options_menu/show_details=false", "--no-window" ] dependencies = [ "omni.kit.renderer.capture", "omni.kit.mainwindow", "omni.kit.widget.stage", "omni.kit.window.content_browser", "omni.kit.window.stage", "omni.kit.ui_test", "omni.kit.test_suite.helpers", "omni.hydra.pxr", "omni.kit.window.viewport" ] stdoutFailPatterns.exclude = [ "*HydraRenderer failed to render this frame*", # Can drop a frame or two rendering with OpenGL interop "*Cannot use omni.hydra.pxr without OpenGL interop*" # Linux TC configs with multi-GPU might not have OpenGL available ]
2,489
TOML
31.337662
122
0.703495
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/__init__.py
from .scripts import *
23
Python
10.999995
22
0.73913
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/scripts/material_utils.py
import carb from pxr import Usd, Sdf, UsdShade class Constant: def __setattr__(self, name, value): raise Exception(f"Can't change Constant.{name}") ICON_SIZE = 96 BOUND_LABEL_WIDTH = 50 FONT_SIZE = 14.0 SDF_PATH_INVALID = "$NONE$" PERSISTENT_SETTINGS_PREFIX = "/persistent" MIXED = "Mixed" MIXED_COLOR = 0xFFCC9E61 # verify SDF_PATH_INVALID is invalid if Sdf.Path.IsValidPathString(SDF_PATH_INVALID): raise Exception(f"SDF_PATH_INVALID is Sdf.Path.IsValidPathString - FIXME") def _populate_data(stage, material_data, collection_or_prim, material=None, relationship=None): def update_strength(value, strength): if value is None: value = strength elif value != strength: value = Constant.MIXED return value if isinstance(collection_or_prim, Usd.CollectionAPI): prim_path = collection_or_prim.GetCollectionPath() else: prim_path = collection_or_prim.GetPath() inherited = False strength_default = carb.settings.get_settings().get( Constant.PERSISTENT_SETTINGS_PREFIX + "/app/stage/materialStrength" ) strength = strength_default material_name = Constant.SDF_PATH_INVALID if material: relationship_source_path = None if relationship: relationship_source_path = relationship.GetPrim().GetPath() if isinstance(collection_or_prim, Usd.CollectionAPI): relationship_source_path = relationship.GetTargets()[0] if ( material and relationship and prim_path.pathString != relationship_source_path.pathString ): #If we have a material, but it's not assigned directly to us, it must be inherited inherited = True if relationship: strength = UsdShade.MaterialBindingAPI.GetMaterialBindingStrength(relationship) material_name = material.GetPrim().GetPath().pathString if not material_name in material_data["material"]: material_data["material"][material_name] = { "bound": set(), "inherited": set(), "bound_info": set(), "inherited_info": set(), "relationship": set(), "strength": None, } if inherited: material_data["material"][material_name]["inherited"].add(collection_or_prim) material_data["material"][material_name]["inherited_info"].add( (prim_path.pathString, material_name, strength) ) material_data["inherited"].add(collection_or_prim) material_data["inherited_info"].add((prim_path.pathString, material_name, strength)) else: material_data["material"][material_name]["bound"].add(collection_or_prim) material_data["material"][material_name]["bound_info"].add( (prim_path.pathString, material_name, strength) ) material_data["bound"].add(collection_or_prim) material_data["bound_info"].add((prim_path.pathString, material_name, strength)) if relationship: material_data["relationship"].add(relationship) material_data["material"][material_name]["relationship"].add(relationship) if strength is not None: material_data["material"][material_name]["strength"] = update_strength( material_data["material"][material_name]["strength"], strength ) material_data["strength"] = update_strength(material_data["strength"], strength) def get_binding_from_prims(stage, prim_paths): material_data = {"material": {}, "bound": set(), "bound_info": set(), "inherited": set(), "inherited_info": set(), "relationship": set(), "strength": None} for prim_path in prim_paths: if prim_path.IsPrimPath(): prim = stage.GetPrimAtPath(prim_path) if prim: material, relationship = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() _populate_data(stage, material_data, prim, material, relationship) elif Usd.CollectionAPI.IsCollectionAPIPath(prim_path): real_prim_path = prim_path.GetPrimPath() prim = stage.GetPrimAtPath(real_prim_path) binding_api = UsdShade.MaterialBindingAPI(prim) all_bindings = binding_api.GetCollectionBindings() collection_name = prim_path.pathString[prim_path.pathString.find(".collection:")+12:] #TODO: test this when we have multiple collections on a prim if all_bindings: for b in all_bindings: collection = b.GetCollection() if collection_name==collection.GetName(): relationship = b.GetBindingRel() material = b.GetMaterial() _populate_data(stage, material_data, collection, material, relationship) else: #If there are no bindings we want to set up defaults anyway so the widget appears with "None" assigned collection = Usd.CollectionAPI.Get(stage, prim_path) _populate_data(stage, material_data, collection) return material_data
5,252
Python
40.690476
159
0.619954
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/scripts/__init__.py
from .material_properties import *
35
Python
16.999992
34
0.8
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/scripts/usd_attribute_widget.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from typing import List from omni.kit.window.property.templates import SimplePropertyWidget from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidget, UsdPropertyUiEntry from .subIdentifier_utils import SubIdentifierUtils import copy import asyncio import carb import omni.ui as ui import omni.usd from pxr import Usd, Tf, Vt, Sdf, UsdShade, UsdUI class UsdMaterialAttributeWidget(UsdPropertiesWidget): def __init__(self, schema: Usd.SchemaBase, title: str, include_names: List[str], exclude_names: List[str], schema_ignore: Usd.SchemaBase=None): """ Constructor. Args: schema (Usd.SchemaBase): schema class schema_ignore (List[Usd.SchemaBase]): ignored schema class title (str): Title of the widgets on the Collapsable Frame. include_names (list): list of names to be included exclude_names (list): list of names to be excluded """ super().__init__(title=title, collapsed=False) self._title = title self._schema = schema self._schema_ignore = schema_ignore self._schema_attr_names = self._schema.GetSchemaAttributeNames(True) self._schema_attr_names = self._schema_attr_names + include_names self._schema_attr_names = set(self._schema_attr_names) - set(exclude_names) self._additional_paths = [] self._lookup_table = { # materials - should be set "inputs:diffuse_color_constant": {"name": "Base Color", "group": "Albedo"}, "inputs:diffuse_texture": {"name": "Albedo Map", "group": "Albedo"}, "inputs:albedo_desaturation": {"name": "Albedo Desaturation", "group": "Albedo"}, "inputs:albedo_add": {"name": "Albedo Add", "group": "Albedo"}, "inputs:albedo_brightness": {"name": "Albedo Brightness", "group": "Albedo"}, "inputs:diffuse_tint": {"name": "Color Tint", "group": "Albedo"}, "inputs:reflection_roughness_constant": {"name": "Roughness Amount", "group": "Reflectivity"}, "inputs:reflection_roughness_texture_influence": { "name": "Roughness Map Influence", "group": "Reflectivity", }, "inputs:reflectionroughness_texture": {"name": "Roughness Map", "group": "Reflectivity"}, "inputs:metallic_constant": {"name": "Metallic Amount", "group": "Reflectivity"}, "inputs:metallic_texture_influence": {"name": "Metallic Map Influence", "group": "Reflectivity"}, "inputs:metallic_texture": {"name": "Metallic Map", "group": "Reflectivity"}, "inputs:specular_level": {"name": "Specular", "group": "Reflectivity"}, "inputs:enable_ORM_texture": {"name": "Enable ORM Texture", "group": "Reflectivity"}, "inputs:ORM_texture": {"name": "ORM Map", "group": "Reflectivity"}, "inputs:ao_to_diffuse": {"name": "AO to Diffuse", "group": "AO"}, "inputs:ao_texture": {"name": "Ambient Occlusion Map", "group": "AO"}, "inputs:enable_emission": {"name": "Enable Emission", "group": "Emissive"}, "inputs:emissive_color": {"name": "Emissive Color", "group": "Emissive"}, "inputs:emissive_color_texture": {"name": "Emissive Color map", "group": "Emissive"}, "inputs:emissive_mask_texture": {"name": "Emissive Mask map", "group": "Emissive"}, "inputs:emissive_intensity": {"name": "Emissive Intensity", "group": "Emissive"}, "inputs:bump_factor": {"name": "Normal Map Strength", "group": "Normal"}, "inputs:normalmap_texture": {"name": "Normal Map", "group": "Normal"}, "inputs:detail_bump_factor": {"name": "Detail Normal Strength", "group": "Normal"}, "inputs:detail_normalmap_texture": {"name": "Detail Normal Map", "group": "Normal"}, "inputs:project_uvw": {"name": "Enable Project UVW Coordinates", "group": "UV"}, "inputs:world_or_object": {"name": "Enable World Space", "group": "UV"}, "inputs:uv_space_index": {"name": "UV Space Index", "group": "UV"}, "inputs:texture_translate": {"name": "Texture Translate", "group": "UV"}, "inputs:texture_rotate": {"name": "Texture Rotate", "group": "UV"}, "inputs:texture_scale": {"name": "Texture Scale", "group": "UV"}, "inputs:detail_texture_translate": {"name": "Detail Texture Translate", "group": "UV"}, "inputs:detail_texture_rotate": {"name": "Detail Texture Rotate", "group": "UV"}, "inputs:detail_texture_scale": {"name": "Detail Texture Scale", "group": "UV"}, "inputs:excludeFromWhiteMode": {"group": "Material Flags", "name": "Exclude from White Mode"}, # UsdUVTexture "inputs:sourceColorSpace": {"group": "UsdUVTexture", "name": "inputs:sourceColorSpace"}, "inputs:fallback": {"group": "UsdUVTexture", "name": "inputs:fallback"}, "inputs:file": {"group": "UsdUVTexture", "name": "inputs:file"}, "inputs:sdrMetadata": {"group": "UsdUVTexture", "name": "inputs:sdrMetadata"}, "inputs:rgb": {"group": "UsdUVTexture", "name": "inputs:rgb"}, "inputs:scale": {"group": "UsdUVTexture", "name": "inputs:scale"}, "inputs:bias": {"group": "UsdUVTexture", "name": "inputs:bias"}, "inputs:wrapS": {"group": "UsdUVTexture", "name": "inputs:wrapS"}, "inputs:wrapT": {"group": "UsdUVTexture", "name": "inputs:wrapT"}, # preview surface inputs "inputs:diffuseColor": {"name": "Diffuse Color", "group": "Inputs"}, "inputs:emissiveColor": {"name": "Emissive Color", "group": "Inputs"}, "inputs:useSpecularWorkflow": {"name": "Use Specular Workflow", "group": "Inputs"}, "inputs:specularColor": {"name": "Specular Color", "group": "Inputs"}, "inputs:metallic": {"name": "Metallic", "group": "Inputs"}, "inputs:roughness": {"name": "Roughness", "group": "Inputs"}, "inputs:clearcoat": {"name": "Clearcoat", "group": "Inputs"}, "inputs:clearcoatRoughness": {"name": "Clearcoat Roughness", "group": "Inputs"}, "inputs:opacity": {"name": "Opacity", "group": "Inputs"}, "inputs:opacityThreshold": {"name": "Opacity Threshold", "group": "Inputs"}, "inputs:ior": {"name": "Index Of Refraction", "group": "Inputs"}, "inputs:normal": {"name": "Normal", "group": "Inputs"}, "inputs:displacement": {"name": "Displacement", "group": "Inputs"}, "inputs:occlusion": {"name": "Occlusion", "group": "Inputs"}, # info "info:id": {"name": "ID", "group": "Info"}, "info:implementationSource": {"name": "Implementation Source", "group": "Info"}, "info:mdl:sourceAsset": {"name": "", "group": "Info"}, "info:mdl:sourceAsset:subIdentifier": {"name": "", "group": "Info"}, # nodegraph "ui:nodegraph:node:displayColor": {"name": "Display Color", "group": "UI Properties"}, "ui:nodegraph:node:expansionState": {"name": "Expansion State", "group": "UI Properties"}, "ui:nodegraph:node:icon": {"name": "Icon", "group": "UI Properties"}, "ui:nodegraph:node:pos": {"name": "Position", "group": "UI Properties"}, "ui:nodegraph:node:size": {"name": "Size", "group": "UI Properties"}, "ui:nodegraph:node:stackingOrder": {"name": "Stacking Order", "group": "UI Properties"}, # backdrop "ui:description": {"name": "Description", "group": "UI Properties"}, } def on_new_payload(self, payload): """ See PropertyWidget.on_new_payload """ self._anchor_prim = None self._shader_paths = [] self._add_source_color_space_placeholder = False self._material_annotations = {} if not super().on_new_payload(payload): return False if len(self._payload) == 0: return False anchor_prim = None shader_paths = [] mtl_paths = [] for prim_path in self._payload: prim = self._get_prim(prim_path) if not prim or not prim.IsA(self._schema): return False if self._schema_ignore and prim.IsA(self._schema_ignore): return False shader_prim = omni.usd.get_shader_from_material(prim, True) if shader_prim: shader_paths.append(shader_prim.GetPath()) shader = UsdShade.Shader(shader_prim if shader_prim else prim) asset = shader.GetSourceAsset("mdl") if shader else None mdl_file = asset.resolvedPath if asset else None if mdl_file: def loaded_mdl_subids(mtl_list, filename): mdl_dict = {} for mtl in mtl_list: mdl_dict[mtl.name] = mtl.annotations self._material_annotations[filename] = mdl_dict mtl_paths.append(mdl_file) asyncio.ensure_future(omni.kit.material.library.get_subidentifier_from_mdl(mdl_file=mdl_file, on_complete_fn=lambda l, f=mdl_file: loaded_mdl_subids(mtl_list=l, filename=f))) anchor_prim = prim if anchor_prim: stage = payload.get_stage() shader = UsdShade.Shader.Get(stage, anchor_prim.GetPath()) if shader and shader.GetShaderId() == "UsdUVTexture": attr = anchor_prim.GetAttribute("inputs:sourceColorSpace") if not attr: self._add_source_color_space_placeholder = True elif attr.GetTypeName() == Sdf.ValueTypeNames.Token: tokens = attr.GetMetadata("allowedTokens") if not tokens: # fix missing tokens on attribute attr.SetMetadata("allowedTokens", ["auto", "raw", "sRGB"]) self._mtl_identical = True if mtl_paths: self._mtl_identical = mtl_paths.count(mtl_paths[0]) == len(mtl_paths) self._anchor_prim = anchor_prim self._shader_paths = shader_paths if anchor_prim: return True return False def _filter_props_to_build(self, attrs): if not self._mtl_identical: for attr in copy.copy(attrs): if attr.GetName() == "info:mdl:sourceAsset:subIdentifier": attrs.remove(attr) return [ attr for attr in attrs if isinstance(attr, Usd.Attribute) and (attr.GetName() in self._schema_attr_names and not attr.IsHidden() or UsdShade.Input.IsInput(attr) and not attr.IsHidden() or UsdShade.Output.IsOutput(attr) and not attr.IsHidden()) ] def _customize_props_layout(self, attrs): from omni.kit.property.usd.custom_layout_helper import ( CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty, ) from omni.kit.window.property.templates import ( SimplePropertyWidget, LABEL_WIDTH, LABEL_HEIGHT, HORIZONTAL_SPACING, ) self._additional_paths = [] if not self._anchor_prim: return [] ignore_list = ["outputs:out", "info:id", "info:implementationSource", "info:mdl:sourceAsset", "info:mdl:sourceAsset:subIdentifier"] # check for duplicate attributes in material/shader stage = self._payload.get_stage() add_source_color_space_placeholder = len(self._payload) for path in self._payload: prim = stage.GetPrimAtPath(path) shader_prim = omni.usd.get_shader_from_material(prim, True) if shader_prim: shader = UsdShade.Shader.Get(stage, shader_prim.GetPath()) if shader and shader.GetShaderId() == "UsdUVTexture": attr = shader_prim.GetAttribute("inputs:sourceColorSpace") if not attr: add_source_color_space_placeholder -= 1 if add_source_color_space_placeholder == 0: self._add_source_color_space_placeholder = True # get child attributes attr_added = {} for path in self._payload: if not path in attr_added: attr_added[path.pathString] = {} material_prim = stage.GetPrimAtPath(path) shader_prim = omni.usd.get_shader_from_material(material_prim, True) if shader_prim: asyncio.ensure_future(omni.usd.get_context().load_mdl_parameters_for_prim_async(shader_prim)) for shader_attr in shader_prim.GetAttributes(): if shader_attr.IsHidden(): continue # check if shader attribute already exists in material material_attr = material_prim.GetAttribute(shader_attr.GetName()) if material_attr.IsHidden(): continue if material_attr: # use material attribute NOT shader attribute attr_added[path.pathString][shader_attr.GetName()] = material_attr continue # add paths to usd_changed watch list prim_path = shader_attr.GetPrimPath() if not prim_path in self._payload and not prim_path in self._additional_paths: self._additional_paths.append(prim_path) if not any(name in shader_attr.GetName() for name in ignore_list): attr_added[path.pathString][shader_attr.GetName()] = shader_attr if not self._anchor_prim: return [] # remove uncommon keys anchor_path = self._anchor_prim.GetPath().pathString anchor_attr = attr_added[anchor_path] common_keys = anchor_attr.keys() for key in attr_added: if anchor_path != key: common_keys = common_keys & attr_added[key].keys() def compare_metadata(meta1, meta2) -> bool: ignored_metadata = {"default", "colorSpace"} for key, value in meta1.items(): if key not in ignored_metadata and (key not in meta2 or meta2[key] != value): return False for key, value in meta2.items(): if key not in ignored_metadata and (key not in meta1 or meta1[key] != value): return False return True # remove any keys that metadata's differ for key in copy.copy(list(common_keys)): attr1 = attr_added[anchor_path][key] for path in self._payload: if path == anchor_path: continue attr2 = attr_added[path.pathString][key] if not ( attr1.GetName() == attr2.GetName() and attr1.GetDisplayGroup() == attr2.GetDisplayGroup() and attr1.GetConnections() == attr2.GetConnections() and compare_metadata(attr1.GetAllMetadata(), attr2.GetAllMetadata()) and type(attr1) == type(attr2) ): common_keys.remove(key) break # add remaining common keys # use anchor_attr.keys() to keep the original order as common_keys order has changed for key in anchor_attr.keys(): if key not in common_keys: continue attr = anchor_attr[key] attrs.append( UsdPropertyUiEntry( attr.GetName(), attr.GetDisplayGroup(), attr.GetAllMetadata(), type(attr), prim_paths=self._shader_paths, )) if self._add_source_color_space_placeholder: attrs.append( UsdPropertyUiEntry( "inputs:sourceColorSpace", "UsdUVTexture", { Sdf.PrimSpec.TypeNameKey: "token", "allowedTokens": Vt.TokenArray(3, ("auto", "raw", "sRGB")), "customData": {"default": "auto"}, }, Usd.Attribute, ) ) # move inputs/outputs to own group for attr in attrs: if attr.attr_name and attr.attr_name in self._lookup_table: lookup = self._lookup_table[attr.attr_name] displayName = attr.metadata.get("displayName", None) if not displayName and lookup["name"]: attr.override_display_name(lookup["name"]) if not attr.display_group and lookup["group"]: attr.override_display_group(lookup["group"]) if not attr.display_group: if attr.prop_name.startswith("output"): attr.override_display_group("Outputs") elif attr.prop_name.startswith("inputs"): attr.override_display_group("Inputs") if attr.display_group == "UI Properties": if self._anchor_prim.IsA(UsdUI.Backdrop): attr.display_group_collapsed = False else: attr.display_group_collapsed = True elif attr.display_group in ["Outputs", "Material Flags"]: attr.display_group_collapsed = True #remove inputs: and outputs: prefixes from items w/o explicit display name metadata if Sdf.PropertySpec.DisplayNameKey not in attr.metadata: attr.metadata[Sdf.PropertySpec.DisplayNameKey] = attr.attr_name.split(":")[-1] # move groups to top... frame = CustomLayoutFrame(hide_extra=False) with frame: with CustomLayoutGroup("Info"): CustomLayoutProperty("info:implementationSource", "implementationSource") CustomLayoutProperty("info:mdl:sourceAsset", "mdl:sourceAsset") CustomLayoutProperty("info:mdl:sourceAsset:subIdentifier", "mdl:sourceAsset:subIdentifier") CustomLayoutProperty("info:id", "id") material_annotations = SubIdentifierUtils.get_annotations("description", prim, self._material_annotations) if material_annotations: with CustomLayoutGroup("Description", collapsed=True): CustomLayoutProperty(None, None, build_fn=lambda s, a, m, pt, pp, al, aw, mal=material_annotations: SubIdentifierUtils.annotations_build_fn(stage=s, attr_name=a, metadata=m, property_type=pt, prim_paths=pp, additional_label_kwargs=al, additional_widget_kwarg=aw, material_annotations=mal)) with CustomLayoutGroup("Outputs", collapsed=True): CustomLayoutProperty("outputs:mdl:surface", "mdl:surface") CustomLayoutProperty("outputs:mdl:displacement", "mdl:displacement") CustomLayoutProperty("outputs:mdl:volume", "mdl:volume") CustomLayoutProperty("outputs:surface", "surface") CustomLayoutProperty("outputs:displacement", "displacement") CustomLayoutProperty("outputs:volume", "volume") attrs = frame.apply(attrs) # move Outputs to last, anything appearing after needs adding to CustomLayout above def output_sort(attr): if attr.prop_name.startswith("output"): if attr.prop_name == "outputs:out": return 2 return 1 return 0 attrs.sort(key=output_sort) return attrs def build_property_item(self, stage, ui_attr: UsdPropertyUiEntry, prim_paths: List[Sdf.Path]): if ui_attr.prop_name == "info:mdl:sourceAsset:subIdentifier": if self._anchor_prim: attr = self._anchor_prim.GetAttribute(ui_attr.prop_name) material_annotations = None if attr: shader = UsdShade.Shader(self._anchor_prim) asset = shader.GetSourceAsset("mdl") if shader else None mdl_file = asset.resolvedPath if asset else None if mdl_file and mdl_file in self._material_annotations: material_annotations = self._material_annotations[mdl_file] model = SubIdentifierUtils.build_subidentifier( stage, attr_name=ui_attr.prop_name, type_name=ui_attr.property_type, metadata=ui_attr.metadata, attr=attr, prim_paths=prim_paths, ) return model return super().build_property_item(stage, ui_attr, prim_paths) def _on_usd_changed(self, notice, stage): if stage != self._payload.get_stage(): return if not self._collapsable_frame: return if len(self._payload) == 0: return # Widget is pending rebuild, no need to check for dirty if self._pending_rebuild_task is not None: return for path in notice.GetChangedInfoOnlyPaths(): if path.name.startswith("info:"): self.request_rebuild() return for path in notice.GetResyncedPaths(): if path in self._additional_paths or path in self._payload: self.request_rebuild() return elif ( path.GetPrimPath() in self._additional_paths or path.GetPrimPath() in self._shader_paths or path.GetPrimPath() in self._payload ): # If prop is added or removed, rebuild frame # TODO only check against the attributes this widget cares about if bool(stage.GetPropertyAtPath(path)) != bool(self._models.get(path)): self.request_rebuild() return else: # OM-75480: For material prim, it needs special treatment. So modifying shader prim # needs to refresh material prim widget also. # How to avoid accessing private variable of parent class? self._pending_dirty_paths.add(path) super()._on_usd_changed(notice=notice, stage=stage)
23,730
Python
49.277542
190
0.55196
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/scripts/subIdentifier_utils.py
from typing import List from collections import defaultdict, OrderedDict from omni.kit.window.property.templates import SimplePropertyWidget, LABEL_WIDTH, LABEL_HEIGHT, HORIZONTAL_SPACING from omni.kit.property.usd.usd_property_widget import ( UsdPropertiesWidget, UsdPropertyUiEntry, UsdPropertiesWidgetBuilder, ) from omni.kit.property.usd.usd_attribute_model import UsdAttributeModel, TfTokenAttributeModel import asyncio import carb import omni.ui as ui import omni.usd from pxr import Usd, Tf, Vt, Sdf, UsdShade class SubIdentifierUtils: class AllowedAnnoItem(ui.AbstractItem): def __init__(self, item, token=None): from omni.kit.material.library import MaterialLibraryExtension super().__init__() if isinstance(item, MaterialLibraryExtension.SubIDEntry): if "subid_token" in item.annotations: self.token = item.annotations["subid_token"] else: self.token = item.name self.model = ui.SimpleStringModel(item.name) if "subid_display_name" in item.annotations: self.model = ui.SimpleStringModel(item.annotations['subid_display_name']) elif "display_name" in item.annotations: self.model = ui.SimpleStringModel(item.annotations['display_name']) else: self.model = ui.SimpleStringModel(item.name) else: if token: self.token = token self.model = ui.SimpleStringModel(item) else: self.token = item self.model = ui.SimpleStringModel(item) class SubIdentifierModel(TfTokenAttributeModel): def __init__( self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], self_refresh: bool, metadata: dict, options: list, attr: Usd.Attribute, ): self._widget = None self._combobox_options = [attr.Get()] super().__init__(stage=stage, attribute_paths=attribute_paths, self_refresh=self_refresh, metadata=metadata) self._has_index = False async def load_subids(): await omni.kit.app.get_app().next_update_async() await omni.kit.material.library.get_subidentifier_from_material(prim=attr.GetPrim(), on_complete_fn=self._have_list, use_functions=True) asyncio.ensure_future(load_subids()) def _get_allowed_tokens(self, attr): return self._combobox_options def _update_allowed_token(self): super()._update_allowed_token(SubIdentifierUtils.AllowedAnnoItem) def _update_value(self, force=False): from omni.kit.property.usd.usd_model_base import UsdBase was_updating_value = self._updating_value self._updating_value = True if UsdBase._update_value(self, force): # TODO don't have to do this every time. Just needed when "allowedTokens" actually changed self._update_allowed_token() def find_allowed_token(value): # try to match the full token, i.e. simple name with function parameters for i in range(0, len(self._allowed_tokens)): if self._allowed_tokens[i].token == value: return i # if the above failed, drop the parameter list of the query # try to find a match based on the simple name alone # note, because of overloads there can be more than one match query = value.split("(", 1)[0] match_count = 0 first_match_index = -1 for i in range(0, len(self._allowed_tokens)): if self._allowed_tokens[i].token.split("(", 1)[0] == query: if match_count == 0: first_match_index = i match_count += 1 # if there is one match based on simple name, we can safely return this one if match_count == 1: return first_match_index # the match is not unique, we need to return a `<not found>` else: return -1 index = find_allowed_token(self._value) if self._value and index == -1: carb.log_warn(f"failed to find '{self._value}' in function name list") index = len(self._allowed_tokens) self._allowed_tokens.append(SubIdentifierUtils.AllowedAnnoItem(token=self._value, item=f"<sub-identifier not found: '{self._value}'>")) if index != -1 and self._current_index.as_int != index: self._current_index.set_value(index) self._item_changed(None) self._updating_value = was_updating_value def _have_list(self, mtl_list: list): if mtl_list: self._combobox_options = mtl_list self._set_dirty() if self._has_index is False: self._update_value() self._has_index = True def build_subidentifier( stage, attr_name, type_name, metadata, attr: Usd.Attribute, prim_paths: List[Sdf.Path], additional_label_kwargs=None, additional_widget_kwargs=None, ): with ui.HStack(spacing=HORIZONTAL_SPACING): model = None UsdPropertiesWidgetBuilder._create_label(attr_name, metadata, additional_label_kwargs) tokens = metadata.get("allowedTokens") if not tokens: tokens = [attr.Get()] model = SubIdentifierUtils.SubIdentifierModel( stage, attribute_paths=[path.AppendProperty(attr_name) for path in prim_paths], self_refresh=False, metadata=metadata, options=tokens, attr=attr, ) widget_kwargs = {"name": "choices", "no_default": True} if additional_widget_kwargs: widget_kwargs.update(additional_widget_kwargs) with ui.ZStack(): value_widget = ui.ComboBox(model, **widget_kwargs) value_widget.identifier = 'sdf_asset_info:mdl:sourceAsset:subIdentifier' mixed_overlay = UsdPropertiesWidgetBuilder._create_mixed_text_overlay() UsdPropertiesWidgetBuilder._create_control_state( model=model, value_widget=value_widget, mixed_overlay=mixed_overlay, **widget_kwargs ) return model def annotations_build_fn( stage, attr_name, metadata, property_type, prim_paths: List[Sdf.Path], additional_label_kwargs, additional_widget_kwarg, material_annotations ): additional_label_kwargs = {"width": ui.Fraction(1), "read_only": True} description = material_annotations["description"] description = description.replace("\n\r", "\r").replace("\n", "\r") description_list = description.split("\r") if len(description_list) > 1: with ui.VStack(spacing=2): for description in description_list: if not description: continue parts = description.split("\t", maxsplit=1) if len(parts) == 1: parts = description.split(" ", maxsplit=1) with ui.HStack(spacing=HORIZONTAL_SPACING): if len(parts) == 1: parts.append("") UsdPropertiesWidgetBuilder._create_label(parts[0]) if parts[1].startswith("http"): additional_label_kwargs["tooltip"] = f"Click to open \"{parts[1]}\"" else: additional_label_kwargs["tooltip"] = parts[1] UsdPropertiesWidgetBuilder._create_text_label(parts[1], additional_label_kwargs=additional_label_kwargs) else: with ui.HStack(spacing=HORIZONTAL_SPACING): UsdPropertiesWidgetBuilder._create_label("Description") additional_label_kwargs["tooltip"] = description UsdPropertiesWidgetBuilder._create_text_label(description, additional_label_kwargs=additional_label_kwargs) def get_annotations( annotation_key, prim, material_annotation_list, ): if prim.IsA(UsdShade.Material): shader = omni.usd.get_shader_from_material(prim, False) attr = shader.GetPrim().GetAttribute("info:mdl:sourceAsset:subIdentifier") if shader else None else: attr = prim.GetAttribute("info:mdl:sourceAsset:subIdentifier") if prim else None shader = UsdShade.Shader(prim) if attr: asset = shader.GetSourceAsset("mdl") if shader else None mdl_file = asset.resolvedPath if asset else None if mdl_file and mdl_file in material_annotation_list: material_annotations = material_annotation_list[mdl_file] if attr.Get() in material_annotations: material_annotations = material_annotations[attr.Get()] if annotation_key in material_annotations: return material_annotations return None
9,774
Python
42.061674
155
0.558625
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/scripts/context_menu.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.kit.context_menu from typing import Set from pxr import Usd, Sdf, UsdShade material_clipboard = [] # menu functions.... def is_material_selected(objects): material_prim = objects["material_prim"] if material_prim: return True return False def is_multiple_material_selected(objects): selected_paths = omni.usd.get_context().get_selection().get_selected_prim_paths() mtl_list = [] for path in selected_paths: prim = objects["stage"].GetPrimAtPath(path) if not prim: return False bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() if bound_material and bound_material not in mtl_list: mtl_list.append(bound_material) return bool(len(mtl_list)>1) def is_material_copied(objects): return bool(len(material_clipboard) > 0) def is_bindable_prim_selected(objects): for prim_path in omni.usd.get_context().get_selection().get_selected_prim_paths(): prim = objects["stage"].GetPrimAtPath(prim_path) if prim and omni.usd.is_prim_material_supported(prim): return True return False def is_prim_selected(self, objects: dict): """ checks if any prims are selected """ if not any(item in objects for item in ["prim", "prim_list"]): return False return True def is_paste_all(objects): return bool(len(omni.usd.get_context().get_selection().get_selected_prim_paths()) > len(material_clipboard)) def goto_material(objects): material_prim = objects["material_prim"] if material_prim: omni.usd.get_context().get_selection().set_prim_path_selected(material_prim.GetPath().pathString, True, True, True, True) def copy_material(objects: dict, all: bool): global material_clipboard material_clipboard = [] for prim in objects["prim_list"]: mat, rel = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() material_path = mat.GetPath().pathString if mat else None material_strength = UsdShade.MaterialBindingAPI.GetMaterialBindingStrength(rel) if rel else UsdShade.Tokens.weakerThanDescendants material_clipboard.append((material_path, material_strength)) def paste_material(objects: dict): selected_paths = omni.usd.get_context().get_selection().get_selected_prim_paths() prims = [objects["stage"].GetPrimAtPath(p) for p in selected_paths] with omni.kit.undo.group(): max_paste = len(material_clipboard) for index, prim in enumerate(prims): if index >= max_paste: break material_path, material_strength = material_clipboard[index] if material_path: omni.kit.commands.execute( "BindMaterial", prim_path=prim.GetPath(), material_path=material_path, strength=material_strength, ) def paste_material_all(objects: dict): selected_paths = omni.usd.get_context().get_selection().get_selected_prim_paths() prims = [objects["stage"].GetPrimAtPath(p) for p in selected_paths] with omni.kit.undo.group(): max_paste = len(material_clipboard) for index, prim in enumerate(prims): material_path, material_strength = material_clipboard[index % max_paste] if material_path: omni.kit.commands.execute( "BindMaterial", prim_path=prim.GetPath(), material_path=material_path, strength=material_strength, ) def get_paste_name(objects): if len(material_clipboard) <2: return "Paste" return f"Paste ({len(material_clipboard)} Materials)" def show_context_menu(stage, material_path, bound_prims: Set[Usd.Prim]): # get context menu core functionality & check its enabled context_menu = omni.kit.context_menu.get_instance() if context_menu is None: carb.log_error("context_menu is disabled!") return None # setup objects, this is passed to all functions if not stage: return objects = {"material_prim": stage.GetPrimAtPath(material_path), "prim_list": bound_prims} # setup menu menu_dict = [ {"name": "Copy", "enabled_fn": [], "onclick_fn": lambda o: copy_material(o, False)}, {"name_fn": get_paste_name, "show_fn": [is_bindable_prim_selected, is_material_copied], "onclick_fn": paste_material}, {"name": "", "show_fn": is_material_selected}, {"name": "Select Material", "show_fn": is_material_selected, "onclick_fn": goto_material}, ] # show menu menu_dict += omni.kit.context_menu.get_menu_dict("MENU_THUMBNAIL", "") omni.kit.context_menu.reorder_menu_dict(menu_dict) context_menu.show_context_menu("material_thumbnail", objects, menu_dict)
5,286
Python
38.455224
137
0.659289
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/scripts/usd_binding_widget.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.kit.window.property.templates import SimplePropertyWidget, LABEL_WIDTH, LABEL_HEIGHT from omni.kit.material.library.listbox_widget import MaterialListBoxWidget from omni.kit.material.library.thumbnail_loader import ThumbnailLoader from omni.kit.material.library.search_widget import SearchWidget from .material_utils import Constant, get_binding_from_prims from .context_menu import show_context_menu from typing import List, Set from functools import partial from pxr import Usd, Tf, Sdf, UsdShade import copy import os import weakref import asyncio import weakref import carb import omni.ui as ui import omni.usd import omni.kit.material.library import omni.kit.context_menu class UsdBindingAttributeWidget(SimplePropertyWidget): def __init__(self, extension_path, add_context_menu=False): super().__init__(title="Materials on selected models", collapsed=False) self._strengths = { "Weaker than Descendants": UsdShade.Tokens.weakerThanDescendants, "Stronger than Descendants": UsdShade.Tokens.strongerThanDescendants, } self._extension_path = extension_path self._thumbnail_loader = ThumbnailLoader() BUTTON_BACKGROUND_COLOR = 0xFF323434 GENERAL_BACKGROUND_COLOR = 0xFF1F2124 self._theme = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark" if self._theme != "NvidiaDark": BUTTON_BACKGROUND_COLOR = 0xFF545454 GENERAL_BACKGROUND_COLOR = 0xFF545454 self._listbox_widget = None self._search_widget = SearchWidget(theme=self._theme, icon_path=None) self._style = { "Image::material": {"margin": 12}, "Button::material_mixed": {"margin": 10}, "Button.Image::material_mixed": {"image_url": f"{self._extension_path}/data/icons/[email protected]"}, "Button::material_solo": {"margin": 10}, "Button.Image::material_solo": {"image_url": f"{self._extension_path}/data/icons/[email protected]"}, "Field::prims" : {"font_size": Constant.FONT_SIZE}, "Field::prims_mixed" : {"font_size": Constant.FONT_SIZE, "color": Constant.MIXED_COLOR}, "Label::prim" : {"font_size": Constant.FONT_SIZE}, "ComboBox": {"font_size": Constant.FONT_SIZE}, "Label::combo_mixed": { "font_size": Constant.FONT_SIZE, "color": Constant.MIXED_COLOR, "margin_width": 5, }, } self._listener = None self._pending_frame_rebuild_task = None self._paste_all_menu = None if add_context_menu: # paste all on collapsible frame header from .context_menu import is_bindable_prim_selected, is_material_copied, is_paste_all, paste_material_all menu_dict = {"name": "Paste To All", "enabled_fn": [is_bindable_prim_selected, is_material_copied, is_paste_all], "onclick_fn": paste_material_all} self._paste_all_menu = omni.kit.context_menu.add_menu(menu_dict, "group_context_menu.Materials on selected models", "omni.kit.window.property") def clean(self): self._thumbnail_loader = None if self._listbox_widget: self._listbox_widget.clean() self._listbox_widget = None self._search_widget.clean() self._paste_all_menu = None super().clean() def _materials_changed(self): self.request_rebuild() def _get_prim(self, prim_path): if prim_path: stage = self._payload.get_stage() if stage: return stage.GetPrimAtPath(prim_path) return None def on_new_payload(self, payload): """ See PropertyWidget.on_new_payload """ if not super().on_new_payload(payload): return False if not payload: return False if len(payload) == 0: return False for prim_path in payload: prim = self._get_prim(prim_path) if prim and not omni.usd.is_prim_material_supported(prim): return False if not prim and not Usd.CollectionAPI.IsCollectionAPIPath(prim_path): return False return True def _get_index(self, items: List[str], value: str, default_value: int = 0): index = default_value try: index = items.index(value) except: pass return index def _get_theme_name(self, darkname, lightname): if self._theme=="NvidiaDark": return darkname return lightname def _show_material_popup(self, name_field: ui.StringField, material_index: int, bind_material_fn: callable): if self._listbox_widget: self._listbox_widget.clean() del self._listbox_widget self._listbox_widget = None self._listbox_widget = MaterialListBoxWidget(icon_path=None, index=material_index, on_click_fn=bind_material_fn, theme=self._theme) self._listbox_widget.set_parent(name_field) self._listbox_widget.set_selection_on_loading_complete(name_field.model.get_value_as_string() if material_index >= 0 else None) self._listbox_widget.build_ui() def _build_material_popup(self, material_list: List[str], material_index: int, thumbnail_image: ui.Button, bound_prim_list: Set[Usd.Prim], bind_material_fn: callable, on_goto_fn: callable, on_dragdrop_fn: callable): def drop_accept(url): if len(url.split('\n')) > 1: carb.log_warn(f"build_material_popup multifile drag/drop not supported") return False if url.startswith("material::"): return True url_ext = os.path.splitext(url)[1] return url_ext.lower() in [".mdl"] def dropped_mtl(event, bind_material_fn): url = event.mime_data subid = None # remove omni.kit.browser.material "material::" prefix if url.startswith("material::"): url=url[10:] parts = url.split(".mdl@") if len(parts) == 2: subid = parts[1] url = url.replace(f".mdl@{subid}", ".mdl") bind_material_fn(url=url, subid=subid) name_field, listbox_button, goto_button = self._search_widget.build_ui_popup(search_size=LABEL_HEIGHT, popup_text=material_list[material_index] if material_index >= 0 else "Mixed", index=material_index, update_fn=bind_material_fn) name_field.set_mouse_pressed_fn(lambda x, y, b, m, f=name_field: self._show_material_popup(f, material_index, bind_material_fn)) name_field.set_accept_drop_fn(drop_accept) name_field.set_drop_fn(partial(dropped_mtl, bind_material_fn=on_dragdrop_fn)) listbox_button.set_mouse_pressed_fn(lambda x, y, b, m, f=name_field: self._show_material_popup(f, material_index, bind_material_fn)) if material_index > 0: goto_button.set_mouse_pressed_fn(lambda x, y, b, m, f=name_field: on_goto_fn(f.model)) if self._collapsable_frame: def mouse_clicked(b, f): if b == 0: on_goto_fn(f.model) elif b == 1: show_context_menu(self._payload.get_stage(), f.model.get_value_as_string(), bound_prim_list) thumbnail_image.set_mouse_pressed_fn(lambda x, y, b, m, f=name_field: mouse_clicked(b, f)) thumbnail_image.set_accept_drop_fn(drop_accept) thumbnail_image.set_drop_fn(partial(dropped_mtl, bind_material_fn=on_dragdrop_fn)) def _build_combo(self, material_list: List[str], material_index: int, on_fn: callable): def set_visible(widget, visible): widget.visible = visible with ui.ZStack(): combo = ui.ComboBox(material_index, *material_list) combo.model.add_item_changed_fn(on_fn) if material_index == -1: placeholder = ui.Label( "Mixed", height=LABEL_HEIGHT, name="combo_mixed", ) self._combo_subscription.append( combo.model.get_item_value_model().subscribe_value_changed_fn( lambda m, w=placeholder: set_visible(w, m.as_int < 0) ) ) return combo def _build_binding_info( self, inherited: bool, style_name: str, material_list: List[str], material_path: str, strength_value: str, bound_prim_list: Set[str], on_material_fn: callable, on_strength_fn: callable, on_goto_fn: callable, on_dragdrop_fn: callable, ): prim_style = "prims" ## fixup Constant.SDF_PATH_INVALID vs "None" material_list = copy.copy(material_list) if material_list[0] == Constant.SDF_PATH_INVALID: material_list[0] = "None" if material_path == Constant.SDF_PATH_INVALID: material_path = "None" type_label = 'Prim' if len(bound_prim_list) == 1: if isinstance(bound_prim_list[0], Usd.Prim): bound_prims = bound_prim_list[0].GetPath().pathString elif isinstance(bound_prim_list[0], Usd.CollectionAPI): bound_prims = bound_prim_list[0].GetCollectionPath().pathString type_label = 'Collection' else: bound_prims = bound_prim_list[0] elif len(bound_prim_list) > 1: bound_prims = Constant.MIXED prim_style = "prims_mixed" else: bound_prims = "None" if not self._first_row: ui.Separator(height=10) self._first_row = False index = self._get_index(material_list, material_path, -1) with ui.HStack(style=self._style): with ui.ZStack(width=0): image_button = ui.Button( "", width=Constant.ICON_SIZE, height=Constant.ICON_SIZE, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, name=style_name, identifier="preview_drop_target" ) if index != -1: material_prim = self._get_prim(material_path) if material_prim: def on_image_progress(button: ui.Button, image: ui.Image, progress: float): if progress > 0.999: button.image_url = image.source_url image.visible = False thumbnail_image = ui.Image( width=Constant.ICON_SIZE, height=Constant.ICON_SIZE, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, name="material" ) self._thumbnail_loader.load(material_prim, thumbnail_image) # callback when image is loading thumbnail_image.set_progress_changed_fn(lambda p, b=image_button, i=thumbnail_image: on_image_progress(b, i, p)) with ui.VStack(spacing=10): with ui.HStack(): ui.Label( type_label, width=Constant.BOUND_LABEL_WIDTH, height=LABEL_HEIGHT, name="prim", ) ui.StringField(name=prim_style, height=LABEL_HEIGHT, enabled=False).model.set_value( bound_prims ) if index != -1 and inherited: inherited_list = copy.copy(material_list) inherited_list[index] = f"{inherited_list[index]} (inherited)" self._build_material_popup(inherited_list, index, image_button, bound_prim_list, on_material_fn, on_goto_fn, on_dragdrop_fn) else: self._build_material_popup(material_list, index, image_button, bound_prim_list, on_material_fn, on_goto_fn, on_dragdrop_fn) with ui.HStack(): ui.Label( "Strength", width=Constant.BOUND_LABEL_WIDTH, height=LABEL_HEIGHT, name="prim", ) index = self._get_index(list(self._strengths.values()), strength_value, -1) self._build_combo(list(self._strengths.keys()), index, on_strength_fn) def build_items(self): binding = get_binding_from_prims(self._payload.get_stage(), self._payload) if binding is None: return strengths = self._strengths material_list = [Constant.SDF_PATH_INVALID] + [mtl for mtl in binding["material"]] stage = self._payload.get_stage() if not stage or len(self._payload) == 0: return last_prim = self._get_prim(self._payload[-1]) if not self._listener: self._listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._on_usd_changed, stage) def bind_material_to_prims(bind_material_path, items): prim_path_list = [] strength_list = [] for prim_path, material_name, strength in items: if str(material_name) != str(bind_material_path): prim_path_list.append(prim_path) strength_list.append(strength) if str(bind_material_path) == Constant.SDF_PATH_INVALID: bind_material_path = None omni.kit.commands.execute( "BindMaterial", material_path=bind_material_path, prim_path=prim_path_list, strength=strength_list, ) def on_strength_changed(model, item, relationships): index = model.get_item_value_model().as_int if index < 0: carb.log_error(f"on_strength_changed with invalid index {index}") return bind_strength = list(strengths.values())[index] omni.kit.undo.begin_group() for relationship in relationships: omni.kit.commands.execute("SetMaterialStrength", rel=relationship, strength=bind_strength) omni.kit.undo.end_group() if self._collapsable_frame: self._collapsable_frame.rebuild() def on_material_changed(model, item, items): if isinstance(model, omni.ui._ui.AbstractItemModel): index = model.get_item_value_model().as_int if index < 0: carb.log_error(f"on_material_changed with invalid index {index}") return bind_material_path = material_list[index] if material_list[index] != Constant.SDF_PATH_INVALID else None elif isinstance(model, omni.ui._ui.SimpleStringModel): bind_material_path = model.get_value_as_string() if bind_material_path == "None": bind_material_path = None else: carb.log_error(f"on_material_changed model {type(model)} unsupported") return bind_material_to_prims(bind_material_path, items) if self._collapsable_frame: self._collapsable_frame.rebuild() def on_dragdrop(url, items, subid=""): if len(url.split('\n')) > 1: carb.log_warn(f"build_binding_info multifile drag/drop not supported") return def on_create_func(mtl_prim): bind_material_to_prims(mtl_prim.GetPath(), items) if self._collapsable_frame: self._collapsable_frame.rebuild() def reload_frame(prim): self._materials_changed() stage = self._payload.get_stage() mtl_name, _ = os.path.splitext(os.path.basename(url)) def loaded_mdl_subids(mtl_list, mdl_path, filename, subid): if not mtl_list: return if subid: omni.kit.material.library.create_mdl_material( stage=stage, mtl_url=mdl_path, mtl_name=subid, on_create_fn=on_create_func, mtl_real_name=subid) return if len(mtl_list) > 1: prim_paths = [prim_path for prim_path, material_name, strength in items] omni.kit.material.library.custom_material_dialog(mdl_path=mdl_path, bind_prim_paths=prim_paths, on_complete_fn=reload_frame) return omni.kit.material.library.create_mdl_material( stage=stage, mtl_url=mdl_path, mtl_name=mtl_name, on_create_fn=on_create_func, mtl_real_name=mtl_list[0].name if len(mtl_list) > 0 else "") # get subids from material asyncio.ensure_future(omni.kit.material.library.get_subidentifier_from_mdl(mdl_file=url, on_complete_fn=lambda l, p=url, n=mtl_name: loaded_mdl_subids(mtl_list=l, mdl_path=p, filename=n, subid=subid), show_alert=True)) def on_material_goto(model, items): prim_list = sorted(list(set([item[1] for item in items if item[1] != Constant.SDF_PATH_INVALID]))) if prim_list: omni.usd.get_context().get_selection().set_selected_prim_paths(prim_list, True) else: carb.log_warn(f"on_material_goto failed. No materials in list") self._combo_subscription = [] self._first_row = True data = binding["material"] # show mixed material for all selected prims if len(data) > 1: self._build_binding_info( inherited=False, style_name="material_mixed", material_list=material_list, material_path=Constant.MIXED, strength_value=binding["strength"], bound_prim_list=list(binding["bound"]), on_material_fn=partial(on_material_changed, items=list(binding["bound_info"])), on_strength_fn=partial(on_strength_changed, relationships=list(binding["relationship"])), on_goto_fn=partial(on_material_goto, items=list(binding["bound_info"] | binding["inherited_info"])), on_dragdrop_fn=partial(on_dragdrop, items=list(binding["bound_info"])), ) for material_path in data: if data[material_path]["bound"]: self._build_binding_info( inherited=False, style_name="material_solo", material_list=material_list, material_path=material_path, strength_value=data[material_path]["strength"], bound_prim_list=list(data[material_path]["bound"]), on_material_fn=partial(on_material_changed, items=list(data[material_path]["bound_info"])), on_strength_fn=partial( on_strength_changed, relationships=list(data[material_path]["relationship"]) ), on_goto_fn=partial(on_material_goto, items=list(data[material_path]["bound_info"])), on_dragdrop_fn=partial(on_dragdrop, items=list(data[material_path]["bound_info"])), ) for material_path in data: if data[material_path]["inherited"]: self._build_binding_info( inherited=True, style_name="material_solo", material_list=material_list, material_path=material_path, strength_value=data[material_path]["strength"], bound_prim_list=list(data[material_path]["inherited"]), on_material_fn=partial(on_material_changed, items=list(data[material_path]["inherited_info"])), on_strength_fn=partial( on_strength_changed, relationships=list(data[material_path]["relationship"]) ), on_goto_fn=partial(on_material_goto, items=list(data[material_path]["inherited_info"])), on_dragdrop_fn=partial(on_dragdrop, items=list(data[material_path]["inherited_info"])), ) def reset(self): if self._listener: self._listener.Revoke() self._listener = None if self._pending_frame_rebuild_task: self._pending_frame_rebuild_task.cancel() self._pending_frame_rebuild_task = None def _on_usd_changed(self, notice, stage): if self._pending_frame_rebuild_task: return items = set(notice.GetResyncedPaths()+notice.GetChangedInfoOnlyPaths()) if any(path.elementString == ".material:binding" for path in items): async def rebuild(): if self._collapsable_frame: self._collapsable_frame.rebuild() self._pending_frame_rebuild_task = None self._pending_frame_rebuild_task = asyncio.ensure_future(rebuild())
22,277
Python
42.854331
230
0.558423
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/scripts/material_properties.py
import os import carb import omni.ext from pathlib import Path from pxr import Sdf, UsdShade, UsdUI from omni.kit.material.library.treeview_model import MaterialListModel, MaterialListDelegate TEST_DATA_PATH = "" class MaterialPropertyExtension(omni.ext.IExt): def __init__(self): self._registered = False def on_startup(self, ext_id): self._extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path(ext_id) self._register_widget() self._hooks = [] manager = omni.kit.app.get_app().get_extension_manager() extension_path = manager.get_extension_path(ext_id) global TEST_DATA_PATH TEST_DATA_PATH = Path(extension_path).joinpath("data").joinpath("tests") def on_shutdown(self): self._hooks = None if self._registered: self._unregister_widget() def _register_widget(self): import omni.kit.window.property as p from omni.kit.window.property.property_scheme_delegate import PropertySchemeDelegate from .usd_attribute_widget import UsdMaterialAttributeWidget from .usd_binding_widget import UsdBindingAttributeWidget w = p.get_window() if w: w.register_widget("prim", "material_binding", UsdBindingAttributeWidget(self._extension_path, add_context_menu=True)) w.register_widget( "prim", "material", UsdMaterialAttributeWidget( schema=UsdShade.Material, title="Material and Shader", include_names=[], exclude_names=[]) ) w.register_widget( "prim", "shader", UsdMaterialAttributeWidget( schema=UsdShade.Shader, title="Shader", include_names=["info:mdl:sourceAsset", "info:mdl:sourceAsset:subIdentifier"], exclude_names=[], ), ) # NOTE: UsdShade.Material is also a UsdShade.NodeGraph. So NodeGraphs ignore Material's w.register_widget( "prim", "nodegraph", UsdMaterialAttributeWidget( schema=UsdShade.NodeGraph, schema_ignore=UsdShade.Material, title="Node Graph", include_names=[ "ui:nodegraph:node:displayColor", "ui:nodegraph:node:expansionState", "ui:nodegraph:node:icon", "ui:nodegraph:node:pos", "ui:nodegraph:node:stackingOrder", "ui:nodegraph:node:size"], exclude_names=[], ), ) w.register_widget( "prim", "backdrop", UsdMaterialAttributeWidget( schema=UsdUI.Backdrop, title="Backdrop", include_names=[ "ui:nodegraph:node:displayColor", "ui:nodegraph:node:expansionState", "ui:nodegraph:node:icon", "ui:nodegraph:node:pos", "ui:nodegraph:node:stackingOrder", "ui:nodegraph:node:size"], exclude_names=[], ), ) self._registered = True def _unregister_widget(self): import omni.kit.window.property as p w = p.get_window() if w: w.unregister_widget("prim", "material") w.unregister_widget("prim", "shader") w.unregister_widget("prim", "nodegraph") w.unregister_widget("prim", "backdrop") w.unregister_widget("prim", "material_binding") self._registered = False
3,947
Python
36.6
129
0.522169
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/tests/test_drag_drop.py
import omni.kit.test from pathlib import Path from pxr import Sdf, UsdShade, UsdGeom from omni.ui.tests.test_base import OmniUiTest from omni.kit import ui_test from omni.kit.test_suite.helpers import select_prims, arrange_windows from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper class TestDragDropMDLFile(OmniUiTest): async def test_drag_drop_single_mdl_file_target(self): await arrange_windows() extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) mdl_path1 = Path(extension_path).joinpath("data/tests/TESTEXPORT.mdl").absolute() # setup await ui_test.find("Stage").focus() await ui_test.find("Content").focus() # new stage usd_context = omni.usd.get_context() await usd_context.new_stage_async() stage = usd_context.get_stage() # create prims omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere") await select_prims(["/Sphere"]) await ui_test.human_delay() # drag/drop async with ContentBrowserTestHelper() as content_browser_helper: property_widget = ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'") await content_browser_helper.drag_and_drop_tree_view(str(mdl_path1), drag_target=property_widget.center) # verify - TESTEXPORT should be bound # NOTE: TESTEXPORT.mdl material is named "Material" so that is the prim created prim = stage.GetPrimAtPath("/Sphere") bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() self.assertTrue(bound_material.GetPrim().IsValid() == True) self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, "/Looks/Material") async def test_drag_drop_multi_mdl_file_target(self): extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) mdl_path = str(Path(extension_path).joinpath("data/tests").absolute()) # setup await ui_test.find("Stage").focus() await ui_test.find("Content").focus() # new stage usd_context = omni.usd.get_context() await usd_context.new_stage_async() stage = usd_context.get_stage() # create prims omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere") await select_prims(["/Sphere"]) await ui_test.human_delay() # drag/drop async with ContentBrowserTestHelper() as content_browser_helper: property_widget = ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'") await content_browser_helper.drag_and_drop_tree_view( mdl_path, names=["TESTEXPORT.mdl", "TESTEXPORT2.mdl"], drag_target=property_widget.center) # verify - nothing should be bound as 2 items where selected prim = stage.GetPrimAtPath("/Sphere") bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() self.assertFalse(bound_material.GetPrim().IsValid()) async def test_drag_drop_single_mdl_file_combo(self): extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) mdl_path1 = Path(extension_path).joinpath("data/tests/TESTEXPORT.mdl").absolute() # setup await ui_test.find("Stage").focus() await ui_test.find("Content").focus() # new stage usd_context = omni.usd.get_context() await usd_context.new_stage_async() stage = usd_context.get_stage() # create prims omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere") await select_prims(["/Sphere"]) await ui_test.human_delay() # drag/drop async with ContentBrowserTestHelper() as content_browser_helper: property_widget = ui_test.find("Property//Frame/**/StringField[*].identifier=='combo_drop_target'") await content_browser_helper.drag_and_drop_tree_view(str(mdl_path1), drag_target=property_widget.center) # verify - TESTEXPORT should be bound # NOTE: TESTEXPORT.mdl material is named "Material" so that is the prim created prim = stage.GetPrimAtPath("/Sphere") bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() self.assertTrue(bound_material.GetPrim().IsValid() == True) self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, "/Looks/Material") async def test_drag_drop_multi_mdl_file_combo(self): extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) mdl_path = str(Path(extension_path).joinpath("data/tests").absolute()) # setup await ui_test.find("Stage").focus() await ui_test.find("Content").focus() # new stage usd_context = omni.usd.get_context() await usd_context.new_stage_async() stage = usd_context.get_stage() # create prims omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere") await select_prims(["/Sphere"]) await ui_test.human_delay() # drag/drop async with ContentBrowserTestHelper() as content_browser_helper: property_widget = ui_test.find("Property//Frame/**/StringField[*].identifier=='combo_drop_target'") await content_browser_helper.drag_and_drop_tree_view( mdl_path, names=["TESTEXPORT.mdl", "TESTEXPORT2.mdl"], drag_target=property_widget.center) # verify - nothing should be bound as 2 items where selected prim = stage.GetPrimAtPath("/Sphere") bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() self.assertFalse(bound_material.GetPrim().IsValid())
5,948
Python
44.412213
116
0.661903
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/tests/test_material_thumb.py
import weakref import unittest import pathlib import omni.kit.test import omni.ui as ui import carb from pathlib import Path from pxr import Sdf, UsdShade, UsdGeom from omni.ui.tests.test_base import OmniUiTest from omni.kit import ui_test from omni.kit.test_suite.helpers import ( open_stage, get_test_data_path, arrange_windows, select_prims, wait_stage_loading, ) class TestMaterialThumb(OmniUiTest): async def setUp(self): await super().setUp() await open_stage(get_test_data_path(__name__, "thumbnail_test.usda")) await wait_stage_loading() from omni.kit.property.usd.usd_attribute_widget import UsdPropertiesWidget import omni.kit.window.property as p self._w = p.get_window() async def tearDown(self): await super().tearDown() await wait_stage_loading() async def test_material_thumb(self): stage = omni.usd.get_context().get_stage() golden_img_dir = pathlib.Path(get_test_data_path(__name__, "golden_img")) await self.docked_test_window( window=self._w._window, width=450, height=285, restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position = ui.DockPosition.BOTTOM) # select source prim await select_prims(["/World/Sphere"]) await wait_stage_loading() await ui_test.human_delay(50) await self.finalize_test(golden_img_dir=golden_img_dir, golden_img_name="test_thumb_with_alpha.png") await select_prims([])
1,605
Python
28.74074
108
0.654206
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/tests/drag_drop_path.py
## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import os import omni.kit.app import omni.usd import carb from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from omni.kit.material.library.test_helper import MaterialLibraryTestHelper from omni.kit.test_suite.helpers import ( open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows ) from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper PERSISTENT_SETTINGS_PREFIX = "/persistent" class DragDropFilePropertyMaterialPath(AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows("Stage", 64) await open_stage(get_test_data_path(__name__, "bound_material.usda")) # After running each test async def tearDown(self): await wait_stage_loading() carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "absolute") async def test_l1_drag_drop_path_drop_target_absolute(self): carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "absolute") await ui_test.find("Stage").focus() await ui_test.find("Content").focus() # new stage usd_context = omni.usd.get_context() stage = usd_context.get_stage() # create prims omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere") await select_prims(["/World/Sphere"]) await ui_test.human_delay() # drag file from content window property_widget = ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'") drag_target = property_widget.center async with ContentBrowserTestHelper() as content_browser_helper: mdl_path = get_test_data_path(__name__, "mtl/badname.mdl") await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=drag_target) # verify prims shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath('/World/Looks/Ue4basedMDL'), False) self.assertTrue(bool(shader), "/World/Looks/Ue4basedMDL not found") asset = shader.GetSourceAsset("mdl") self.assertTrue(os.path.isabs(asset.path)) async def test_l1_drag_drop_path_combo_absolute(self): carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "absolute") await ui_test.find("Stage").focus() await ui_test.find("Content").focus() # new stage usd_context = omni.usd.get_context() stage = usd_context.get_stage() # create prims omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere") await select_prims(["/World/Sphere"]) await ui_test.human_delay() # drag file from content window property_widget = ui_test.find("Property//Frame/**/StringField[*].identifier=='combo_drop_target'") drag_target = property_widget.center async with ContentBrowserTestHelper() as content_browser_helper: mdl_path = get_test_data_path(__name__, "mtl/badname.mdl") await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=drag_target) # verify prims shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath('/World/Looks/Ue4basedMDL'), False) self.assertTrue(bool(shader), "/World/Looks/Ue4basedMDL not found") asset = shader.GetSourceAsset("mdl") self.assertTrue(os.path.isabs(asset.path)) async def test_l1_drag_drop_path_asset_absolute(self): carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "absolute") usd_context = omni.usd.get_context() stage = usd_context.get_stage() await select_prims(["/World/Looks/OmniHair/Shader"]) await wait_stage_loading() # drag file from content window property_widget = ui_test.find("Property//Frame/**/StringField[*].identifier=='sdf_asset_info:mdl:sourceAsset'") drag_target = property_widget.center async with ContentBrowserTestHelper() as content_browser_helper: mdl_path = get_test_data_path(__name__, "mtl/OmniHairTest.mdl") await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=drag_target) # verify prims shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath('/World/Looks/OmniHair'), False) asset = shader.GetSourceAsset("mdl") self.assertTrue(os.path.isabs(asset.path)) async def test_l1_drag_drop_path_drop_target_relative(self): carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "relative") await ui_test.find("Stage").focus() await ui_test.find("Content").focus() # new stage usd_context = omni.usd.get_context() stage = usd_context.get_stage() # create prims omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere") await select_prims(["/World/Sphere"]) await ui_test.human_delay() # drag file from content window property_widget = ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'") drag_target = property_widget.center async with ContentBrowserTestHelper() as content_browser_helper: mdl_path = get_test_data_path(__name__, "mtl/badname.mdl") await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=drag_target) # verify prims shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath('/World/Looks/Ue4basedMDL'), False) self.assertTrue(bool(shader), "/World/Looks/Ue4basedMDL not found") asset = shader.GetSourceAsset("mdl") self.assertFalse(os.path.isabs(asset.path)) async def test_l1_drag_drop_path_combo_relative(self): carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "relative") await ui_test.find("Stage").focus() await ui_test.find("Content").focus() # new stage usd_context = omni.usd.get_context() stage = usd_context.get_stage() # create prims omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere") await select_prims(["/World/Sphere"]) await ui_test.human_delay() # drag file from content window property_widget = ui_test.find("Property//Frame/**/StringField[*].identifier=='combo_drop_target'") drag_target = property_widget.center async with ContentBrowserTestHelper() as content_browser_helper: mdl_path = get_test_data_path(__name__, "mtl/badname.mdl") await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=drag_target) # verify prims shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath('/World/Looks/Ue4basedMDL'), False) self.assertTrue(bool(shader), "/World/Looks/Ue4basedMDL not found") asset = shader.GetSourceAsset("mdl") self.assertFalse(os.path.isabs(asset.path)) async def test_l1_drag_drop_path_asset_relative(self): carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "relative") usd_context = omni.usd.get_context() stage = usd_context.get_stage() await select_prims(["/World/Looks/OmniHair/Shader"]) await wait_stage_loading() # drag file from content window property_widget = ui_test.find("Property//Frame/**/StringField[*].identifier=='sdf_asset_info:mdl:sourceAsset'") drag_target = property_widget.center async with ContentBrowserTestHelper() as content_browser_helper: mdl_path = get_test_data_path(__name__, "mtl/OmniHairTest.mdl") await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=drag_target) # verify prims shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath('/World/Looks/OmniHair'), False) asset = shader.GetSourceAsset("mdl") self.assertFalse(os.path.isabs(asset.path)) async def test_l1_drag_drop_path_drop_target_multi_absolute(self): carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "absolute") await ui_test.find("Stage").focus() await ui_test.find("Content").focus() # new stage usd_context = omni.usd.get_context() stage = usd_context.get_stage() # create prims omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere") await select_prims(["/World/Sphere"]) await ui_test.human_delay() # drag file from content window property_widget = ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'") drag_target = property_widget.center async with ContentBrowserTestHelper() as content_browser_helper: mdl_path = get_test_data_path(__name__, "mtl/multi_hair.mdl") await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=drag_target) async with MaterialLibraryTestHelper() as material_test_helper: await material_test_helper.handle_create_material_dialog(str(mdl_path), "OmniHair_Green") # verify prims shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath('/World/Looks/OmniHair_Green'), False) self.assertTrue(bool(shader), "/World/Looks/OmniHair_Green not found") asset = shader.GetSourceAsset("mdl") self.assertTrue(os.path.isabs(asset.path)) async def test_l1_drag_drop_path_drop_target_multi_relative(self): carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "relative") await ui_test.find("Stage").focus() await ui_test.find("Content").focus() # new stage usd_context = omni.usd.get_context() stage = usd_context.get_stage() # create prims omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere") await select_prims(["/World/Sphere"]) await ui_test.human_delay() # drag file from content window property_widget = ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'") drag_target = property_widget.center async with ContentBrowserTestHelper() as content_browser_helper: mdl_path = get_test_data_path(__name__, "mtl/multi_hair.mdl") await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=drag_target) async with MaterialLibraryTestHelper() as material_test_helper: await material_test_helper.handle_create_material_dialog(str(mdl_path), "OmniHair_Green") # verify prims shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath('/World/Looks/OmniHair_Green'), False) self.assertTrue(bool(shader), "/World/Looks/OmniHair_Green not found") asset = shader.GetSourceAsset("mdl") self.assertFalse(os.path.isabs(asset.path))
11,722
Python
43.915709
120
0.673349
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/tests/create_prims.py
import os import carb import carb.settings import omni.kit.commands from pxr import Usd, Sdf, UsdGeom, Gf, Tf, UsdShade, UsdLux def create_test_stage(): created_mdl_prims = [] created_bound_prims = [] stage = omni.usd.get_context().get_stage() rootname = "" if stage.HasDefaultPrim(): rootname = stage.GetDefaultPrim().GetPath().pathString kit_folder = carb.tokens.get_tokens_interface().resolve("${kit}") omni_pbr_mtl = os.path.normpath(kit_folder + "/mdl/core/Base/OmniPBR.mdl") # create Looks folder omni.kit.commands.execute( "CreatePrim", prim_path="{}/Looks".format(rootname), prim_type="Scope", select_new_prim=False ) # create GroundMat material mtl_name = "GroundMat" mtl_path = omni.usd.get_stage_next_free_path( stage, "{}/Looks/{}".format(rootname, Tf.MakeValidIdentifier(mtl_name)), False ) created_mdl_prims.append(mtl_path) omni.kit.commands.execute( "CreateMdlMaterialPrim", mtl_url=omni_pbr_mtl, mtl_name=mtl_name, mtl_path=mtl_path ) ground_mat_prim = stage.GetPrimAtPath(mtl_path) shader = UsdShade.Material(ground_mat_prim).ComputeSurfaceSource("mdl")[0] shader.SetSourceAssetSubIdentifier("OmniPBR", "mdl") omni.usd.create_material_input(ground_mat_prim, "reflection_roughness_constant", 0.36, Sdf.ValueTypeNames.Float) omni.usd.create_material_input(ground_mat_prim, "specular_level", 0.25, Sdf.ValueTypeNames.Float) omni.usd.create_material_input( ground_mat_prim, "diffuse_color_constant", Gf.Vec3f(0.08, 0.08, 0.08), Sdf.ValueTypeNames.Color3f ) omni.usd.create_material_input(ground_mat_prim, "diffuse_tint", Gf.Vec3f(1, 1, 1), Sdf.ValueTypeNames.Color3f) omni.usd.create_material_input(ground_mat_prim, "diffuse_tint", Gf.Vec3f(1, 1, 1), Sdf.ValueTypeNames.Color3f) omni.usd.create_material_input(ground_mat_prim, "metallic_constant", 0.0, Sdf.ValueTypeNames.Float) omni.usd.create_material_input(ground_mat_prim, "reflection_roughness_constant", 0.36, Sdf.ValueTypeNames.Float) # create BackSideMat mtl_name = "BackSideMat" backside_mtl_path = omni.usd.get_stage_next_free_path( stage, "{}/Looks/{}".format(rootname, Tf.MakeValidIdentifier(mtl_name)), False ) created_mdl_prims.append(backside_mtl_path) omni.kit.commands.execute( "CreateMdlMaterialPrim", mtl_url=omni_pbr_mtl, mtl_name=mtl_name, mtl_path=backside_mtl_path ) backside_mtl_prim = stage.GetPrimAtPath(backside_mtl_path) shader = UsdShade.Material(backside_mtl_prim).ComputeSurfaceSource("mdl")[0] shader.SetSourceAssetSubIdentifier("OmniPBR", "mdl") omni.usd.create_material_input( backside_mtl_prim, "diffuse_color_constant", Gf.Vec3f(0.11814344, 0.118142255, 0.118142255), Sdf.ValueTypeNames.Color3f, ) omni.usd.create_material_input(backside_mtl_prim, "reflection_roughness_constant", 0.27, Sdf.ValueTypeNames.Float) omni.usd.create_material_input(backside_mtl_prim, "specular_level", 0.163, Sdf.ValueTypeNames.Float) # create EmissiveMat mtl_name = "EmissiveMat" emissive_mtl_path = omni.usd.get_stage_next_free_path( stage, "{}/Looks/{}".format(rootname, Tf.MakeValidIdentifier(mtl_name)), False ) created_mdl_prims.append(emissive_mtl_path) omni.kit.commands.execute( "CreateMdlMaterialPrim", mtl_url=omni_pbr_mtl, mtl_name=mtl_name, mtl_path=emissive_mtl_path ) emissive_mtl_prim = stage.GetPrimAtPath(emissive_mtl_path) shader = UsdShade.Material(emissive_mtl_prim).ComputeSurfaceSource("mdl")[0] shader.SetSourceAssetSubIdentifier("OmniPBR", "mdl") omni.usd.create_material_input( emissive_mtl_prim, "diffuse_color_constant", Gf.Vec3f(0, 0, 0), Sdf.ValueTypeNames.Color3f ) omni.usd.create_material_input(emissive_mtl_prim, "reflection_roughness_constant", 1, Sdf.ValueTypeNames.Float) omni.usd.create_material_input(emissive_mtl_prim, "specular_level", 0, Sdf.ValueTypeNames.Float) omni.usd.create_material_input(emissive_mtl_prim, "enable_emission", True, Sdf.ValueTypeNames.Bool) omni.usd.create_material_input(emissive_mtl_prim, "emissive_color", Gf.Vec3f(1, 1, 1), Sdf.ValueTypeNames.Color3f) omni.usd.create_material_input(emissive_mtl_prim, "emissive_intensity", 15000, Sdf.ValueTypeNames.Float) # create studiohemisphere hemisphere_path = omni.usd.get_stage_next_free_path(stage, "{}/studiohemisphere".format(rootname), False) omni.kit.commands.execute( "CreatePrim", prim_path=hemisphere_path, prim_type="Xform", select_new_prim=False, attributes={} ) hemisphere_prim = stage.GetPrimAtPath(hemisphere_path) UsdGeom.PrimvarsAPI(hemisphere_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # create sphere hemisphere_sphere_path = omni.usd.get_stage_next_free_path( stage, "{}/studiohemisphere/Sphere".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=hemisphere_sphere_path, prim_type="Sphere", select_new_prim=False, attributes={UsdGeom.Tokens.radius: 100}, ) hemisphere_prim = stage.GetPrimAtPath(hemisphere_sphere_path) # set transform hemisphere_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(2500, 2500, 2500)) hemisphere_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(["xformOp:scale"]) UsdGeom.PrimvarsAPI(hemisphere_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # bind material omni.kit.commands.execute( "BindMaterial", prim_path=hemisphere_sphere_path, material_path=mtl_path, strength=UsdShade.Tokens.strongerThanDescendants, ) created_bound_prims.append((hemisphere_sphere_path, UsdShade.Tokens.strongerThanDescendants)) # create floor hemisphere_floor_path = omni.usd.get_stage_next_free_path( stage, "{}/studiohemisphere/Floor".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=hemisphere_floor_path, prim_type="Cube", select_new_prim=False, attributes={UsdGeom.Tokens.size: 100}, ) hemisphere_floor_prim = stage.GetPrimAtPath(hemisphere_floor_path) # set transform hemisphere_floor_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(2500, 0.1, 2500) ) hemisphere_floor_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(["xformOp:scale"]) UsdGeom.PrimvarsAPI(hemisphere_floor_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # bind material omni.kit.commands.execute( "BindMaterial", prim_path=hemisphere_floor_path, material_path=mtl_path, strength=UsdShade.Tokens.weakerThanDescendants, ) created_bound_prims.append((hemisphere_floor_path, UsdShade.Tokens.weakerThanDescendants)) # create LightPivot_01 light_pivot1_path = omni.usd.get_stage_next_free_path(stage, "{}/LightPivot_01".format(rootname), False) omni.kit.commands.execute( "CreatePrim", prim_path=light_pivot1_path, prim_type="Xform", select_new_prim=False, attributes={} ) light_pivot1_prim = stage.GetPrimAtPath(light_pivot1_path) UsdGeom.PrimvarsAPI(light_pivot1_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # set transform light_pivot1_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) light_pivot1_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(-30.453436397207547, 16.954190666353664, 9.728788165428536) ) light_pivot1_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(0.9999999445969171, 1.000000574567198, 0.9999995086845976) ) light_pivot1_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] ) # create AreaLight light_pivot1_al_path = omni.usd.get_stage_next_free_path( stage, "{}/LightPivot_01/AreaLight".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=light_pivot1_al_path, prim_type="Xform", select_new_prim=False, attributes={} ) light_pivot1_al_prim = stage.GetPrimAtPath(light_pivot1_al_path) UsdGeom.PrimvarsAPI(light_pivot1_al_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # set transform light_pivot1_al_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(0, 0, 800) ) light_pivot1_al_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) light_pivot1_al_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(4.5, 4.5, 4.5) ) light_pivot1_al_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] ) # create AreaLight RectLight light_pivot1_alrl_path = omni.usd.get_stage_next_free_path( stage, "{}/LightPivot_01/AreaLight/RectLight".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=light_pivot1_alrl_path, prim_type="RectLight", select_new_prim=False, attributes={}, ) light_pivot1_alrl_prim = stage.GetPrimAtPath(light_pivot1_alrl_path) # set values light_pivot1_alrl_prim.CreateAttribute("height", Sdf.ValueTypeNames.Float, False).Set(100) light_pivot1_alrl_prim.CreateAttribute("width", Sdf.ValueTypeNames.Float, False).Set(100) light_pivot1_alrl_prim.CreateAttribute("intensity", Sdf.ValueTypeNames.Float, False).Set(15000) light_pivot1_alrl_prim.CreateAttribute("shaping:cone:angle", Sdf.ValueTypeNames.Float, False).Set(180) # create AreaLight Backside backside_albs_path = omni.usd.get_stage_next_free_path( stage, "{}/LightPivot_01/AreaLight/Backside".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=backside_albs_path, prim_type="Cube", select_new_prim=False, attributes={UsdGeom.Tokens.size: 100, UsdGeom.Tokens.extent: [(-50, -50, -50), (50, 50, 50)]}, ) backside_albs_prim = stage.GetPrimAtPath(backside_albs_path) # set values backside_albs_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 1.1)) backside_albs_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) backside_albs_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(1, 1, 0.02)) backside_albs_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] ) UsdGeom.PrimvarsAPI(backside_albs_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # bind material omni.kit.commands.execute( "BindMaterial", prim_path=backside_albs_path, material_path=backside_mtl_path, strength=UsdShade.Tokens.strongerThanDescendants, ) created_bound_prims.append((backside_albs_path, UsdShade.Tokens.strongerThanDescendants)) # create AreaLight EmissiveSurface backside_ales_path = omni.usd.get_stage_next_free_path( stage, "{}/LightPivot_01/AreaLight/EmissiveSurface".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=backside_ales_path, prim_type="Cube", select_new_prim=False, attributes={UsdGeom.Tokens.size: 100, UsdGeom.Tokens.extent: [(-50, -50, -50), (50, 50, 50)]}, ) backside_ales_prim = stage.GetPrimAtPath(backside_ales_path) # set values backside_ales_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(0, 0, 0.002) ) backside_ales_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) backside_ales_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(1, 1, 0.02)) backside_ales_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] ) UsdGeom.PrimvarsAPI(backside_ales_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # bind material omni.kit.commands.execute( "BindMaterial", prim_path=backside_ales_path, material_path=emissive_mtl_path, strength=UsdShade.Tokens.weakerThanDescendants, ) created_bound_prims.append((backside_ales_path, UsdShade.Tokens.weakerThanDescendants)) # create LightPivot_02 light_pivot2_path = omni.usd.get_stage_next_free_path(stage, "{}/LightPivot_02".format(rootname), False) omni.kit.commands.execute( "CreatePrim", prim_path=light_pivot2_path, prim_type="Xform", select_new_prim=False, attributes={} ) light_pivot2_prim = stage.GetPrimAtPath(light_pivot2_path) UsdGeom.PrimvarsAPI(light_pivot2_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # set transform light_pivot2_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) light_pivot2_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(-149.8694695859529, 35.87684189578612, -18.78499937937383) ) light_pivot2_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(0.9999999347425043, 0.9999995656418647, 1.0000001493100235) ) light_pivot2_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] ) # create AreaLight light_pivot2_al_path = omni.usd.get_stage_next_free_path( stage, "{}/LightPivot_02/AreaLight".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=light_pivot2_al_path, prim_type="Xform", select_new_prim=False, attributes={} ) light_pivot2_al_prim = stage.GetPrimAtPath(light_pivot2_al_path) UsdGeom.PrimvarsAPI(light_pivot2_al_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # set transform light_pivot2_al_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(0, 0, 800) ) light_pivot2_al_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) light_pivot2_al_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(1.5, 1.5, 1.5) ) light_pivot2_al_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] ) # create AreaLight RectLight light_pivot2_alrl_path = omni.usd.get_stage_next_free_path( stage, "{}/LightPivot_02/AreaLight/RectLight".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=light_pivot2_alrl_path, prim_type="RectLight", select_new_prim=False, attributes={}, ) light_pivot2_alrl_prim = stage.GetPrimAtPath(light_pivot2_alrl_path) # set values light_pivot2_alrl_prim.CreateAttribute("height", Sdf.ValueTypeNames.Float, False).Set(100) light_pivot2_alrl_prim.CreateAttribute("width", Sdf.ValueTypeNames.Float, False).Set(100) light_pivot2_alrl_prim.CreateAttribute("intensity", Sdf.ValueTypeNames.Float, False).Set(55000) light_pivot2_alrl_prim.CreateAttribute("shaping:cone:angle", Sdf.ValueTypeNames.Float, False).Set(180) # create AreaLight Backside backside_albs_path = omni.usd.get_stage_next_free_path( stage, "{}/LightPivot_02/AreaLight/Backside".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=backside_albs_path, prim_type="Cube", select_new_prim=False, attributes={UsdGeom.Tokens.size: 100, UsdGeom.Tokens.extent: [(-50, -50, -50), (50, 50, 50)]}, ) backside_albs_prim = stage.GetPrimAtPath(backside_albs_path) # set values backside_albs_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 1.1)) backside_albs_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) backside_albs_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(1, 1, 0.02)) backside_albs_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] ) UsdGeom.PrimvarsAPI(backside_albs_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # bind material omni.kit.commands.execute( "BindMaterial", prim_path=backside_albs_path, material_path=backside_mtl_path, strength=UsdShade.Tokens.strongerThanDescendants, ) created_bound_prims.append((backside_albs_path, UsdShade.Tokens.strongerThanDescendants)) # create AreaLight EmissiveSurface backside_ales_path = omni.usd.get_stage_next_free_path( stage, "{}/LightPivot_02/AreaLight/EmissiveSurface".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=backside_ales_path, prim_type="Cube", select_new_prim=False, attributes={UsdGeom.Tokens.size: 100, UsdGeom.Tokens.extent: [(-50, -50, -50), (50, 50, 50)]}, ) backside_ales_prim = stage.GetPrimAtPath(backside_ales_path) # set values backside_ales_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(0, 0, 0.002) ) backside_ales_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) backside_ales_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(1, 1, 0.02)) backside_ales_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] ) UsdGeom.PrimvarsAPI(backside_ales_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # bind material omni.kit.commands.execute( "BindMaterial", prim_path=backside_ales_path, material_path=emissive_mtl_path, strength=UsdShade.Tokens.weakerThanDescendants, ) created_bound_prims.append((backside_ales_path, UsdShade.Tokens.weakerThanDescendants)) return created_mdl_prims, created_bound_prims
19,107
Python
46.29703
119
0.70325
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/tests/test_add_mdl_file.py
import omni.kit.test import omni.kit.app from pathlib import Path from pxr import Sdf, UsdShade, UsdGeom from omni.ui.tests.test_base import OmniUiTest from omni.kit import ui_test from omni.kit.test_suite.helpers import arrange_windows, select_prims from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper class TestAddMDLFile(OmniUiTest): async def test_add_mdl_file(self): await arrange_windows() extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) mdl_path = Path(extension_path).joinpath("data/tests/TESTEXPORT.mdl").absolute() # setup await ui_test.find("Stage").focus() await ui_test.find("Content").focus() # new stage usd_context = omni.usd.get_context() await usd_context.new_stage_async() stage = usd_context.get_stage() # create prims omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere") await select_prims(["/Sphere"]) await ui_test.human_delay() # drag/drop async with ContentBrowserTestHelper() as content_browser_helper: property_widget = ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'") await content_browser_helper.drag_and_drop_tree_view(str(mdl_path), drag_target=property_widget.center) # verify # NOTE: TESTEXPORT.mdl material is named "Material" so that is the prim created shader = UsdShade.Shader(stage.GetPrimAtPath("/Looks/Material/Shader")) identifier = shader.GetSourceAssetSubIdentifier("mdl") self.assertTrue(identifier == "Material")
1,700
Python
38.558139
115
0.686471
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/tests/test_drag_drop_texture_property.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.app from omni.kit.test.async_unittest import AsyncTestCase import omni.usd from omni.kit import ui_test from pxr import Sdf, UsdShade from omni.kit.test_suite.helpers import ( open_stage, get_test_data_path, select_prims, wait_stage_loading, build_sdf_asset_frame_dictonary, arrange_windows ) from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper class DragDropTextureProperty(AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows("Stage", 64) await open_stage(get_test_data_path(__name__, "bound_material.usda")) # After running each test async def tearDown(self): await wait_stage_loading() async def test_l1_drag_drop_texture_property(self): await ui_test.find("Stage").focus() await ui_test.find("Content").focus() usd_context = omni.usd.get_context() stage = usd_context.get_stage() to_select = ["/World/Looks/OmniHair/Shader"] # wait for material to load & UI to refresh await wait_stage_loading() # select prim await select_prims(to_select) await ui_test.human_delay() # open all CollapsableFrames for frame in ui_test.find_all("Property//Frame/**/CollapsableFrame[*]"): if frame.widget.title != "Raw USD Properties": frame.widget.scroll_here_y(0.5) frame.widget.collapsed = False await ui_test.human_delay() # prep content window for drag/drop texture_path = get_test_data_path(__name__, "textures/granite_a_mask.png") content_browser_helper = ContentBrowserTestHelper() # NOTE: cannot keep using widget as they become stale as window refreshes due to set_value # do tests widget_table = await build_sdf_asset_frame_dictonary() for frame_name in widget_table.keys(): for field_name in widget_table[frame_name].keys(): if field_name in ["sdf_asset_info:mdl:sourceAsset"]: continue # NOTE: sdf_asset_ could be used more than once, if so skip if widget_table[frame_name][field_name] == 1: def get_widget(): return ui_test.find(f"Property//Frame/**/CollapsableFrame[*].title=='{frame_name}'").find(f"**/StringField[*].identifier=='{field_name}'") # scroll to widget get_widget().widget.scroll_here_y(0.5) await ui_test.human_delay() # reset for test get_widget().model.set_value("") # drag/drop await content_browser_helper.drag_and_drop_tree_view(texture_path, drag_target=get_widget().center) # verify dragged item(s) for prim_path in to_select: prim = stage.GetPrimAtPath(Sdf.Path(prim_path)) self.assertTrue(prim.IsValid()) attr = prim.GetAttribute(field_name[10:]) self.assertTrue(attr.IsValid()) asset_path = attr.Get() self.assertTrue(asset_path != None) self.assertTrue(asset_path.resolvedPath.replace("\\", "/").lower() == texture_path.replace("\\", "/").lower()) # reset for next test get_widget().model.set_value("")
3,958
Python
39.814433
162
0.601314
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/tests/__init__.py
from .create_prims import * from .test_material import * from .test_add_mdl_file import * from .test_drag_drop import * from .test_material_thumb_context_menu import * from .test_material_thumb import * from .test_drag_drop_texture_property import * from .drag_drop_path import * from .test_material_goto import * from .test_refresh import *
342
Python
30.181815
47
0.760234
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/tests/test_refresh.py
import math import weakref import platform import unittest import pathlib import omni.kit.test import omni.ui as ui import carb from pxr import Usd, Sdf, UsdGeom from omni.ui.tests.test_base import OmniUiTest from omni.kit import ui_test from omni.kit.test_suite.helpers import arrange_windows, open_stage, get_test_data_path, select_prims, wait_stage_loading class TestMaterialRefreshWidget(OmniUiTest): async def setUp(self): await super().setUp() await arrange_windows() await open_stage(get_test_data_path(__name__, "thumbnail_test.usda")) async def tearDown(self): await super().tearDown() await select_prims(["/World/Sphere"]) ui_test.find("Property//Frame/**/CollapsableFrame[*].title=='Raw USD Properties'").widget.collapsed = True async def test_material_refresh_ui(self): stage_widget = ui_test.find("Stage") await stage_widget.focus() # Select the prim. await select_prims(["/World/Sphere"]) # get raw frame & open raw_frame = ui_test.find("Property//Frame/**/CollapsableFrame[*].title=='Raw USD Properties'") raw_frame.widget.collapsed = False await ui_test.human_delay(10) # get material:binding label & scroll to it raw_frame.find("**/Label[*].text=='material:binding'").widget.scroll_here_y(0.5) await ui_test.human_delay(10) # get raw relationship widgets for w in ui_test.find_all("Property//Frame/**/*.identifier!=''"): if w.widget.identifier == "remove_relationship_World_Looks_Material": # verify material binding in material widget self.assertEqual(ui_test.find("Property//Frame/**/StringField[*].identifier=='combo_drop_target'").widget.model.as_string, "/World/Looks/Material") # remove raw material binding await w.click() await ui_test.human_delay(10) # verify material binding updated in material widget self.assertEqual(ui_test.find("Property//Frame/**/StringField[*].identifier=='combo_drop_target'").widget.model.as_string, "None") break
2,182
Python
37.982142
163
0.649404
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/tests/test_material_thumb_context_menu.py
import weakref import unittest import pathlib import omni.kit.test import omni.ui as ui import carb from pathlib import Path from pxr import Sdf, UsdShade, UsdGeom from omni.ui.tests.test_base import OmniUiTest from omni.kit import ui_test from omni.kit.test_suite.helpers import ( open_stage, get_test_data_path, arrange_windows, select_prims, wait_stage_loading, ) class TestMaterialThumbContextMenu(OmniUiTest): async def setUp(self): await super().setUp() await arrange_windows("Stage", 200) await open_stage(get_test_data_path(__name__, "material_context.usda")) await wait_stage_loading() async def tearDown(self): await super().tearDown() await wait_stage_loading() async def test_material_thumb_context_menu_copy_1_to_1(self): stage = omni.usd.get_context().get_stage() # test copy single material from Cone_01 to Sphere_00 bound_material, _ = UsdShade.MaterialBindingAPI(stage.GetPrimAtPath("/World/Sphere_00")).ComputeBoundMaterial() self.assertFalse(bound_material.GetPrim().IsValid()) # select source prim await select_prims(["/World/Cone_01"]) await wait_stage_loading() # right click and "copy" await ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'").click(right_click=True) await ui_test.select_context_menu("Copy", offset=ui_test.Vec2(10, 10)) # select target prim await select_prims(["/World/Sphere_00"]) await ui_test.human_delay() # right click and "paste" await ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'").click(right_click=True) await ui_test.select_context_menu("Paste", offset=ui_test.Vec2(10, 10)) # verify binding bound_material, _ = UsdShade.MaterialBindingAPI(stage.GetPrimAtPath("/World/Sphere_00")).ComputeBoundMaterial() self.assertTrue(bound_material.GetPrim().IsValid() == True) self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, "/World/Looks/PreviewSurface") async def test_material_thumb_context_menu_copy_2_to_1(self): stage = omni.usd.get_context().get_stage() # test copy single material from Cone_01 to Sphere_00 bound_material, _ = UsdShade.MaterialBindingAPI(stage.GetPrimAtPath("/World/Sphere_00")).ComputeBoundMaterial() self.assertFalse(bound_material.GetPrim().IsValid()) # select source prim await select_prims(["/World/Cone_01", "/World/Cone_02"]) await wait_stage_loading() # right click and "copy" await ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'").click(right_click=True) await ui_test.select_context_menu("Copy", offset=ui_test.Vec2(10, 10)) # select target prim await select_prims(["/World/Sphere_00"]) await ui_test.human_delay() # right click and "paste" await ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'").click(right_click=True) await ui_test.select_context_menu("Paste (2 Materials)", offset=ui_test.Vec2(10, 10)) # verify binding bound_material, _ = UsdShade.MaterialBindingAPI(stage.GetPrimAtPath("/World/Sphere_00")).ComputeBoundMaterial() self.assertTrue(bound_material.GetPrim().IsValid() == True) self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, "/World/Looks/PreviewSurface") async def test_material_thumb_context_menu_copy_4_to_2(self): stage = omni.usd.get_context().get_stage() # test copy single material from Cone_01 to Sphere_00 bound_material, _ = UsdShade.MaterialBindingAPI(stage.GetPrimAtPath("/World/Sphere_00")).ComputeBoundMaterial() self.assertFalse(bound_material.GetPrim().IsValid()) bound_material, _ = UsdShade.MaterialBindingAPI(stage.GetPrimAtPath("/World/Sphere_01")).ComputeBoundMaterial() self.assertFalse(bound_material.GetPrim().IsValid()) # select source prim await select_prims(["/World/Cone_01", "/World/Cone_02"]) await wait_stage_loading() # right click and "copy" await ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'").click(right_click=True) await ui_test.select_context_menu("Copy", offset=ui_test.Vec2(10, 10)) # select target prim await select_prims(["/World/Sphere_00", "/World/Sphere_01"]) await wait_stage_loading() # right click and "paste" await ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'").click(right_click=True) await ui_test.select_context_menu("Paste (2 Materials)", offset=ui_test.Vec2(10, 10)) # verify binding bound_material, _ = UsdShade.MaterialBindingAPI(stage.GetPrimAtPath("/World/Sphere_00")).ComputeBoundMaterial() self.assertTrue(bound_material.GetPrim().IsValid() == True) self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, "/World/Looks/PreviewSurface") bound_material, _ = UsdShade.MaterialBindingAPI(stage.GetPrimAtPath("/World/Sphere_01")).ComputeBoundMaterial() self.assertTrue(bound_material.GetPrim().IsValid() == True) self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, "/World/Looks/PreviewSurface") async def test_material_thumb_context_menu_copy_4211_to_2(self): stage = omni.usd.get_context().get_stage() def get_bindings(prim_paths): bindings = [] for prim_path in prim_paths: prim = stage.GetPrimAtPath(prim_path) bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() bindings.append(bound_material.GetPath().pathString if bound_material else "None") # fixme - due to get_binding_from_prims using sets which are not ordered return sorted(bindings) for index, data in enumerate([("Paste (4 Materials)", ['/World/Looks/OmniGlass_Opacity', '/World/Looks/OmniPBR_ClearCoat', '/World/Looks/PreviewSurface', '/World/Looks/PreviewSurface']), ("Paste (2 Materials)", ['/World/Looks/PreviewSurface', '/World/Looks/PreviewSurface', 'None', 'None']), ("Paste", ['/World/Looks/OmniPBR_ClearCoat', 'None', 'None', 'None']), ("Paste", ['/World/Looks/OmniGlass_Opacity', 'None', 'None', 'None'])]): # select source prims await select_prims(["/World/Cone_01", "/World/Cone_02", "/World/Cube_01", "/World/Cube_02"]) await wait_stage_loading() # verify copy material materials = get_bindings(["/World/Sphere_00", "/World/Sphere_01", "/World/Sphere_03", "/World/Sphere_04"]) self.assertEqual(materials, ['None', 'None', 'None', 'None']) # right click and "copy" widgets = ui_test.find_all("Property//Frame/**/Button[*].identifier=='preview_drop_target'") await widgets[index].click(right_click=True) await ui_test.select_context_menu("Copy", offset=ui_test.Vec2(10, 10)) # select target prim await select_prims(["/World/Sphere_00", "/World/Sphere_01", "/World/Sphere_03", "/World/Sphere_04"]) await wait_stage_loading() # right click and "paste" await ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'").click(right_click=True) await ui_test.select_context_menu(data[0], offset=ui_test.Vec2(10, 10)) materials = get_bindings(["/World/Sphere_00", "/World/Sphere_01", "/World/Sphere_03", "/World/Sphere_04"]) self.assertEqual(materials, data[1]) omni.kit.undo.undo() async def test_material_thumb_context_menu_copy_1_to_many(self): stage = omni.usd.get_context().get_stage() # test copy single material from Cone_01 to Sphere_* for index in range(0, 64): bound_material, _ = UsdShade.MaterialBindingAPI(stage.GetPrimAtPath(f"/World/Sphere_{index:02d}")).ComputeBoundMaterial() self.assertFalse(bound_material.GetPrim().IsValid()) # select source prim await select_prims(["/World/Cone_01"]) await wait_stage_loading() # right click and "copy" await ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'").click(right_click=True) await ui_test.select_context_menu("Copy", offset=ui_test.Vec2(10, 10)) # select target prims to_select = [] for index in range(0, 64): to_select.append(f"/World/Sphere_{index:02d}") await select_prims(to_select) # right click in frame to "paste" widget = ui_test.find("Property//Frame/**/CollapsableFrame[*].title=='Materials on selected models'") await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10), right_click=True) await ui_test.select_context_menu("Paste To All", offset=ui_test.Vec2(10, 10)) # verify binding for index in range(0, 64): bound_material, _ = UsdShade.MaterialBindingAPI(stage.GetPrimAtPath(f"/World/Sphere_{index:02d}")).ComputeBoundMaterial() self.assertTrue(bound_material.GetPrim().IsValid() == True) self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, "/World/Looks/PreviewSurface") async def test_material_thumb_context_menu_copy_2_to_many(self): stage = omni.usd.get_context().get_stage() # test copy 2 materials from Cone_01, Cone_02 to Sphere_* for index in range(0, 64): bound_material, _ = UsdShade.MaterialBindingAPI(stage.GetPrimAtPath(f"/World/Sphere_{index:02d}")).ComputeBoundMaterial() self.assertFalse(bound_material.GetPrim().IsValid()) # select source prim await select_prims(["/World/Cone_01", "/World/Cone_02"]) await wait_stage_loading() # right click and "copy" await ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'").click(right_click=True) await ui_test.select_context_menu("Copy", offset=ui_test.Vec2(10, 10)) # select target prims to_select = [] for index in range(0, 64): to_select.append(f"/World/Sphere_{index:02d}") await select_prims(to_select) # right click in frame to "paste" widget = ui_test.find("Property//Frame/**/CollapsableFrame[*].title=='Materials on selected models'") await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10), right_click=True) await ui_test.select_context_menu("Paste To All", offset=ui_test.Vec2(10, 10)) # verify binding for index in range(0, 64): bound_material, _ = UsdShade.MaterialBindingAPI(stage.GetPrimAtPath(f"/World/Sphere_{index:02d}")).ComputeBoundMaterial() self.assertTrue(bound_material.GetPrim().IsValid() == True) self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, "/World/Looks/PreviewSurface")
11,353
Python
47.110169
194
0.642826
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/tests/test_material.py
import weakref import platform import unittest import pathlib import omni.kit.test import omni.ui as ui import carb from pxr import Usd, Sdf, UsdGeom from omni.ui.tests.test_base import OmniUiTest from omni.kit import ui_test from omni.kit.test_suite.helpers import arrange_windows, wait_stage_loading class TestMaterialWidget(OmniUiTest): async def setUp(self): await super().setUp() await arrange_windows() from omni.kit.property.material.scripts.material_properties import TEST_DATA_PATH self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() self._usd_path = TEST_DATA_PATH.absolute() self._icon_path = TEST_DATA_PATH.resolve().parent.joinpath("icons") from omni.kit.property.usd.usd_attribute_widget import UsdPropertiesWidget import omni.kit.window.property as p self._w = p.get_window() async def tearDown(self): await super().tearDown() async def test_material_ui(self): usd_context = omni.usd.get_context() await usd_context.new_stage_async() material_prims, bound_prims = omni.kit.property.material.tests.create_test_stage() await self.docked_test_window( window=self._w._window, width=450, height=285, restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position = ui.DockPosition.BOTTOM) # Select the prim. usd_context.get_selection().set_selected_prim_paths(["/LightPivot_01/AreaLight/Backside"], True) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(10) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_material_ui.png") usd_context.get_selection().set_selected_prim_paths([], True) async def __test_material_multiselect_ui(self): usd_context = omni.usd.get_context() await self.docked_test_window( window=self._w._window, width=450, height=520, restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position = ui.DockPosition.BOTTOM) # Select the prim. usd_context.get_selection().set_selected_prim_paths(["/LightPivot_01/AreaLight/Backside", "/LightPivot_01/AreaLight/EmissiveSurface"], True) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(10) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_material_multiselect_ui.png") usd_context.get_selection().set_selected_prim_paths([], True) async def test_material_popup_full_ui(self): from omni.kit.window.property.templates import SimplePropertyWidget, LABEL_WIDTH, LABEL_HEIGHT from omni.kit.material.library.listbox_widget import MaterialListBoxWidget usd_context = omni.usd.get_context() test_file_path = self._usd_path.joinpath("material_binding.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await omni.kit.app.get_app().next_update_async() # full window window = await self.create_test_window(width=460, height=380) with window.frame: with ui.VStack(width=0, height=0): with ui.HStack(width=0, height=0): name_field = ui.StringField(width=400, height=20, enabled=False) name_field.model.set_value("TEST"*4) await ui_test.human_delay(10) listbox_widget = MaterialListBoxWidget(icon_path=None, index=0, on_click_fn=None, theme={}) listbox_widget.set_parent(name_field) listbox_widget.build_ui() # material loading is async so alow for loadng await ui_test.human_delay(50) await ui_test.human_delay(10) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_material_popup1_ui.png") async def test_material_popup_search_ui(self): from omni.kit.window.property.templates import SimplePropertyWidget, LABEL_WIDTH, LABEL_HEIGHT from omni.kit.material.library.listbox_widget import MaterialListBoxWidget usd_context = omni.usd.get_context() test_file_path = self._usd_path.joinpath("material_binding.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await omni.kit.app.get_app().next_update_async() # search window = await self.create_test_window(width=460, height=380) with window.frame: with ui.VStack(width=0, height=0): with ui.HStack(width=0, height=0): name_field = ui.StringField(width=400, height=20, enabled=False) name_field.model.set_value("SEARCH"*4) await ui_test.human_delay(10) listbox_widget = MaterialListBoxWidget(icon_path=None, index=0, on_click_fn=None, theme={}) listbox_widget.set_parent(name_field) listbox_widget.build_ui() await ui_test.human_delay(10) listbox_widget._search_updated("PBR") # material loading is async so alow for loadng await wait_stage_loading() await ui_test.human_delay(10) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_material_popup2_ui.png") async def test_material_description_ui(self): from omni.kit import ui_test usd_context = omni.usd.get_context() test_file_path = self._usd_path.joinpath("material_binding.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await self.docked_test_window( window=self._w._window, width=450, height=285, restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position = ui.DockPosition.BOTTOM) # Select the prim. usd_context.get_selection().set_selected_prim_paths(["/World/Looks/OmniPBR"], True) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay() for w in ui_test.find_all("Property//Frame/**/CollapsableFrame[*]"): if w.widget.title != "Raw USD Properties": w.widget.collapsed = False await ui_test.human_delay() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_material_description_ui.png") usd_context.get_selection().set_selected_prim_paths([], True)
6,806
Python
40.006024
148
0.644431
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/tests/test_material_goto.py
## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import os import omni.kit.app import omni.usd import carb from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from omni.kit.material.library.test_helper import MaterialLibraryTestHelper from omni.kit.test_suite.helpers import ( open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows ) class PropertyMaterialGotoMDL(AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows("Stage", 256) await open_stage(get_test_data_path(__name__, "material_binding_inherited.usda")) # After running each test async def tearDown(self): await wait_stage_loading() async def test_l1_mesh_goto_material_button(self): pass await ui_test.find("Stage").focus() # setup stage = omni.usd.get_context().get_stage() # goto single prims for prim_list, expected in [("/World/Xform/Cone", ['/World/Looks/OmniSurface']), ("/World/Xform/Cone_01", ['/World/Looks/OmniPBR']), ("/World/Xform_Inherited/Cone_02", ['/World/Looks/OmniSurface_Blood']), ("/World/Xform_Inherited/Cone_03", ['/World/Looks/OmniSurface_Blood']), ("/World/Xform_Unbound/Sphere", ['/World/Xform_Unbound/Sphere'])]: await select_prims([prim_list]) thumb_widget = ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'") await thumb_widget.click() await ui_test.human_delay(50) # verify self.assertEqual(omni.usd.get_context().get_selection().get_selected_prim_paths(), expected) # goto multiple prims for index, expected in enumerate([['/World/Looks/OmniPBR', '/World/Looks/OmniSurface'], ['/World/Looks/OmniSurface'], ['/World/Looks/OmniPBR']]): await select_prims(["/World/Xform/Cone", "/World/Xform/Cone_01"]) thumb_widget = ui_test.find_all("Property//Frame/**/Button[*].identifier=='preview_drop_target'") await thumb_widget[index].click() await ui_test.human_delay(50) # verify self.assertEqual(omni.usd.get_context().get_selection().get_selected_prim_paths(), expected) # goto multiple selected inherited prims await select_prims(["/World/Xform_Inherited/Cone_02", "/World/Xform_Inherited/Cone_03"]) thumb_widget = ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'") await thumb_widget.click() await ui_test.human_delay(50) # verify self.assertEqual(omni.usd.get_context().get_selection().get_selected_prim_paths(), ['/World/Looks/OmniSurface_Blood'])
3,262
Python
41.376623
153
0.642244
omniverse-code/kit/exts/omni.kit.property.material/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.8.19] - 2023-01-23 ### Changes - Material property widget parameters - don't override displayName and/or displayGroup if already set. ## [1.8.18] - 2023-01-10 ### Changes - Fix ui refresh issue when modifying material prim. ## [1.8.17] - 2022-12-20 ### Changes - Add arrange_windows to fix some tests when run in random order. ## [1.8.16] - 2022-11-25 ### Changes - Use notification instead of popup to avoid hang. ## [1.8.15] - 2022-11-16 ### Changes - Fixed widget rebuilding w/ any property change. ## [1.8.14] - 2022-10-28 ### Changes - added add_context_menu to UsdBindingAttributeWidget to prevent multiple menu dditions ## [1.8.13] - 2022-08-17 ### Changes - Updated "material:binding" widget refreshing ## [1.8.12] - 2022-08-17 ### Changes - Fixed clicking on thumbnail to goto material. Now works with inherited materials & multiple selections ## [1.8.11] - 2022-08-09 ### Changes - Updated golden images for TreeView. ## [1.8.10] - 2022-07-25 ### Changes - Refactored unittests to make use of content_browser test helpers ## [1.8.9] - 2022-05-30 ### Changes - Update material thumbnail image to prevent multiple images being overlayed ## [1.8.8] - 2022-05-24 ### Changes - Material thumbnail context menu update - Copy and Paste material groups ## [1.8.7] - 2022-05-23 ### Changes - Support legacy and new Viewport API - Add dependency on omni.kit.viewport.utility ## [1.8.6] - 2022-05-11 ### Changes - Support material browser drag/drop ## [1.8.5] - 2022-05-17 ### Changes - Support multi-file drag & drop ## [1.8.4] - 2022-05-12 ### Changes - Show shader description on material ## [1.8.3] - 2022-05-03 ### Changes - Fixed unittest stemming from content browser changes ## [1.8.2] - 2022-01-11 ### Changes - Improved info:mdl:sourceAsset:subidentifier match with combobox list from material library ## [1.8.1] - 2021-12-02 ### Changes - Exception fixes and shader preload stall fix ## [1.8.0] - 2021-11-29 ### Changes - Added material annotations "description" property ## [1.7.5] - 2021-11-12 ### Changes - Updated to new omni.kit.material.library with new neuraylib ## [1.7.4] - 2021-11-02 ### Changes - Fixed refresh on binding ## [1.7.3] - 2021-10-27 ### Changes - Prevent crash in event callback ## [1.7.2] - 2021-09-10 ### Changes - Dragging a multi-material .mdl file onto preview icon shows material dialog - Added widget identifiers ## [1.7.1] - 2021-08-11 ### Changes - Fixed Sdf.Path warning due to string <-> Sdf.Path compare ## [1.7.0] - 2021-06-30 ### Changes - Updated material list handling to use async Treeview and prevent stalls on large scenes - Moved `MaterialUtils`, `MaterialListBoxWidget`, `SearchWidget`, `ThumbnailLoader`, `MaterialListModel` & `MaterialListDelegate` into omni.kit.material.library ## [1.6.5] - 2021-05-31 ### Changes - Changed "Material & Shader" to "Material and Shader" ## [1.6.4] - 2021-05-20 ### Changes - Material search resets scroll position when typing to prevent user not seeing results ## [1.6.3] - 2021-05-11 ### Changes - Updated material info so Outputs, UI Properties and Material Flags are closed by default ## [1.6.2] - 2021-04-15 ### Changes - Changed how material input is populated. ## [1.6.1] - 2021-03-17 ### Changes - Add material thumnail context menu ## [1.6.0] - 2021-03-16 ### Changes - Add support for UsdShade.NodeGraph prims - Add support for UsdUI.Backdrop prims ## [1.5.0] - 2021-03-09 ### Changes - Updated material search dialog - Added current materials to quicksearch ## [1.4.3] - 2021-02-25 ### Changes - Fixed issue with materials with Relationship ## [1.4.2] - 2021-02-10 ### Changes - Updated StyleUI handling ## [1.4.1] - 2021-02-03 ### Changes - Fixed text issue with long lists in material name search dialog ## [1.4.0] - 2021-01-28 ### Changes - Added material name search dialog ## [1.3.8] - 2020-12-16 ### Changes - Fixed material shader preloading ## [1.3.7] - 2020-12-10 ### Changes - fixed button leak ## [1.3.6] - 2020-12-09 ### Changes - Added extension icon - Added readme - Updated preview image ## [1.3.5] - 2020-12-01 ### Updated - When property in both material and shader don't show shader properties in material ## [1.3.5] - 2020-11-20 ### Updated - Added Sub-Identifier support ## [1.3.4] - 2020-11-19 ### Updated - Fixed issue with newly created materials not refreshing when loaded ## [1.3.3] - 2020-11-18 ### Added - Updates thumbnail loading to use async and quiet error messages ## [1.3.2] - 2020-11-13 ### Added - Improved material group/name & added PreviewSurface values ## [1.3.1] - 2020-11-12 ### Added - Fixed issue where bound material didn't show sometimes - Added refresh on bound material when material created/modified to update material list ## [1.3.0] - 2020-11-06 ### Added - Materials now show Materials & Shader values ## [1.2.1] - 2020-10-21 ### Added - Moved schema into bundle ## [1.2.0] - 2020-10-16 ### Added - Added thumbnail preview - Added click to goto material on thumbnail ## [1.1.0] - 2020-10-02 ### Added - Added material binding UI ## [1.0.0] - 2020-09-17 ### Added - Created
5,176
Markdown
22.857143
160
0.688756
omniverse-code/kit/exts/omni.kit.property.material/docs/README.md
# omni.kit.property.material ## Introduction Property window extensions are for viewing and editing Usd Prim Attributes ## This extension supports editing of these Usd Types; - UsdShade.Material - UsdShade.Shader ## also allows material bindings on other prims to be edited
280
Markdown
19.071427
74
0.785714
omniverse-code/kit/exts/omni.kit.property.material/docs/index.rst
omni.kit.property.material ########################### Property Material Values .. toctree:: :maxdepth: 1 CHANGELOG
127
reStructuredText
9.666666
27
0.551181
omniverse-code/kit/exts/omni.activity.usd_resolver/PACKAGE-LICENSES/omni.activity.usd_resolver-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
412
Markdown
57.999992
74
0.839806
omniverse-code/kit/exts/omni.activity.usd_resolver/config/extension.toml
[package] title = "Omni Activity plugin for UsdResolver" category = "Telemetry" version = "1.0.1" description = "The activity and the progress processor gets pumped every frame" authors = ["NVIDIA"] keywords = ["activity"] changelog = "docs/CHANGELOG.md" [[python.module]] name = "omni.activity.usd_resolver" [[native.plugin]] path = "bin/*.plugin" [dependencies] "omni.activity.core" = {} "omni.usd" = {} [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] stdoutFailPatterns.exclude = [ "*failed to load native plugin*", ]
604
TOML
19.166666
79
0.675497
omniverse-code/kit/exts/omni.activity.usd_resolver/omni/activity/usd_resolver/__init__.py
## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## # Required to be able to instantiate the object types import omni.core
508
Python
41.416663
77
0.793307
omniverse-code/kit/exts/omni.activity.usd_resolver/omni/activity/usd_resolver/tests/test_skip.py
## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.activity.core as act import omni.kit.app import omni.kit.test class TestSkip(omni.kit.test.AsyncTestCase): async def test_general(self): """ Temporarly placeholder for tests """ self.assertTrue(True)
686
Python
33.349998
77
0.747813
omniverse-code/kit/exts/omni.activity.usd_resolver/omni/activity/usd_resolver/tests/__init__.py
## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## from .test_skip import TestSkip
469
Python
41.727269
77
0.793177
omniverse-code/kit/exts/omni.kit.widget.fast_search/PACKAGE-LICENSES/omni.kit.widget.fast_search-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited. "Icon made by Pixel perfect from www.flaticon.com" "Icon made by prettycons from www.flaticon.com"
513
Markdown
45.727269
74
0.826511
omniverse-code/kit/exts/omni.kit.widget.fast_search/config/extension.toml
[package] version = "0.3.0" authors = ["NVIDIA"] changelog = "docs/CHANGELOG" readme = "docs/README.md" keywords = ["search", "fast"] title = "Fast Search" description = "Fast search bar" preview_image = "data/preview.png" [ui] name = "Fast Search" [dependencies] "omni.appwindow" = {} "omni.ui" = {} [[python.module]] name = "omni.kit.widget.fast_search.python" [[test]] waiver = "extension is being deprecated"
416
TOML
17.954545
43
0.675481
omniverse-code/kit/exts/omni.kit.widget.fast_search/omni/kit/widget/fast_search/python/delegate.py
""" * Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. * * NVIDIA CORPORATION and its licensors retain all intellectual property * and proprietary rights in and to this software, related documentation * and any modifications thereto. Any use, reproduction, disclosure or * distribution of this software and related documentation without an express * license agreement from NVIDIA CORPORATION is strictly prohibited. """ import omni.ui as ui import os ICONS_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "icons") DICT_ICONS = { "forbidden": os.path.join(ICONS_DIR, "forbidden.svg"), "forbidden_black": os.path.join(ICONS_DIR, "forbidden_black.svg"), "star": os.path.join(ICONS_DIR, "star.svg"), "star_black": os.path.join(ICONS_DIR, "star_black.svg"), "plus": os.path.join(ICONS_DIR, "{style}", "Plus.svg"), "minus": os.path.join(ICONS_DIR, "{style}", "Minus.svg"), } class FastSearchDelegate(ui.AbstractItemDelegate): """Delegate of the Mapper Batcher""" def __init__(self): super(FastSearchDelegate, self).__init__() self._highlighting_enabled = None # Text that is highlighted in flat mode self._highlighting_text = None self.show_column_visibility = True self._style = None self.init_editor_style() def init_editor_style(self): import carb.settings self._style = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark" def build_branch(self, model, item, column_id, level, expanded): """Create a branch widget that opens or closes subtree""" if column_id == 0: with ui.HStack(width=16 * (level + 2), height=0): ui.Spacer() if model.can_item_have_children(item): # Draw the +/- icon image_name = "minus" if expanded else "plus" ui.Image( DICT_ICONS[image_name].format(style=self._style), width=10, height=10, style_type_name_override="TreeView.Item", ) ui.Spacer(width=4) def build_widget(self, model, item, column_id, level, expanded): """Create a widget per item""" # Disable the item if it's an Instance Proxy because Kit can't interact with such object and crashes. enabled = True if column_id == 0: name = item.name.get_value_as_string() star_path = self.get_fav_icon(item) forbidden_path = self.get_block_icon(item) with ui.HStack(height=20): label = ui.Label(name) label.set_mouse_released_fn(lambda x, y, b, m, i=item: self._on_item_clicked(i, b)) ui.Spacer() fav_icon = ui.Image(star_path, width=15, height=15) fav_icon.set_mouse_released_fn(lambda x, y, b, m, i=item, f=fav_icon: self._on_fav_clicked(i, f, b)) ui.Spacer(width=10) blocklist_icon = ui.Image(forbidden_path, width=15, height=15) blocklist_icon.set_mouse_released_fn(lambda x, y, b, m, i=item, f=blocklist_icon: self._on_block_clicked(i, f, b)) ui.Spacer(width=10) @staticmethod def get_fav_icon(item): """Get favorite icon path""" return DICT_ICONS["star_black"] if not item.favorite else DICT_ICONS["star"] @staticmethod def get_block_icon(item): """Get blocked icon path""" return DICT_ICONS["forbidden_black"] if not item.blocklist else DICT_ICONS["forbidden"] def _on_item_clicked(self, item, button): if button != 0: return item.item_mouse_released() def _on_fav_clicked(self, item, image_widget, button): """Called when favorite icon is clicked""" if button != 0: return item.favorite = not item.favorite image_widget.source_url = self.get_fav_icon(item) def _on_block_clicked(self, item, image_widget, button): """Called when blocked icon is clicked""" if button != 0: return item.blocklist = not item.blocklist image_widget.source_url = self.get_block_icon(item) def build_header(self, column_id): """Build the header""" style_type_name = "TreeView.Header" with ui.HStack(): ui.Label("Node name", style_type_name_override=style_type_name)
4,521
Python
39.017699
130
0.597655
omniverse-code/kit/exts/omni.kit.widget.fast_search/omni/kit/widget/fast_search/python/__init__.py
""" * Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. * * NVIDIA CORPORATION and its licensors retain all intellectual property * and proprietary rights in and to this software, related documentation * and any modifications thereto. Any use, reproduction, disclosure or * distribution of this software and related documentation without an express * license agreement from NVIDIA CORPORATION is strictly prohibited. """ from .widget import FastSearchWidget
472
Python
38.416663
76
0.800847
omniverse-code/kit/exts/omni.kit.widget.fast_search/omni/kit/widget/fast_search/python/model.py
""" * Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. * * NVIDIA CORPORATION and its licensors retain all intellectual property * and proprietary rights in and to this software, related documentation * and any modifications thereto. Any use, reproduction, disclosure or * distribution of this software and related documentation without an express * license agreement from NVIDIA CORPORATION is strictly prohibited. """ import omni.ui as ui class SimpleItem(ui.AbstractItem): """Single item of the model""" def __init__(self, model, name, fav=False, block=False): super(SimpleItem, self).__init__() self._model = model self.name = name self._favorite = fav self._blocklist = block def item_mouse_released(self): self._model.item_mouse_released(self) @property def favorite(self): return self._favorite @favorite.setter def favorite(self, value: bool): """Add favorite""" if value: self._model.prepend_item("favorites", self, refresh=False) else: if self in self._model.favorites: self._model.favorites.remove(self) self._favorite = value @property def blocklist(self): return self._blocklist @blocklist.setter def blocklist(self, value: bool): """Add blocklist""" if value: self._model.prepend_item("blocklist", self, refresh=False) if self in self._model.favorites: self._model.favorites.remove(self) if self in self._model.previous_items: self._model.previous_items.remove(self) else: if self in self._model.blocklist: self._model.blocklist.remove(self) if self.favorite and self not in self._model.favorites: self._model.prepend_item("favorites", self, refresh=False) if self not in self._model.previous_items: self._model.prepend_item("previous_items", self, refresh=False) self._blocklist = value class SimpleModel(ui.AbstractItemModel): """Simple list model that can be used in a lot of different way""" class _Event(set): """ A list of callable objects. Calling an instance of this will cause a call to each item in the list in ascending order by index. """ def __call__(self, *args, **kwargs): """Called when the instance is “called” as a function""" # Call all the saved functions for f in self: f(*args, **kwargs) def __repr__(self): """ Called by the repr() built-in function to compute the “official” string representation of an object. """ return f"Event({set.__repr__(self)})" class _EventSubscription: """ Event subscription. _Event has callback while this object exists. """ def __init__(self, event, fn): """ Save the function, the event, and add the function to the event. """ self._fn = fn self._event = event event.add(self._fn) def __del__(self): """Called by GC.""" self._event.remove(self._fn) def __init__(self, column_count: int): super(SimpleModel, self).__init__() self.items = [] self.latest = [] self.favorites = [] self.blocklist = [] self.previous_items = [] self._column_count = column_count self.__on_item_mouse_released = self._Event() def item_mouse_released(self, item): """Call the event object that has the list of functions""" self.__on_item_mouse_released(item) def subscribe_item_mouse_released(self, fn): """ Return the object that will automatically unsubscribe when destroyed. """ return self._EventSubscription(self.__on_item_mouse_released, fn) def get_item_children(self, item: SimpleItem) -> list: """Returns all the children when the widget asks it.""" if item is not None: # Since we are doing a flat list, we return the children of root only. # If it's not root we return. return [] return self.items def set_items(self, mode_attr: str, items: list, refresh: bool = True): """Set items on the list""" setattr(self, mode_attr, items) if refresh: self.refresh() def append_item(self, mode_attr: str, item, refresh: bool = True): """Append items on the list""" current_items = getattr(self, mode_attr) indexes = [] for i, current_item in enumerate(current_items): if item.name.get_value_as_string() == current_item.name.get_value_as_string(): indexes.append(i) indexes.reverse() for index in indexes: current_items.pop(index) current_items.append(item) self.set_items(mode_attr, current_items, refresh=refresh) def prepend_item(self, mode_attr: str, item, refresh: bool = True): """Prepend items on the list""" current_items = getattr(self, mode_attr) indexes = [] for i, current_item in enumerate(current_items): if item.name.get_value_as_string() == current_item.name.get_value_as_string(): indexes.append(i) indexes.reverse() for index in indexes: current_items.pop(index) current_items.insert(0, item) self.set_items(mode_attr, current_items, refresh=refresh) def refresh(self): """Reset the model""" self._item_changed(None) def get_item_value_model_count(self, item) -> int: """The number of columns""" return self._column_count def get_item_value_model(self, item: SimpleItem, column_id: int): """ Return value model. It's the object that tracks the specific value. In our case we use ui.SimpleStringModel. """ return item.name
6,141
Python
33.122222
90
0.586875
omniverse-code/kit/exts/omni.kit.widget.fast_search/omni/kit/widget/fast_search/python/widget.py
""" * Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. * * NVIDIA CORPORATION and its licensors retain all intellectual property * and proprietary rights in and to this software, related documentation * and any modifications thereto. Any use, reproduction, disclosure or * distribution of this software and related documentation without an express * license agreement from NVIDIA CORPORATION is strictly prohibited. """ import carb import omni.ui as ui from . import delegate, model class FastSearchWidget(object): def __init__(self, items_dict): self._items_dict = items_dict self._is_visible = False self._current_selection = [] self._menus_global_selection = [] self._tab_first_item_set = False self._current_global_selection_index = 0 self._style = {"Menu.ItemSelected": {"color": 0xFFC8C8C8}, "Menu.ItemUnseleted": {"color": 0xFF646464}} self._default_attr = { "_model": None, "_delegate": None, "_window": None, "_search_field": None, "_tree_view": None, "_menu_all": None, "_menu_latest": None, "_menu_favorites": None, "_menu_blocklist": None, "_subscription_item_mouse_released": None, } for attr, value in self._default_attr.items(): setattr(self, attr, value) def create_widget(self): """Create the widget UI""" self._model = model.SimpleModel(column_count=1) self._delegate = delegate.FastSearchDelegate() self._window = ui.Window( "Graph search", width=400, height=400, flags=ui.WINDOW_FLAGS_POPUP | ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_MENU_BAR, ) menu_bar = self._window.menu_bar menu_bar.set_style(self._style) with menu_bar: self._menu_all = ui.MenuItem( "All", triggered_fn=self.show_all, style_type_name_override="Menu.ItemSelected" ) self._menu_latest = ui.MenuItem( "Latest", triggered_fn=self.show_only_latest, style_type_name_override="Menu.ItemUnseleted" ) self._menu_favorites = ui.MenuItem( "Favorites", triggered_fn=self.show_only_favorites, style_type_name_override="Menu.ItemUnseleted" ) self._menu_blocklist = ui.MenuItem( "Blocklist", triggered_fn=self.show_only_blocklist, style_type_name_override="Menu.ItemUnseleted" ) self._menus_global_selection.extend( [self._menu_all, self._menu_latest, self._menu_favorites, self._menu_blocklist] ) self._window.frame.set_key_pressed_fn(self.__on_key_pressed) with self._window.frame: with ui.VStack(): with ui.Frame(height=20): with ui.VStack(): self._search_field = ui.StringField() self._search_field.model.add_value_changed_fn(self._filter) ui.Spacer(height=5) with ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style_type_name_override="TreeView", ): self._tree_view = ui.TreeView( self._model, delegate=self._delegate, root_visible=False, header_visible=False, style={"TreeView.Item": {"margin": 4}}, ) self._tree_view.set_selection_changed_fn(self._on_widget_attr_selection_changed) self._model.set_items( "items", [model.SimpleItem(self._model, ui.SimpleStringModel(attr)) for attr in self._items_dict.keys()] ) self._model.previous_items = self._model.items self._subscription_item_mouse_released = self._model.subscribe_item_mouse_released( self.item_mouse_released ) self._select_first_item() def show_all(self): print("show all") def show_only_latest(self): print("show latest") def show_only_favorites(self): print("show favorites") def show_only_blocklist(self): print("show blocklist") def _select_first_item(self): """Select first item of the list""" if self._model.items: self._tree_view.selection = [self._model.items[0]] def _select_down_item(self): """Select the item down""" if self._tree_view.selection: current_index = self._model.items.index(self._tree_view.selection[-1]) index = current_index + 1 if index >= len(self._model.items) - 1: index = len(self._model.items) - 1 self._tree_view.selection = [self._model.items[index]] def _select_up_item(self): """Select the item up""" if self._tree_view.selection: current_index = self._model.items.index(self._tree_view.selection[-1]) index = current_index - 1 if index <= 0: index = 0 self._tree_view.selection = [self._model.items[index]] def _filter(self, str_model): """Filter from the windows""" # set the global mode (all, latest...) if self._current_global_selection_index == 0: self._model.items = self._model.previous_items self._model.refresh() elif self._current_global_selection_index == 1: self._model.items = self._model.latest self._model.refresh() elif self._current_global_selection_index == 2: self._model.items = self._model.favorites self._model.refresh() elif self._current_global_selection_index == 3: self._model.items = self._model.blocklist self._model.refresh() value = str_model.get_value_as_string() if not value.strip(): self._select_first_item() return items = [] for item in self._model.items: current_attr = item.name.get_value_as_string() if value.lower() not in current_attr.lower(): continue items.append(item) if not items: self._model.items = [] self._model.refresh() return self._model.items = items self._model.refresh() self._select_first_item() def _on_widget_attr_selection_changed(self, selection): """Fill self.current_attrs_selection when the selection change into the attribute chooser""" self._current_selection = selection def set_window_visible(self, visible): """Set the widget visible""" self._window.visible = visible if visible: self._search_field.model.set_value("") self._search_field.focus_keyboard() self._select_first_item() def item_mouse_released(self, item): self.execute_item(item) def __key_enter_pressed(self): """Called when key enter is pressed. Add the item in the latest list""" if self.is_visible: if self._current_selection: self.execute_item(self._current_selection[0]) def execute_item(self, item): selection_str = item.name.get_value_as_string() self._items_dict[selection_str]() current_latest = [x.name.get_value_as_string() for x in self._model.latest] if not current_latest or current_latest[-1] != selection_str: if selection_str in current_latest: current_latest.remove(selection_str) current_latest.insert(0, selection_str) self._model.set_items( "latest", [model.SimpleItem(self._model, ui.SimpleStringModel(attr)) for attr in current_latest] ) self.set_window_visible(False) def __key_escape_pressed(self): if self.is_visible: self.set_window_visible(False) self._tab_first_item_set = False def __key_tab_pressed(self): """Roll modes""" if self.is_visible and self._model.items and not self._tab_first_item_set: selection_str = self._current_selection[0].name.get_value_as_string() self._search_field.model.set_value(selection_str) self._tab_first_item_set = True elif self.is_visible and self._model.items and self._tab_first_item_set: self.__key_enter_pressed() self._tab_first_item_set = False def __key_ctrl_tab_pressed(self): """Roll modes""" if self.is_visible: if self._current_global_selection_index == len(self._menus_global_selection) - 1: self._current_global_selection_index = 0 else: self._current_global_selection_index += 1 for i, menu in enumerate(self._menus_global_selection): if i == self._current_global_selection_index: menu.style_type_name_override = "Menu.ItemSelected" else: menu.style_type_name_override = "Menu.ItemUnseleted" self._filter(self._search_field.model) def __key_select_down_pressed(self): if self.is_visible: self._select_down_item() def __key_select_up_pressed(self): if self.is_visible: self._select_up_item() def __on_key_pressed(self, key_index, key_flags, key_down): key_mod = key_flags & ~ui.Widget.FLAG_WANT_CAPTURE_KEYBOARD if key_index == int(carb.input.KeyboardInput.ESCAPE) and key_mod == 0 and key_down: self.__key_escape_pressed() if key_index == int(carb.input.KeyboardInput.DOWN) and key_mod == 0 and key_down: self.__key_select_down_pressed() if key_index == int(carb.input.KeyboardInput.UP) and key_mod == 0 and key_down: self.__key_select_up_pressed() if key_index == int(carb.input.KeyboardInput.ENTER) and key_mod == 0 and key_down: self.__key_enter_pressed() if key_index == int(carb.input.KeyboardInput.TAB) and key_mod == 0 and key_down: self.__key_tab_pressed() if key_index == int(carb.input.KeyboardInput.TAB) and key_mod == 2 and key_down: self.__key_ctrl_tab_pressed() if key_index == int(carb.input.KeyboardInput.BACKSPACE) and key_mod == 0 and key_down: self._tab_first_item_set = False @property def is_visible(self): return self._window.visible def destroy(self): """Delete the UI""" for attr, value in self._default_attr.items(): m_attr = getattr(self, attr) del m_attr setattr(self, attr, value)
10,983
Python
39.832714
116
0.575344
omniverse-code/kit/exts/omni.kit.widget.fast_search/docs/README.md
# Fast search Fast search is a widget that let you found an item from a list quickly. You can set an item as: - favorite - blocklist You can see items from a: - main list - list of latest items chosen - favorite items list - blocked items list ## Usage First Tab: auto complete Second Tab: create what was wrote Ctrl + tab = role on different lists ## API You just have to give a dictionary to Fast Search with: - key: name of the item - value: callable function to be executed when the item is chosen Fast Search can be used anywhere. ### Example ```python from omni.kit.widget.fast_search.python import FastSearchWidget _fast_search_widget = FastSearchWidget( { registered_node_type: lambda: print(registered_node_type) for registered_node_type in omnigraph.get_registered_nodes() } ) _fast_search_widget.create_widget() _fast_search_widget.set_window_visible(False) ```
906
Markdown
21.121951
71
0.735099
omniverse-code/kit/exts/omni.kit.widget.fast_search/docs/LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited. "Icon made by Pixel perfect from www.flaticon.com" "Icon made by prettycons from www.flaticon.com"
513
Markdown
45.727269
74
0.826511
omniverse-code/kit/exts/omni.kit.ui_test/omni/kit/ui_test/common.py
import omni.ext import asyncio import omni.kit.app import carb import sys import logging logger = logging.getLogger(__name__) def setup_logging(): printInfoLog = carb.settings.get_settings().get("/exts/omni.kit.ui_test/printInfoLog") if not printInfoLog: return # Always log info to stdout to debug tests. Since we tend to reload modules avoid adding more than once. logger = logging.getLogger("omni.kit.ui_test") if len(logger.handlers) == 0: stdout_hdlr = logging.StreamHandler(sys.stdout) stdout_hdlr.setLevel(logging.INFO) stdout_hdlr.setFormatter(logging.Formatter("[%(name)s] [%(levelname)s] %(message)s", "%H:%M:%S")) logger.addHandler(stdout_hdlr) class InitExt(omni.ext.IExt): def on_startup(self): setup_logging() async def wait_n_updates_internal(update_count=2): for _ in range(update_count): await omni.kit.app.get_app().next_update_async() async def wait_n_updates(update_count=2): """Wait N updates (frames).""" logger.debug(f"wait {update_count} updates") await wait_n_updates_internal(update_count) async def human_delay(human_delay_speed: int = 2): """Imitate human delay/slowness. In practice that function just waits couple of frames, but semantically it is different from other wait function. It is used when we want to wait because it would look like normal person interaction. E.g. instead of moving mouse and clicking with speed of light wait a bit. This is also a place where delay can be increased with a setting to debug UI tests. """ logger.debug("human delay") await wait_n_updates_internal(human_delay_speed) # Optional extra delay human_delay = carb.settings.get_settings().get("/exts/omni.kit.ui_test/humanDelay") if human_delay: await asyncio.sleep(human_delay)
1,858
Python
31.614035
118
0.698062
omniverse-code/kit/exts/omni.kit.ui_test/omni/kit/ui_test/vec2.py
from __future__ import annotations class Vec2: """Generic 2D Vector Constructed from other `Vec2`, tuple of 2 floats or just 2 floats. Common vector operation supported: .. code-block:: python v0 = Vec2(1, 2) v1 = Vec2((1, 2)) v2 = Vec2(v1) print(v0 + v1) # (2, 4) print(v2 * 3) # (3, 6) print(v2 / 4) # (0.25, 0.5) """ def __init__(self, *args): if len(args) == 0: self.x, self.y = 0, 0 elif len(args) == 1: v = args[0] if isinstance(v, Vec2): self.x, self.y = v.x, v.y else: self.x, self.y = v[0], v[1] else: self.x, self.y = args[0], args[1] def __str__(self) -> str: return f"({self.x}, {self.y})" def __repr__(self) -> str: return f"Vec2 ({self.x}, {self.y})" def __sub__(self, other) -> Vec2: return Vec2(self.x - other.x, self.y - other.y) def __add__(self, other) -> Vec2: return Vec2(self.x + other.x, self.y + other.y) def __mul__(self, scalar) -> Vec2: return Vec2(self.x * scalar, self.y * scalar) def __rmul__(self, scalar) -> Vec2: return self.__mul__(scalar) def __neg__(self) -> Vec2: return Vec2(-self.x, -self.y) def __truediv__(self, scalar) -> Vec2: return Vec2(self.x / scalar, self.y / scalar) def __mod__(self, scalar) -> Vec2: return Vec2(self.x % scalar, self.y % scalar) def to_tuple(self): return (self.x, self.y) def __eq__(self, other): if other == None: return False return self.x == other.x and self.y == other.y def __ne__(self, other): if other == None: return True return not (self.x == other.x and self.y == other.y) def __lt__(self, other): return self.x < other.x and self.y < other.y def __le__(self, other): return self.x <= other.x and self.y <= other.y def __gt__(self, other): return self.x > other.x and self.y > other.y def __ge__(self, other): return self.x >= other.x and self.y >= other.y
2,175
Python
25.216867
105
0.496552
omniverse-code/kit/exts/omni.kit.ui_test/omni/kit/ui_test/query.py
from __future__ import annotations import logging from typing import List import carb from omni import ui from omni.ui_query import OmniUIQuery from carb.input import KeyboardInput from .input import emulate_mouse_move_and_click, emulate_char_press, emulate_keyboard_press, emulate_keyboard, emulate_mouse_drag_and_drop from .common import wait_n_updates_internal from .vec2 import Vec2 logger = logging.getLogger(__name__) class WindowStub(): """stub window class for use with WidgetRef & """ def undock(_): pass def focus(_): pass window_stub = WindowStub() class WidgetRef: """Reference to `omni.ui.Widget` and a path it was found with.""" def __init__(self, widget: ui.Widget, path: str, window: ui.Window = None): self._widget = widget self._path = path self._window = window if window else ui.Workspace.get_window(path.split("//")[0]) @property def widget(self) -> ui.Widget: return self._widget @property def model(self): return self._widget.model @property def window(self) -> ui.Window: return self._window @property def path(self) -> str: """Path this widget was found with.""" return self._path @property def realpath(self) -> str: """Actual unique path to this widget from the window.""" return OmniUIQuery.get_widget_path(self.window, self.widget) def __str__(self) -> str: return f"WidgetRef({self.widget}, {self.path})" @property def position(self) -> Vec2: """Screen position of widget's top left corner.""" return Vec2(self._widget.screen_position_x, self._widget.screen_position_y) @property def size(self) -> Vec2: """Computed size of the widget.""" return Vec2(self._widget.computed_content_width, self._widget.computed_content_height) @property def center(self) -> Vec2: """Center of the widget.""" return self.position + (self.size / 2) def offset(self, *kwargs) -> Vec2: if len(kwargs) == 2: return self.position + Vec2(kwargs[0], kwargs[1]) if len(kwargs) == 1 and isinstance(kwargs[0], Vec2): return self.position + kwargs[0] return None async def _wait(self, update_count=2): await wait_n_updates_internal(update_count) async def focus(self): """Focus on a window this widget belongs to.""" self.window.focus() await self._wait() async def undock(self): """Undock a window this widget belongs to.""" self.window.undock() await self._wait() async def bring_to_front(self): """Bring window this widget belongs to on top. Currently this is implemented as undock() + focus().""" await self.undock() await self.focus() async def click(self, pos: Vec2 = None, right_click=False, double=False, human_delay_speed: int = 2): """Emulate mouse click on the widget.""" logger.info(f"click on {str(self)} (right_click: {right_click}, double: {double})") await self.bring_to_front() if not pos: pos = self.center await emulate_mouse_move_and_click( pos, right_click=right_click, double=double, human_delay_speed=human_delay_speed ) async def right_click(self, pos=None, human_delay_speed: int = 2): await self.click(pos=pos, right_click=True, human_delay_speed=human_delay_speed) async def double_click(self, pos=None, human_delay_speed: int = 2): await self.click(pos, double=True, human_delay_speed=human_delay_speed) async def input(self, text: str, end_key = KeyboardInput.ENTER, human_delay_speed: int = 2): """Emulate keyboard input of characters (text) into the widget. It is a helper function for the following sequence: 1. Double click on the widget 2. Input characters 3. Press enter """ if type(self.widget) == ui.FloatSlider or type(self.widget) == ui.FloatDrag or type(self.widget) == ui.IntSlider: from carb.input import MouseEventType, KeyboardEventType await emulate_keyboard(KeyboardEventType.KEY_PRESS, KeyboardInput.UNKNOWN, KeyboardInput.LEFT_CONTROL) await wait_n_updates_internal() await self.click(human_delay_speed=human_delay_speed) await emulate_keyboard(KeyboardEventType.KEY_RELEASE, KeyboardInput.UNKNOWN, KeyboardInput.LEFT_CONTROL) await wait_n_updates_internal() elif type(self.widget) == ui.IntDrag: await wait_n_updates_internal(20) await self.double_click(human_delay_speed=human_delay_speed) else: await self.double_click(human_delay_speed=human_delay_speed) await wait_n_updates_internal(human_delay_speed) await emulate_char_press(text) await emulate_keyboard_press(end_key) async def drag_and_drop(self, drop_target: Vec2, human_delay_speed: int = 4): """Drag/drop for widget.centre to `drop_target`""" await emulate_mouse_drag_and_drop(self.center, drop_target, human_delay_speed=human_delay_speed) def find(self, path: str) -> WidgetRef: """Find omni.ui Widget or Window by search query starting from this widget. .. code-block:: python stage_window = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True") label = stage_window.find("**/Label[*].text=='hello'") await label.right_click() Returns: Found Widget or Window wrapped into `WidgetRef` object. """ return _find(path, self) def find_all(self, path: str) -> List[WidgetRef]: """Find all omni.ui Widget or Window by search query starting from this widget. .. code-block:: python stage_window = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True") labels = stage_window.find_all("**/Label[*]") for label in labels: await label.right_click() Returns: List of found Widget or Window wrapped into `WidgetRef` objects. """ return _find_all(path, self) class WindowRef(WidgetRef): """Reference to `omni.ui.WindowHandle`""" def __init__(self, widget: ui.WindowHandle, path: str): super().__init__(widget, path, window=widget) @property def position(self) -> Vec2: return Vec2(self._widget.position_x, self._widget.position_y) @property def size(self) -> Vec2: return Vec2(self._widget.width, self._widget.height) def _find_all(path: str, root_widget: WidgetRef = None) -> List[WidgetRef]: # Special case for just window (can be supported in omni.ui.query better) if "/" not in path and not root_widget: window = ui.Workspace.get_window(path) if not window: carb.log_warn(f"Can't find window at path: {path}") return None return [WindowRef(window, path)] root_widgets = [root_widget.widget] if root_widget else [] widgets = OmniUIQuery.find_widgets(path, root_widgets=root_widgets) # Build list of Window and Widget references: res = [] for widget in widgets: fullpath = path window = None if root_widget: sep = "//" if isinstance(root_widget.widget, ui.WindowHandle) else "/" fullpath = f"{root_widget.path}{sep}{path}" window = root_widget.window if isinstance(widget, ui.WindowHandle): res.append(WindowRef(widget, fullpath, window=window)) else: res.append(WidgetRef(widget, fullpath, window=window)) return res def _find(path: str, root_widget: WidgetRef = None) -> WidgetRef: widgets = _find_all(path, root_widget) if not widgets or len(widgets) == 0: carb.log_warn(f"Can't find any widgets at path: {path}") return None MAX_OUTPUT = 10 if len(widgets) > 1: carb.log_warn(f"Found {len(widgets)} widgets at path: {path} instead of one.") for i in range(len(widgets)): carb.log_warn( "[{0}] {1} name: '{2}', realpath: '{3}'".format( i, widgets[i], widgets[i].widget.name, widgets[i].realpath ) ) if i > MAX_OUTPUT: carb.log_warn("...") break return None return widgets[0] class MenuRef(WidgetRef): """Reference to `omni.ui.Menu`""" def __init__(self, widget: ui.Menu, path: str): super().__init__(widget, path, window=window_stub) @staticmethod async def menu_click(path, human_delay_speed: int = 8, show: bool=True): menu_widget = get_menubar() for menu_name in path.split("/"): menu_widget = menu_widget.find_menu(menu_name) if isinstance(menu_widget.widget, ui.Menu): if menu_widget.widget.shown != show: await menu_widget.click() await wait_n_updates_internal(human_delay_speed) if menu_widget.widget.shown != show: carb.log_warn(f"ui.Menu item failed to {'show' if show else 'hide'}") else: await menu_widget.click() await wait_n_updates_internal(human_delay_speed) await wait_n_updates_internal(human_delay_speed) @property def center(self) -> Vec2: # Menu/MenuItem doesn't have width/height if isinstance(self._widget, ui.Menu): return self.position + Vec2(10, 5) * ui.Workspace.get_dpi_scale() return self.position + Vec2(25, 5) * ui.Workspace.get_dpi_scale() def find_menu(self, path: str, ignore_case: bool=False, contains_path: bool=False) -> MenuRef: for widget in self.find_all("**/"): if isinstance(widget.widget, ui.Menu) or isinstance(widget.widget, ui.MenuItem): menu_path = widget.widget.text.encode('ascii', 'ignore').decode().strip() if menu_path == path or \ (ignore_case and menu_path.lower() == path.lower()) or \ (contains_path and path in menu_path) or \ (ignore_case and contains_path and path.lower() in menu_path.lower() ): return MenuRef(widget=widget.widget, path=widget.path) return None def find(path: str) -> WidgetRef: """Find omni.ui Widget or Window by search query. `omni.ui_query` is used under the hood. Returned object can be used to get actual found item or/and do UI test operations on it. .. code-block:: python stage_window = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True") await stage_window.right_click() viewport = ui_test.find("Viewport") center = viewport.center print(center) Returns: Found Widget or Window wrapped into `WidgetRef` object. """ return _find(path) def find_all(path: str) -> List[WidgetRef]: """Find all omni.ui Widget or Window by search query. .. code-block:: python buttons = ui_test.find_all("Stage//Frame/**/Button[*]") for button in buttons: await button.click() Returns: List of found Widget or Window wrapped into `WidgetRef` objects. """ return _find_all(path) def get_menubar() -> MenuRef: from omni.kit.mainwindow import get_main_window window = get_main_window() return MenuRef(widget=window._ui_main_window.main_menu_bar, path="MainWindow//Frame/MenuBar") async def menu_click(path, human_delay_speed: int = 32, show: bool=True) -> None: await MenuRef.menu_click(path, human_delay_speed=human_delay_speed, show=show)
11,825
Python
34.091988
138
0.615222