file_path
stringlengths
22
162
content
stringlengths
19
501k
size
int64
19
501k
lang
stringclasses
1 value
avg_line_length
float64
6.33
100
max_line_length
int64
18
935
alphanum_fraction
float64
0.34
0.93
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnMatrixMultiplyDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.nodes.MatrixMultiply Computes the matrix product of the inputs. Inputs must be compatible. Also accepts tuples (treated as vectors) as inputs. Tuples in input A will be treated as row vectors. Tuples in input B will be treated as column vectors. Arrays of inputs will be computed element-wise with broadcasting if necessary. """ from typing import Any import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnMatrixMultiplyDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.nodes.MatrixMultiply Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.a inputs.b Outputs: outputs.output """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:a', 'colord[3],colord[4],colorf[3],colorf[4],colorh[3],colorh[4],double[2],double[2][],double[3],double[3][],double[4],double[4][],float[2],float[2][],float[3],float[3][],float[4],float[4][],frame[4],half[2],half[2][],half[3],half[3][],half[4],half[4][],matrixd[3],matrixd[3][],matrixd[4],matrixd[4][],normald[3],normalf[3],normalh[3],pointd[3],pointf[3],pointh[3],quatd[4],quatf[4],quath[4],texcoordd[2],texcoordd[3],texcoordf[2],texcoordf[3],texcoordh[2],texcoordh[3],transform[4],vectord[3],vectorf[3],vectorh[3]', 1, 'A', 'First matrix or row vector to multiply', {}, True, None, False, ''), ('inputs:b', 'colord[3],colord[4],colorf[3],colorf[4],colorh[3],colorh[4],double[2],double[2][],double[3],double[3][],double[4],double[4][],float[2],float[2][],float[3],float[3][],float[4],float[4][],frame[4],half[2],half[2][],half[3],half[3][],half[4],half[4][],matrixd[3],matrixd[3][],matrixd[4],matrixd[4][],normald[3],normalf[3],normalh[3],pointd[3],pointf[3],pointh[3],quatd[4],quatf[4],quath[4],texcoordd[2],texcoordd[3],texcoordf[2],texcoordf[3],texcoordh[2],texcoordh[3],transform[4],vectord[3],vectorf[3],vectorh[3]', 1, 'B', 'Second matrix or column vector to multiply', {}, True, None, False, ''), ('outputs:output', 'colord[3],colord[4],colorf[3],colorf[4],colorh[3],colorh[4],double,double[2],double[2][],double[3],double[3][],double[4],double[4][],double[],float,float[2],float[2][],float[3],float[3][],float[4],float[4][],float[],frame[4],half,half[2],half[2][],half[3],half[3][],half[4],half[4][],half[],matrixd[3],matrixd[3][],matrixd[4],matrixd[4][],normald[3],normalf[3],normalh[3],pointd[3],pointf[3],pointh[3],quatd[4],quatf[4],quath[4],texcoordd[2],texcoordd[3],texcoordf[2],texcoordf[3],texcoordh[2],texcoordh[3],transform[4],vectord[3],vectorf[3],vectorh[3]', 1, 'Product', 'Product of the two matrices', {}, True, None, False, ''), ]) class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [] self._batchedReadValues = [] @property def a(self) -> og.RuntimeAttribute: """Get the runtime wrapper class for the attribute inputs.a""" return og.RuntimeAttribute(self._attributes.a.get_attribute_data(), self._context, True) @a.setter def a(self, value_to_set: Any): """Assign another attribute's value to outputs.a""" if isinstance(value_to_set, og.RuntimeAttribute): self.a.value = value_to_set.value else: self.a.value = value_to_set @property def b(self) -> og.RuntimeAttribute: """Get the runtime wrapper class for the attribute inputs.b""" return og.RuntimeAttribute(self._attributes.b.get_attribute_data(), self._context, True) @b.setter def b(self, value_to_set: Any): """Assign another attribute's value to outputs.b""" if isinstance(value_to_set, og.RuntimeAttribute): self.b.value = value_to_set.value else: self.b.value = value_to_set def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def output(self) -> og.RuntimeAttribute: """Get the runtime wrapper class for the attribute outputs.output""" return og.RuntimeAttribute(self._attributes.output.get_attribute_data(), self._context, False) @output.setter def output(self, value_to_set: Any): """Assign another attribute's value to outputs.output""" if isinstance(value_to_set, og.RuntimeAttribute): self.output.value = value_to_set.value else: self.output.value = value_to_set def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnMatrixMultiplyDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnMatrixMultiplyDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnMatrixMultiplyDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
7,894
Python
59.267175
655
0.661895
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnFindPrimsDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.nodes.FindPrims Finds Prims on the stage which match the given criteria """ import numpy import usdrt import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnFindPrimsDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.nodes.FindPrims Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.ignoreSystemPrims inputs.namePrefix inputs.pathPattern inputs.recursive inputs.requiredAttributes inputs.requiredRelationship inputs.requiredRelationshipTarget inputs.requiredTarget inputs.rootPrim inputs.rootPrimPath inputs.type Outputs: outputs.primPaths outputs.prims State: state.ignoreSystemPrims state.inputType state.namePrefix state.pathPattern state.recursive state.requiredAttributes state.requiredRelationship state.requiredRelationshipTarget state.requiredTarget state.rootPrim state.rootPrimPath """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:ignoreSystemPrims', 'bool', 0, None, "Ignore system prims such as omni graph nodes that shouldn't be considered during the import.", {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:namePrefix', 'token', 0, 'Prim Name Prefix', 'Only prims with a name starting with the given prefix will be returned.', {}, True, "", False, ''), ('inputs:pathPattern', 'token', 0, 'Prim Path Pattern', "A list of wildcard patterns used to match the prim paths\n\nSupported syntax of wildcard pattern:\n '*' - match an arbitrary number of any characters\n '?' - match any single character\n '^' - (caret) is used to define a pattern that is to be excluded\n\nExample of wildcard patterns, input: ['/Cube0', '/Cube1', '/Box']\n '*' - match any\n '* ^/Box' - match any, but exclude '/Box'\n '* ^/Cube*' - match any, but exclude '/Cube0' and '/Cube1'", {}, True, "", False, ''), ('inputs:recursive', 'bool', 0, None, 'False means only consider children of the root prim, True means all prims in the hierarchy', {}, True, False, False, ''), ('inputs:requiredAttributes', 'string', 0, 'Attribute Names', 'A space-separated list of attribute names that are required to be present on matched prims', {}, True, "", False, ''), ('inputs:requiredRelationship', 'token', 0, 'Relationship Name', 'The name of a relationship which must have a target specified by requiredRelationshipTarget or requiredTarget', {}, True, "", False, ''), ('inputs:requiredRelationshipTarget', 'path', 0, 'Relationship Prim Path', 'The path that must be a target of the requiredRelationship', {}, True, "", True, 'Use requiredTarget instead'), ('inputs:requiredTarget', 'target', 0, 'Relationship Prim', 'The target of the requiredRelationship', {}, True, [], False, ''), ('inputs:rootPrim', 'target', 0, 'Root Prim', 'Only children of the given prim will be considered. If rootPrim is specified, rootPrimPath will be ignored.', {}, True, [], False, ''), ('inputs:rootPrimPath', 'token', 0, 'Root Prim Path', 'Only children of the given prim will be considered. Empty will search the whole stage.', {}, True, "", True, 'Use rootPrim input attribute instead'), ('inputs:type', 'token', 0, 'Prim Type Pattern', "A list of wildcard patterns used to match the prim types that are to be imported\n\nSupported syntax of wildcard pattern:\n '*' - match an arbitrary number of any characters\n '?' - match any single character\n '^' - (caret) is used to define a pattern that is to be excluded\n\nExample of wildcard patterns, input: ['Mesh', 'Cone', 'Cube']\n '*' - match any\n '* ^Mesh' - match any, but exclude 'Mesh'\n '* ^Cone ^Cube' - match any, but exclude 'Cone' and 'Cube'", {ogn.MetadataKeys.DEFAULT: '"*"'}, True, "*", False, ''), ('outputs:primPaths', 'token[]', 0, None, 'A list of Prim paths as tokens which match the given type', {}, True, None, False, ''), ('outputs:prims', 'target', 0, None, 'A list of Prim paths which match the given type', {}, True, [], False, ''), ('state:ignoreSystemPrims', 'bool', 0, None, 'last corresponding input seen', {}, True, None, False, ''), ('state:inputType', 'token', 0, None, 'last corresponding input seen', {}, True, None, False, ''), ('state:namePrefix', 'token', 0, None, 'last corresponding input seen', {}, True, None, False, ''), ('state:pathPattern', 'token', 0, None, 'last corresponding input seen', {}, True, None, False, ''), ('state:recursive', 'bool', 0, None, 'last corresponding input seen', {}, True, None, False, ''), ('state:requiredAttributes', 'string', 0, None, 'last corresponding input seen', {}, True, None, False, ''), ('state:requiredRelationship', 'token', 0, None, 'last corresponding input seen', {}, True, None, False, ''), ('state:requiredRelationshipTarget', 'string', 0, None, 'last corresponding input seen', {}, True, None, False, ''), ('state:requiredTarget', 'target', 0, None, 'last corresponding input seen', {}, True, [], False, ''), ('state:rootPrim', 'target', 0, None, 'last corresponding input seen', {}, True, [], False, ''), ('state:rootPrimPath', 'token', 0, None, 'last corresponding input seen', {}, True, None, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.requiredAttributes = og.AttributeRole.TEXT role_data.inputs.requiredRelationshipTarget = og.AttributeRole.PATH role_data.inputs.requiredTarget = og.AttributeRole.TARGET role_data.inputs.rootPrim = og.AttributeRole.TARGET role_data.outputs.prims = og.AttributeRole.TARGET role_data.state.requiredAttributes = og.AttributeRole.TEXT role_data.state.requiredRelationshipTarget = og.AttributeRole.TEXT role_data.state.requiredTarget = og.AttributeRole.TARGET role_data.state.rootPrim = og.AttributeRole.TARGET return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [] self._batchedReadValues = [] @property def ignoreSystemPrims(self): data_view = og.AttributeValueHelper(self._attributes.ignoreSystemPrims) return data_view.get() @ignoreSystemPrims.setter def ignoreSystemPrims(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.ignoreSystemPrims) data_view = og.AttributeValueHelper(self._attributes.ignoreSystemPrims) data_view.set(value) @property def namePrefix(self): data_view = og.AttributeValueHelper(self._attributes.namePrefix) return data_view.get() @namePrefix.setter def namePrefix(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.namePrefix) data_view = og.AttributeValueHelper(self._attributes.namePrefix) data_view.set(value) @property def pathPattern(self): data_view = og.AttributeValueHelper(self._attributes.pathPattern) return data_view.get() @pathPattern.setter def pathPattern(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.pathPattern) data_view = og.AttributeValueHelper(self._attributes.pathPattern) data_view.set(value) @property def recursive(self): data_view = og.AttributeValueHelper(self._attributes.recursive) return data_view.get() @recursive.setter def recursive(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.recursive) data_view = og.AttributeValueHelper(self._attributes.recursive) data_view.set(value) @property def requiredAttributes(self): data_view = og.AttributeValueHelper(self._attributes.requiredAttributes) return data_view.get() @requiredAttributes.setter def requiredAttributes(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.requiredAttributes) data_view = og.AttributeValueHelper(self._attributes.requiredAttributes) data_view.set(value) self.requiredAttributes_size = data_view.get_array_size() @property def requiredRelationship(self): data_view = og.AttributeValueHelper(self._attributes.requiredRelationship) return data_view.get() @requiredRelationship.setter def requiredRelationship(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.requiredRelationship) data_view = og.AttributeValueHelper(self._attributes.requiredRelationship) data_view.set(value) @property def requiredRelationshipTarget(self): data_view = og.AttributeValueHelper(self._attributes.requiredRelationshipTarget) return data_view.get() @requiredRelationshipTarget.setter def requiredRelationshipTarget(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.requiredRelationshipTarget) data_view = og.AttributeValueHelper(self._attributes.requiredRelationshipTarget) data_view.set(value) self.requiredRelationshipTarget_size = data_view.get_array_size() @property def requiredTarget(self): data_view = og.AttributeValueHelper(self._attributes.requiredTarget) return data_view.get() @requiredTarget.setter def requiredTarget(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.requiredTarget) data_view = og.AttributeValueHelper(self._attributes.requiredTarget) data_view.set(value) self.requiredTarget_size = data_view.get_array_size() @property def rootPrim(self): data_view = og.AttributeValueHelper(self._attributes.rootPrim) return data_view.get() @rootPrim.setter def rootPrim(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.rootPrim) data_view = og.AttributeValueHelper(self._attributes.rootPrim) data_view.set(value) self.rootPrim_size = data_view.get_array_size() @property def rootPrimPath(self): data_view = og.AttributeValueHelper(self._attributes.rootPrimPath) return data_view.get() @rootPrimPath.setter def rootPrimPath(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.rootPrimPath) data_view = og.AttributeValueHelper(self._attributes.rootPrimPath) data_view.set(value) @property def type(self): data_view = og.AttributeValueHelper(self._attributes.type) return data_view.get() @type.setter def type(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.type) data_view = og.AttributeValueHelper(self._attributes.type) data_view.set(value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self.primPaths_size = None self.prims_size = None self._batchedWriteValues = { } @property def primPaths(self): data_view = og.AttributeValueHelper(self._attributes.primPaths) return data_view.get(reserved_element_count=self.primPaths_size) @primPaths.setter def primPaths(self, value): data_view = og.AttributeValueHelper(self._attributes.primPaths) data_view.set(value) self.primPaths_size = data_view.get_array_size() @property def prims(self): data_view = og.AttributeValueHelper(self._attributes.prims) return data_view.get(reserved_element_count=self.prims_size) @prims.setter def prims(self, value): data_view = og.AttributeValueHelper(self._attributes.prims) data_view.set(value) self.prims_size = data_view.get_array_size() def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self.requiredAttributes_size = None self.requiredRelationshipTarget_size = None self.requiredTarget_size = None self.rootPrim_size = None @property def ignoreSystemPrims(self): data_view = og.AttributeValueHelper(self._attributes.ignoreSystemPrims) return data_view.get() @ignoreSystemPrims.setter def ignoreSystemPrims(self, value): data_view = og.AttributeValueHelper(self._attributes.ignoreSystemPrims) data_view.set(value) @property def inputType(self): data_view = og.AttributeValueHelper(self._attributes.inputType) return data_view.get() @inputType.setter def inputType(self, value): data_view = og.AttributeValueHelper(self._attributes.inputType) data_view.set(value) @property def namePrefix(self): data_view = og.AttributeValueHelper(self._attributes.namePrefix) return data_view.get() @namePrefix.setter def namePrefix(self, value): data_view = og.AttributeValueHelper(self._attributes.namePrefix) data_view.set(value) @property def pathPattern(self): data_view = og.AttributeValueHelper(self._attributes.pathPattern) return data_view.get() @pathPattern.setter def pathPattern(self, value): data_view = og.AttributeValueHelper(self._attributes.pathPattern) data_view.set(value) @property def recursive(self): data_view = og.AttributeValueHelper(self._attributes.recursive) return data_view.get() @recursive.setter def recursive(self, value): data_view = og.AttributeValueHelper(self._attributes.recursive) data_view.set(value) @property def requiredAttributes(self): data_view = og.AttributeValueHelper(self._attributes.requiredAttributes) self.requiredAttributes_size = data_view.get_array_size() return data_view.get() @requiredAttributes.setter def requiredAttributes(self, value): data_view = og.AttributeValueHelper(self._attributes.requiredAttributes) data_view.set(value) self.requiredAttributes_size = data_view.get_array_size() @property def requiredRelationship(self): data_view = og.AttributeValueHelper(self._attributes.requiredRelationship) return data_view.get() @requiredRelationship.setter def requiredRelationship(self, value): data_view = og.AttributeValueHelper(self._attributes.requiredRelationship) data_view.set(value) @property def requiredRelationshipTarget(self): data_view = og.AttributeValueHelper(self._attributes.requiredRelationshipTarget) self.requiredRelationshipTarget_size = data_view.get_array_size() return data_view.get() @requiredRelationshipTarget.setter def requiredRelationshipTarget(self, value): data_view = og.AttributeValueHelper(self._attributes.requiredRelationshipTarget) data_view.set(value) self.requiredRelationshipTarget_size = data_view.get_array_size() @property def requiredTarget(self): data_view = og.AttributeValueHelper(self._attributes.requiredTarget) self.requiredTarget_size = data_view.get_array_size() return data_view.get() @requiredTarget.setter def requiredTarget(self, value): data_view = og.AttributeValueHelper(self._attributes.requiredTarget) data_view.set(value) self.requiredTarget_size = data_view.get_array_size() @property def rootPrim(self): data_view = og.AttributeValueHelper(self._attributes.rootPrim) self.rootPrim_size = data_view.get_array_size() return data_view.get() @rootPrim.setter def rootPrim(self, value): data_view = og.AttributeValueHelper(self._attributes.rootPrim) data_view.set(value) self.rootPrim_size = data_view.get_array_size() @property def rootPrimPath(self): data_view = og.AttributeValueHelper(self._attributes.rootPrimPath) return data_view.get() @rootPrimPath.setter def rootPrimPath(self, value): data_view = og.AttributeValueHelper(self._attributes.rootPrimPath) data_view.set(value) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnFindPrimsDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnFindPrimsDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnFindPrimsDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
20,870
Python
47.424594
599
0.64322
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnWritePrimsV2Database.py
"""Support for simplified access to data on nodes of type omni.graph.nodes.WritePrimsV2 Write back bundle(s) containing multiple prims to the stage. """ import usdrt import carb import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnWritePrimsV2Database(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.nodes.WritePrimsV2 Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.attrNamesToExport inputs.execIn inputs.layerIdentifier inputs.pathPattern inputs.prims inputs.primsBundle inputs.scatterUnderTargets inputs.typePattern inputs.usdWriteBack Outputs: outputs.execOut State: state.attrNamesToExport state.layerIdentifier state.pathPattern state.primBundleDirtyId state.scatterUnderTargets state.typePattern state.usdWriteBack """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:attrNamesToExport', 'string', 0, 'Attribute Name Pattern', "A list of wildcard patterns used to match primitive attributes by name.\n\nSupported syntax of wildcard pattern:\n `*` - match an arbitrary number of any characters\n `?` - match any single character\n `^` - (caret) is used to define a pattern that is to be excluded\n\nExample of wildcard patterns, input: ['xFormOp:translate', 'xformOp:scale','radius']\n '*' - match any\n 'xformOp:*' - matches 'xFormOp:translate' and 'xformOp:scale'\n '* ^radius' - match any, but exclude 'radius'\n '* ^xformOp*' - match any, but exclude 'xFormOp:translate', 'xformOp:scale'", {ogn.MetadataKeys.DEFAULT: '"*"'}, True, "*", False, ''), ('inputs:execIn', 'execution', 0, None, 'The input execution (for action graphs only)', {}, True, None, False, ''), ('inputs:layerIdentifier', 'token', 0, 'Layer Identifier', 'Identifier of the layer to export to. If empty, it\'ll be exported to the current edit target at the time of usd wirte back.\'\nThis is only used when "Persist To USD" is enabled.', {ogn.MetadataKeys.DEFAULT: '""'}, True, "", False, ''), ('inputs:pathPattern', 'string', 0, 'Prim Path Pattern', "A list of wildcard patterns used to match primitives by path.\n\nSupported syntax of wildcard pattern:\n `*` - match an arbitrary number of any characters\n `?` - match any single character\n `^` - (caret) is used to define a pattern that is to be excluded\n\nExample of wildcard patterns, input: ['/Cube0', '/Cube1', '/Box']\n '*' - match any\n '* ^/Box' - match any, but exclude '/Box'\n '* ^/Cube*' - match any, but exclude '/Cube0' and '/Cube1'", {ogn.MetadataKeys.DEFAULT: '"*"'}, True, "*", False, ''), ('inputs:prims', 'target', 0, 'Prims', "Target(s) to which the prims in 'primsBundle' will be written to.\nThere is a 1:1 mapping between root prims paths in 'primsBundle' and the Target Prims targets\n*For advanced usage, if 'primsBundle' contains hierarchy, the unique common ancesor paths will have \n the 1:1 mapping to Target Prims targets, with the descendant paths remapped.\n*NOTE* See 'scatterUnderTargets' input for modified exporting behavior\n*WARNING* this can create new prims on the stage.\nIf attributes or prims are removed from 'primsBundle' in subsequent evaluation, they will be removed from targets as well.", {ogn.MetadataKeys.ALLOW_MULTI_INPUTS: '1'}, True, [], False, ''), ('inputs:primsBundle', 'bundle', 0, 'Prims Bundle', 'The bundle(s) of multiple prims to be written back.\nThe sourcePrimPath attribute is used to find the destination prim.', {ogn.MetadataKeys.ALLOW_MULTI_INPUTS: '1'}, True, None, False, ''), ('inputs:scatterUnderTargets', 'bool', 0, 'Scatter Under Targets', 'If true, the target prims become the parent prims that the bundled prims will be exported *UNDER*. \nIf multiple prims targets are provided, the primsBundle will be duplicated *UNDER* each \ntarget prims.', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:typePattern', 'string', 0, 'Prim Type Pattern', "A list of wildcard patterns used to match primitives by type.\n\nSupported syntax of wildcard pattern:\n `*` - match an arbitrary number of any characters\n `?` - match any single character\n `^` - (caret) is used to define a pattern that is to be excluded\n\nExample of wildcard patterns, input: ['Mesh', 'Cone', 'Cube']\n '*' - match any\n '* ^Mesh' - match any, but exclude 'Mesh'\n '* ^Cone ^Cube' - match any, but exclude 'Cone' and 'Cube'", {ogn.MetadataKeys.DEFAULT: '"*"'}, True, "*", False, ''), ('inputs:usdWriteBack', 'bool', 0, 'Persist To USD', 'Whether or not the value should be written back to USD, or kept a Fabric only value', {ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('outputs:execOut', 'execution', 0, None, 'The output execution port (for action graphs only)', {}, True, None, False, ''), ('state:attrNamesToExport', 'string', 0, None, 'State from previous evaluation', {ogn.MetadataKeys.DEFAULT: '"*"'}, True, "*", False, ''), ('state:layerIdentifier', 'token', 0, None, 'State from previous evaluation', {ogn.MetadataKeys.DEFAULT: '""'}, True, "", False, ''), ('state:pathPattern', 'string', 0, None, 'State from previous evaluation', {ogn.MetadataKeys.DEFAULT: '"*"'}, True, "*", False, ''), ('state:primBundleDirtyId', 'uint64', 0, None, 'State from previous evaluation', {}, True, None, False, ''), ('state:scatterUnderTargets', 'bool', 0, None, 'State from previous evaluation', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('state:typePattern', 'string', 0, None, 'State from previous evaluation', {ogn.MetadataKeys.DEFAULT: '"*"'}, True, "*", False, ''), ('state:usdWriteBack', 'bool', 0, None, 'State from previous evaluation', {ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.attrNamesToExport = og.AttributeRole.TEXT role_data.inputs.execIn = og.AttributeRole.EXECUTION role_data.inputs.pathPattern = og.AttributeRole.TEXT role_data.inputs.prims = og.AttributeRole.TARGET role_data.inputs.primsBundle = og.AttributeRole.BUNDLE role_data.inputs.typePattern = og.AttributeRole.TEXT role_data.outputs.execOut = og.AttributeRole.EXECUTION role_data.state.attrNamesToExport = og.AttributeRole.TEXT role_data.state.pathPattern = og.AttributeRole.TEXT role_data.state.typePattern = og.AttributeRole.TEXT return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self.__bundles = og.BundleContainer(context, node, attributes, [], read_only=True, gpu_ptr_kinds={}) self._batchedReadAttributes = [] self._batchedReadValues = [] @property def attrNamesToExport(self): data_view = og.AttributeValueHelper(self._attributes.attrNamesToExport) return data_view.get() @attrNamesToExport.setter def attrNamesToExport(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.attrNamesToExport) data_view = og.AttributeValueHelper(self._attributes.attrNamesToExport) data_view.set(value) self.attrNamesToExport_size = data_view.get_array_size() @property def execIn(self): data_view = og.AttributeValueHelper(self._attributes.execIn) return data_view.get() @execIn.setter def execIn(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.execIn) data_view = og.AttributeValueHelper(self._attributes.execIn) data_view.set(value) @property def layerIdentifier(self): data_view = og.AttributeValueHelper(self._attributes.layerIdentifier) return data_view.get() @layerIdentifier.setter def layerIdentifier(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.layerIdentifier) data_view = og.AttributeValueHelper(self._attributes.layerIdentifier) data_view.set(value) @property def pathPattern(self): data_view = og.AttributeValueHelper(self._attributes.pathPattern) return data_view.get() @pathPattern.setter def pathPattern(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.pathPattern) data_view = og.AttributeValueHelper(self._attributes.pathPattern) data_view.set(value) self.pathPattern_size = data_view.get_array_size() @property def prims(self): data_view = og.AttributeValueHelper(self._attributes.prims) return data_view.get() @prims.setter def prims(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.prims) data_view = og.AttributeValueHelper(self._attributes.prims) data_view.set(value) self.prims_size = data_view.get_array_size() @property def primsBundle(self) -> og.BundleContents: """Get the bundle wrapper class for the attribute inputs.primsBundle""" return self.__bundles.primsBundle @property def scatterUnderTargets(self): data_view = og.AttributeValueHelper(self._attributes.scatterUnderTargets) return data_view.get() @scatterUnderTargets.setter def scatterUnderTargets(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.scatterUnderTargets) data_view = og.AttributeValueHelper(self._attributes.scatterUnderTargets) data_view.set(value) @property def typePattern(self): data_view = og.AttributeValueHelper(self._attributes.typePattern) return data_view.get() @typePattern.setter def typePattern(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.typePattern) data_view = og.AttributeValueHelper(self._attributes.typePattern) data_view.set(value) self.typePattern_size = data_view.get_array_size() @property def usdWriteBack(self): data_view = og.AttributeValueHelper(self._attributes.usdWriteBack) return data_view.get() @usdWriteBack.setter def usdWriteBack(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.usdWriteBack) data_view = og.AttributeValueHelper(self._attributes.usdWriteBack) data_view.set(value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def execOut(self): data_view = og.AttributeValueHelper(self._attributes.execOut) return data_view.get() @execOut.setter def execOut(self, value): data_view = og.AttributeValueHelper(self._attributes.execOut) data_view.set(value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self.attrNamesToExport_size = 1 self.pathPattern_size = 1 self.typePattern_size = 1 @property def attrNamesToExport(self): data_view = og.AttributeValueHelper(self._attributes.attrNamesToExport) self.attrNamesToExport_size = data_view.get_array_size() return data_view.get() @attrNamesToExport.setter def attrNamesToExport(self, value): data_view = og.AttributeValueHelper(self._attributes.attrNamesToExport) data_view.set(value) self.attrNamesToExport_size = data_view.get_array_size() @property def layerIdentifier(self): data_view = og.AttributeValueHelper(self._attributes.layerIdentifier) return data_view.get() @layerIdentifier.setter def layerIdentifier(self, value): data_view = og.AttributeValueHelper(self._attributes.layerIdentifier) data_view.set(value) @property def pathPattern(self): data_view = og.AttributeValueHelper(self._attributes.pathPattern) self.pathPattern_size = data_view.get_array_size() return data_view.get() @pathPattern.setter def pathPattern(self, value): data_view = og.AttributeValueHelper(self._attributes.pathPattern) data_view.set(value) self.pathPattern_size = data_view.get_array_size() @property def primBundleDirtyId(self): data_view = og.AttributeValueHelper(self._attributes.primBundleDirtyId) return data_view.get() @primBundleDirtyId.setter def primBundleDirtyId(self, value): data_view = og.AttributeValueHelper(self._attributes.primBundleDirtyId) data_view.set(value) @property def scatterUnderTargets(self): data_view = og.AttributeValueHelper(self._attributes.scatterUnderTargets) return data_view.get() @scatterUnderTargets.setter def scatterUnderTargets(self, value): data_view = og.AttributeValueHelper(self._attributes.scatterUnderTargets) data_view.set(value) @property def typePattern(self): data_view = og.AttributeValueHelper(self._attributes.typePattern) self.typePattern_size = data_view.get_array_size() return data_view.get() @typePattern.setter def typePattern(self, value): data_view = og.AttributeValueHelper(self._attributes.typePattern) data_view.set(value) self.typePattern_size = data_view.get_array_size() @property def usdWriteBack(self): data_view = og.AttributeValueHelper(self._attributes.usdWriteBack) return data_view.get() @usdWriteBack.setter def usdWriteBack(self, value): data_view = og.AttributeValueHelper(self._attributes.usdWriteBack) data_view.set(value) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnWritePrimsV2Database.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnWritePrimsV2Database.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnWritePrimsV2Database.ValuesForState(node, self.attributes.state, dynamic_attributes)
17,916
Python
53.129909
720
0.653271
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnMakeArrayDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.nodes.MakeArray Makes an output array attribute from input values, in the order of the inputs. If 'arraySize' is less than 5, the top 'arraySize' elements will be taken. If 'arraySize' is greater than 5 element e will be repeated to fill the remaining space """ from typing import Any import sys import traceback import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnMakeArrayDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.nodes.MakeArray Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.a inputs.arraySize inputs.b inputs.c inputs.d inputs.e Outputs: outputs.array """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:a', 'colord[3],colord[4],colorf[3],colorf[4],colorh[3],colorh[4],double,double[2],double[3],double[4],float,float[2],float[3],float[4],frame[4],half,half[2],half[3],half[4],int,int64,int[2],int[3],int[4],matrixd[3],matrixd[4],normald[3],normalf[3],normalh[3],pointd[3],pointf[3],pointh[3],quatd[4],quatf[4],quath[4],texcoordd[2],texcoordd[3],texcoordf[2],texcoordf[3],texcoordh[2],texcoordh[3],timecode,token,transform[4],uchar,uint,uint64,vectord[3],vectorf[3],vectorh[3]', 1, None, 'Element 1', {}, True, None, False, ''), ('inputs:arraySize', 'int', 0, None, 'The size of the array to create', {}, True, 0, False, ''), ('inputs:b', 'colord[3],colord[4],colorf[3],colorf[4],colorh[3],colorh[4],double,double[2],double[3],double[4],float,float[2],float[3],float[4],frame[4],half,half[2],half[3],half[4],int,int64,int[2],int[3],int[4],matrixd[3],matrixd[4],normald[3],normalf[3],normalh[3],pointd[3],pointf[3],pointh[3],quatd[4],quatf[4],quath[4],texcoordd[2],texcoordd[3],texcoordf[2],texcoordf[3],texcoordh[2],texcoordh[3],timecode,token,transform[4],uchar,uint,uint64,vectord[3],vectorf[3],vectorh[3]', 1, None, 'Element 2', {}, True, None, False, ''), ('inputs:c', 'colord[3],colord[4],colorf[3],colorf[4],colorh[3],colorh[4],double,double[2],double[3],double[4],float,float[2],float[3],float[4],frame[4],half,half[2],half[3],half[4],int,int64,int[2],int[3],int[4],matrixd[3],matrixd[4],normald[3],normalf[3],normalh[3],pointd[3],pointf[3],pointh[3],quatd[4],quatf[4],quath[4],texcoordd[2],texcoordd[3],texcoordf[2],texcoordf[3],texcoordh[2],texcoordh[3],timecode,token,transform[4],uchar,uint,uint64,vectord[3],vectorf[3],vectorh[3]', 1, None, 'Element 3', {}, True, None, False, ''), ('inputs:d', 'colord[3],colord[4],colorf[3],colorf[4],colorh[3],colorh[4],double,double[2],double[3],double[4],float,float[2],float[3],float[4],frame[4],half,half[2],half[3],half[4],int,int64,int[2],int[3],int[4],matrixd[3],matrixd[4],normald[3],normalf[3],normalh[3],pointd[3],pointf[3],pointh[3],quatd[4],quatf[4],quath[4],texcoordd[2],texcoordd[3],texcoordf[2],texcoordf[3],texcoordh[2],texcoordh[3],timecode,token,transform[4],uchar,uint,uint64,vectord[3],vectorf[3],vectorh[3]', 1, None, 'Element 4', {}, True, None, False, ''), ('inputs:e', 'colord[3],colord[4],colorf[3],colorf[4],colorh[3],colorh[4],double,double[2],double[3],double[4],float,float[2],float[3],float[4],frame[4],half,half[2],half[3],half[4],int,int64,int[2],int[3],int[4],matrixd[3],matrixd[4],normald[3],normalf[3],normalh[3],pointd[3],pointf[3],pointh[3],quatd[4],quatf[4],quath[4],texcoordd[2],texcoordd[3],texcoordf[2],texcoordf[3],texcoordh[2],texcoordh[3],timecode,token,transform[4],uchar,uint,uint64,vectord[3],vectorf[3],vectorh[3]', 1, None, 'Element 5', {}, True, None, False, ''), ('outputs:array', 'colord[3][],colord[4][],colorf[3][],colorf[4][],colorh[3][],colorh[4][],double[2][],double[3][],double[4][],double[],float[2][],float[3][],float[4][],float[],frame[4][],half[2][],half[3][],half[4][],half[],int64[],int[2][],int[3][],int[4][],int[],matrixd[3][],matrixd[4][],normald[3][],normalf[3][],normalh[3][],pointd[3][],pointf[3][],pointh[3][],quatd[4][],quatf[4][],quath[4][],texcoordd[2][],texcoordd[3][],texcoordf[2][],texcoordf[3][],texcoordh[2][],texcoordh[3][],timecode[],token[],transform[4][],uchar[],uint64[],uint[],vectord[3][],vectorf[3][],vectorh[3][]', 1, None, 'The array of copied values of inputs in the given order', {}, True, None, False, ''), ]) class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"arraySize", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.arraySize] self._batchedReadValues = [0] @property def a(self) -> og.RuntimeAttribute: """Get the runtime wrapper class for the attribute inputs.a""" return og.RuntimeAttribute(self._attributes.a.get_attribute_data(), self._context, True) @a.setter def a(self, value_to_set: Any): """Assign another attribute's value to outputs.a""" if isinstance(value_to_set, og.RuntimeAttribute): self.a.value = value_to_set.value else: self.a.value = value_to_set @property def b(self) -> og.RuntimeAttribute: """Get the runtime wrapper class for the attribute inputs.b""" return og.RuntimeAttribute(self._attributes.b.get_attribute_data(), self._context, True) @b.setter def b(self, value_to_set: Any): """Assign another attribute's value to outputs.b""" if isinstance(value_to_set, og.RuntimeAttribute): self.b.value = value_to_set.value else: self.b.value = value_to_set @property def c(self) -> og.RuntimeAttribute: """Get the runtime wrapper class for the attribute inputs.c""" return og.RuntimeAttribute(self._attributes.c.get_attribute_data(), self._context, True) @c.setter def c(self, value_to_set: Any): """Assign another attribute's value to outputs.c""" if isinstance(value_to_set, og.RuntimeAttribute): self.c.value = value_to_set.value else: self.c.value = value_to_set @property def d(self) -> og.RuntimeAttribute: """Get the runtime wrapper class for the attribute inputs.d""" return og.RuntimeAttribute(self._attributes.d.get_attribute_data(), self._context, True) @d.setter def d(self, value_to_set: Any): """Assign another attribute's value to outputs.d""" if isinstance(value_to_set, og.RuntimeAttribute): self.d.value = value_to_set.value else: self.d.value = value_to_set @property def e(self) -> og.RuntimeAttribute: """Get the runtime wrapper class for the attribute inputs.e""" return og.RuntimeAttribute(self._attributes.e.get_attribute_data(), self._context, True) @e.setter def e(self, value_to_set: Any): """Assign another attribute's value to outputs.e""" if isinstance(value_to_set, og.RuntimeAttribute): self.e.value = value_to_set.value else: self.e.value = value_to_set @property def arraySize(self): return self._batchedReadValues[0] @arraySize.setter def arraySize(self, value): self._batchedReadValues[0] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def array(self) -> og.RuntimeAttribute: """Get the runtime wrapper class for the attribute outputs.array""" return og.RuntimeAttribute(self._attributes.array.get_attribute_data(), self._context, False) @array.setter def array(self, value_to_set: Any): """Assign another attribute's value to outputs.array""" if isinstance(value_to_set, og.RuntimeAttribute): self.array.value = value_to_set.value else: self.array.value = value_to_set def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnMakeArrayDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnMakeArrayDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnMakeArrayDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes) class abi: """Class defining the ABI interface for the node type""" @staticmethod def get_node_type(): get_node_type_function = getattr(OgnMakeArrayDatabase.NODE_TYPE_CLASS, 'get_node_type', None) if callable(get_node_type_function): return get_node_type_function() return 'omni.graph.nodes.MakeArray' @staticmethod def compute(context, node): def database_valid(): if db.inputs.a.type.base_type == og.BaseDataType.UNKNOWN: db.log_warning('Required extended attribute inputs:a is not resolved, compute skipped') return False if db.inputs.b.type.base_type == og.BaseDataType.UNKNOWN: db.log_warning('Required extended attribute inputs:b is not resolved, compute skipped') return False if db.inputs.c.type.base_type == og.BaseDataType.UNKNOWN: db.log_warning('Required extended attribute inputs:c is not resolved, compute skipped') return False if db.inputs.d.type.base_type == og.BaseDataType.UNKNOWN: db.log_warning('Required extended attribute inputs:d is not resolved, compute skipped') return False if db.inputs.e.type.base_type == og.BaseDataType.UNKNOWN: db.log_warning('Required extended attribute inputs:e is not resolved, compute skipped') return False if db.outputs.array.type.base_type == og.BaseDataType.UNKNOWN: db.log_warning('Required extended attribute outputs:array is not resolved, compute skipped') return False return True try: per_node_data = OgnMakeArrayDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get('_db') if db is None: db = OgnMakeArrayDatabase(node) per_node_data['_db'] = db if not database_valid(): per_node_data['_db'] = None return False except: db = OgnMakeArrayDatabase(node) try: compute_function = getattr(OgnMakeArrayDatabase.NODE_TYPE_CLASS, 'compute', None) if callable(compute_function) and compute_function.__code__.co_argcount > 1: return compute_function(context, node) db.inputs._prefetch() db.inputs._setting_locked = True with og.in_compute(): return OgnMakeArrayDatabase.NODE_TYPE_CLASS.compute(db) except Exception as error: stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next)) db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False) finally: db.inputs._setting_locked = False db.outputs._commit() return False @staticmethod def initialize(context, node): OgnMakeArrayDatabase._initialize_per_node_data(node) initialize_function = getattr(OgnMakeArrayDatabase.NODE_TYPE_CLASS, 'initialize', None) if callable(initialize_function): initialize_function(context, node) per_node_data = OgnMakeArrayDatabase.PER_NODE_DATA[node.node_id()] def on_connection_or_disconnection(*args): per_node_data['_db'] = None node.register_on_connected_callback(on_connection_or_disconnection) node.register_on_disconnected_callback(on_connection_or_disconnection) @staticmethod def release(node): release_function = getattr(OgnMakeArrayDatabase.NODE_TYPE_CLASS, 'release', None) if callable(release_function): release_function(node) OgnMakeArrayDatabase._release_per_node_data(node) @staticmethod def release_instance(node, target): OgnMakeArrayDatabase._release_per_node_instance_data(node, target) @staticmethod def update_node_version(context, node, old_version, new_version): update_node_version_function = getattr(OgnMakeArrayDatabase.NODE_TYPE_CLASS, 'update_node_version', None) if callable(update_node_version_function): return update_node_version_function(context, node, old_version, new_version) return False @staticmethod def initialize_type(node_type): initialize_type_function = getattr(OgnMakeArrayDatabase.NODE_TYPE_CLASS, 'initialize_type', None) needs_initializing = True if callable(initialize_type_function): needs_initializing = initialize_type_function(node_type) if needs_initializing: node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.nodes") node_type.set_metadata(ogn.MetadataKeys.HIDDEN, "true") node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Make Array") node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "math:array") node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Makes an output array attribute from input values, in the order of the inputs. If 'arraySize' is less than 5, the top 'arraySize' elements will be taken. If 'arraySize' is greater than 5 element e will be repeated to fill the remaining space") node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python") OgnMakeArrayDatabase.INTERFACE.add_to_node_type(node_type) @staticmethod def on_connection_type_resolve(node): on_connection_type_resolve_function = getattr(OgnMakeArrayDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None) if callable(on_connection_type_resolve_function): on_connection_type_resolve_function(node) NODE_TYPE_CLASS = None @staticmethod def register(node_type_class): OgnMakeArrayDatabase.NODE_TYPE_CLASS = node_type_class og.register_node_type(OgnMakeArrayDatabase.abi, 1) @staticmethod def deregister(): og.deregister_node_type("omni.graph.nodes.MakeArray")
18,278
Python
55.416666
692
0.629226
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnMakeTransformDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.nodes.MakeTransform Make a transformation matrix that performs a translation, rotation (in euler angles), and scale in that order """ import numpy import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnMakeTransformDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.nodes.MakeTransform Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.rotationXYZ inputs.scale inputs.translation Outputs: outputs.transform """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:rotationXYZ', 'vector3d', 0, None, 'The desired orientation in euler angles (XYZ)', {ogn.MetadataKeys.DEFAULT: '[0, 0, 0]'}, True, [0, 0, 0], False, ''), ('inputs:scale', 'vector3d', 0, None, 'The desired scaling factor about the X, Y, and Z axis respectively', {ogn.MetadataKeys.DEFAULT: '[1, 1, 1]'}, True, [1, 1, 1], False, ''), ('inputs:translation', 'vector3d', 0, None, 'the desired translation as a vector', {ogn.MetadataKeys.DEFAULT: '[0, 0, 0]'}, True, [0, 0, 0], False, ''), ('outputs:transform', 'matrix4d', 0, None, 'the resulting transformation matrix', {}, True, None, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.rotationXYZ = og.AttributeRole.VECTOR role_data.inputs.scale = og.AttributeRole.VECTOR role_data.inputs.translation = og.AttributeRole.VECTOR role_data.outputs.transform = og.AttributeRole.MATRIX return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [] self._batchedReadValues = [] @property def rotationXYZ(self): data_view = og.AttributeValueHelper(self._attributes.rotationXYZ) return data_view.get() @rotationXYZ.setter def rotationXYZ(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.rotationXYZ) data_view = og.AttributeValueHelper(self._attributes.rotationXYZ) data_view.set(value) @property def scale(self): data_view = og.AttributeValueHelper(self._attributes.scale) return data_view.get() @scale.setter def scale(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.scale) data_view = og.AttributeValueHelper(self._attributes.scale) data_view.set(value) @property def translation(self): data_view = og.AttributeValueHelper(self._attributes.translation) return data_view.get() @translation.setter def translation(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.translation) data_view = og.AttributeValueHelper(self._attributes.translation) data_view.set(value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def transform(self): data_view = og.AttributeValueHelper(self._attributes.transform) return data_view.get() @transform.setter def transform(self, value): data_view = og.AttributeValueHelper(self._attributes.transform) data_view.set(value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnMakeTransformDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnMakeTransformDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnMakeTransformDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
6,921
Python
45.77027
185
0.661321
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnReadPrimBundleDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.nodes.ReadPrimBundle DEPRECATED - use ReadPrims! """ import carb import usdrt import carb import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnReadPrimBundleDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.nodes.ReadPrimBundle Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.attrNamesToImport inputs.computeBoundingBox inputs.prim inputs.primPath inputs.usdTimecode inputs.usePath Outputs: outputs.primBundle State: state.attrNamesToImport state.computeBoundingBox state.primPath state.usdTimecode state.usePath """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:attrNamesToImport', 'token', 0, 'Attributes To Import', "A list of wildcard patterns used to match the attribute names that are to be imported\n\nSupported syntax of wildcard pattern:\n '*' - match an arbitrary number of any characters\n '?' - match any single character\n '^' - (caret) is used to define a pattern that is to be excluded\n\nExample of wildcard patterns, input: ['points', 'faceVertexCount', 'faceVertexIndices', 'size']\n '*' - match any\n '* ^points' - match any, but exclude 'points'\n '* ^face*' - match any, but exclude 'faceVertexCount' and 'faceVertexIndices'", {ogn.MetadataKeys.DEFAULT: '"*"'}, True, "*", False, ''), ('inputs:computeBoundingBox', 'bool', 0, 'Compute Bounding Box', "For each primitive compute local bounding box and store them as 'bboxMinCorner', 'bboxMaxCorner' and 'bboxTransform' attributes.", {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:prim', 'target', 0, None, "The prims to be read from when 'usePath' is false", {}, False, [], False, ''), ('inputs:primPath', 'token', 0, 'Prim Path', "The paths of the prims to be read from when 'usePath' is true", {ogn.MetadataKeys.DEFAULT: '""'}, False, "", True, 'Use prim input with a GetPrimsAtPath node instead'), ('inputs:usdTimecode', 'timecode', 0, 'Time', 'The time at which to evaluate the transform of the USD prim. A value of "NaN" indicates that the default USD time stamp should be used', {ogn.MetadataKeys.DEFAULT: '"NaN"'}, True, float("NaN"), False, ''), ('inputs:usePath', 'bool', 0, 'Use Path', "When true, the 'primPath' attribute is used as the path to the prim being read, otherwise it will read the connection at the 'prim' attribute", {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, True, 'Use prim input with a GetPrimsAtPath node instead'), ('outputs:primBundle', 'bundle', 0, None, 'A bundle containing multiple prims as children.\nEach child contains data attributes and two additional token attributes named sourcePrimPath and sourcePrimType\nwhich contain the path and the type of the Prim being read', {}, True, None, False, ''), ('state:attrNamesToImport', 'uint64', 0, None, 'State from previous evaluation', {}, True, None, False, ''), ('state:computeBoundingBox', 'bool', 0, None, 'State from previous evaluation', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('state:primPath', 'uint64', 0, None, 'State from previous evaluation', {}, True, None, False, ''), ('state:usdTimecode', 'timecode', 0, None, 'State from previous evaluation', {ogn.MetadataKeys.DEFAULT: '"NaN"'}, True, float("NaN"), False, ''), ('state:usePath', 'bool', 0, None, 'State from previous evaluation', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.prim = og.AttributeRole.TARGET role_data.inputs.usdTimecode = og.AttributeRole.TIMECODE role_data.outputs.primBundle = og.AttributeRole.BUNDLE role_data.state.usdTimecode = og.AttributeRole.TIMECODE return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [] self._batchedReadValues = [] @property def attrNamesToImport(self): data_view = og.AttributeValueHelper(self._attributes.attrNamesToImport) return data_view.get() @attrNamesToImport.setter def attrNamesToImport(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.attrNamesToImport) data_view = og.AttributeValueHelper(self._attributes.attrNamesToImport) data_view.set(value) @property def computeBoundingBox(self): data_view = og.AttributeValueHelper(self._attributes.computeBoundingBox) return data_view.get() @computeBoundingBox.setter def computeBoundingBox(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.computeBoundingBox) data_view = og.AttributeValueHelper(self._attributes.computeBoundingBox) data_view.set(value) @property def prim(self): data_view = og.AttributeValueHelper(self._attributes.prim) return data_view.get() @prim.setter def prim(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.prim) data_view = og.AttributeValueHelper(self._attributes.prim) data_view.set(value) self.prim_size = data_view.get_array_size() @property def primPath(self): data_view = og.AttributeValueHelper(self._attributes.primPath) return data_view.get() @primPath.setter def primPath(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.primPath) data_view = og.AttributeValueHelper(self._attributes.primPath) data_view.set(value) @property def usdTimecode(self): data_view = og.AttributeValueHelper(self._attributes.usdTimecode) return data_view.get() @usdTimecode.setter def usdTimecode(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.usdTimecode) data_view = og.AttributeValueHelper(self._attributes.usdTimecode) data_view.set(value) @property def usePath(self): data_view = og.AttributeValueHelper(self._attributes.usePath) return data_view.get() @usePath.setter def usePath(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.usePath) data_view = og.AttributeValueHelper(self._attributes.usePath) data_view.set(value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self.__bundles = og.BundleContainer(context, node, attributes, [], read_only=False, gpu_ptr_kinds={}) self._batchedWriteValues = { } @property def primBundle(self) -> og.BundleContents: """Get the bundle wrapper class for the attribute outputs.primBundle""" return self.__bundles.primBundle @primBundle.setter def primBundle(self, bundle: og.BundleContents): """Overwrite the bundle attribute outputs.primBundle with a new bundle""" if not isinstance(bundle, og.BundleContents): carb.log_error("Only bundle attributes can be assigned to another bundle attribute") self.__bundles.primBundle.bundle = bundle def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) @property def attrNamesToImport(self): data_view = og.AttributeValueHelper(self._attributes.attrNamesToImport) return data_view.get() @attrNamesToImport.setter def attrNamesToImport(self, value): data_view = og.AttributeValueHelper(self._attributes.attrNamesToImport) data_view.set(value) @property def computeBoundingBox(self): data_view = og.AttributeValueHelper(self._attributes.computeBoundingBox) return data_view.get() @computeBoundingBox.setter def computeBoundingBox(self, value): data_view = og.AttributeValueHelper(self._attributes.computeBoundingBox) data_view.set(value) @property def primPath(self): data_view = og.AttributeValueHelper(self._attributes.primPath) return data_view.get() @primPath.setter def primPath(self, value): data_view = og.AttributeValueHelper(self._attributes.primPath) data_view.set(value) @property def usdTimecode(self): data_view = og.AttributeValueHelper(self._attributes.usdTimecode) return data_view.get() @usdTimecode.setter def usdTimecode(self, value): data_view = og.AttributeValueHelper(self._attributes.usdTimecode) data_view.set(value) @property def usePath(self): data_view = og.AttributeValueHelper(self._attributes.usePath) return data_view.get() @usePath.setter def usePath(self, value): data_view = og.AttributeValueHelper(self._attributes.usePath) data_view.set(value) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnReadPrimBundleDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnReadPrimBundleDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnReadPrimBundleDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
12,861
Python
49.046692
677
0.655003
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnGatherByPathDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.nodes.GatherByPath Node to vectorize data by paths passed in via input. PROTOTYPE DO NOT USE. Requires GatherPrototype """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import numpy class OgnGatherByPathDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.nodes.GatherByPath Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.allAttributes inputs.attributes inputs.checkResyncAttributes inputs.forceExportToHistory inputs.hydraFastPath inputs.primPaths inputs.shouldWriteBack Outputs: outputs.gatherId outputs.gatheredPaths Predefined Tokens: tokens.Disabled tokens.World tokens.Local """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:allAttributes', 'bool', 0, None, "When true, all USD attributes will be gathered. Otherwise those specified by 'attributes' will be gathered.", {ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('inputs:attributes', 'string', 0, None, 'A space-separated list of attribute names to be gathered when allAttributes is false', {}, True, '', False, ''), ('inputs:checkResyncAttributes', 'bool', 0, None, 'When true, the data vectorization will be updated when new attributes to the Prims are added.', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:forceExportToHistory', 'bool', 0, None, 'When true, all USD gathered paths will be tagged for being exported to the history.', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:hydraFastPath', 'token', 0, None, "When not 'Disabled', will extract USD Geometry transforms into Hydra fast-path attributes.\n'World' will add _worldPosition, _worldOrientation. 'Local' will add _localMatrix.", {ogn.MetadataKeys.ALLOWED_TOKENS: 'Disabled,World,Local', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '["Disabled", "World", "Local"]', ogn.MetadataKeys.DEFAULT: '"Disabled"'}, True, 'Disabled', False, ''), ('inputs:primPaths', 'token[]', 0, None, 'A list of Prim paths whose data should be vectorized', {}, True, [], False, ''), ('inputs:shouldWriteBack', 'bool', 0, 'Should Write Back To USD', 'Write the data back into USD if true.', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('outputs:gatherId', 'uint64', 0, None, 'The GatherId corresponding to this Gather, kInvalidGatherId if the Gather failed', {}, True, None, False, ''), ('outputs:gatheredPaths', 'token[]', 0, None, 'The list of gathered prim paths in gathered-order', {}, True, None, False, ''), ]) class tokens: Disabled = "Disabled" World = "World" Local = "Local" class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"allAttributes", "attributes", "checkResyncAttributes", "forceExportToHistory", "hydraFastPath", "shouldWriteBack", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.allAttributes, self._attributes.attributes, self._attributes.checkResyncAttributes, self._attributes.forceExportToHistory, self._attributes.hydraFastPath, self._attributes.shouldWriteBack] self._batchedReadValues = [True, "", False, False, "Disabled", False] @property def primPaths(self): data_view = og.AttributeValueHelper(self._attributes.primPaths) return data_view.get() @primPaths.setter def primPaths(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.primPaths) data_view = og.AttributeValueHelper(self._attributes.primPaths) data_view.set(value) self.primPaths_size = data_view.get_array_size() @property def allAttributes(self): return self._batchedReadValues[0] @allAttributes.setter def allAttributes(self, value): self._batchedReadValues[0] = value @property def attributes(self): return self._batchedReadValues[1] @attributes.setter def attributes(self, value): self._batchedReadValues[1] = value @property def checkResyncAttributes(self): return self._batchedReadValues[2] @checkResyncAttributes.setter def checkResyncAttributes(self, value): self._batchedReadValues[2] = value @property def forceExportToHistory(self): return self._batchedReadValues[3] @forceExportToHistory.setter def forceExportToHistory(self, value): self._batchedReadValues[3] = value @property def hydraFastPath(self): return self._batchedReadValues[4] @hydraFastPath.setter def hydraFastPath(self, value): self._batchedReadValues[4] = value @property def shouldWriteBack(self): return self._batchedReadValues[5] @shouldWriteBack.setter def shouldWriteBack(self, value): self._batchedReadValues[5] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"gatherId", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self.gatheredPaths_size = None self._batchedWriteValues = { } @property def gatheredPaths(self): data_view = og.AttributeValueHelper(self._attributes.gatheredPaths) return data_view.get(reserved_element_count=self.gatheredPaths_size) @gatheredPaths.setter def gatheredPaths(self, value): data_view = og.AttributeValueHelper(self._attributes.gatheredPaths) data_view.set(value) self.gatheredPaths_size = data_view.get_array_size() @property def gatherId(self): value = self._batchedWriteValues.get(self._attributes.gatherId) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.gatherId) return data_view.get() @gatherId.setter def gatherId(self, value): self._batchedWriteValues[self._attributes.gatherId] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnGatherByPathDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnGatherByPathDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnGatherByPathDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
10,368
Python
49.091787
428
0.650656
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnReadPrimAttributeDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.nodes.ReadPrimAttribute Given a path to a prim on the current USD stage and the name of an attribute on that prim, gets the value of that attribute, at the global timeline value. """ from typing import Any import carb import usdrt import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnReadPrimAttributeDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.nodes.ReadPrimAttribute Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.name inputs.prim inputs.primPath inputs.usdTimecode inputs.usePath Outputs: outputs.value State: state.correctlySetup state.importPath state.srcAttrib state.srcPath state.srcPathAsToken state.time """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:name', 'token', 0, 'Attribute Name', 'The name of the attribute to get on the specified prim', {}, True, "", False, ''), ('inputs:prim', 'target', 0, None, "The prim to be read from when 'usePath' is false", {}, False, [], False, ''), ('inputs:primPath', 'token', 0, None, "The path of the prim to be modified when 'usePath' is true", {}, False, None, True, 'Use prim input with a GetPrimsAtPath node instead'), ('inputs:usdTimecode', 'timecode', 0, 'Time', 'The time at which to evaluate the transform of the USD prim attribute. A value of "NaN" indicates that the default USD time stamp should be used', {ogn.MetadataKeys.DEFAULT: '"NaN"'}, True, float("NaN"), False, ''), ('inputs:usePath', 'bool', 0, None, "When true, the 'primPath' attribute is used as the path to the prim being read, otherwise it will read the connection at the 'prim' attribute", {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, True, 'Use prim input with a GetPrimsAtPath node instead'), ('outputs:value', 'any', 2, None, 'The attribute value', {}, True, None, False, ''), ('state:correctlySetup', 'bool', 0, None, 'Wheter or not the instance is properly setup', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('state:importPath', 'uint64', 0, None, 'Path at which data has been imported', {}, True, None, False, ''), ('state:srcAttrib', 'uint64', 0, None, 'A TokenC to the source attribute', {}, True, None, False, ''), ('state:srcPath', 'uint64', 0, None, 'A PathC to the source prim', {}, True, None, False, ''), ('state:srcPathAsToken', 'uint64', 0, None, 'A TokenC to the source prim', {}, True, None, False, ''), ('state:time', 'double', 0, None, 'The timecode at which we have imported the value', {}, True, None, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.prim = og.AttributeRole.TARGET role_data.inputs.usdTimecode = og.AttributeRole.TIMECODE return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [] self._batchedReadValues = [] @property def name(self): data_view = og.AttributeValueHelper(self._attributes.name) return data_view.get() @name.setter def name(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.name) data_view = og.AttributeValueHelper(self._attributes.name) data_view.set(value) @property def prim(self): data_view = og.AttributeValueHelper(self._attributes.prim) return data_view.get() @prim.setter def prim(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.prim) data_view = og.AttributeValueHelper(self._attributes.prim) data_view.set(value) self.prim_size = data_view.get_array_size() @property def primPath(self): data_view = og.AttributeValueHelper(self._attributes.primPath) return data_view.get() @primPath.setter def primPath(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.primPath) data_view = og.AttributeValueHelper(self._attributes.primPath) data_view.set(value) @property def usdTimecode(self): data_view = og.AttributeValueHelper(self._attributes.usdTimecode) return data_view.get() @usdTimecode.setter def usdTimecode(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.usdTimecode) data_view = og.AttributeValueHelper(self._attributes.usdTimecode) data_view.set(value) @property def usePath(self): data_view = og.AttributeValueHelper(self._attributes.usePath) return data_view.get() @usePath.setter def usePath(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.usePath) data_view = og.AttributeValueHelper(self._attributes.usePath) data_view.set(value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def value(self) -> og.RuntimeAttribute: """Get the runtime wrapper class for the attribute outputs.value""" return og.RuntimeAttribute(self._attributes.value.get_attribute_data(), self._context, False) @value.setter def value(self, value_to_set: Any): """Assign another attribute's value to outputs.value""" if isinstance(value_to_set, og.RuntimeAttribute): self.value.value = value_to_set.value else: self.value.value = value_to_set def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) @property def correctlySetup(self): data_view = og.AttributeValueHelper(self._attributes.correctlySetup) return data_view.get() @correctlySetup.setter def correctlySetup(self, value): data_view = og.AttributeValueHelper(self._attributes.correctlySetup) data_view.set(value) @property def importPath(self): data_view = og.AttributeValueHelper(self._attributes.importPath) return data_view.get() @importPath.setter def importPath(self, value): data_view = og.AttributeValueHelper(self._attributes.importPath) data_view.set(value) @property def srcAttrib(self): data_view = og.AttributeValueHelper(self._attributes.srcAttrib) return data_view.get() @srcAttrib.setter def srcAttrib(self, value): data_view = og.AttributeValueHelper(self._attributes.srcAttrib) data_view.set(value) @property def srcPath(self): data_view = og.AttributeValueHelper(self._attributes.srcPath) return data_view.get() @srcPath.setter def srcPath(self, value): data_view = og.AttributeValueHelper(self._attributes.srcPath) data_view.set(value) @property def srcPathAsToken(self): data_view = og.AttributeValueHelper(self._attributes.srcPathAsToken) return data_view.get() @srcPathAsToken.setter def srcPathAsToken(self, value): data_view = og.AttributeValueHelper(self._attributes.srcPathAsToken) data_view.set(value) @property def time(self): data_view = og.AttributeValueHelper(self._attributes.time) return data_view.get() @time.setter def time(self, value): data_view = og.AttributeValueHelper(self._attributes.time) data_view.set(value) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnReadPrimAttributeDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnReadPrimAttributeDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnReadPrimAttributeDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
11,432
Python
44.011811
298
0.638121
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnGetPrimDirectionVectorDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.nodes.GetPrimDirectionVector Given a prim, find its direction vectors (up vector, forward vector, right vector, etc.) """ import numpy import usdrt import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnGetPrimDirectionVectorDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.nodes.GetPrimDirectionVector Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.prim inputs.primPath inputs.usePath Outputs: outputs.backwardVector outputs.downVector outputs.forwardVector outputs.leftVector outputs.rightVector outputs.upVector """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:prim', 'target', 0, None, "The connection to the input prim - this attribute is used when 'usePath' is false", {}, False, [], False, ''), ('inputs:primPath', 'token', 0, None, "The path of the input prim - this attribute is used when 'usePath' is true", {}, True, "", True, 'Use prim input with a GetPrimsAtPath node instead'), ('inputs:usePath', 'bool', 0, None, "When true, it will use the 'primPath' attribute as the path to the prim, otherwise it will read the connection at the 'prim' attribute", {ogn.MetadataKeys.DEFAULT: 'true'}, True, True, True, 'Use prim input with a GetPrimsAtPath node instead'), ('outputs:backwardVector', 'double3', 0, 'Backward Vector', 'The backward vector of the prim', {}, True, None, False, ''), ('outputs:downVector', 'double3', 0, 'Down Vector', 'The down vector of the prim', {}, True, None, False, ''), ('outputs:forwardVector', 'double3', 0, 'Forward Vector', 'The forward vector of the prim', {}, True, None, False, ''), ('outputs:leftVector', 'double3', 0, 'Left Vector', 'The left vector of the prim', {}, True, None, False, ''), ('outputs:rightVector', 'double3', 0, 'Right Vector', 'The right vector of the prim', {}, True, None, False, ''), ('outputs:upVector', 'double3', 0, 'Up Vector', 'The up vector of the prim', {}, True, None, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.prim = og.AttributeRole.TARGET return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [] self._batchedReadValues = [] @property def prim(self): data_view = og.AttributeValueHelper(self._attributes.prim) return data_view.get() @prim.setter def prim(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.prim) data_view = og.AttributeValueHelper(self._attributes.prim) data_view.set(value) self.prim_size = data_view.get_array_size() @property def primPath(self): data_view = og.AttributeValueHelper(self._attributes.primPath) return data_view.get() @primPath.setter def primPath(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.primPath) data_view = og.AttributeValueHelper(self._attributes.primPath) data_view.set(value) @property def usePath(self): data_view = og.AttributeValueHelper(self._attributes.usePath) return data_view.get() @usePath.setter def usePath(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.usePath) data_view = og.AttributeValueHelper(self._attributes.usePath) data_view.set(value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def backwardVector(self): data_view = og.AttributeValueHelper(self._attributes.backwardVector) return data_view.get() @backwardVector.setter def backwardVector(self, value): data_view = og.AttributeValueHelper(self._attributes.backwardVector) data_view.set(value) @property def downVector(self): data_view = og.AttributeValueHelper(self._attributes.downVector) return data_view.get() @downVector.setter def downVector(self, value): data_view = og.AttributeValueHelper(self._attributes.downVector) data_view.set(value) @property def forwardVector(self): data_view = og.AttributeValueHelper(self._attributes.forwardVector) return data_view.get() @forwardVector.setter def forwardVector(self, value): data_view = og.AttributeValueHelper(self._attributes.forwardVector) data_view.set(value) @property def leftVector(self): data_view = og.AttributeValueHelper(self._attributes.leftVector) return data_view.get() @leftVector.setter def leftVector(self, value): data_view = og.AttributeValueHelper(self._attributes.leftVector) data_view.set(value) @property def rightVector(self): data_view = og.AttributeValueHelper(self._attributes.rightVector) return data_view.get() @rightVector.setter def rightVector(self, value): data_view = og.AttributeValueHelper(self._attributes.rightVector) data_view.set(value) @property def upVector(self): data_view = og.AttributeValueHelper(self._attributes.upVector) return data_view.get() @upVector.setter def upVector(self, value): data_view = og.AttributeValueHelper(self._attributes.upVector) data_view.set(value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnGetPrimDirectionVectorDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnGetPrimDirectionVectorDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnGetPrimDirectionVectorDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
9,394
Python
44.386473
289
0.648073
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnNoiseDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.nodes.Noise Sample values from a Perlin noise field. The noise field for any given seed is static: the same input position will always give the same result. This is useful in many areas, such as texturing and animation, where repeatability is essential. If you want a result that varies then you will need to vary either the position or the seed. For example, connecting the 'frame' output of an OnTick node to position will provide a noise result which varies from frame to frame. Perlin noise is locally smooth, meaning that small changes in the sample position will produce small changes in the resulting noise. Varying the seed value will produce a more chaotic result. Another characteristic of Perlin noise is that it is zero at the corners of each cell in the field. In practical terms this means that integral positions, such as 5.0 in a one-dimensional field or (3.0, -1.0) in a two-dimensional field, will return a result of 0.0. Thus, if the source of your sample positions provides only integral values then all of your results will be zero. To avoid this try offsetting your position values by a fractional amount, such as 0.5. """ from typing import Any import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnNoiseDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.nodes.Noise Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.position inputs.seed Outputs: outputs.result """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:position', 'float,float[2],float[2][],float[3],float[3][],float[4],float[4][],float[]', 1, None, 'Position(s) within the noise field to be sampled. For a given seed, the same position \nwill always return the same noise value.', {}, True, None, False, ''), ('inputs:seed', 'uint', 0, None, 'Seed for generating the noise field.', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''), ('outputs:result', 'float,float[]', 1, None, 'Value at the selected position(s) in the noise field.', {}, True, None, False, ''), ]) class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [] self._batchedReadValues = [] @property def position(self) -> og.RuntimeAttribute: """Get the runtime wrapper class for the attribute inputs.position""" return og.RuntimeAttribute(self._attributes.position.get_attribute_data(), self._context, True) @position.setter def position(self, value_to_set: Any): """Assign another attribute's value to outputs.position""" if isinstance(value_to_set, og.RuntimeAttribute): self.position.value = value_to_set.value else: self.position.value = value_to_set @property def seed(self): data_view = og.AttributeValueHelper(self._attributes.seed) return data_view.get() @seed.setter def seed(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.seed) data_view = og.AttributeValueHelper(self._attributes.seed) data_view.set(value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def result(self) -> og.RuntimeAttribute: """Get the runtime wrapper class for the attribute outputs.result""" return og.RuntimeAttribute(self._attributes.result.get_attribute_data(), self._context, False) @result.setter def result(self, value_to_set: Any): """Assign another attribute's value to outputs.result""" if isinstance(value_to_set, og.RuntimeAttribute): self.result.value = value_to_set.value else: self.result.value = value_to_set def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnNoiseDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnNoiseDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnNoiseDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
7,259
Python
51.230215
273
0.678744
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnReadPrimAttributesDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.nodes.ReadPrimAttributes Read Prim attributes and exposes them as dynamic attributes Does not produce output bundle. """ import usdrt import carb import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnReadPrimAttributesDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.nodes.ReadPrimAttributes Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.attrNamesToImport inputs.prim inputs.primPath inputs.usdTimecode inputs.usePath Outputs: outputs.primBundle State: state.attrNamesToImport state.primPath state.usdTimecode """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:attrNamesToImport', 'string', 0, 'Attribute Name Pattern', "A list of wildcard patterns used to match the attribute names that are to be imported\n\nSupported syntax of wildcard pattern:\n '*' - match an arbitrary number of any characters\n '?' - match any single character\n '^' - (caret) is used to define a pattern that is to be excluded\n\nExample of wildcard patterns, input: ['points', 'faceVertexCount', 'faceVertexIndices', 'size']\n '*' - match any\n '* ^points' - match any, but exclude 'points'\n '* ^face*' - match any, but exclude 'faceVertexCount' and 'faceVertexIndices'", {ogn.MetadataKeys.DEFAULT: '"*"'}, True, "*", False, ''), ('inputs:prim', 'target', 0, None, "The prim to be read from when 'usePath' is false", {}, True, [], False, ''), ('inputs:primPath', 'path', 0, 'Prim Path', "The path of the prim to be read from when 'usePath' is true", {ogn.MetadataKeys.DEFAULT: '""'}, False, "", True, 'Use prim input with a GetPrimsAtPath node instead'), ('inputs:usdTimecode', 'timecode', 0, 'Time', 'The time at which to evaluate the transform of the USD prim. A value of "NaN" indicates that the default USD time stamp should be used', {ogn.MetadataKeys.DEFAULT: '"NaN"'}, True, float("NaN"), False, ''), ('inputs:usePath', 'bool', 0, 'Use Path', "When true, the 'primPath' attribute is used as the path to the prim being read, otherwise it will read the connection at the 'prim' attribute", {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, True, 'Use prim input with a GetPrimsAtPath node instead'), ('outputs:primBundle', 'bundle', 0, None, 'A bundle of the target Prim attributes.\nIn addition to the data attributes, there are token attributes named sourcePrimPath and sourcePrimType\nwhich contains the path of the Prim being read', {ogn.MetadataKeys.HIDDEN: 'true', ogn.MetadataKeys.LITERAL_ONLY: '1'}, True, None, False, ''), ('state:attrNamesToImport', 'string', 0, None, 'State from previous evaluation', {}, True, None, False, ''), ('state:primPath', 'uint64', 0, None, 'State from previous evaluation', {}, True, None, False, ''), ('state:usdTimecode', 'timecode', 0, None, 'State from previous evaluation', {ogn.MetadataKeys.DEFAULT: '"NaN"'}, True, float("NaN"), False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.attrNamesToImport = og.AttributeRole.TEXT role_data.inputs.prim = og.AttributeRole.TARGET role_data.inputs.primPath = og.AttributeRole.PATH role_data.inputs.usdTimecode = og.AttributeRole.TIMECODE role_data.outputs.primBundle = og.AttributeRole.BUNDLE role_data.state.attrNamesToImport = og.AttributeRole.TEXT role_data.state.usdTimecode = og.AttributeRole.TIMECODE return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [] self._batchedReadValues = [] @property def attrNamesToImport(self): data_view = og.AttributeValueHelper(self._attributes.attrNamesToImport) return data_view.get() @attrNamesToImport.setter def attrNamesToImport(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.attrNamesToImport) data_view = og.AttributeValueHelper(self._attributes.attrNamesToImport) data_view.set(value) self.attrNamesToImport_size = data_view.get_array_size() @property def prim(self): data_view = og.AttributeValueHelper(self._attributes.prim) return data_view.get() @prim.setter def prim(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.prim) data_view = og.AttributeValueHelper(self._attributes.prim) data_view.set(value) self.prim_size = data_view.get_array_size() @property def primPath(self): data_view = og.AttributeValueHelper(self._attributes.primPath) return data_view.get() @primPath.setter def primPath(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.primPath) data_view = og.AttributeValueHelper(self._attributes.primPath) data_view.set(value) self.primPath_size = data_view.get_array_size() @property def usdTimecode(self): data_view = og.AttributeValueHelper(self._attributes.usdTimecode) return data_view.get() @usdTimecode.setter def usdTimecode(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.usdTimecode) data_view = og.AttributeValueHelper(self._attributes.usdTimecode) data_view.set(value) @property def usePath(self): data_view = og.AttributeValueHelper(self._attributes.usePath) return data_view.get() @usePath.setter def usePath(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.usePath) data_view = og.AttributeValueHelper(self._attributes.usePath) data_view.set(value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self.__bundles = og.BundleContainer(context, node, attributes, [], read_only=False, gpu_ptr_kinds={}) self._batchedWriteValues = { } @property def primBundle(self) -> og.BundleContents: """Get the bundle wrapper class for the attribute outputs.primBundle""" return self.__bundles.primBundle @primBundle.setter def primBundle(self, bundle: og.BundleContents): """Overwrite the bundle attribute outputs.primBundle with a new bundle""" if not isinstance(bundle, og.BundleContents): carb.log_error("Only bundle attributes can be assigned to another bundle attribute") self.__bundles.primBundle.bundle = bundle def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self.attrNamesToImport_size = None @property def attrNamesToImport(self): data_view = og.AttributeValueHelper(self._attributes.attrNamesToImport) self.attrNamesToImport_size = data_view.get_array_size() return data_view.get() @attrNamesToImport.setter def attrNamesToImport(self, value): data_view = og.AttributeValueHelper(self._attributes.attrNamesToImport) data_view.set(value) self.attrNamesToImport_size = data_view.get_array_size() @property def primPath(self): data_view = og.AttributeValueHelper(self._attributes.primPath) return data_view.get() @primPath.setter def primPath(self, value): data_view = og.AttributeValueHelper(self._attributes.primPath) data_view.set(value) @property def usdTimecode(self): data_view = og.AttributeValueHelper(self._attributes.usdTimecode) return data_view.get() @usdTimecode.setter def usdTimecode(self, value): data_view = og.AttributeValueHelper(self._attributes.usdTimecode) data_view.set(value) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnReadPrimAttributesDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnReadPrimAttributesDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnReadPrimAttributesDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
11,635
Python
50.486725
680
0.65896
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnAttrTypeDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.nodes.AttributeType Queries information about the type of a specified attribute in an input bundle """ import carb import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnAttrTypeDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.nodes.AttributeType Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.attrName inputs.data Outputs: outputs.arrayDepth outputs.baseType outputs.componentCount outputs.fullType outputs.role """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:attrName', 'token', 0, 'Attribute To Query', 'The name of the attribute to be queried', {ogn.MetadataKeys.DEFAULT: '"input"'}, True, "input", False, ''), ('inputs:data', 'bundle', 0, 'Bundle To Examine', 'Bundle of attributes to examine', {}, True, None, False, ''), ('outputs:arrayDepth', 'int', 0, 'Attribute Array Depth', 'Zero for a single value, one for an array, two for an array of arrays.\nSet to -1 if the named attribute was not in the bundle.', {}, True, None, False, ''), ('outputs:baseType', 'int', 0, 'Attribute Base Type', 'An integer representing the type of the individual components.\nSet to -1 if the named attribute was not in the bundle.', {}, True, None, False, ''), ('outputs:componentCount', 'int', 0, 'Attribute Component Count', 'Number of components in each tuple, e.g. one for float, three for point3f, 16 for\nmatrix4d. Set to -1 if the named attribute was not in the bundle.', {}, True, None, False, ''), ('outputs:fullType', 'int', 0, 'Full Attribute Type', 'A single int representing the full type information.\nSet to -1 if the named attribute was not in the bundle.', {}, True, None, False, ''), ('outputs:role', 'int', 0, 'Attribute Role', 'An integer representing semantic meaning of the type, e.g. point3f vs. normal3f vs. vector3f vs. float3.\nSet to -1 if the named attribute was not in the bundle.', {}, True, None, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.data = og.AttributeRole.BUNDLE return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self.__bundles = og.BundleContainer(context, node, attributes, [], read_only=True, gpu_ptr_kinds={}) self._batchedReadAttributes = [] self._batchedReadValues = [] @property def attrName(self): data_view = og.AttributeValueHelper(self._attributes.attrName) return data_view.get() @attrName.setter def attrName(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.attrName) data_view = og.AttributeValueHelper(self._attributes.attrName) data_view.set(value) @property def data(self) -> og.BundleContents: """Get the bundle wrapper class for the attribute inputs.data""" return self.__bundles.data def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def arrayDepth(self): data_view = og.AttributeValueHelper(self._attributes.arrayDepth) return data_view.get() @arrayDepth.setter def arrayDepth(self, value): data_view = og.AttributeValueHelper(self._attributes.arrayDepth) data_view.set(value) @property def baseType(self): data_view = og.AttributeValueHelper(self._attributes.baseType) return data_view.get() @baseType.setter def baseType(self, value): data_view = og.AttributeValueHelper(self._attributes.baseType) data_view.set(value) @property def componentCount(self): data_view = og.AttributeValueHelper(self._attributes.componentCount) return data_view.get() @componentCount.setter def componentCount(self, value): data_view = og.AttributeValueHelper(self._attributes.componentCount) data_view.set(value) @property def fullType(self): data_view = og.AttributeValueHelper(self._attributes.fullType) return data_view.get() @fullType.setter def fullType(self, value): data_view = og.AttributeValueHelper(self._attributes.fullType) data_view.set(value) @property def role(self): data_view = og.AttributeValueHelper(self._attributes.role) return data_view.get() @role.setter def role(self, value): data_view = og.AttributeValueHelper(self._attributes.role) data_view.set(value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnAttrTypeDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnAttrTypeDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnAttrTypeDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
8,297
Python
46.965318
253
0.655538
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnBundleInspectorDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.nodes.BundleInspector This node creates independent outputs containing information about the contents of a bundle attribute. It can be used for testing or debugging what is inside a bundle as it flows through the graph. The bundle is inspected recursively, so any bundles inside of the main bundle have their contents added to the output as well. The bundle contents can be printed when the node evaluates, and it passes the input straight through unchanged so you can insert this node between two nodes to inspect the data flowing through the graph. """ import carb import numpy import carb import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnBundleInspectorDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.nodes.BundleInspector Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.bundle inputs.inspectDepth inputs.print Outputs: outputs.arrayDepths outputs.attributeCount outputs.bundle outputs.childCount outputs.count outputs.names outputs.roles outputs.tupleCounts outputs.types outputs.values """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:bundle', 'bundle', 0, 'Bundle To Analyze', 'The attribute bundle to be inspected', {}, True, None, False, ''), ('inputs:inspectDepth', 'int', 0, 'Inspect Depth', 'The depth that the inspector is going to traverse and print.\n0 means just attributes on the input bundles. 1 means its immediate children. -1 means infinity.', {ogn.MetadataKeys.DEFAULT: '1'}, True, 1, False, ''), ('inputs:print', 'bool', 0, 'Print Contents', 'Setting to true prints the contents of the bundle when the node evaluates', {}, True, False, False, ''), ('outputs:arrayDepths', 'int[]', 0, 'Array Depths', 'List of the array depths of attributes present in the bundle', {}, True, None, False, ''), ('outputs:attributeCount', 'uint64', 0, 'Attribute Count', 'Number of attributes present in the bundle. Every other output is an array that\nshould have this number of elements in it.', {}, True, None, False, ''), ('outputs:bundle', 'bundle', 0, 'Bundle Passthrough', 'The attribute bundle passed through as-is from the input bundle', {}, True, None, False, ''), ('outputs:childCount', 'uint64', 0, 'Child Count', 'Number of child bundles present in the bundle.', {}, True, None, False, ''), ('outputs:count', 'uint64', 0, 'Attribute Count', 'Number of attributes present in the bundle. Every other output is an array that\nshould have this number of elements in it.', {ogn.MetadataKeys.HIDDEN: 'true'}, True, None, False, ''), ('outputs:names', 'token[]', 0, 'Attribute Names', 'List of the names of attributes present in the bundle', {}, True, None, False, ''), ('outputs:roles', 'token[]', 0, 'Attribute Roles', 'List of the names of the roles of attributes present in the bundle', {}, True, None, False, ''), ('outputs:tupleCounts', 'int[]', 0, 'Tuple Counts', 'List of the tuple counts of attributes present in the bundle', {}, True, None, False, ''), ('outputs:types', 'token[]', 0, 'Attribute Base Types', 'List of the types of attributes present in the bundle', {}, True, None, False, ''), ('outputs:values', 'token[]', 0, 'Attribute Values', 'List of the bundled attribute values, converted to token format', {}, True, None, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.bundle = og.AttributeRole.BUNDLE role_data.outputs.bundle = og.AttributeRole.BUNDLE return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self.__bundles = og.BundleContainer(context, node, attributes, [], read_only=True, gpu_ptr_kinds={}) self._batchedReadAttributes = [] self._batchedReadValues = [] @property def bundle(self) -> og.BundleContents: """Get the bundle wrapper class for the attribute inputs.bundle""" return self.__bundles.bundle @property def inspectDepth(self): data_view = og.AttributeValueHelper(self._attributes.inspectDepth) return data_view.get() @inspectDepth.setter def inspectDepth(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.inspectDepth) data_view = og.AttributeValueHelper(self._attributes.inspectDepth) data_view.set(value) @property def print(self): data_view = og.AttributeValueHelper(self._attributes.print) return data_view.get() @print.setter def print(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.print) data_view = og.AttributeValueHelper(self._attributes.print) data_view.set(value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self.__bundles = og.BundleContainer(context, node, attributes, [], read_only=False, gpu_ptr_kinds={}) self.arrayDepths_size = None self.names_size = None self.roles_size = None self.tupleCounts_size = None self.types_size = None self.values_size = None self._batchedWriteValues = { } @property def arrayDepths(self): data_view = og.AttributeValueHelper(self._attributes.arrayDepths) return data_view.get(reserved_element_count=self.arrayDepths_size) @arrayDepths.setter def arrayDepths(self, value): data_view = og.AttributeValueHelper(self._attributes.arrayDepths) data_view.set(value) self.arrayDepths_size = data_view.get_array_size() @property def attributeCount(self): data_view = og.AttributeValueHelper(self._attributes.attributeCount) return data_view.get() @attributeCount.setter def attributeCount(self, value): data_view = og.AttributeValueHelper(self._attributes.attributeCount) data_view.set(value) @property def bundle(self) -> og.BundleContents: """Get the bundle wrapper class for the attribute outputs.bundle""" return self.__bundles.bundle @bundle.setter def bundle(self, bundle: og.BundleContents): """Overwrite the bundle attribute outputs.bundle with a new bundle""" if not isinstance(bundle, og.BundleContents): carb.log_error("Only bundle attributes can be assigned to another bundle attribute") self.__bundles.bundle.bundle = bundle @property def childCount(self): data_view = og.AttributeValueHelper(self._attributes.childCount) return data_view.get() @childCount.setter def childCount(self, value): data_view = og.AttributeValueHelper(self._attributes.childCount) data_view.set(value) @property def count(self): data_view = og.AttributeValueHelper(self._attributes.count) return data_view.get() @count.setter def count(self, value): data_view = og.AttributeValueHelper(self._attributes.count) data_view.set(value) @property def names(self): data_view = og.AttributeValueHelper(self._attributes.names) return data_view.get(reserved_element_count=self.names_size) @names.setter def names(self, value): data_view = og.AttributeValueHelper(self._attributes.names) data_view.set(value) self.names_size = data_view.get_array_size() @property def roles(self): data_view = og.AttributeValueHelper(self._attributes.roles) return data_view.get(reserved_element_count=self.roles_size) @roles.setter def roles(self, value): data_view = og.AttributeValueHelper(self._attributes.roles) data_view.set(value) self.roles_size = data_view.get_array_size() @property def tupleCounts(self): data_view = og.AttributeValueHelper(self._attributes.tupleCounts) return data_view.get(reserved_element_count=self.tupleCounts_size) @tupleCounts.setter def tupleCounts(self, value): data_view = og.AttributeValueHelper(self._attributes.tupleCounts) data_view.set(value) self.tupleCounts_size = data_view.get_array_size() @property def types(self): data_view = og.AttributeValueHelper(self._attributes.types) return data_view.get(reserved_element_count=self.types_size) @types.setter def types(self, value): data_view = og.AttributeValueHelper(self._attributes.types) data_view.set(value) self.types_size = data_view.get_array_size() @property def values(self): data_view = og.AttributeValueHelper(self._attributes.values) return data_view.get(reserved_element_count=self.values_size) @values.setter def values(self, value): data_view = og.AttributeValueHelper(self._attributes.values) data_view.set(value) self.values_size = data_view.get_array_size() def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnBundleInspectorDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnBundleInspectorDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnBundleInspectorDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
13,048
Python
47.509294
274
0.650061
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnGetGatheredAttributeDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.nodes.GetGatheredAttribute Copies gathered scaler/vector attribute values from the Gather buckets into an array attribute PROTOTYPE DO NOT USE, Requires GatherPrototype """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn from typing import Any class OgnGetGatheredAttributeDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.nodes.GetGatheredAttribute Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.gatherId inputs.name Outputs: outputs.value """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:gatherId', 'uint64', 0, None, 'The GatherId of the Gather containing the attribute values', {}, True, 0, False, ''), ('inputs:name', 'token', 0, None, 'The name of the gathered attribute to join', {}, True, '', False, ''), ('outputs:value', 'any', 2, None, 'The gathered attribute values as an array', {}, True, None, False, ''), ]) class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"gatherId", "name", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.gatherId, self._attributes.name] self._batchedReadValues = [0, ""] @property def gatherId(self): return self._batchedReadValues[0] @gatherId.setter def gatherId(self, value): self._batchedReadValues[0] = value @property def name(self): return self._batchedReadValues[1] @name.setter def name(self, value): self._batchedReadValues[1] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def value(self) -> og.RuntimeAttribute: """Get the runtime wrapper class for the attribute outputs.value""" return og.RuntimeAttribute(self._attributes.value.get_attribute_data(), self._context, False) @value.setter def value(self, value_to_set: Any): """Assign another attribute's value to outputs.value""" if isinstance(value_to_set, og.RuntimeAttribute): self.value.value = value_to_set.value else: self.value.value = value_to_set def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnGetGatheredAttributeDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnGetGatheredAttributeDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnGetGatheredAttributeDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
5,986
Python
49.737288
133
0.659372
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnGetPrimPathsDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.nodes.GetPrimPaths Generates a path array from the specified relationship. This is useful when absolute prim paths may change. """ import numpy import usdrt import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnGetPrimPathsDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.nodes.GetPrimPaths Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.prims Outputs: outputs.primPaths """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:prims', 'target', 0, None, 'Relationship to prims on the stage', {ogn.MetadataKeys.ALLOW_MULTI_INPUTS: '1'}, True, [], False, ''), ('outputs:primPaths', 'token[]', 0, None, 'The absolute paths of the given prims as a token array', {}, True, None, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.prims = og.AttributeRole.TARGET return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [] self._batchedReadValues = [] @property def prims(self): data_view = og.AttributeValueHelper(self._attributes.prims) return data_view.get() @prims.setter def prims(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.prims) data_view = og.AttributeValueHelper(self._attributes.prims) data_view.set(value) self.prims_size = data_view.get_array_size() def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self.primPaths_size = None self._batchedWriteValues = { } @property def primPaths(self): data_view = og.AttributeValueHelper(self._attributes.primPaths) return data_view.get(reserved_element_count=self.primPaths_size) @primPaths.setter def primPaths(self, value): data_view = og.AttributeValueHelper(self._attributes.primPaths) data_view.set(value) self.primPaths_size = data_view.get_array_size() def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnGetPrimPathsDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnGetPrimPathsDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnGetPrimPathsDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
5,629
Python
45.528925
147
0.671345
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/OgnModuloDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.nodes.Modulo Computes the modulo of integer inputs (A % B), which is the remainder of A / B If B is zero, the result is zero. If A and B are both non-negative the result is non-negative, otherwise the sign of the result is undefined. """ from typing import Any import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnModuloDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.nodes.Modulo Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.a inputs.b Outputs: outputs.result """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:a', 'int,int64,uchar,uint,uint64', 1, 'A', 'The dividend of (A % B)', {}, True, None, False, ''), ('inputs:b', 'int,int64,uchar,uint,uint64', 1, 'B', 'The divisor of (A % B)', {}, True, None, False, ''), ('outputs:result', 'int,int64,uchar,uint,uint64', 1, 'Result', 'Modulo (A % B), the remainder of A / B', {}, True, None, False, ''), ]) class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [] self._batchedReadValues = [] @property def a(self) -> og.RuntimeAttribute: """Get the runtime wrapper class for the attribute inputs.a""" return og.RuntimeAttribute(self._attributes.a.get_attribute_data(), self._context, True) @a.setter def a(self, value_to_set: Any): """Assign another attribute's value to outputs.a""" if isinstance(value_to_set, og.RuntimeAttribute): self.a.value = value_to_set.value else: self.a.value = value_to_set @property def b(self) -> og.RuntimeAttribute: """Get the runtime wrapper class for the attribute inputs.b""" return og.RuntimeAttribute(self._attributes.b.get_attribute_data(), self._context, True) @b.setter def b(self, value_to_set: Any): """Assign another attribute's value to outputs.b""" if isinstance(value_to_set, og.RuntimeAttribute): self.b.value = value_to_set.value else: self.b.value = value_to_set def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def result(self) -> og.RuntimeAttribute: """Get the runtime wrapper class for the attribute outputs.result""" return og.RuntimeAttribute(self._attributes.result.get_attribute_data(), self._context, False) @result.setter def result(self, value_to_set: Any): """Assign another attribute's value to outputs.result""" if isinstance(value_to_set, og.RuntimeAttribute): self.result.value = value_to_set.value else: self.result.value = value_to_set def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnModuloDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnModuloDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnModuloDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
6,245
Python
47.046153
140
0.6506
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnFMod.py
""" Module contains the OmniGraph node implementation of omni.graph.fmod """ import carb import numpy as np import omni.graph.core as og class OgnFMod: """Node to find floating point remainder""" @staticmethod def compute(db) -> bool: try: db.outputs.result.value = np.fmod(db.inputs.a.value, db.inputs.b.value) except TypeError as error: db.log_error(f"Remainder could not be performed: {error}") return False return True @staticmethod def on_connection_type_resolve(node) -> None: atype = node.get_attribute("inputs:a").get_resolved_type() btype = node.get_attribute("inputs:b").get_resolved_type() resultattr = node.get_attribute("outputs:result") resulttype = resultattr.get_resolved_type() # we can only infer the output given both inputs are resolved and they are the same. if ( atype.base_type != og.BaseDataType.UNKNOWN and btype.base_type != og.BaseDataType.UNKNOWN and resulttype.base_type == og.BaseDataType.UNKNOWN ): if atype.base_type == btype.base_type: sum_type = og.Type( atype.base_type, max(atype.tuple_count, btype.tuple_count), max(atype.array_depth, btype.array_depth), ) resultattr.set_resolved_type(sum_type) else: carb.log_warn(f"Can not compute remainder of types {atype} and {btype}")
1,538
Python
33.977272
92
0.598179
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/math/OgnATan2.py
""" This is the implementation of the OGN node defined in OgnATan2.ogn """ import math import omni.graph.core as og class OgnATan2: """ Calculates the arc tangent of A,B. This is the angle in radians between the ray ending at the origin and passing through the point (B, A). """ @staticmethod def compute(db) -> bool: """Compute the outputs from the current input""" try: db.outputs.result.value = math.degrees(math.atan2(db.inputs.a.value, db.inputs.b.value)) except TypeError as error: db.log_error(f"atan2 could not be performed: {error}") return False return True @staticmethod def on_connection_type_resolve(node) -> None: aattr = node.get_attribute("inputs:a") battr = node.get_attribute("inputs:b") resultattr = node.get_attribute("outputs:result") og.resolve_fully_coupled([aattr, battr, resultattr])
949
Python
27.787878
109
0.640674
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/logic/OgnBooleanExpr.py
""" NOTE: DEPRECATED AS OF 1.26.0 IN FAVOUR OF INDIVIDAL BOOLEAN OP NODES This is the implementation of the OGN node defined in OgnBooleanExpr.ogn """ class OgnBooleanExpr: """ Boolean AND of two inputs """ @staticmethod def compute(db) -> bool: """Compute the outputs from the current input""" # convert to numpy bool arrays a = db.inputs.a b = db.inputs.b op = db.inputs.operator.lower() if not op: return False if op == "and": result = a and b elif op == "or": result = a or b elif op == "nand": result = not (a and b) elif op == "nor": result = not (a or b) elif op in ["xor", "!="]: result = a != b elif op in ["xnor", "=="]: result = a == b else: return False db.outputs.result = result return True
947
Python
22.699999
72
0.498416
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnMakeArray.py
""" This is the implementation of the OGN node defined in OgnMakeArrayDouble3.ogn """ import omni.graph.core as og class OgnMakeArray: """ Makes an output array attribute from input values """ @staticmethod def compute(db) -> bool: """Compute the outputs from the current input""" if db.inputs.a.type.base_type == og.BaseDataType.UNKNOWN: return False array_size = db.inputs.arraySize out_array = [] if array_size > 0: out_array.append(db.inputs.a.value) if array_size > 1: out_array.append(db.inputs.b.value) if array_size > 2: out_array.append(db.inputs.c.value) if array_size > 3: out_array.append(db.inputs.d.value) if array_size > 4: out_array.append(db.inputs.e.value) out_array.extend([db.inputs.e.value] * (array_size - 5)) db.outputs.array.value = out_array return True @staticmethod def on_connection_type_resolve(node) -> None: attribs = [(node.get_attribute("inputs:" + a), None, 0, None) for a in ("a", "b", "c", "d", "e")] attribs.append((node.get_attribute("outputs:array"), None, 1, None)) og.resolve_base_coupled(attribs)
1,266
Python
29.902438
105
0.591627
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/nodes/utility/OgnBundleConstructor.py
""" Module contains the OmniGraph node implementation of BundleConstructor """ import omni.graph.core as og class OgnBundleConstructor: """Node to create a bundle out of dynamic attributes""" @staticmethod def compute(db) -> bool: """Compute the bundle from the dynamic input attributes""" # Start with an empty output bundle. output_bundle = db.outputs.bundle output_bundle.clear() # Walk the list of node attribute, looking for dynamic inputs for attribute in db.abi_node.get_attributes(): if attribute.is_dynamic(): if attribute.get_port_type() != og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT: continue if attribute.get_extended_type() != og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR: db.log_warn(f"Cannot add extended attribute types like '{attribute.get_name()}' to a bundle") continue if attribute.get_resolved_type().base_type in [og.BaseDataType.RELATIONSHIP]: db.log_warn(f"Cannot add bundle attribute types like '{attribute.get_name()}' to a bundle") continue # The bundled name does not need the port namespace new_name = attribute.get_name().replace("inputs:", "") output_bundle.insert((attribute.get_resolved_type(), new_name)) return True
1,448
Python
37.131578
113
0.619475
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnNthRoot.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:value', {'type': 'float', 'value': 36.0}, False], ], 'outputs': [ ['outputs:result', {'type': 'float', 'value': 6.0}, False], ], }, { 'inputs': [ ['inputs:value', {'type': 'double', 'value': 27.0}, False], ['inputs:nthRoot', 3, False], ], 'outputs': [ ['outputs:result', {'type': 'double', 'value': 3.0}, False], ], }, { 'inputs': [ ['inputs:value', {'type': 'float[2]', 'value': [0.25, 4.0]}, False], ], 'outputs': [ ['outputs:result', {'type': 'float[2]', 'value': [0.5, 2.0]}, False], ], }, { 'inputs': [ ['inputs:value', {'type': 'float[]', 'value': [1.331, 8.0]}, False], ['inputs:nthRoot', 3, False], ], 'outputs': [ ['outputs:result', {'type': 'float[]', 'value': [1.1, 2.0]}, False], ], }, { 'inputs': [ ['inputs:value', {'type': 'float[2][]', 'value': [[4.0, 16.0], [2.25, 64.0]]}, False], ], 'outputs': [ ['outputs:result', {'type': 'float[2][]', 'value': [[2.0, 4.0], [1.5, 8.0]]}, False], ], }, { 'inputs': [ ['inputs:value', {'type': 'int64', 'value': 9223372036854775807}, False], ['inputs:nthRoot', 1, False], ], 'outputs': [ ['outputs:result', {'type': 'double', 'value': 9.223372036854776e+18}, False], ], }, { 'inputs': [ ['inputs:value', {'type': 'int', 'value': 256}, False], ['inputs:nthRoot', 4, False], ], 'outputs': [ ['outputs:result', {'type': 'double', 'value': 4.0}, False], ], }, { 'inputs': [ ['inputs:value', {'type': 'uint64', 'value': 8}, False], ['inputs:nthRoot', 3, False], ], 'outputs': [ ['outputs:result', {'type': 'double', 'value': 2.0}, False], ], }, { 'inputs': [ ['inputs:value', {'type': 'half[2]', 'value': [0.125, 1.0]}, False], ['inputs:nthRoot', 3, False], ], 'outputs': [ ['outputs:result', {'type': 'half[2]', 'value': [0.5, 1.0]}, False], ], }, { 'inputs': [ ['inputs:value', {'type': 'uchar', 'value': 25}, False], ], 'outputs': [ ['outputs:result', {'type': 'double', 'value': 5.0}, False], ], }, { 'inputs': [ ['inputs:value', {'type': 'int64', 'value': 16}, False], ['inputs:nthRoot', -2, False], ], 'outputs': [ ['outputs:result', {'type': 'double', 'value': 0.25}, False], ], }, { 'inputs': [ ['inputs:value', {'type': 'double', 'value': 0.125}, False], ['inputs:nthRoot', -3, False], ], 'outputs': [ ['outputs:result', {'type': 'double', 'value': 2}, False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_NthRoot", "omni.graph.nodes.NthRoot", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.NthRoot User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_NthRoot","omni.graph.nodes.NthRoot", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.NthRoot User test case #{i+1}", 16) async def test_thread_safety(self): import omni.kit # Generate multiple instances of the test setup to run them concurrently instance_setup = dict() for n in range(24): instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) for (key, test_info) in instance_setup.items(): test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_nodes_NthRoot", "omni.graph.nodes.NthRoot", test_run, test_info) self.assertEqual(len(og.get_all_graphs()), 24) # We want to evaluate all graphs concurrently. Kick them all. # Evaluate multiple times to skip 2 serial frames and increase chances for a race condition. for _ in range(10): await omni.kit.app.get_app().next_update_async() for (key, test_instance) in instance_setup.items(): _test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.nodes.NthRoot User test case #{i+1}, instance{key}") async def test_data_access(self): from omni.graph.nodes.ogn.OgnNthRootDatabase import OgnNthRootDatabase test_file_name = "OgnNthRootTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_NthRoot") database = OgnNthRootDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:nthRoot")) attribute = test_node.get_attribute("inputs:nthRoot") db_value = database.inputs.nthRoot expected_value = 2 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
7,684
Python
40.54054
187
0.520432
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnATan2.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:a', {'type': 'float', 'value': 5.0}, False], ['inputs:b', {'type': 'float', 'value': 3.0}, False], ], 'outputs': [ ['outputs:result', {'type': 'float', 'value': 59.0362434679}, False], ], }, { 'inputs': [ ['inputs:a', {'type': 'double', 'value': 70.0}, False], ['inputs:b', {'type': 'double', 'value': 10.0}, False], ], 'outputs': [ ['outputs:result', {'type': 'double', 'value': 81.8698976458}, False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_ATan2", "omni.graph.nodes.ATan2", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.ATan2 User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_ATan2","omni.graph.nodes.ATan2", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.ATan2 User test case #{i+1}", 16) async def test_data_access(self): from omni.graph.nodes.ogn.OgnATan2Database import OgnATan2Database test_file_name = "OgnATan2Template.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_ATan2") database = OgnATan2Database(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
3,279
Python
45.857142
164
0.609332
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnBooleanExpr.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:a', True, False], ['inputs:b', True, False], ['inputs:operator', "XOR", False], ], 'outputs': [ ['outputs:result', False, False], ], }, { 'inputs': [ ['inputs:a', True, False], ['inputs:b', True, False], ['inputs:operator', "XNOR", False], ], 'outputs': [ ['outputs:result', True, False], ], }, { 'inputs': [ ['inputs:a', True, False], ['inputs:b', False, False], ['inputs:operator', "OR", False], ], 'outputs': [ ['outputs:result', True, False], ], }, { 'inputs': [ ['inputs:a', True, False], ['inputs:b', False, False], ['inputs:operator', "AND", False], ], 'outputs': [ ['outputs:result', False, False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_BooleanExpr", "omni.graph.nodes.BooleanExpr", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.BooleanExpr User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_BooleanExpr","omni.graph.nodes.BooleanExpr", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.BooleanExpr User test case #{i+1}", 16) async def test_data_access(self): from omni.graph.nodes.ogn.OgnBooleanExprDatabase import OgnBooleanExprDatabase test_file_name = "OgnBooleanExprTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_BooleanExpr") database = OgnBooleanExprDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:a")) attribute = test_node.get_attribute("inputs:a") db_value = database.inputs.a expected_value = False actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:b")) attribute = test_node.get_attribute("inputs:b") db_value = database.inputs.b expected_value = False actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:operator")) attribute = test_node.get_attribute("inputs:operator") db_value = database.inputs.operator expected_value = "AND" actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:result")) attribute = test_node.get_attribute("outputs:result") db_value = database.outputs.result
5,285
Python
43.05
176
0.600189
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnFindPrims.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:namePrefix', "Xform", False], ], 'outputs': [ ['outputs:primPaths', ["/Xform1", "/Xform2", "/XformTagged1"], False], ], 'setup': {'create_nodes': [['TestNode', 'omni.graph.nodes.FindPrims']], 'create_prims': [['Empty', {}], ['Xform1', {'_translate': ['pointd[3][]', [[1, 2, 3]]]}], ['Xform2', {'_translate': ['pointd[3][]', [[4, 5, 6]]]}], ['XformTagged1', {'foo': ['token', ''], '_translate': ['pointd[3][]', [[1, 2, 3]]]}], ['Tagged1', {'foo': ['token', '']}]]} }, { 'inputs': [ ['inputs:namePrefix', "", False], ['inputs:requiredAttributes', "foo _translate", False], ], 'outputs': [ ['outputs:primPaths', ["/XformTagged1"], False], ], 'setup': {} }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_FindPrims", "omni.graph.nodes.FindPrims", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.FindPrims User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_FindPrims","omni.graph.nodes.FindPrims", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.FindPrims User test case #{i+1}", 16) async def test_thread_safety(self): import omni.kit # Generate multiple instances of the test setup to run them concurrently instance_setup = dict() for n in range(24): instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) for (key, test_info) in instance_setup.items(): test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_nodes_FindPrims", "omni.graph.nodes.FindPrims", test_run, test_info) self.assertEqual(len(og.get_all_graphs()), 24) # We want to evaluate all graphs concurrently. Kick them all. # Evaluate multiple times to skip 2 serial frames and increase chances for a race condition. for _ in range(10): await omni.kit.app.get_app().next_update_async() for (key, test_instance) in instance_setup.items(): _test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.nodes.FindPrims User test case #{i+1}, instance{key}") async def test_data_access(self): from omni.graph.nodes.ogn.OgnFindPrimsDatabase import OgnFindPrimsDatabase test_file_name = "OgnFindPrimsTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_FindPrims") database = OgnFindPrimsDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 2) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:ignoreSystemPrims")) attribute = test_node.get_attribute("inputs:ignoreSystemPrims") db_value = database.inputs.ignoreSystemPrims expected_value = False actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:namePrefix")) attribute = test_node.get_attribute("inputs:namePrefix") db_value = database.inputs.namePrefix expected_value = "" actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:pathPattern")) attribute = test_node.get_attribute("inputs:pathPattern") db_value = database.inputs.pathPattern expected_value = "" actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:recursive")) attribute = test_node.get_attribute("inputs:recursive") db_value = database.inputs.recursive expected_value = False actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:requiredAttributes")) attribute = test_node.get_attribute("inputs:requiredAttributes") db_value = database.inputs.requiredAttributes expected_value = "" actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:requiredRelationship")) attribute = test_node.get_attribute("inputs:requiredRelationship") db_value = database.inputs.requiredRelationship expected_value = "" actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:requiredRelationshipTarget")) attribute = test_node.get_attribute("inputs:requiredRelationshipTarget") db_value = database.inputs.requiredRelationshipTarget expected_value = "" actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:requiredTarget")) attribute = test_node.get_attribute("inputs:requiredTarget") db_value = database.inputs.requiredTarget self.assertTrue(test_node.get_attribute_exists("inputs:rootPrim")) attribute = test_node.get_attribute("inputs:rootPrim") db_value = database.inputs.rootPrim self.assertTrue(test_node.get_attribute_exists("inputs:rootPrimPath")) attribute = test_node.get_attribute("inputs:rootPrimPath") db_value = database.inputs.rootPrimPath expected_value = "" actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:type")) attribute = test_node.get_attribute("inputs:type") db_value = database.inputs.type expected_value = "*" actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:primPaths")) attribute = test_node.get_attribute("outputs:primPaths") db_value = database.outputs.primPaths self.assertTrue(test_node.get_attribute_exists("outputs:prims")) attribute = test_node.get_attribute("outputs:prims") db_value = database.outputs.prims self.assertTrue(test_node.get_attribute_exists("state:ignoreSystemPrims")) attribute = test_node.get_attribute("state:ignoreSystemPrims") db_value = database.state.ignoreSystemPrims self.assertTrue(test_node.get_attribute_exists("state:inputType")) attribute = test_node.get_attribute("state:inputType") db_value = database.state.inputType self.assertTrue(test_node.get_attribute_exists("state:namePrefix")) attribute = test_node.get_attribute("state:namePrefix") db_value = database.state.namePrefix self.assertTrue(test_node.get_attribute_exists("state:pathPattern")) attribute = test_node.get_attribute("state:pathPattern") db_value = database.state.pathPattern self.assertTrue(test_node.get_attribute_exists("state:recursive")) attribute = test_node.get_attribute("state:recursive") db_value = database.state.recursive self.assertTrue(test_node.get_attribute_exists("state:requiredAttributes")) attribute = test_node.get_attribute("state:requiredAttributes") db_value = database.state.requiredAttributes self.assertTrue(test_node.get_attribute_exists("state:requiredRelationship")) attribute = test_node.get_attribute("state:requiredRelationship") db_value = database.state.requiredRelationship self.assertTrue(test_node.get_attribute_exists("state:requiredRelationshipTarget")) attribute = test_node.get_attribute("state:requiredRelationshipTarget") db_value = database.state.requiredRelationshipTarget self.assertTrue(test_node.get_attribute_exists("state:requiredTarget")) attribute = test_node.get_attribute("state:requiredTarget") db_value = database.state.requiredTarget self.assertTrue(test_node.get_attribute_exists("state:rootPrim")) attribute = test_node.get_attribute("state:rootPrim") db_value = database.state.rootPrim self.assertTrue(test_node.get_attribute_exists("state:rootPrimPath")) attribute = test_node.get_attribute("state:rootPrimPath") db_value = database.state.rootPrimPath
11,264
Python
49.743243
365
0.694158
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnCurveTubeST.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.nodes.ogn.OgnCurveTubeSTDatabase import OgnCurveTubeSTDatabase test_file_name = "OgnCurveTubeSTTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_CurveTubeST") database = OgnCurveTubeSTDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:cols")) attribute = test_node.get_attribute("inputs:cols") db_value = database.inputs.cols expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:curveVertexCounts")) attribute = test_node.get_attribute("inputs:curveVertexCounts") db_value = database.inputs.curveVertexCounts expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:curveVertexStarts")) attribute = test_node.get_attribute("inputs:curveVertexStarts") db_value = database.inputs.curveVertexStarts expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:scaleTLikeS")) attribute = test_node.get_attribute("inputs:scaleTLikeS") db_value = database.inputs.scaleTLikeS expected_value = False actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:t")) attribute = test_node.get_attribute("inputs:t") db_value = database.inputs.t expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:tubeQuadStarts")) attribute = test_node.get_attribute("inputs:tubeQuadStarts") db_value = database.inputs.tubeQuadStarts expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:tubeSTStarts")) attribute = test_node.get_attribute("inputs:tubeSTStarts") db_value = database.inputs.tubeSTStarts expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:width")) attribute = test_node.get_attribute("inputs:width") db_value = database.inputs.width expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:primvars:st")) attribute = test_node.get_attribute("outputs:primvars:st") db_value = database.outputs.primvars_st self.assertTrue(test_node.get_attribute_exists("outputs:primvars:st:indices")) attribute = test_node.get_attribute("outputs:primvars:st:indices") db_value = database.outputs.primvars_st_indices
5,437
Python
51.796116
92
0.691926
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnTimelineGet.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.nodes.ogn.OgnTimelineGetDatabase import OgnTimelineGetDatabase test_file_name = "OgnTimelineGetTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_GetTimeline") database = OgnTimelineGetDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("outputs:endFrame")) attribute = test_node.get_attribute("outputs:endFrame") db_value = database.outputs.endFrame self.assertTrue(test_node.get_attribute_exists("outputs:endTime")) attribute = test_node.get_attribute("outputs:endTime") db_value = database.outputs.endTime self.assertTrue(test_node.get_attribute_exists("outputs:frame")) attribute = test_node.get_attribute("outputs:frame") db_value = database.outputs.frame self.assertTrue(test_node.get_attribute_exists("outputs:framesPerSecond")) attribute = test_node.get_attribute("outputs:framesPerSecond") db_value = database.outputs.framesPerSecond self.assertTrue(test_node.get_attribute_exists("outputs:isLooping")) attribute = test_node.get_attribute("outputs:isLooping") db_value = database.outputs.isLooping self.assertTrue(test_node.get_attribute_exists("outputs:isPlaying")) attribute = test_node.get_attribute("outputs:isPlaying") db_value = database.outputs.isPlaying self.assertTrue(test_node.get_attribute_exists("outputs:startFrame")) attribute = test_node.get_attribute("outputs:startFrame") db_value = database.outputs.startFrame self.assertTrue(test_node.get_attribute_exists("outputs:startTime")) attribute = test_node.get_attribute("outputs:startTime") db_value = database.outputs.startTime self.assertTrue(test_node.get_attribute_exists("outputs:time")) attribute = test_node.get_attribute("outputs:time") db_value = database.outputs.time
3,183
Python
46.522387
92
0.699969
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnCreateTubeTopology.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:rows', [1, 2, 3], False], ['inputs:cols', [2, 3, 4], False], ], 'outputs': [ ['outputs:faceVertexCounts', [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4], False], ['outputs:faceVertexIndices', [0, 1, 3, 2, 1, 0, 2, 3, 4, 5, 8, 7, 5, 6, 9, 8, 6, 4, 7, 9, 7, 8, 11, 10, 8, 9, 12, 11, 9, 7, 10, 12, 13, 14, 18, 17, 14, 15, 19, 18, 15, 16, 20, 19, 16, 13, 17, 20, 17, 18, 22, 21, 18, 19, 23, 22, 19, 20, 24, 23, 20, 17, 21, 24, 21, 22, 26, 25, 22, 23, 27, 26, 23, 24, 28, 27, 24, 21, 25, 28], False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_CreateTubeTopology", "omni.graph.nodes.CreateTubeTopology", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.CreateTubeTopology User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_CreateTubeTopology","omni.graph.nodes.CreateTubeTopology", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.CreateTubeTopology User test case #{i+1}", 16) async def test_thread_safety(self): import omni.kit # Generate multiple instances of the test setup to run them concurrently instance_setup = dict() for n in range(24): instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) for (key, test_info) in instance_setup.items(): test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_nodes_CreateTubeTopology", "omni.graph.nodes.CreateTubeTopology", test_run, test_info) self.assertEqual(len(og.get_all_graphs()), 24) # We want to evaluate all graphs concurrently. Kick them all. # Evaluate multiple times to skip 2 serial frames and increase chances for a race condition. for _ in range(10): await omni.kit.app.get_app().next_update_async() for (key, test_instance) in instance_setup.items(): _test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.nodes.CreateTubeTopology User test case #{i+1}, instance{key}") async def test_data_access(self): from omni.graph.nodes.ogn.OgnCreateTubeTopologyDatabase import OgnCreateTubeTopologyDatabase test_file_name = "OgnCreateTubeTopologyTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_CreateTubeTopology") database = OgnCreateTubeTopologyDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:cols")) attribute = test_node.get_attribute("inputs:cols") db_value = database.inputs.cols expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:rows")) attribute = test_node.get_attribute("inputs:rows") db_value = database.inputs.rows expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:faceVertexCounts")) attribute = test_node.get_attribute("outputs:faceVertexCounts") db_value = database.outputs.faceVertexCounts self.assertTrue(test_node.get_attribute_exists("outputs:faceVertexIndices")) attribute = test_node.get_attribute("outputs:faceVertexIndices") db_value = database.outputs.faceVertexIndices
5,763
Python
52.869158
349
0.661635
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnRandomNumeric.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:useSeed', True, False], ['inputs:seed', 6649909271, False], ['inputs:min', {'type': 'uint', 'value': 0}, False], ['inputs:max', {'type': 'uint', 'value': 4294967295}, False], ['inputs:execIn', 1, False], ['inputs:isNoise', True, False], ], 'outputs': [ ['outputs:random', {'type': 'uint', 'value': 0}, False], ['outputs:execOut', 1, False], ], }, { 'inputs': [ ['inputs:useSeed', True, False], ['inputs:seed', 6159018942, False], ['inputs:min', {'type': 'uint[]', 'value': [0, 100]}, False], ['inputs:max', {'type': 'uint', 'value': 4294967295}, False], ['inputs:execIn', 1, False], ['inputs:isNoise', True, False], ], 'outputs': [ ['outputs:random', {'type': 'uint[]', 'value': [2147483648, 2160101208]}, False], ['outputs:execOut', 1, False], ], }, { 'inputs': [ ['inputs:useSeed', True, False], ['inputs:seed', 3280530163, False], ['inputs:min', {'type': 'uint', 'value': 0}, False], ['inputs:max', {'type': 'uint[]', 'value': [4294967295, 199]}, False], ['inputs:execIn', 1, False], ['inputs:isNoise', True, False], ], 'outputs': [ ['outputs:random', {'type': 'uint[]', 'value': [4294967295, 19]}, False], ['outputs:execOut', 1, False], ], }, { 'inputs': [ ['inputs:useSeed', True, False], ['inputs:seed', 6159018942, False], ['inputs:min', {'type': 'int', 'value': -2147483648}, False], ['inputs:max', {'type': 'int', 'value': 2147483647}, False], ['inputs:execIn', 1, False], ['inputs:isNoise', True, False], ], 'outputs': [ ['outputs:random', {'type': 'int', 'value': 0}, False], ['outputs:execOut', 1, False], ], }, { 'inputs': [ ['inputs:useSeed', True, False], ['inputs:seed', 6649909271, False], ['inputs:min', {'type': 'int[2]', 'value': [-2147483648, -100]}, False], ['inputs:max', {'type': 'int', 'value': 2147483647}, False], ['inputs:execIn', 1, False], ['inputs:isNoise', True, False], ], 'outputs': [ ['outputs:random', {'type': 'int[2]', 'value': [-2147483648, 1629773655]}, False], ['outputs:execOut', 1, False], ], }, { 'inputs': [ ['inputs:useSeed', True, False], ['inputs:seed', 3280530163, False], ['inputs:min', {'type': 'int', 'value': -2147483648}, False], ['inputs:max', {'type': 'int[2]', 'value': [2147483647, 99]}, False], ['inputs:execIn', 1, False], ['inputs:isNoise', True, False], ], 'outputs': [ ['outputs:random', {'type': 'int[2]', 'value': [2147483647, -2146948710]}, False], ['outputs:execOut', 1, False], ], }, { 'inputs': [ ['inputs:useSeed', True, False], ['inputs:seed', 8280086, False], ['inputs:min', {'type': 'float', 'value': 0}, False], ['inputs:max', {'type': 'float', 'value': 1}, False], ['inputs:execIn', 1, False], ['inputs:isNoise', True, False], ], 'outputs': [ ['outputs:random', {'type': 'float', 'value': 0}, False], ['outputs:execOut', 1, False], ], }, { 'inputs': [ ['inputs:useSeed', True, False], ['inputs:seed', 17972581, False], ['inputs:min', {'type': 'float[]', 'value': [0, -10]}, False], ['inputs:max', {'type': 'float', 'value': 1}, False], ['inputs:execIn', 1, False], ['inputs:isNoise', True, False], ], 'outputs': [ ['outputs:random', {'type': 'float[]', 'value': [0.5, -6.7663326]}, False], ['outputs:execOut', 1, False], ], }, { 'inputs': [ ['inputs:useSeed', True, False], ['inputs:seed', 15115159, False], ['inputs:min', {'type': 'float', 'value': 0}, False], ['inputs:max', {'type': 'float[]', 'value': [1, 10]}, False], ['inputs:execIn', 1, False], ['inputs:isNoise', True, False], ], 'outputs': [ ['outputs:random', {'type': 'float[]', 'value': [0.9999999403953552, 4.0452986]}, False], ['outputs:execOut', 1, False], ], }, { 'inputs': [ ['inputs:useSeed', True, False], ['inputs:seed', 14092058508772706262, False], ['inputs:min', {'type': 'uint64', 'value': 0}, False], ['inputs:max', {'type': 'uint64', 'value': 18446744073709551615}, False], ['inputs:execIn', 1, False], ['inputs:isNoise', True, False], ], 'outputs': [ ['outputs:random', {'type': 'uint64', 'value': 0}, False], ['outputs:execOut', 1, False], ], }, { 'inputs': [ ['inputs:useSeed', True, False], ['inputs:seed', 9302349107990861236, False], ['inputs:min', {'type': 'uint64', 'value': 0}, False], ['inputs:max', {'type': 'uint64', 'value': 18446744073709551615}, False], ['inputs:execIn', 1, False], ['inputs:isNoise', True, False], ], 'outputs': [ ['outputs:random', {'type': 'uint64', 'value': 9223372036854775808}, False], ['outputs:execOut', 1, False], ], }, { 'inputs': [ ['inputs:useSeed', True, False], ['inputs:seed', 1955209015103813879, False], ['inputs:min', {'type': 'uint64', 'value': 0}, False], ['inputs:max', {'type': 'uint64', 'value': 18446744073709551615}, False], ['inputs:execIn', 1, False], ['inputs:isNoise', True, False], ], 'outputs': [ ['outputs:random', {'type': 'uint64', 'value': 18446744073709551615}, False], ['outputs:execOut', 1, False], ], }, { 'inputs': [ ['inputs:useSeed', True, False], ['inputs:seed', 123456789, False], ['inputs:min', {'type': 'uint64', 'value': 1099511627776}, False], ['inputs:max', {'type': 'uint64', 'value': 1125899906842624}, False], ['inputs:execIn', 1, False], ['inputs:isNoise', True, False], ], 'outputs': [ ['outputs:random', {'type': 'uint64', 'value': 923489197424953}, False], ['outputs:execOut', 1, False], ], }, { 'inputs': [ ['inputs:useSeed', True, False], ['inputs:seed', 1955209015103813879, False], ['inputs:min', {'type': 'double[2][]', 'value': [[0, -10], [10, 0]]}, False], ['inputs:max', {'type': 'double', 'value': 1}, False], ['inputs:execIn', 1, False], ['inputs:isNoise', True, False], ], 'outputs': [ ['outputs:random', {'type': 'double[2][]', 'value': [[0, 0.28955788], [7.98645811, 0.09353537]]}, False], ['outputs:execOut', 1, False], ], }, { 'inputs': [ ['inputs:useSeed', True, False], ['inputs:seed', 123456789, False], ['inputs:min', {'type': 'half[]', 'value': [0, -100]}, False], ['inputs:max', {'type': 'half[]', 'value': [1, 100]}, False], ['inputs:execIn', 1, False], ['inputs:isNoise', True, False], ], 'outputs': [ ['outputs:random', {'type': 'half[]', 'value': [0.17993164, -76.375]}, False], ['outputs:execOut', 1, False], ], }, { 'inputs': [ ['inputs:useSeed', True, False], ['inputs:seed', 0, False], ['inputs:min', {'type': 'uchar[]', 'value': [0, 100]}, False], ['inputs:max', {'type': 'uchar[]', 'value': [255, 200]}, False], ['inputs:execIn', 1, False], ['inputs:isNoise', True, False], ], 'outputs': [ ['outputs:random', {'type': 'uchar[]', 'value': [153, 175]}, False], ['outputs:execOut', 1, False], ], }, { 'inputs': [ ['inputs:useSeed', True, False], ['inputs:seed', 9302349107990861236, False], ['inputs:execIn', 1, False], ['inputs:isNoise', True, False], ], 'outputs': [ ['outputs:random', {'type': 'double', 'value': 0.5}, False], ['outputs:execOut', 1, False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_RandomNumeric", "omni.graph.nodes.RandomNumeric", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.RandomNumeric User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_RandomNumeric","omni.graph.nodes.RandomNumeric", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.RandomNumeric User test case #{i+1}", 16) async def test_thread_safety(self): import omni.kit # Generate multiple instances of the test setup to run them concurrently instance_setup = dict() for n in range(24): instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) for (key, test_info) in instance_setup.items(): test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_nodes_RandomNumeric", "omni.graph.nodes.RandomNumeric", test_run, test_info) self.assertEqual(len(og.get_all_graphs()), 24) # We want to evaluate all graphs concurrently. Kick them all. # Evaluate multiple times to skip 2 serial frames and increase chances for a race condition. for _ in range(10): await omni.kit.app.get_app().next_update_async() for (key, test_instance) in instance_setup.items(): _test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.nodes.RandomNumeric User test case #{i+1}, instance{key}") async def test_data_access(self): from omni.graph.nodes.ogn.OgnRandomNumericDatabase import OgnRandomNumericDatabase test_file_name = "OgnRandomNumericTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_RandomNumeric") database = OgnRandomNumericDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:execIn")) attribute = test_node.get_attribute("inputs:execIn") db_value = database.inputs.execIn self.assertTrue(test_node.get_attribute_exists("inputs:isNoise")) attribute = test_node.get_attribute("inputs:isNoise") db_value = database.inputs.isNoise expected_value = False actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:useSeed")) attribute = test_node.get_attribute("inputs:useSeed") db_value = database.inputs.useSeed expected_value = False actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:execOut")) attribute = test_node.get_attribute("outputs:execOut") db_value = database.outputs.execOut self.assertTrue(test_node.get_attribute_exists("state:gen")) attribute = test_node.get_attribute("state:gen") db_value = database.state.gen
15,030
Python
43.602374
199
0.499135
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnGatherByPath.py
import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts import os class TestOgn(ogts.OmniGraphTestCase): async def test_generated(self): test_data = [{'inputs': [['inputs:primPaths', ['/Xform1', '/Xform2'], False], ['inputs:attributes', '_translate', False], ['inputs:allAttributes', False, False]], 'outputs': [['outputs:gatheredPaths', ['/Xform1', '/Xform2'], False], ['outputs:gatherId', 1, False]], 'setup': {'create_nodes': [['TestNode', 'omni.graph.nodes.GatherByPath']], 'create_prims': [['Empty', {}], ['Xform1', {'_translate': ['pointd[3]', [1, 2, 3]]}], ['Xform2', {'_translate': ['pointd[3]', [4, 5, 6]]}], ['XformTagged1', {'foo': ['token', ''], '_translate': ['pointd[3]', [1, 2, 3]]}], ['Tagged1', {'foo': ['token', '']}]]}}, {'inputs': [['inputs:primPaths', ['/XformTagged1', '/Xform2', '/Xform1'], False], ['inputs:attributes', '_translate', False], ['inputs:allAttributes', False, False]], 'outputs': [['outputs:gatheredPaths', ['/XformTagged1', '/Xform1', '/Xform2'], False]], 'setup': {}}] test_node = None test_graph = None for i, test_run in enumerate(test_data): inputs = test_run.get('inputs', []) outputs = test_run.get('outputs', []) state_set = test_run.get('state_set', []) state_get = test_run.get('state_get', []) setup = test_run.get('setup', None) if setup is None or setup: await omni.usd.get_context().new_stage_async() test_graph = None elif not setup: self.assertTrue(test_graph is not None and test_graph.is_valid(), "Test is misconfigured - empty setup cannot be in the first test") if setup: (test_graph, test_nodes, _, _) = og.Controller.edit("/TestGraph", setup) self.assertTrue(test_nodes) test_node = test_nodes[0] elif setup is None: if test_graph is None: test_graph = og.Controller.create_graph("/TestGraph") self.assertTrue(test_graph is not None and test_graph.is_valid()) test_node = og.Controller.create_node( ("TestNode_omni_graph_nodes_GatherByPath", test_graph), "omni.graph.nodes.GatherByPath" ) self.assertTrue(test_graph is not None and test_graph.is_valid(), "Test graph invalid") self.assertTrue(test_node is not None and test_node.is_valid(), "Test node invalid") await og.Controller.evaluate(test_graph) values_to_set = inputs + state_set if values_to_set: for attribute_name, attribute_value, _ in inputs + state_set: og.Controller((attribute_name, test_node)).set(attribute_value) await og.Controller.evaluate(test_graph) for attribute_name, expected_value, _ in outputs + state_get: attribute = og.Controller.attribute(attribute_name, test_node) actual_output = og.Controller.get(attribute) expected_type = None if isinstance(expected_value, dict): expected_type = expected_value["type"] expected_value = expected_value["value"] ogts.verify_values(expected_value, actual_output, f"omni.graph.nodes.GatherByPath User test case #{i+1}: {attribute_name} attribute value error") if expected_type: tp = og.AttributeType.type_from_ogn_type_name(expected_type) actual_type = attribute.get_resolved_type() if tp != actual_type: raise ValueError(f"omni.graph.nodes.GatherByPath User tests - {attribute_name}: Expected {expected_type}, saw {actual_type.get_ogn_type_name()}") async def test_data_access(self): from omni.graph.nodes.ogn.OgnGatherByPathDatabase import OgnGatherByPathDatabase test_file_name = "OgnGatherByPathTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_GatherByPath") database = OgnGatherByPathDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:allAttributes")) attribute = test_node.get_attribute("inputs:allAttributes") db_value = database.inputs.allAttributes expected_value = True actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:attributes")) attribute = test_node.get_attribute("inputs:attributes") db_value = database.inputs.attributes expected_value = "" actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:checkResyncAttributes")) attribute = test_node.get_attribute("inputs:checkResyncAttributes") db_value = database.inputs.checkResyncAttributes expected_value = False actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:forceExportToHistory")) attribute = test_node.get_attribute("inputs:forceExportToHistory") db_value = database.inputs.forceExportToHistory expected_value = False actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:hydraFastPath")) attribute = test_node.get_attribute("inputs:hydraFastPath") db_value = database.inputs.hydraFastPath expected_value = "Disabled" actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:primPaths")) attribute = test_node.get_attribute("inputs:primPaths") db_value = database.inputs.primPaths expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:shouldWriteBack")) attribute = test_node.get_attribute("inputs:shouldWriteBack") db_value = database.inputs.shouldWriteBack expected_value = False actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:gatherId")) attribute = test_node.get_attribute("outputs:gatherId") db_value = database.outputs.gatherId self.assertTrue(test_node.get_attribute_exists("outputs:gatheredPaths")) attribute = test_node.get_attribute("outputs:gatheredPaths") db_value = database.outputs.gatheredPaths
8,500
Python
60.158273
879
0.639529
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnReadPrimAttribute.py
import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.nodes.ogn.OgnReadPrimAttributeDatabase import OgnReadPrimAttributeDatabase (_, (test_node,), _, _) = og.Controller.edit("/TestGraph", { og.Controller.Keys.CREATE_NODES: ("Template_omni_graph_nodes_ReadPrimAttribute", "omni.graph.nodes.ReadPrimAttribute") }) database = OgnReadPrimAttributeDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 3) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:name")) attribute = test_node.get_attribute("inputs:name") db_value = database.inputs.name expected_value = "" ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:usdTimecode")) attribute = test_node.get_attribute("inputs:usdTimecode") db_value = database.inputs.usdTimecode expected_value = float("NaN") ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:usePath")) attribute = test_node.get_attribute("inputs:usePath") db_value = database.inputs.usePath expected_value = False ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("state:correctlySetup")) attribute = test_node.get_attribute("state:correctlySetup") db_value = database.state.correctlySetup self.assertTrue(test_node.get_attribute_exists("state:importPath")) attribute = test_node.get_attribute("state:importPath") db_value = database.state.importPath self.assertTrue(test_node.get_attribute_exists("state:srcAttrib")) attribute = test_node.get_attribute("state:srcAttrib") db_value = database.state.srcAttrib self.assertTrue(test_node.get_attribute_exists("state:srcPath")) attribute = test_node.get_attribute("state:srcPath") db_value = database.state.srcPath self.assertTrue(test_node.get_attribute_exists("state:srcPathAsToken")) attribute = test_node.get_attribute("state:srcPathAsToken") db_value = database.state.srcPathAsToken self.assertTrue(test_node.get_attribute_exists("state:time")) attribute = test_node.get_attribute("state:time") db_value = database.state.time
3,252
Python
46.838235
130
0.696187
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnMakeVector3.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:x', {'type': 'float', 'value': 42.0}, False], ['inputs:y', {'type': 'float', 'value': 1.0}, False], ['inputs:z', {'type': 'float', 'value': 0.0}, False], ], 'outputs': [ ['outputs:tuple', {'type': 'float[3]', 'value': [42.0, 1.0, 0.0]}, False], ], }, { 'inputs': [ ['inputs:x', {'type': 'float', 'value': 42.0}, False], ], 'outputs': [ ['outputs:tuple', {'type': 'float[3]', 'value': [42.0, 0.0, 0.0]}, False], ], }, { 'inputs': [ ['inputs:x', {'type': 'float[]', 'value': [42, 1, 0]}, False], ['inputs:y', {'type': 'float[]', 'value': [0, 1, 2]}, False], ['inputs:z', {'type': 'float[]', 'value': [0, 2, 4]}, False], ], 'outputs': [ ['outputs:tuple', {'type': 'float[3][]', 'value': [[42, 0, 0], [1, 1, 2], [0, 2, 4]]}, False], ], }, { 'inputs': [ ['inputs:x', {'type': 'int', 'value': 42}, False], ['inputs:y', {'type': 'int', 'value': -42}, False], ['inputs:z', {'type': 'int', 'value': 5}, False], ], 'outputs': [ ['outputs:tuple', {'type': 'int[3]', 'value': [42, -42, 5]}, False], ], }, { 'inputs': [ ['inputs:x', {'type': 'double', 'value': 42.0}, False], ['inputs:y', {'type': 'double', 'value': 1.0}, False], ['inputs:z', {'type': 'double', 'value': 0.0}, False], ], 'outputs': [ ['outputs:tuple', {'type': 'pointd[3]', 'value': [42.0, 1.0, 0.0]}, False], ], 'setup': {'create_nodes': [['TestNode', 'omni.graph.nodes.MakeVector3'], ['ConstPoint3d', 'omni.graph.nodes.ConstantPoint3d']], 'connect': [['TestNode.outputs:tuple', 'ConstPoint3d.inputs:value']]} }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_MakeVector3", "omni.graph.nodes.MakeVector3", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.MakeVector3 User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_MakeVector3","omni.graph.nodes.MakeVector3", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.MakeVector3 User test case #{i+1}", 16) async def test_thread_safety(self): import omni.kit # Generate multiple instances of the test setup to run them concurrently instance_setup = dict() for n in range(24): instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) for (key, test_info) in instance_setup.items(): test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_nodes_MakeVector3", "omni.graph.nodes.MakeVector3", test_run, test_info) self.assertEqual(len(og.get_all_graphs()), 24) # We want to evaluate all graphs concurrently. Kick them all. # Evaluate multiple times to skip 2 serial frames and increase chances for a race condition. for _ in range(10): await omni.kit.app.get_app().next_update_async() for (key, test_instance) in instance_setup.items(): _test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.nodes.MakeVector3 User test case #{i+1}, instance{key}") async def test_data_access(self): from omni.graph.nodes.ogn.OgnMakeVector3Database import OgnMakeVector3Database test_file_name = "OgnMakeVector3Template.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_MakeVector3") database = OgnMakeVector3Database(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
5,922
Python
47.950413
219
0.565181
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnMakeTransform.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:rotationXYZ', [0, 0, 0], False], ['inputs:translation', [0, 0, 0], False], ], 'outputs': [ ['outputs:transform', [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], False], ], }, { 'inputs': [ ['inputs:rotationXYZ', [0, 0, 0], False], ['inputs:translation', [1, 2, 3], False], ], 'outputs': [ ['outputs:transform', [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 2, 3, 1], False], ], }, { 'inputs': [ ['inputs:rotationXYZ', [20, 0, 30], False], ['inputs:translation', [1, -2, 3], False], ], 'outputs': [ ['outputs:transform', [0.866025404, 0.5, 4.16333634e-17, 0.0, -0.46984631, 0.813797681, 0.342020143, 0.0, 0.171010072, -0.296198133, 0.939692621, 0.0, 1.0, -2.0, 3.0, 1.0], False], ], }, { 'inputs': [ ['inputs:scale', [10, 5, 2], False], ], 'outputs': [ ['outputs:transform', [10, 0, 0, 0, 0, 5, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1], False], ], }, { 'inputs': [ ['inputs:translation', [1, -2, 3], False], ['inputs:rotationXYZ', [20, 0, 30], False], ['inputs:scale', [10, 5, 2], False], ], 'outputs': [ ['outputs:transform', [8.66025404, 5.0, 0.0, 0.0, -2.34923155, 4.06898841, 1.71010072, 0.0, 0.34202014, -0.59239627, 1.87938524, 0.0, 1.0, -2.0, 3.0, 1.0], False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_MakeTransform", "omni.graph.nodes.MakeTransform", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.MakeTransform User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_MakeTransform","omni.graph.nodes.MakeTransform", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.MakeTransform User test case #{i+1}", 16) async def test_thread_safety(self): import omni.kit # Generate multiple instances of the test setup to run them concurrently instance_setup = dict() for n in range(24): instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) for (key, test_info) in instance_setup.items(): test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_nodes_MakeTransform", "omni.graph.nodes.MakeTransform", test_run, test_info) self.assertEqual(len(og.get_all_graphs()), 24) # We want to evaluate all graphs concurrently. Kick them all. # Evaluate multiple times to skip 2 serial frames and increase chances for a race condition. for _ in range(10): await omni.kit.app.get_app().next_update_async() for (key, test_instance) in instance_setup.items(): _test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.nodes.MakeTransform User test case #{i+1}, instance{key}") async def test_data_access(self): from omni.graph.nodes.ogn.OgnMakeTransformDatabase import OgnMakeTransformDatabase test_file_name = "OgnMakeTransformTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_MakeTransform") database = OgnMakeTransformDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:rotationXYZ")) attribute = test_node.get_attribute("inputs:rotationXYZ") db_value = database.inputs.rotationXYZ expected_value = [0, 0, 0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:scale")) attribute = test_node.get_attribute("inputs:scale") db_value = database.inputs.scale expected_value = [1, 1, 1] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:translation")) attribute = test_node.get_attribute("inputs:translation") db_value = database.inputs.translation expected_value = [0, 0, 0] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:transform")) attribute = test_node.get_attribute("outputs:transform") db_value = database.outputs.transform
7,006
Python
46.99315
199
0.611476
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnCurveTubePositions.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.nodes.ogn.OgnCurveTubePositionsDatabase import OgnCurveTubePositionsDatabase test_file_name = "OgnCurveTubePositionsTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_CurveTubePositions") database = OgnCurveTubePositionsDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:cols")) attribute = test_node.get_attribute("inputs:cols") db_value = database.inputs.cols expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:curvePoints")) attribute = test_node.get_attribute("inputs:curvePoints") db_value = database.inputs.curvePoints expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:curveVertexCounts")) attribute = test_node.get_attribute("inputs:curveVertexCounts") db_value = database.inputs.curveVertexCounts expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:curveVertexStarts")) attribute = test_node.get_attribute("inputs:curveVertexStarts") db_value = database.inputs.curveVertexStarts expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:out")) attribute = test_node.get_attribute("inputs:out") db_value = database.inputs.out expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:tubePointStarts")) attribute = test_node.get_attribute("inputs:tubePointStarts") db_value = database.inputs.tubePointStarts expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:up")) attribute = test_node.get_attribute("inputs:up") db_value = database.inputs.up expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:width")) attribute = test_node.get_attribute("inputs:width") db_value = database.inputs.width expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:points")) attribute = test_node.get_attribute("outputs:points") db_value = database.outputs.points
5,214
Python
51.676767
100
0.691024
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnGetGatheredAttribute.py
import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts import os class TestOgn(ogts.OmniGraphTestCase): async def test_generated(self): test_data = [{'inputs': [['inputs:name', '_translate', False]], 'outputs': [['outputs:value', {'type': 'pointd[3][]', 'value': [[1, 2, 3], [4, 5, 6]]}, False]], 'setup': {'create_nodes': [['TestNode', 'omni.graph.nodes.GetGatheredAttribute'], ['GatherByPath', 'omni.graph.nodes.GatherByPath']], 'create_prims': [['Empty', {}], ['Xform1', {'_translate': ['pointd[3]', [1, 2, 3]]}], ['Xform2', {'_translate': ['pointd[3]', [4, 5, 6]]}], ['XformTagged1', {'foo': ['token', ''], '_translate': ['pointd[3]', [1, 2, 3]]}], ['Tagged1', {'foo': ['token', '']}]], 'connect': [['GatherByPath.outputs:gatherId', 'TestNode.inputs:gatherId']], 'set_values': [['GatherByPath.inputs:primPaths', ['/Xform1', '/Xform2']], ['GatherByPath.inputs:attributes', '_translate'], ['GatherByPath.inputs:allAttributes', False]]}}] test_node = None test_graph = None for i, test_run in enumerate(test_data): inputs = test_run.get('inputs', []) outputs = test_run.get('outputs', []) state_set = test_run.get('state_set', []) state_get = test_run.get('state_get', []) setup = test_run.get('setup', None) if setup is None or setup: await omni.usd.get_context().new_stage_async() test_graph = None elif not setup: self.assertTrue(test_graph is not None and test_graph.is_valid(), "Test is misconfigured - empty setup cannot be in the first test") if setup: (test_graph, test_nodes, _, _) = og.Controller.edit("/TestGraph", setup) self.assertTrue(test_nodes) test_node = test_nodes[0] elif setup is None: if test_graph is None: test_graph = og.Controller.create_graph("/TestGraph") self.assertTrue(test_graph is not None and test_graph.is_valid()) test_node = og.Controller.create_node( ("TestNode_omni_graph_nodes_GetGatheredAttribute", test_graph), "omni.graph.nodes.GetGatheredAttribute" ) self.assertTrue(test_graph is not None and test_graph.is_valid(), "Test graph invalid") self.assertTrue(test_node is not None and test_node.is_valid(), "Test node invalid") await og.Controller.evaluate(test_graph) values_to_set = inputs + state_set if values_to_set: for attribute_name, attribute_value, _ in inputs + state_set: og.Controller((attribute_name, test_node)).set(attribute_value) await og.Controller.evaluate(test_graph) for attribute_name, expected_value, _ in outputs + state_get: attribute = og.Controller.attribute(attribute_name, test_node) actual_output = og.Controller.get(attribute) expected_type = None if isinstance(expected_value, dict): expected_type = expected_value["type"] expected_value = expected_value["value"] ogts.verify_values(expected_value, actual_output, f"omni.graph.nodes.GetGatheredAttribute User test case #{i+1}: {attribute_name} attribute value error") if expected_type: tp = og.AttributeType.type_from_ogn_type_name(expected_type) actual_type = attribute.get_resolved_type() if tp != actual_type: raise ValueError(f"omni.graph.nodes.GetGatheredAttribute User tests - {attribute_name}: Expected {expected_type}, saw {actual_type.get_ogn_type_name()}") async def test_data_access(self): from omni.graph.nodes.ogn.OgnGetGatheredAttributeDatabase import OgnGetGatheredAttributeDatabase test_file_name = "OgnGetGatheredAttributeTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_GetGatheredAttribute") database = OgnGetGatheredAttributeDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:gatherId")) attribute = test_node.get_attribute("inputs:gatherId") db_value = database.inputs.gatherId expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:name")) attribute = test_node.get_attribute("inputs:name") db_value = database.inputs.name expected_value = "" actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
5,780
Python
62.527472
811
0.614879
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnLengthAlongCurve.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:curveVertexStarts', [0], False], ['inputs:curveVertexCounts', [4], False], ['inputs:curvePoints', [[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 4.0, 4.0], [12.0, 13.0, 4.0]], False], ['inputs:normalize', False, False], ], 'outputs': [ ['outputs:length', [0.0, 1.0, 6.0, 21.0], False], ], }, { 'inputs': [ ['inputs:curveVertexStarts', [0], False], ['inputs:curveVertexCounts', [3], False], ['inputs:curvePoints', [[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 1.0, 1.0]], False], ['inputs:normalize', True, False], ], 'outputs': [ ['outputs:length', [0.0, 0.5, 1.0], False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_LengthAlongCurve", "omni.graph.nodes.LengthAlongCurve", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.LengthAlongCurve User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_LengthAlongCurve","omni.graph.nodes.LengthAlongCurve", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.LengthAlongCurve User test case #{i+1}", 16) async def test_thread_safety(self): import omni.kit # Generate multiple instances of the test setup to run them concurrently instance_setup = dict() for n in range(24): instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) for (key, test_info) in instance_setup.items(): test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_nodes_LengthAlongCurve", "omni.graph.nodes.LengthAlongCurve", test_run, test_info) self.assertEqual(len(og.get_all_graphs()), 24) # We want to evaluate all graphs concurrently. Kick them all. # Evaluate multiple times to skip 2 serial frames and increase chances for a race condition. for _ in range(10): await omni.kit.app.get_app().next_update_async() for (key, test_instance) in instance_setup.items(): _test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.nodes.LengthAlongCurve User test case #{i+1}, instance{key}") async def test_data_access(self): from omni.graph.nodes.ogn.OgnLengthAlongCurveDatabase import OgnLengthAlongCurveDatabase test_file_name = "OgnLengthAlongCurveTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_LengthAlongCurve") database = OgnLengthAlongCurveDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:curvePoints")) attribute = test_node.get_attribute("inputs:curvePoints") db_value = database.inputs.curvePoints expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:curveVertexCounts")) attribute = test_node.get_attribute("inputs:curveVertexCounts") db_value = database.inputs.curveVertexCounts expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:curveVertexStarts")) attribute = test_node.get_attribute("inputs:curveVertexStarts") db_value = database.inputs.curveVertexStarts expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:normalize")) attribute = test_node.get_attribute("inputs:normalize") db_value = database.inputs.normalize expected_value = False actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:length")) attribute = test_node.get_attribute("outputs:length") db_value = database.outputs.length
6,622
Python
49.557252
205
0.657505
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnBundleInspector.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'outputs': [ ['outputs:count', 0, False], ['outputs:names', [], False], ['outputs:types', [], False], ['outputs:roles', [], False], ['outputs:arrayDepths', [], False], ['outputs:tupleCounts', [], False], ['outputs:values', [], False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_BundleInspector", "omni.graph.nodes.BundleInspector", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.BundleInspector User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_BundleInspector","omni.graph.nodes.BundleInspector", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.BundleInspector User test case #{i+1}", 16) async def test_data_access(self): from omni.graph.nodes.ogn.OgnBundleInspectorDatabase import OgnBundleInspectorDatabase test_file_name = "OgnBundleInspectorTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_BundleInspector") database = OgnBundleInspectorDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 3) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:bundle")) attribute = test_node.get_attribute("inputs:bundle") db_value = database.inputs.bundle self.assertTrue(test_node.get_attribute_exists("inputs:inspectDepth")) attribute = test_node.get_attribute("inputs:inspectDepth") db_value = database.inputs.inspectDepth expected_value = 1 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:print")) attribute = test_node.get_attribute("inputs:print") db_value = database.inputs.print expected_value = False actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:arrayDepths")) attribute = test_node.get_attribute("outputs:arrayDepths") db_value = database.outputs.arrayDepths self.assertTrue(test_node.get_attribute_exists("outputs:attributeCount")) attribute = test_node.get_attribute("outputs:attributeCount") db_value = database.outputs.attributeCount self.assertTrue(test_node.get_attribute_exists("outputs_bundle")) attribute = test_node.get_attribute("outputs_bundle") db_value = database.outputs.bundle self.assertTrue(test_node.get_attribute_exists("outputs:childCount")) attribute = test_node.get_attribute("outputs:childCount") db_value = database.outputs.childCount self.assertTrue(test_node.get_attribute_exists("outputs:count")) attribute = test_node.get_attribute("outputs:count") db_value = database.outputs.count self.assertTrue(test_node.get_attribute_exists("outputs:names")) attribute = test_node.get_attribute("outputs:names") db_value = database.outputs.names self.assertTrue(test_node.get_attribute_exists("outputs:roles")) attribute = test_node.get_attribute("outputs:roles") db_value = database.outputs.roles self.assertTrue(test_node.get_attribute_exists("outputs:tupleCounts")) attribute = test_node.get_attribute("outputs:tupleCounts") db_value = database.outputs.tupleCounts self.assertTrue(test_node.get_attribute_exists("outputs:types")) attribute = test_node.get_attribute("outputs:types") db_value = database.outputs.types self.assertTrue(test_node.get_attribute_exists("outputs:values")) attribute = test_node.get_attribute("outputs:values") db_value = database.outputs.values
6,031
Python
48.04065
184
0.666556
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnInterpolateTo.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): TEST_DATA = [ { 'inputs': [ ['inputs:current', {'type': 'float', 'value': 0.0}, False], ['inputs:target', {'type': 'float', 'value': 10.0}, False], ['inputs:deltaSeconds', 0.1, False], ], 'outputs': [ ['outputs:result', {'type': 'float', 'value': 1.9}, False], ], }, { 'inputs': [ ['inputs:current', {'type': 'double[3]', 'value': [0.0, 1.0, 2.0]}, False], ['inputs:target', {'type': 'double[3]', 'value': [10.0, 11.0, 12.0]}, False], ['inputs:deltaSeconds', 0.1, False], ], 'outputs': [ ['outputs:result', {'type': 'double[3]', 'value': [1.9, 2.9, 3.9]}, False], ], }, { 'inputs': [ ['inputs:current', {'type': 'float[]', 'value': [0.0, 1.0, 2.0]}, False], ['inputs:target', {'type': 'float[]', 'value': [10.0, 11.0, 12.0]}, False], ['inputs:deltaSeconds', 0.1, False], ], 'outputs': [ ['outputs:result', {'type': 'float[]', 'value': [1.9, 2.9, 3.9]}, False], ], }, { 'inputs': [ ['inputs:current', {'type': 'double[3][]', 'value': [[0.0, 1.0, 2.0], [0.0, 1.0, 2.0]]}, False], ['inputs:target', {'type': 'double[3][]', 'value': [[10.0, 11.0, 12.0], [10.0, 11.0, 12.0]]}, False], ['inputs:deltaSeconds', 0.1, False], ], 'outputs': [ ['outputs:result', {'type': 'double[3][]', 'value': [[1.9, 2.9, 3.9], [1.9, 2.9, 3.9]]}, False], ], }, { 'inputs': [ ['inputs:current', {'type': 'quatd[4]', 'value': [0, 0, 0, 1]}, False], ['inputs:target', {'type': 'quatd[4]', 'value': [0.7071068, 0, 0, 0.7071068]}, False], ['inputs:deltaSeconds', 0.5, False], ['inputs:exponent', 1, False], ], 'outputs': [ ['outputs:result', {'type': 'quatd[4]', 'value': [0.3826834, 0, 0, 0.9238795]}, False], ], }, { 'inputs': [ ['inputs:current', {'type': 'quatf[4]', 'value': [0, 0, 0, 1]}, False], ['inputs:target', {'type': 'quatf[4]', 'value': [0.7071068, 0, 0, 0.7071068]}, False], ['inputs:deltaSeconds', 0.5, False], ['inputs:exponent', 1, False], ], 'outputs': [ ['outputs:result', {'type': 'quatf[4]', 'value': [0.3826834, 0, 0, 0.9238795]}, False], ], }, { 'inputs': [ ['inputs:current', {'type': 'float[4]', 'value': [0, 0, 0, 1]}, False], ['inputs:target', {'type': 'float[4]', 'value': [0.7071068, 0, 0, 0.7071068]}, False], ['inputs:deltaSeconds', 0.5, False], ['inputs:exponent', 1, False], ], 'outputs': [ ['outputs:result', {'type': 'float[4]', 'value': [0.3535534, 0, 0, 0.8535534]}, False], ], }, ] async def test_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_InterpolateTo", "omni.graph.nodes.InterpolateTo", test_run, test_info) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.InterpolateTo User test case #{i+1}") async def test_vectorized_generated(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) test_info = await _test_setup_scene(self, controller, "/TestGraph", "TestNode_omni_graph_nodes_InterpolateTo","omni.graph.nodes.InterpolateTo", test_run, test_info, 16) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.InterpolateTo User test case #{i+1}", 16) async def test_thread_safety(self): import omni.kit # Generate multiple instances of the test setup to run them concurrently instance_setup = dict() for n in range(24): instance_setup[f"/TestGraph_{n}"] = _TestGraphAndNode() for i, test_run in enumerate(self.TEST_DATA): await _test_clear_scene(self, test_run) for (key, test_info) in instance_setup.items(): test_info = await _test_setup_scene(self, og.Controller(allow_exists_prim=True), key, "TestNode_omni_graph_nodes_InterpolateTo", "omni.graph.nodes.InterpolateTo", test_run, test_info) self.assertEqual(len(og.get_all_graphs()), 24) # We want to evaluate all graphs concurrently. Kick them all. # Evaluate multiple times to skip 2 serial frames and increase chances for a race condition. for _ in range(10): await omni.kit.app.get_app().next_update_async() for (key, test_instance) in instance_setup.items(): _test_verify_scene(self, og.Controller(), test_run, test_info, f"omni.graph.nodes.InterpolateTo User test case #{i+1}, instance{key}") async def test_data_access(self): from omni.graph.nodes.ogn.OgnInterpolateToDatabase import OgnInterpolateToDatabase test_file_name = "OgnInterpolateToTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_InterpolateTo") database = OgnInterpolateToDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 2) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:deltaSeconds")) attribute = test_node.get_attribute("inputs:deltaSeconds") db_value = database.inputs.deltaSeconds expected_value = 0.0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:exponent")) attribute = test_node.get_attribute("inputs:exponent") db_value = database.inputs.exponent expected_value = 2.0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:speed")) attribute = test_node.get_attribute("inputs:speed") db_value = database.inputs.speed expected_value = 1.0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
8,282
Python
47.723529
199
0.570514
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/ogn/tests/TestOgnRpResourceExampleDeformer.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.nodes.ogn.OgnRpResourceExampleDeformerDatabase import OgnRpResourceExampleDeformerDatabase test_file_name = "OgnRpResourceExampleDeformerTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_nodes_RpResourceExampleDeformer") database = OgnRpResourceExampleDeformerDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:deformScale")) attribute = test_node.get_attribute("inputs:deformScale") db_value = database.inputs.deformScale expected_value = 1.0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:displacementAxis")) attribute = test_node.get_attribute("inputs:displacementAxis") db_value = database.inputs.displacementAxis expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:pointCountCollection")) attribute = test_node.get_attribute("inputs:pointCountCollection") db_value = database.inputs.pointCountCollection expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:positionScale")) attribute = test_node.get_attribute("inputs:positionScale") db_value = database.inputs.positionScale expected_value = 1.0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:primPathCollection")) attribute = test_node.get_attribute("inputs:primPathCollection") db_value = database.inputs.primPathCollection expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:resourcePointerCollection")) attribute = test_node.get_attribute("inputs:resourcePointerCollection") db_value = database.inputs.resourcePointerCollection expected_value = [] actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:runDeformerKernel")) attribute = test_node.get_attribute("inputs:runDeformerKernel") db_value = database.inputs.runDeformerKernel expected_value = True actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:stream")) attribute = test_node.get_attribute("inputs:stream") db_value = database.inputs.stream expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:timeScale")) attribute = test_node.get_attribute("inputs:timeScale") db_value = database.inputs.timeScale expected_value = 0.01 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:verbose")) attribute = test_node.get_attribute("inputs:verbose") db_value = database.inputs.verbose expected_value = False actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:pointCountCollection")) attribute = test_node.get_attribute("outputs:pointCountCollection") db_value = database.outputs.pointCountCollection self.assertTrue(test_node.get_attribute_exists("outputs:primPathCollection")) attribute = test_node.get_attribute("outputs:primPathCollection") db_value = database.outputs.primPathCollection self.assertTrue(test_node.get_attribute_exists("outputs:reload")) attribute = test_node.get_attribute("outputs:reload") db_value = database.outputs.reload self.assertTrue(test_node.get_attribute_exists("outputs:resourcePointerCollection")) attribute = test_node.get_attribute("outputs:resourcePointerCollection") db_value = database.outputs.resourcePointerCollection self.assertTrue(test_node.get_attribute_exists("outputs:stream")) attribute = test_node.get_attribute("outputs:stream") db_value = database.outputs.stream self.assertTrue(test_node.get_attribute_exists("state:sequenceCounter")) attribute = test_node.get_attribute("state:sequenceCounter") db_value = database.state.sequenceCounter
7,336
Python
53.348148
114
0.705153
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/_impl/extension.py
"""Support required by the Carbonite extension loader - no visible API exists.""" from contextlib import suppress import omni.ext from omni.graph.nodes.bindings._omni_graph_nodes import acquire_interface as _acquire_interface from omni.graph.nodes.bindings._omni_graph_nodes import release_interface as _release_interface __all__ = [] """This module has no public API""" class _PublicExtension(omni.ext.IExt): """Object that tracks the lifetime of the Python part of the extension loading""" def __init__(self): super().__init__() self.__interface = None with suppress(ImportError): import omni.kit.app # noqa: PLW0621 app = omni.kit.app.get_app() manager = app.get_extension_manager() # This is a bit of a hack to make the template directory visible to the OmniGraph UI extension # if it happens to already be enabled. The "hack" part is that this logic really should be in # omni.graph.ui, but it would be much more complicated there, requiring management of extensions # that both do and do not have dependencies on omni.graph.ui. if manager.is_extension_enabled("omni.graph.ui"): import omni.graph.ui # noqa: PLW0621 omni.graph.ui.ComputeNodeWidget.get_instance().add_template_path(__file__) def on_startup(self): """Set up initial conditions for the Python part of the extension""" self.__interface = _acquire_interface() def on_shutdown(self): """Shutting down this part of the extension prepares it for hot reload""" if self.__interface is not None: _release_interface(self.__interface) self.__interface = None
1,754
Python
40.785713
108
0.657925
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/_impl/templates/template_omni.graph.nodes.ConstructArray.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 pathlib import Path import omni.graph.core as og import omni.ui as ui from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty from omni.kit.window.property.templates import HORIZONTAL_SPACING class CustomLayout: def __init__(self, compute_node_widget): self.enable = True self.compute_node_widget = compute_node_widget self.controller = og.Controller() self.add_button = None self.remove_button = None self.node_prim_path = self.compute_node_widget._payload[-1] self.node = self.controller.node(self.node_prim_path) def _retrieve_existing_inputs(self): # Retrieve all existing attributes of the form "inputs:input{num}" # Also find the largest suffix among all such attributes # Returned largest suffix = -1 if there are no such attributes input_attribs = [attrib for attrib in self.node.get_attributes() if attrib.get_name()[:12] == "inputs:input"] largest_suffix = -1 for attrib in input_attribs: largest_suffix = max(largest_suffix, int(attrib.get_name()[12:])) return (input_attribs, largest_suffix) def _on_click_add(self): (_, largest_suffix) = self._retrieve_existing_inputs() prev_attrib = self.node.get_attribute(f"inputs:input{largest_suffix}") self.controller.create_attribute( self.node, f"inputs:input{largest_suffix + 1}", "any", og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, None, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY, ).set_resolved_type(prev_attrib.get_resolved_type()) # Bump the array size if it can't accomodate the new input. array_size_attr = self.node.get_attribute("inputs:arraySize") array_size = array_size_attr.get() if array_size <= largest_suffix: array_size_attr.set(array_size + 1) self.remove_button.enabled = True self.compute_node_widget.rebuild_window() def _on_click_remove(self): (input_attribs, largest_suffix) = self._retrieve_existing_inputs() if not input_attribs: return attrib_to_remove = self.node.get_attribute(f"inputs:input{largest_suffix}") self.controller.remove_attribute(attrib_to_remove) self.remove_button.enabled = len(input_attribs) > 2 self.compute_node_widget.rebuild_window() def _controls_build_fn(self, *args): (input_attribs, _) = self._retrieve_existing_inputs() icons_path = Path(__file__).absolute().parent.parent.parent.parent.parent.parent.joinpath("icons") with ui.HStack(height=0, spacing=HORIZONTAL_SPACING): ui.Spacer() self.add_button = ui.Button( image_url=f"{icons_path.joinpath('add.svg')}", width=22, height=22, style={"Button": {"background_color": 0x1F2124}}, clicked_fn=self._on_click_add, tooltip_fn=lambda: ui.Label("Add New Input"), ) self.remove_button = ui.Button( image_url=f"{icons_path.joinpath('remove.svg')}", width=22, height=22, style={"Button": {"background_color": 0x1F2124}}, enabled=(len(input_attribs) > 1), clicked_fn=self._on_click_remove, tooltip_fn=lambda: ui.Label("Remove Input"), ) def apply(self, props): # Called by compute_node_widget to apply UI when selection changes def find_prop(name): return next((p for p in props if p.prop_name == name), None) frame = CustomLayoutFrame(hide_extra=True) (input_attribs, _) = self._retrieve_existing_inputs() with frame: with CustomLayoutGroup("Inputs"): prop = find_prop("inputs:arraySize") if prop is not None: CustomLayoutProperty(prop.prop_name) prop = find_prop("inputs:arrayType") if prop is not None: CustomLayoutProperty(prop.prop_name) for attrib in input_attribs: prop = find_prop(attrib.get_name()) if prop is not None: CustomLayoutProperty(prop.prop_name) CustomLayoutProperty(None, None, build_fn=self._controls_build_fn) prop = find_prop("outputs:array") if prop is not None: with CustomLayoutGroup("Outputs"): CustomLayoutProperty(prop.prop_name) return frame.apply(props)
5,150
Python
41.570248
117
0.615534
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/_impl/templates/template_omni.graph.core.WriteVariable.py
from omni.graph.ui.scripts.graph_variable_custom_layout import GraphVariableCustomLayout class CustomLayout(GraphVariableCustomLayout): _value_is_output = False
167
Python
26.999996
88
0.826347
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/scripts/ui_utils.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. # import string from pathlib import Path from typing import Callable import omni.graph.core as og import omni.ui as ui from omni.kit.window.property.templates import HORIZONTAL_SPACING __string_cache = [] def _get_attribute_ui_name(name: str) -> str: """ Takes a raw name and formats it for use as the corresponding nice name in the UI. o (For attribute names) Standard namespaces ('inputs', 'outputs', 'state') are stripped off the front. o (For attribute names) Any remaining namespaces are converted to words within the name. o Underscores are converted to spaces. o Mixed-case words are broken into separate words (e.g. 'primaryRGBColor' -> 'primary RGB Color'). o Words which are all lower-case are capitalized (e.g. 'primary' -> 'Primary'). """ # Replace '_' with ':' so they will be split name.replace("_", ":") # Split out namespaces words = name.split(":") # If the first namespace is one of our standard ones, get rid of it. if len(words) > 1 and words[0] in ("inputs", "outputs", "state"): words.pop(0) words_out = [] for word in words: # if word is all lower or all upper append it if word.islower() or word.isupper(): words_out.append(word) continue # Mixed case. # Lower-case followed by upper-case breaks between them. E.g. 'usdPrim' -> 'usd Prim' # Upper-case followed by lower-case breaks before them. E.g: 'USDPrim' -> 'USD Prim' # Combined example: abcDEFgHi -> abc DE Fg Hi sub_word = "" uppers = "" for c in word: if c.isupper(): if not uppers and sub_word: words_out.append(sub_word) sub_word = "" uppers += c else: if len(uppers) > 1: words_out.append(uppers[:-1]) sub_word += uppers[-1:] + c uppers = "" if sub_word: words_out.append(sub_word) elif uppers: words_out.append(uppers) # Title-case any words which are all lower case. return " ".join([word.title() if word.islower() else word for word in words_out]) def _get_string_permutation(n: int) -> str: """ Gets the name of the attribute at the given index, assuming the name is n-th permutation of the letters of the alphabet, starting from single characters. Args: n: the index of the permutation Return: str: the n-th string in lexicographical order. """ max_index = len(__string_cache) if max_index <= n: for i in range(max_index, n + 1): __string_cache.append(_convert_index_to_string_permutation(i + 1)) return __string_cache[n] def _convert_index_to_string_permutation(index: int) -> str: """Converts a 1-based index to an alphabetical string which is a permutation of the letters of the alphabet. For example: 1 = a 2 = b ... 26 = z 27 = aa 28 = ab ... Args: index: The number to convert to a string. Represents the index in the lexicographical sequence of generated strings. Returns: str: index'th string in lexicographic order. """ if index <= 0: return "" alphabet = list(string.ascii_lowercase) size = len(alphabet) result = "" while index > 0: r = index % size # noqa: S001 if r == 0: r = size index = (int)((index - r) / size) result += alphabet[r - 1] return result[::-1] def _retrieve_existing_numeric_dynamic_inputs(node: og.Node) -> tuple[list[og.Attribute], int]: """ Retrieves the node inputs which follow the 'inputs:input{num}' naming convention. Args: node: the node reflected in the property panel Return: ([og.Attribute], int): Tuple with the list of input attributes and the largest input index. """ # Retrieve all existing attributes of the form "inputs:input{num}" # Also find the largest suffix among all such attributes # Returned largest suffix = -1 if there are no such attributes input_attribs = [attrib for attrib in node.get_attributes() if attrib.get_name()[:12] == "inputs:input"] largest_suffix = -1 if not input_attribs: return ([], largest_suffix) for attrib in input_attribs: largest_suffix = max(largest_suffix, int(attrib.get_name()[12:])) return (input_attribs, largest_suffix) def _retrieve_existing_alphabetic_dynamic_inputs(node: og.Node) -> tuple[list[og.Attribute], int]: """ Retrieves the node inputs which follow the 'inputs:abc' naming convention. The sequence "abc" is a permutation of the letters of the alphabet, generated sequentially starting with single characters. Args: node: the node reflected in the property panel Return: ([og.Attribute], int): Tuple with the list of input attributes and the largest input index. """ # Retrieve all existing attributes of the form "inputs:abc # The sequence "abc" represents the n-th permutation of the letters of the alphabet, # starting from single characters input_attribs = [attrib for attrib in node.get_attributes() if attrib.get_name()[:7] == "inputs:"] if not input_attribs: return ([], -1) largest_index = len(input_attribs) - 1 return (input_attribs, largest_index) def _retrieve_existing_alphabetic_dynamic_outputs(node: og.Node) -> tuple[list[og.Attribute], int]: """ Retrieves the node outputs which follow the 'outputs:abc' naming convention. The sequence "abc" is a permutation of the letters of the alphabet, generated sequentially starting with single characters. Args: node: the node reflected in the property panel Return: ([og.Attribute], int): Tuple with the list of outputs attributes and the largest output index. """ # Retrieve all existing attributes of the form "outputs:abc # The sequence "abc" represents the n-th permutation of the letters of the alphabet, # starting from single characters output_attribs = [attrib for attrib in node.get_attributes() if attrib.get_name()[:8] == "outputs:"] if not output_attribs: return ([], -1) largest_index = len(output_attribs) - 1 return (output_attribs, largest_index) def _build_add_remove_buttons( layout, on_add_fn: Callable, on_remove_fn: Callable, on_remove_enabled_fn: Callable[[], bool] ): """ Creates the add (+) / remove (-) buttons for the property panel list control. Args: layout: the property panel layout instance on_add_fn: callback invoked when the add button is pushed on_remove_fn: callback invoked when the remove button is pushed on_remove_enabled_fn: callback invoked when creating the remove button to check if the button is enabled or not """ icons_path = Path(__file__).absolute().parent.parent.parent.parent.parent.joinpath("icons") with ui.HStack(height=0, spacing=HORIZONTAL_SPACING): ui.Spacer() layout.add_button = ui.Button( image_url=f"{icons_path.joinpath('add.svg')}", width=22, height=22, style={"Button": {"background_color": 0x1F2124}}, clicked_fn=on_add_fn, tooltip_fn=lambda: ui.Label("Add New Input"), ) layout.remove_button = ui.Button( image_url=f"{icons_path.joinpath('remove.svg')}", width=22, height=22, style={"Button": {"background_color": 0x1F2124}}, enabled=on_remove_enabled_fn(), clicked_fn=on_remove_fn, tooltip_fn=lambda: ui.Label("Remove Input"), )
8,212
Python
35.502222
124
0.636142
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/scripts/layer_identifier_widget_builder.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. # from enum import Enum, auto from typing import Dict, List, Mapping, Type, Union import carb.events import omni.client.utils as clientutils import omni.kit.usd.layers as layers import omni.ui as ui import omni.usd from omni.graph.ui import OmniGraphPropertiesWidgetBuilder, OmniGraphTfTokenAttributeModel from omni.kit.window.property.templates import HORIZONTAL_SPACING from pxr import Pcp, Sdf, Usd CURRENT_AUTHORING_LAYER_TAG = "<Current Authoring Layer>" SESSION_LAYER_TAG = "<Session Layer>" ROOT_LAYER_TAG = "<Root Layer>" INVALID_LAYER_TAG = "<Invalid Layer>" def get_strongest_opinion_layer_from_node(node: Pcp.NodeRef, attr_name: str): layer_stack = node.layerStack spec_path = node.path.AppendProperty(attr_name) for layer in layer_stack.layers: attr_spec = layer.GetAttributeAtPath(spec_path) if attr_spec and attr_spec.HasInfo("default"): return layer for child_node in node.children: layer = get_strongest_opinion_layer_from_node(child_node, attr_name) if layer: return layer return None def get_strongest_opinion_layer(stage: Usd.Stage, prim_path: Union[Sdf.Path, str], attr_name: str): prim = stage.GetPrimAtPath(prim_path) prim_index = prim.GetPrimIndex() return get_strongest_opinion_layer_from_node(prim_index.rootNode, attr_name) class LayerType(Enum): CURRENT_AUTHORING_LAYER = auto() SESSION_LAYER = auto() ROOT_LAYER = auto() OTHER = auto() INVALID = auto() class LayerItem(ui.AbstractItem): def __init__(self, layer: Union[Sdf.Layer, str], stage: Usd.Stage): super().__init__() self.layer = layer if layer is None: self.token = "" self.model = ui.SimpleStringModel(CURRENT_AUTHORING_LAYER_TAG) self.layer_type = LayerType.CURRENT_AUTHORING_LAYER else: prefix = "" suffix = "" if isinstance(layer, Sdf.Layer): if layer == stage.GetRootLayer(): self.layer_type = LayerType.ROOT_LAYER self.token = ROOT_LAYER_TAG suffix = f" {layer.identifier}" elif layer == stage.GetSessionLayer(): self.layer_type = LayerType.SESSION_LAYER self.token = SESSION_LAYER_TAG suffix = f" {layer.identifier}" else: self.layer_type = LayerType.OTHER # make the layer identifier relative to CURRENT EDIT TARGET layer self.token = clientutils.make_relative_url_if_possible( stage.GetEditTarget().GetLayer().realPath, layer.identifier ) elif isinstance(layer, str): self.token = layer self.layer_type = LayerType.INVALID prefix = f"{INVALID_LAYER_TAG} " self.model = ui.SimpleStringModel(prefix + self.token + suffix) class LayerModel(OmniGraphTfTokenAttributeModel): def __init__(self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], self_refresh: bool, metadata: dict): super().__init__(stage, attribute_paths, self_refresh, metadata) usd_context = omni.usd.get_context_from_stage(stage) self._layers = layers.get_layers(usd_context) self._layers_event_subscription = self._layers.get_event_stream().create_subscription_to_pop( self._on_layer_events, name="WritePrims Node Layers Model" ) def clean(self): self._layers_event_subscription = None super().clean() def _update_allowed_token(self, token_item=LayerItem): self._allowed_tokens = [ # noqa PLW0201 LayerItem(None, self._stage) ] # empty entry, meaning do not change target layer current_value_in_list = self._allowed_tokens[-1].token == self._value layer_stack = self._stage.GetLayerStack() for layer in layer_stack: self._allowed_tokens.append(LayerItem(layer, self._stage)) if not current_value_in_list and self._is_value_equal_url(self._allowed_tokens[-1]): current_value_in_list = True if not current_value_in_list: layer = self._get_value_strongest_layer() self._allowed_tokens.append( LayerItem(clientutils.make_absolute_url_if_possible(layer.realPath, self._value), self._stage) ) def _on_layer_events(self, event: carb.events.IEvent): payload = layers.get_layer_event_payload(event) if not payload: return if payload.event_type == layers.LayerEventType.SUBLAYERS_CHANGED: self._update_value(force=True) self._item_changed(None) def _update_index(self): index = -1 for i, token in enumerate(self._allowed_tokens): if self._is_value_equal_url(token): index = i break return index def _is_value_equal_url(self, layer_item: LayerItem) -> bool: if layer_item.layer_type == LayerType.CURRENT_AUTHORING_LAYER: return self._value == "" if layer_item.layer_type == LayerType.SESSION_LAYER: return self._value == SESSION_LAYER_TAG if layer_item.layer_type == LayerType.ROOT_LAYER: return self._value == ROOT_LAYER_TAG identifier = layer_item.layer if layer_item.layer_type == LayerType.INVALID else layer_item.layer.identifier layer = self._get_value_strongest_layer() return clientutils.make_absolute_url_if_possible( self._stage.GetEditTarget().GetLayer().realPath, identifier ) == clientutils.make_absolute_url_if_possible(layer.realPath, self._value) def _get_value_strongest_layer(self): attributes = self._get_attributes() # only process the last entry for now attr_path = attributes[-1].GetPath() prim_path = attr_path.GetPrimPath() attr_name = attr_path.name return get_strongest_opinion_layer(attributes[-1].GetStage(), prim_path, attr_name) class LayerIdentifierWidgetBuilder: @classmethod def build( cls, stage: Usd.Stage, attr_name: str, metadata: Mapping, property_type: Type, prim_paths: List[Sdf.Path], additional_label_kwargs: Dict = None, additional_widget_kwargs: Dict = None, ): with ui.HStack(spacing=HORIZONTAL_SPACING): label_kwargs = {} if additional_label_kwargs: label_kwargs.update(additional_label_kwargs) label = OmniGraphPropertiesWidgetBuilder.create_label(attr_name, metadata, label_kwargs) model = LayerModel(stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata) widget_kwargs = {"name": "choices"} if additional_widget_kwargs: widget_kwargs.update(additional_widget_kwargs) with ui.ZStack(): value_widget = ui.ComboBox(model, **widget_kwargs) mixed_overlay = OmniGraphPropertiesWidgetBuilder.create_mixed_text_overlay() OmniGraphPropertiesWidgetBuilder.create_control_state( model=model, value_widget=value_widget, mixed_overlay=mixed_overlay, **widget_kwargs, label=label ) return model
7,837
Python
39.402062
116
0.633406
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_read_prims_dirty_push.py
import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.test from pxr import Usd, UsdGeom class TestReadPrimsDirtyPush(ogts.OmniGraphTestCase): """Unit tests for dirty push behavior of the ReadPrimsV2 node in this extension""" async def test_read_prims_dirty_push(self): usd_context = omni.usd.get_context() stage: Usd.Stage = usd_context.get_stage() test_graph_path = "/World/TestGraph" controller = og.Controller() keys = og.Controller.Keys tree = UsdGeom.Xform.Define(stage, "/tree") branch = UsdGeom.Xform.Define(stage, "/tree/branch") leaf = ogts.create_cube(stage, "tree/branch/leaf", (1, 0, 0)) # Set initial values UsdGeom.XformCommonAPI(branch).SetTranslate((0, 0, 0)) leaf.GetAttribute("size").Set(1) (graph, [read_prims_node, _], _, _) = controller.edit( {"graph_path": test_graph_path, "evaluator_name": "dirty_push"}, { keys.CREATE_NODES: [ ("Read", "omni.graph.nodes.ReadPrimsV2"), ("Inspector", "omni.graph.nodes.BundleInspector"), ], keys.CONNECT: [ ("Read.outputs_primsBundle", "Inspector.inputs:bundle"), ], keys.SET_VALUES: [ ("Read.inputs:computeBoundingBox", True), ("Inspector.inputs:print", False), ], }, ) graph_context = graph.get_default_graph_context() bundle = None async def update_bundle(expected_child_count=1): nonlocal bundle await controller.evaluate() container = graph_context.get_output_bundle(read_prims_node, "outputs_primsBundle") self.assertTrue(container.valid) child_bundles = container.get_child_bundles() self.assertEqual(len(child_bundles), expected_child_count) bundle = child_bundles[0] if len(child_bundles) == 1 else None # Helpers def assert_bundle_attr(name, expected_value): attr = bundle.get_attribute_by_name(name) if expected_value is None: self.assertFalse(attr.is_valid()) else: actual_value = attr.get() if isinstance(expected_value, list): actual_value = actual_value.tolist() self.assertEqual(actual_value, expected_value) # Observe the branch omni.kit.commands.execute( "SetRelationshipTargets", relationship=stage.GetPropertyAtPath(f"{test_graph_path}/Read.inputs:prims"), targets=[branch.GetPath()], ) # Initial update await update_bundle() assert_bundle_attr("xformOp:translate", [0, 0, 0]) assert_bundle_attr("bboxMaxCorner", [0.5, 0.5, 0.5]) assert_bundle_attr("worldMatrix", [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]) # Change the USD stage on the branch (a tracked prim) UsdGeom.XformCommonAPI(branch).SetTranslate((1, 2, 3)) # The lazy node should compute await update_bundle() # Check the output bundle assert_bundle_attr("xformOp:translate", [1, 2, 3]) assert_bundle_attr("bboxMaxCorner", [1.5, 2.5, 3.5]) assert_bundle_attr("worldMatrix", [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 2, 3, 1]) # Change the leaf cube (a descendant of the tracked prim) leaf.GetAttribute("size").Set(2) # The lazy node should compute await update_bundle() assert_bundle_attr("xformOp:translate", [1, 2, 3]) assert_bundle_attr("bboxMaxCorner", [2.0, 3.0, 4.0]) assert_bundle_attr("worldMatrix", [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 2, 3, 1]) # Change the tree (an ancestor of the tracked prim) UsdGeom.XformCommonAPI(tree).SetTranslate((-1, -2, -3)) # The lazy node should compute await update_bundle() assert_bundle_attr("xformOp:translate", [1, 2, 3]) assert_bundle_attr("bboxMaxCorner", [1.0, 1.0, 1.0]) assert_bundle_attr("worldMatrix", [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]) # Create a new attribute on the tracked prim UsdGeom.XformCommonAPI(branch).SetScale((10, 10, 10)) # The lazy node should compute await update_bundle() assert_bundle_attr("xformOp:translate", [1, 2, 3]) assert_bundle_attr("xformOp:scale", [10, 10, 10]) assert_bundle_attr("bboxMaxCorner", [10.0, 10.0, 10.0]) assert_bundle_attr("worldMatrix", [10, 0, 0, 0, 0, 10, 0, 0, 0, 0, 10, 0, 0, 0, 0, 1]) # Delete the branch stage.RemovePrim(branch.GetPath()) # The lazy node should compute await update_bundle(0) self.assertEqual(bundle, None)
4,908
Python
37.054263
95
0.57172
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_omnigraph_utility_nodes.py
"""Test the node that inspects attribute bundles""" import omni.graph.core as og import omni.graph.core.tests as ogts import omni.graph.nodes.tests as ognts ROLES = [ "none", "vector", "normal", "point", "color", "texcoord", "quat", "transform", "frame", "timecode", "text", "appliedSchema", "prim", "execution", "matrix", "objectId", ] """Mapping of OGN role name to the AttributeRole index used in Type.h""" MATRIX_ROLES = ["frame", "transform", "matrix"] """Special roles that indicate a matrix type""" BASE_TYPES = [ "none", "bool", "uchar", "int", "uint", "int64", "uint64", "half", "float", "double", "token", ] """Mapping of raw OGN base type name to the BaseDataType index in Type.h""" # ====================================================================== class TestOmniGraphUtilityNodes(ogts.OmniGraphTestCase): """Run a simple unit test that exercises graph functionality""" # ---------------------------------------------------------------------- async def test_attr_type(self): """Test the AttrType node with some pre-made input bundle contents""" keys = og.Controller.Keys (_, [attr_type_node, _], [prim], _) = og.Controller.edit( "/TestGraph", { keys.CREATE_NODES: ("AttrTypeNode", "omni.graph.nodes.AttributeType"), keys.CREATE_PRIMS: ("TestPrim", ognts.prim_with_everything_definition()), keys.EXPOSE_PRIMS: (og.Controller.PrimExposureType.AS_BUNDLE, "/TestPrim", "TestPrimExtract"), keys.CONNECT: [ ("TestPrimExtract.outputs_primBundle", "AttrTypeNode.inputs:data"), ], }, ) await og.Controller.evaluate() (_, bundle_values) = ognts.get_bundle_with_all_results(str(prim.GetPrimPath())) name_attr = og.Controller.attribute("inputs:attrName", attr_type_node) type_attr = og.Controller.attribute("outputs:baseType", attr_type_node) tuple_count_attr = og.Controller.attribute("outputs:componentCount", attr_type_node) array_depth_attr = og.Controller.attribute("outputs:arrayDepth", attr_type_node) role_attr = og.Controller.attribute("outputs:role", attr_type_node) full_type_attr = og.Controller.attribute("outputs:fullType", attr_type_node) # Test data consisting of the input attrName followed by the expected output values test_data = [["notExisting", -1, -1, -1, -1]] for attribute_name, (type_name, tuple_count, array_depth, role, _) in bundle_values.items(): base_index = BASE_TYPES.index(type_name) role_index = ROLES.index(role) # Matrix types have 2d tuple counts if role_index in MATRIX_ROLES: tuple_count *= tuple_count test_data.append([attribute_name, base_index, tuple_count, array_depth, role_index]) for (name, base_type, tuple_count, array_depth, role) in test_data: og.Controller.set(name_attr, name) await og.Controller.evaluate() full_type = -1 if base_type >= 0: # This is the bitfield computation used in Type.h full_type = base_type + (tuple_count << 8) + (array_depth << 16) + (role << 24) self.assertEqual(base_type, og.Controller.get(type_attr), f"Type of {name}") self.assertEqual(tuple_count, og.Controller.get(tuple_count_attr), f"Tuple Count of {name}") self.assertEqual(array_depth, og.Controller.get(array_depth_attr), f"Array Depth of {name}") self.assertEqual(role, og.Controller.get(role_attr), f"Role of {name}") self.assertEqual(full_type, og.Controller.get(full_type_attr), f"Full type of {name}") # ---------------------------------------------------------------------- async def test_has_attr(self): """Test the HasAttr node with some pre-made input bundle contents""" keys = og.Controller.Keys (_, [has_attr_node, _], [prim], _) = og.Controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("HasAttrNode", "omni.graph.nodes.HasAttribute"), ], keys.CREATE_PRIMS: ("TestPrim", ognts.prim_with_everything_definition()), keys.EXPOSE_PRIMS: (og.Controller.PrimExposureType.AS_BUNDLE, "/TestPrim", "TestPrimExtract"), keys.CONNECT: [("TestPrimExtract.outputs_primBundle", "HasAttrNode.inputs:data")], }, ) await og.Controller.evaluate() expected_results = ognts.get_bundle_with_all_results(str(prim.GetPrimPath())) # Test data consisting of the input attrName followed by the expected output values test_data = [("notExisting", 0)] for name in expected_results[1].keys(): test_data.append((name, True)) name_attribute = og.Controller.attribute("inputs:attrName", has_attr_node) output_attribute = og.Controller.attribute("outputs:output", has_attr_node) for attribute_name, existence in test_data: og.Controller.set(name_attribute, attribute_name) await og.Controller.evaluate() self.assertEqual(existence, og.Controller.get(output_attribute), f"Has {attribute_name}") # ---------------------------------------------------------------------- async def test_get_attr_names(self): """Test the GetAttrNames node with some pre-made input bundle contents""" keys = og.Controller.Keys (_, [get_names_node, _], [prim], _) = og.Controller.edit( "/TestGraph", { keys.CREATE_NODES: ("GetAttrNamesNode", "omni.graph.nodes.GetAttributeNames"), keys.CREATE_PRIMS: ("TestPrim", ognts.prim_with_everything_definition()), keys.EXPOSE_PRIMS: (og.Controller.PrimExposureType.AS_BUNDLE, "/TestPrim", "TestPrimExtract"), keys.CONNECT: [ ("TestPrimExtract.outputs_primBundle", "GetAttrNamesNode.inputs:data"), ], }, ) await og.Controller.evaluate() (_, all_bundle_values) = ognts.get_bundle_with_all_results( str(prim.GetPrimPath()), prim_source_type=str(prim.GetTypeName()) ) attr_names = list(all_bundle_values.keys()) for is_sorted in [False, True]: og.Controller.set(("inputs:sort", get_names_node), is_sorted) await og.Controller.evaluate() actual_results = og.Controller.get(("outputs:output", get_names_node)) if is_sorted: self.assertEqual(sorted(attr_names), actual_results, "Comparing sorted lists") else: self.assertCountEqual(attr_names, actual_results, "Comparing unsorted lists") # ---------------------------------------------------------------------- async def test_array_length(self): """Test the ArrayLength node with some pre-made input bundle contents""" keys = og.Controller.Keys (_, [length_node, _], [prim], _) = og.Controller.edit( "/TestGraph", { keys.CREATE_NODES: ("ArrayLengthNode", "omni.graph.nodes.ArrayLength"), keys.CREATE_PRIMS: ("TestPrim", ognts.prim_with_everything_definition()), keys.EXPOSE_PRIMS: (og.Controller.PrimExposureType.AS_BUNDLE, "TestPrim", "TestPrimExtract"), keys.CONNECT: [ ("TestPrimExtract.outputs_primBundle", "ArrayLengthNode.inputs:data"), ], }, ) await og.Controller.evaluate() expected_results = ognts.get_bundle_with_all_results(str(prim.GetPrimPath())) # Test data consisting of the input attrName followed by the expected output values test_data = [("notExisting", 0)] for name, (_, _, array_length, _, value) in expected_results[1].items(): test_data.append((name, len(value) if array_length > 0 else 1)) name_attribute = og.Controller.attribute("inputs:attrName", length_node) output_attribute = og.Controller.attribute("outputs:length", length_node) for attribute_name, expected_length in test_data: og.Controller.set(name_attribute, attribute_name) await og.Controller.evaluate() self.assertEqual(expected_length, og.Controller.get(output_attribute), f"{attribute_name} array length") # ---------------------------------------------------------------------- async def test_copy_attr(self): """Test the CopyAttr node with some pre-made input bundle contents on the partialData input""" keys = og.Controller.Keys (_, [copy_node, inspector_node, _], [prim], _) = og.Controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("CopyAttrNode", "omni.graph.nodes.CopyAttribute"), ("Inspector", "omni.graph.nodes.BundleInspector"), ], keys.CREATE_PRIMS: ("TestPrim", ognts.prim_with_everything_definition()), keys.EXPOSE_PRIMS: (og.Controller.PrimExposureType.AS_BUNDLE, "/TestPrim", "TestPrimExtract"), keys.CONNECT: [ # Connect the same prim to both inputs to avoid the overhead of creating two prims ("TestPrimExtract.outputs_primBundle", "CopyAttrNode.inputs:fullData"), ("TestPrimExtract.outputs_primBundle", "CopyAttrNode.inputs:partialData"), ("CopyAttrNode.outputs_data", "Inspector.inputs:bundle"), ], }, ) await og.Controller.evaluate() input_names_attr = og.Controller.attribute("inputs:inputAttrNames", copy_node) output_names_attr = og.Controller.attribute("inputs:outputAttrNames", copy_node) expected_results = ognts.get_bundle_with_all_results( str(prim.GetPrimPath()), prim_source_type=str(prim.GetTypeName()) ) # Use sorted names so that the test is predictable sorted_names = sorted(expected_results[1].keys()) # Restrict to a small subset as a representative test old_names = sorted_names[0:3] new_names = [f"COPIED_{name}" for name in sorted_names[0:3]] copied_results = dict(expected_results[1].items()) copied_results.update( {f"COPIED_{key}": value for key, value in expected_results[1].items() if key in old_names} ) expected_copied_results = (expected_results[0] + len(old_names), copied_results) test_data = [ ("", "", expected_results), (old_names, new_names, expected_copied_results), ] for (to_copy, copied_to, expected_output) in test_data: og.Controller.set(input_names_attr, ",".join(to_copy)) og.Controller.set(output_names_attr, ",".join(copied_to)) await og.Controller.evaluate() results = ognts.bundle_inspector_results(inspector_node) try: # FIXME: OM-44667: Values do not get copied correctly. When they do, check_values=False can be removed ognts.verify_bundles_are_equal(results, expected_output, check_values=False) except ValueError as error: self.assertTrue(False, error) # ---------------------------------------------------------------------- async def test_rename_attr(self): """Test the RenameAttr node with some pre-made input bundle contents""" keys = og.Controller.Keys (_, [rename_node, inspector_node, _], [prim], _) = og.Controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("RenameAttrNode", "omni.graph.nodes.RenameAttribute"), ("Inspector", "omni.graph.nodes.BundleInspector"), ], keys.CREATE_PRIMS: ("TestPrim", ognts.prim_with_everything_definition()), keys.EXPOSE_PRIMS: (og.Controller.PrimExposureType.AS_BUNDLE, "/TestPrim", "TestPrimExtract"), keys.CONNECT: [ ("TestPrimExtract.outputs_primBundle", "RenameAttrNode.inputs:data"), ("RenameAttrNode.outputs_data", "Inspector.inputs:bundle"), ], keys.SET_VALUES: [ ("RenameAttrNode.inputs:inputAttrNames", ""), ("RenameAttrNode.inputs:outputAttrNames", ""), ], }, ) await og.Controller.evaluate() input_names_attr = og.Controller.attribute("inputs:inputAttrNames", rename_node) output_names_attr = og.Controller.attribute("inputs:outputAttrNames", rename_node) expected_results = ognts.get_bundle_with_all_results( str(prim.GetPrimPath()), prim_source_type=str(prim.GetTypeName()) ) # Use sorted names so that the test is predictable sorted_names = sorted(expected_results[1].keys()) # Restrict to a small subset as a representative test old_names = sorted_names[0:3] new_names = [f"RENAMED_{name}" for name in sorted_names[0:3]] renamed_results = {key: value for key, value in expected_results[1].items() if key not in old_names} renamed_results.update( {f"RENAMED_{key}": value for key, value in expected_results[1].items() if key in old_names} ) expected_renamed_results = (expected_results[0], renamed_results) test_data = [ ("", "", expected_results), (old_names, new_names, expected_renamed_results), ] for (to_rename, renamed_to, expected_output) in test_data: og.Controller.set(input_names_attr, ",".join(to_rename)) og.Controller.set(output_names_attr, ",".join(renamed_to)) await og.Controller.evaluate() results = ognts.bundle_inspector_results(inspector_node) try: # FIXME: OM-44667: Values do not get copied correctly. When they do, check_values=False can be removed ognts.verify_bundles_are_equal(results, expected_output, check_values=False) except ValueError as error: self.assertTrue(False, error) # ---------------------------------------------------------------------- async def test_remove_attr(self): """Test the RemoveAttr node with some pre-made input bundle contents""" keys = og.Controller.Keys (_, [remove_node, inspector_node, _], [prim], _) = og.Controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("RemoveAttrNode", "omni.graph.nodes.RemoveAttribute"), ("Inspector", "omni.graph.nodes.BundleInspector"), ], keys.CREATE_PRIMS: ("TestPrim", ognts.prim_with_everything_definition()), keys.EXPOSE_PRIMS: (og.Controller.PrimExposureType.AS_BUNDLE, "/TestPrim", "TestPrimExtract"), keys.CONNECT: [ ("TestPrimExtract.outputs_primBundle", "RemoveAttrNode.inputs:data"), ("RemoveAttrNode.outputs_data", "Inspector.inputs:bundle"), ], keys.SET_VALUES: [ ("RemoveAttrNode.inputs:attrNamesToRemove", ""), ], }, ) await og.Controller.evaluate() (expected_count, expected_results) = ognts.get_bundle_with_all_results( str(prim.GetPrimPath()), prim_source_type=str(prim.GetTypeName()) ) # Use sorted names so that the test is predictable sorted_names = sorted(expected_results.keys()) removal = [ sorted_names[0:2], sorted_names[3:6], ] test_data = [ ("", (expected_count, expected_results)), ( ",".join(removal[0]), ( expected_count - len(removal[0]), {key: value for key, value in expected_results.items() if key not in removal[0]}, ), ), ( ",".join(removal[1]), ( expected_count - len(removal[1]), {key: value for key, value in expected_results.items() if key not in removal[1]}, ), ), ] removal_attribute = og.Controller.attribute("inputs:attrNamesToRemove", remove_node) for (names, expected_output) in test_data: og.Controller.set(removal_attribute, names) await og.Controller.evaluate() results = ognts.bundle_inspector_results(inspector_node) try: # FIXME: OM-44667: Values do not get copied correctly. When they do, check_values=False can be removed ognts.verify_bundles_are_equal(results, expected_output, check_values=False) except ValueError as error: self.assertTrue(False, error) # ---------------------------------------------------------------------- async def test_insert_attr(self): """Test the InsertAttr node with some pre-made input bundle contents""" double_array = [(1.2, -1.2), (3.4, -5.6)] new_name = "newInsertedAttributeName" keys = og.Controller.Keys (_, [_, inspector_node, _], [prim], _) = og.Controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("InsertAttrNode", "omni.graph.nodes.InsertAttribute"), ("Inspector", "omni.graph.nodes.BundleInspector"), ], keys.CREATE_PRIMS: ("TestPrim", ognts.prim_with_everything_definition()), keys.EXPOSE_PRIMS: (og.Controller.PrimExposureType.AS_BUNDLE, "/TestPrim", "TestPrimExtract"), keys.CONNECT: [ ("TestPrimExtract.outputs_primBundle", "InsertAttrNode.inputs:data"), ("InsertAttrNode.outputs_data", "Inspector.inputs:bundle"), ], keys.SET_VALUES: [ ("InsertAttrNode.inputs:outputAttrName", new_name), ("InsertAttrNode.inputs:attrToInsert", double_array, "double[2][]"), ], }, ) await og.Controller.evaluate() results = ognts.bundle_inspector_results(inspector_node) (expected_count, expected_results) = ognts.get_bundle_with_all_results( str(prim.GetPrimPath()), prim_source_type=str(prim.GetTypeName()) ) expected_results[new_name] = ("double", 2, 1, "none", double_array) expected_values = (expected_count + 1, expected_results) try: # FIXME: OM-44667: The values do not get copied correctly. When they do, check_values=False can be removed ognts.verify_bundles_are_equal(results, expected_values, check_values=False) except ValueError as error: self.assertTrue(False, error) # ---------------------------------------------------------------------- async def test_extract_attr(self): """Test the ExtractAttr node with some pre-made input bundle contents""" keys = og.Controller.Keys (_, [extract_node, _, _], [prim], _) = og.Controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("ExtractAttrNode", "omni.graph.nodes.ExtractAttribute"), ("AddArray", "omni.graph.nodes.Add"), ], keys.CREATE_PRIMS: ("TestPrim", ognts.prim_with_everything_definition()), keys.EXPOSE_PRIMS: (og.Controller.PrimExposureType.AS_BUNDLE, "/TestPrim", "TestPrimExtract"), keys.CONNECT: [ ("TestPrimExtract.outputs_primBundle", "ExtractAttrNode.inputs:data"), ("ExtractAttrNode.outputs:output", "AddArray.inputs:a"), ], keys.SET_VALUES: [ ("ExtractAttrNode.inputs:attrName", "IntArrayAttr"), ], }, ) await og.Controller.evaluate() (_, expected_values) = ognts.get_bundle_with_all_results(str(prim.GetPrimPath())) self.assertCountEqual( expected_values["IntArrayAttr"][ognts.BundleResultKeys.VALUE_IDX], og.Controller.get(("outputs:output", extract_node)), ) # ---------------------------------------------------------------------- async def test_bundle_constructor(self): """Test simple operations in the BundleConstructor node. Only a minimal set of attribute types are tested here; just enough to confirm all code paths. The full test of all data types is done in a test node specially constructed for that purpose (OgnTestAllDataTypes) """ keys = og.Controller.Keys (_, [constructor_node, inspector_node], _, _) = og.Controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("Constructor", "omni.graph.nodes.BundleConstructor"), ("Inspector", "omni.graph.nodes.BundleInspector"), ], keys.CONNECT: ("Constructor.outputs_bundle", "Inspector.inputs:bundle"), }, ) await og.Controller.evaluate() empty_bundle_output = (0, {}) # Test data consists of a list of test configurations containing: # Parameters to create_attribute() for dynamic attribute to be added (None if no additions) # Parameters to remove_attribute() for dynamic attribute to be removed (None if no removals) # Expected dictionary of values from the inspector after evaluation of the constructor node test_data = [ # Initial state with an empty bundle [ None, None, empty_bundle_output, ], # Add a simple float[3] attribute [ { "attributeName": "xxx", "attributeType": og.AttributeType.type_from_ogn_type_name("float[3]"), "portType": og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, "value": [1.0, 2.0, 3.0], "extendedType": og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR, "unionTypes": "", }, None, # TODO: Should be [1,2,3] when dynamic attribute defaults work (1, {"xxx": ("float", 3, 0, "none", (0.0, 0.0, 0.0))}), ], # Remove the attribute that was just added to get back to empty [ None, {"attributeName": "inputs:xxx"}, empty_bundle_output, ], # Adding an "any" type that will not show up in the output bundle [ { "attributeName": "xxAny", "attributeType": og.AttributeType.type_from_ogn_type_name("any"), "portType": og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, "value": None, "extendedType": og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY, "unionTypes": "", }, None, empty_bundle_output, ], # Adding a "bundle" type that will not show up in the output bundle [ { "attributeName": "xxBundle", "attributeType": og.AttributeType.type_from_ogn_type_name("bundle"), "portType": og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, "value": None, "extendedType": og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR, "unionTypes": "", }, None, empty_bundle_output, ], # Adding an output float attribute that will not show up in the output bundle [ { "attributeName": "xxFloat", "attributeType": og.AttributeType.type_from_ogn_type_name("float"), "portType": og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT, "value": 5.0, "extendedType": og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR, "unionTypes": "", }, None, empty_bundle_output, ], # Adding a colord[3] and a float[] attribute, one at a time. [ { "attributeName": "xxColor", "attributeType": og.AttributeType.type_from_ogn_type_name("colord[3]"), "portType": og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, "value": [1.0, 2.0, 3.0], "extendedType": og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR, "unionTypes": "", }, None, # TODO: Should be [1.0, 2.0, 3.0] when dynamic attribute defaults work (1, {"xxColor": ("double", 3, 0, "color", (0.0, 0.0, 0.0))}), ], [ { "attributeName": "xxFloatArray", "attributeType": og.AttributeType.type_from_ogn_type_name("float[]"), "portType": og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, "value": [], "extendedType": og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR, "unionTypes": "", }, None, # TODO: Should be [1.0, 2.0, 3.0] when dynamic attribute defaults work ( 2, { "xxColor": ("double", 3, 0, "color", (0.0, 0.0, 0.0)), "xxFloatArray": ("float", 1, 1, "none", []), }, ), ], # Remove the colord[3] that was added before the remaining float[] attribute [ None, {"attributeName": "inputs:xxColor"}, (1, {"xxFloatArray": ("float", 1, 1, "none", [])}), ], ] for attribute_construction, attribute_removal, expected_results in test_data: if attribute_construction is not None: if attribute_construction[ "extendedType" ] == og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY or attribute_construction[ "attributeType" ].base_type in [ og.BaseDataType.RELATIONSHIP, ]: with ogts.ExpectedError(): constructor_node.create_attribute(**attribute_construction) else: constructor_node.create_attribute(**attribute_construction) if attribute_removal is not None: constructor_node.remove_attribute(**attribute_removal) await og.Controller.evaluate() # FIXME: OM-44667: Bug with the bundle copy means the full bundle doesn't come over with its values # Remove this when the bug is fixed. ignore = ["fullInt", "floatArray"] ignore = [] try: ognts.verify_bundles_are_equal( ognts.filter_bundle_inspector_results( ognts.bundle_inspector_results(inspector_node), ignore, filter_for_inclusion=False ), ognts.filter_bundle_inspector_results(expected_results, ignore, filter_for_inclusion=False), ) except ValueError as error: self.assertTrue(False, error)
28,187
Python
46.53457
119
0.539752
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/_1_15.py
"""Backward compatible module for omni.graph.nodes version 1.15. Revert your access to the earlier package to this version: import omni.graph.nodes._1_15 as on Or import both and cherry-pick which versions of specific APIs you want to use import omni.graph.nodes as on import omni.graph.nodes._1_15 as on1_15 if i_want_v1_15: on1_15.old_function() else: on.old_function() """ import ast import json from tempfile import NamedTemporaryFile from typing import Any, Dict, List, Optional, Tuple, Union from unittest import TestCase import omni.graph.core as og import omni.graph.core.tests as ogts import omni.graph.tools as ogt from omni.kit.app import get_app from pxr import Usd __all__ = [ "bundle_inspector_outputs", "bundle_inspector_values_as_dictionary", "compare_bundle_contents", "compare_bundle_inspector_results", "computed_bundle_values", "create_prim_with_everything", "graph_node_path", "inspected_bundle_values", "inspector_node_definition", "prim_node_definition", "set_up_test_stage", ] # ====================================================================== # Type of data coming from a bundle inspector output BundleInspectorOutputType = Tuple[int, List[str], List[str], List[str], List[int], List[int], List[Any]] # ====================================================================== # Attribute information for bundle inspector nodes BUNDLE_INSPECTOR_ATTRIBUTES = [ ("uint64", "outputs:count"), ("token[]", "outputs:names"), ("token[]", "outputs:types"), ("token[]", "outputs:roles"), ("int[]", "outputs:arrayDepths"), ("int[]", "outputs:tupleCounts"), ("token[]", "outputs:values"), ("bundle", "outputs_bundle"), ("bool", "inputs:print"), ] # ====================================================================== # Feed data for constructing sample data with all attribute types in it. This is a list of # (ATTRIBUTE_TYPE, ATTRIBUTE_SAMPLE_VALUE) that can be used to populate bundles. Tuple counts are # lifted from the sample value type information and arrays are constructed explicitly from this simple data. # (Be careful with the half values; they have lower resolution and are better tested in fractionaly powers of 2.) # fmt: off PRIM_SAMPLE_VALUES = [ ("int", 1), ("int64", 2), ("half", 3.5), ("float", 5.6), ("double", 7.8), ("bool", 1), ("token", "goofy"), ("uchar", 9), ("uint", 10), ("uint64", 11), ("int", (12, -13)), ("half", (14.5, -16.5)), ("float", (18.19, 20.21)), ("double", (22.23, 24.25)), ("int", (26, -27, 28)), ("half", (29.5, -31.5, 33.5)), ("float", (35.36, -37.38, 39.40)), ("double", (41.42, -43.44, 45.46)), ("int", (47, -48, 49, -50)), ("half", (51.5, -53.5, 55.5, -57.5)), ("float", (59.60, -61.62, 63.64, -65.66)), ("double", (67.68, -69.70, 71.72, -73.74)), ("quath", (75.5, -77.5, 79.5, -81.5)), ("quatf", (83.84, -85.86, 87.88, -89.90)), ("quatd", (91.92, -93.94, 95.96, -97.98)), ("matrixd", ((1.1, -1.2), (2.1, -2.2))), ("matrixd", ((1.1, -1.2, 1.3), (2.1, -2.2, 2.3), (3.1, -3.2, 3.3))), ("matrixd", ((1.1, -1.2, 1.3, 1.4), (2.1, -2.2, 2.3, -2.4), (3.1, -3.2, 3.3, -3.4), (4.1, -4.2, 4.3, -4.4))), ] # fmt: on # ====================================================================== # Data types used for the node description conversions (set as simple type definitions because you can differentiate # between the two of them just by checking size) PrimAttributeValueType = List[Union[Tuple[str, Any], Tuple[str, str, Any]]] OmniGraphNodeDefinitionType = Tuple[str, str, List[str], List[Tuple[str, str]]] PrimNodeDefinitionType = Tuple[str, Dict[str, Tuple[str, Any, int]]] # ====================================================================== @ogt.deprecated_function("Use og.Controller.create_prim()") def prim_node_definition(prim_name: str, data: PrimAttributeValueType, as_usd: bool = True) -> PrimNodeDefinitionType: """Returns the data as a USD definition compatible with what is needed for node definitions in set_up_test_stage Args: prim_name: Name of the prim to be defined data: List of prim attribute values. The members of the list come in two forms: (TYPE, VALUE) : Creates attributes and arrays of those attributes with names derived from the type roughly ("float", 3) -> "float floatAttr = 3.0", "float[] floatAttrArray = [3.0, 3.0, 3.0]" (TYPE, NAME, VALUE): Creates an attribute with the given name, type, and value roughly ("float", "myFloat", 3) -> "float myFloat = 3.0" as_usd: If True then create the definition with USD ordering (i.e. quaternions reordered) """ definition = {} for attribute_info in data: if len(attribute_info) == 2: (attribute_type, value) = attribute_info if isinstance(value, str) or (not isinstance(value, list) and not isinstance(value, tuple)): tuple_count = 1 attribute_name = f"{attribute_type}Attr" else: tuple_count = len(value) attribute_name = f"{attribute_type}{tuple_count}Attr" # In all of the user-facing data the quaternions are specified as I,J,K,R, however in the USD file and # quaternion constructor they expect R,I,J,K so reorder for consistency if as_usd and attribute_type.find("quat") == 0: the_value = (value[3], value[0], value[1], value[2]) else: the_value = value definition[attribute_name] = (f"{attribute_type}", the_value, False, tuple_count) definition[f"{attribute_name}Array"] = (f"{attribute_type}", [the_value] * 3, True, tuple_count) else: (attribute_type, attribute_name, value) = attribute_info is_array = False the_value = value if isinstance(value, str) or (not isinstance(value, list) and not isinstance(value, tuple)): tuple_count = 1 elif isinstance(value, list) and value: is_array = True if isinstance(value[0], str) or (not isinstance(value[0], list) and not isinstance(value[0], tuple)): tuple_count = 1 else: tuple_count = len(value[0]) # In all of the user-facing data the quaternions are specified as I,J,K,R, however in the USD file # and quaternion constructor they expect R,I,J,K so reorder for consistency if as_usd and attribute_type.find("quat") == 0: the_value = tuple((member[3], member[0], member[1], member[2]) for member in value) elif isinstance(value, tuple): tuple_count = len(value) # In all of the user-facing data the quaternions are specified as I,J,K,R, however in the USD file and # quaternion constructor they expect R,I,J,K so reorder for consistency if as_usd and attribute_type.find("quat") == 0: the_value = (value[3], value[0], value[1], value[2]) definition[attribute_name] = (f"{attribute_type}", the_value, is_array, tuple_count) return (prim_name, definition) # ====================================================================== @ogt.deprecated_function("Use og.Controller.create_prim()") def _write_usd_prim_definition(attribute_information: PrimNodeDefinitionType, out): """Write out a USD Prim definition using the attribute information Args: attribute_information: Tuple(prim_name, Dict of ATTRIBUTE_NAME: (USD_TYPE, USD_VALUE, TUPLE_COUNT)) e.g. a float[3] named foo defaulted to zeroes would be { "foo": ("float", [0.0, 0.0, 0.0], 3) } out: Output object to which the definition will be written """ out.write(f'def Output "{attribute_information[0]}"') if out.indent("{"): for attribute_name, (type_name, attribute_value, is_array, tuple_count) in attribute_information[1].items(): usd_type = ogt.usd_type_name(type_name, tuple_count, is_array) value = attribute_value if usd_type.startswith("token") or usd_type.startswith("string"): value = json.dumps(attribute_value) out.write(f"{usd_type} {attribute_name} = {value}") out.exdent("}") # ====================================================================== @ogt.deprecated_function("Use og.Controller.create_node()") def inspector_node_definition(node_name: str, source_bundle: str) -> Tuple[str, str, List[str]]: """Returns the entry in a node definition list for a bundle inspector node connected to the given source""" return ( node_name, "omni.graph.nodes.BundleInspector", [f"rel inputs:bundle = [<{source_bundle}>]"] + ogt.attributes_as_usd(BUNDLE_INSPECTOR_ATTRIBUTES), BUNDLE_INSPECTOR_ATTRIBUTES, ) # ====================================================================== @ogt.deprecated_function("Use omni.graph.nodes.test.bundle_inspector_results()") def inspected_bundle_values(bundle_data) -> List[Any]: """Returns a list of attribute values expected on the bundle inspector when applied to the bundle data. The list ordering should correspond to what is in BUNDLE_INSPECTOR_ATTRIBUTES, for efficiency. Args: bundle_data: Raw output of all the output attributes the bundle inspector provides """ names = [] type_names = [] role_names = [] array_flags = [] tuple_counts = [] values = [] # Sorting by name is the easiest way to produce a predictable ordering for the expected bundle values for name in sorted(bundle_data.keys()): (raw_type_name, value, is_array, tuple_count) = bundle_data[name] names.append(name) (type_name, role_name) = ogt.separate_ogn_role_and_type(raw_type_name) type_names.append(type_name) role_names.append(role_name) array_flags.append(is_array) tuple_counts.append(tuple_count * tuple_count if role_name in ["frame", "matrix", "transform"] else tuple_count) values.append(value) return [len(bundle_data), names, type_names, role_names, array_flags, tuple_counts, values] # ====================================================================== @ogt.deprecated_function("Use omni.graph.nodes.test.bundle_inspector_results()") def computed_bundle_values(inspector_attributes: List[Any]) -> BundleInspectorOutputType: """Returns attribute values computed from a bundle inspector in the same form as inspected_bundle_values Args: inspector_attributes: List of the Attribute objects on the node in the order of BUNDLE_INSPECTOR_ATTRIBUTES """ # Have to keep these separated because the first attribute is a single value while the rest are lists of strings size = og.Controller.get(inspector_attributes[0]) if size == 0: return (0, [], [], [], [], [], []) results = [] for attribute_index in range(1, 7): attribute_values = og.Controller.get(inspector_attributes[attribute_index]) if attribute_index == 6: # Bundled values are formatted as strings but are actually a mixture of types attribute_values = [ ast.literal_eval(value) if value != "__unsupported__" else "__unsupported__" for value in attribute_values ] results.append(attribute_values) # If these aren't sorted it will be more difficult to compare them zipped = list(zip(results[0], results[1], results[2], results[3], results[4], results[5])) zipped.sort() results = list(zip(*zipped)) return tuple([size] + results) # ====================================================================== @ogt.deprecated_function("Use omni.graph.nodes.test.bundle_inspector_results()") def bundle_inspector_outputs(bundle_inspector: og.NODE_TYPE_HINTS) -> BundleInspectorOutputType: """Returns attribute values computed from a bundle inspector in the same form as inspected_bundle_values Args: bundle_inspector: Node from which the output is to be extracted """ raw_values = [ og.Controller.get(og.Controller.attribute(name, bundle_inspector)) for (attr_type, name) in BUNDLE_INSPECTOR_ATTRIBUTES if attr_type != "bundle" and name.startswith("outputs:") ] size = raw_values[0] if size == 0: return (0, [], [], [], [], [], []) results = [] for attribute_name in [name for (_, name) in BUNDLE_INSPECTOR_ATTRIBUTES[1:] if name.startswith("outputs:")]: results.append(og.Controller.get(og.Controller.attribute(attribute_name, bundle_inspector))) # Bundled values are formatted as strings but are actually a mixture of types results[-1] = [ ast.literal_eval(value) if value != "__unsupported__" else "__unsupported__" for value in results[-1] ] # If these aren't sorted it will be more difficult to compare them zipped = list(zip(results[0], results[1], results[2], results[3], results[4], results[5])) zipped.sort() results = [list(x) for x in zip(*zipped)] return tuple([size] + results) # ====================================================================== @ogt.deprecated_function("Use omni.graph.nodes.test.bundle_inspector_results()") def bundle_inspector_values_as_dictionary(inspected_values: List[Any]) -> Dict[str, Tuple[str, str, bool, int, Any]]: """Converts the results from a list of bundle inspector results into a dictionary of all of the array attributes The dictionary is useful for sorting as the key values will be unique. Args: inspected_values: List of bundle inspector outputs in the format produced by inspected_bundle_values() Returns: Dictionary of { Bundled Attribute Name : (TYPE, ROLE, IS_ARRAY, TUPLE_COUNT, VALUE) } TYPE: Attribute base type name ROLE: Attribute role name IS_ARRAY: Is the attribute an array type? TUPLE_COUNT: How many tuple elements in the attribute? (1 if simple data) VALUE: Value of the attribute extracted from the bundle """ inspector_dictionary = {} for index in range(inspected_values[0]): inspector_dictionary[inspected_values[1][index]] = tuple(inspected_values[i][index] for i in range(2, 7)) return inspector_dictionary # ====================================================================== @ogt.deprecated_function("Use graph and/or node reference directly") def graph_node_path(node_name: str) -> str: """Returns the full graph node prim path for the OmniGraph node of the given name in the test scene""" return f"/defaultPrim/graph/{node_name}" # ====================================================================== @ogt.deprecated_function("Use og.Controller.create_prim()") def _generate_test_file( node_definitions: List[Union[PrimNodeDefinitionType, OmniGraphNodeDefinitionType]], debug: bool = False ): """ Generate a USDA file with data and connections that can exercise the bundle inspection node. The file could have be put into the data/ directory but it is easier to understand and modify here, especially since it is only useful in this test. Normally you wouldn't call this directly, you'd use set_up_test_stage() to do the next steps to load the scene. Args: node_definitions: List of USD node definitions for nodes in the test, not including the bundle source if the type is OmniGraphNodeDefinitionType then the values are tuples with OmniGraph node information: (NODE_NAME, NODE_TYPE, ATTRIBUTE_LINES, ATTRIBUTE_INFO) NODE_NAME: Local name of node in the graph NODE_TYPE: OmniGraph node type name ATTRIBUTE_LINES: List of the node's attribute declarations in USD form, including connections ATTRIBUTE_INFO: List of (TYPE:NAME) for attributes in the node else if the type is PrimNodeDefinitionType it contains data in the format for _write_usd_prim_definition debug: If True then alll bundle inspector nodes are put into debug mode, printing their computed results Returns: Path to the generated USDA file. The caller is responsible for deleting the file when done. """ temp_fd = NamedTemporaryFile(mode="w+", suffix=".usda", delete=False) # noqa: PLR1732 out = ogt.IndentedOutput(temp_fd) # Start with a basic scene containing two cubes and a gather node out.write("#usda 1.0") out.write("(") out.write(' doc = """Bundle Inspection Node Test"""') out.write(")") out.write('def Xform "defaultPrim"') if out.indent("{"): for node_data in node_definitions: if len(node_data) == 2: _write_usd_prim_definition(node_data, out) out.write('def ComputeGraph "graph"') if out.indent("{"): out.write('def ComputeGraphSettings "computegraphSettings"') if out.indent("{"): out.write('custom token evaluator:type = "dirty_push"') out.exdent("}") for node_data in node_definitions: if len(node_data) != 4: continue (node_name, node_type, attribute_lines, _) = node_data out.write(f'def ComputeNode "{node_name}"') if out.indent("{"): out.write(f'custom token node:type = "{node_type}"') out.write("custom int node:typeVersion = 1") for attribute_line in attribute_lines: assign = " = true" if debug and attribute_line.find("inputs:print") >= 0 else "" out.write(f"{attribute_line}{assign}") out.exdent("}") out.exdent("}") out.exdent("}") return temp_fd.name # ====================================================================== @ogt.deprecated_function("Use og.Controller.edit() to set up a test scene") async def set_up_test_stage( node_definitions: List[Union[PrimNodeDefinitionType, OmniGraphNodeDefinitionType]], debug: bool = False ): """Set up an initial stage based on a specific node type and its attributes Args: node_definitions: List of (NODE_NAME, NODE_TYPE_NAME, LIST_OF_USD_ATTRIBUTE_DECLARATIONS, ATTRIBUTE_INFO) debug: If True then all bundle inspector nodes are put into debug mode, printing their computed results Returns: Dictionary by name of a list of "Attribute" objects corresponding to the named attributes """ path_to_file = _generate_test_file(node_definitions, debug) (result, error) = await ogts.load_test_file(path_to_file) if not result: raise ValueError(f"{error} on {path_to_file}") attributes = {} for node_data in node_definitions: node_name = node_data[0] test_node = og.get_current_graph().get_node(graph_node_path(node_name)) if len(node_data) == 4: attribute_info = node_data[3] attributes[node_name] = [ test_node.get_attribute(name) for attr_type, name in attribute_info if attr_type != "bundle" ] await get_app().next_update_async() return attributes # ====================================================================== @ogt.deprecated_function("Use omni.graph.nodes.test.verify_bundles_are_equal()") def compare_bundle_contents(inspector_attributes: List, bundle_inspector_output: Union[Dict[str, Any], List[Any]]): """Helper to compare the contents of two bundled attribute sets Args: inspector_attributes: Attribute list for the bundle inspector node bundle_inspector_output: Outputs retrieved from the inspector in the format generated by inspected_bundle_values() if it's a list, or the format generated by bundle_inspector_values_as_dictionary() if it's a dictionary Raises: ValueError if any of the bundle output values do not match the expected ones """ # Mutating to a dictionary makes it easier to compare lists of lists if isinstance(bundle_inspector_output, list): bundled_size = bundle_inspector_output[0] bundled_data = bundle_inspector_values_as_dictionary(bundle_inspector_output) else: # If the data is already in dictionary form no conversion is needed bundled_size = len(bundle_inspector_output) bundled_data = bundle_inspector_output bundle_inspector_values = computed_bundle_values(inspector_attributes) if bundled_size != bundle_inspector_values[0]: raise ValueError(f"Bundled Count expected {bundled_size}, got {bundle_inspector_values[0]}") computed_values = bundle_inspector_values_as_dictionary(bundle_inspector_values) for attribute_name, attribute_values in computed_values.items(): expected_attribute_values = bundled_data[attribute_name] for attribute_index, computed_value in enumerate(attribute_values): # Bundled attribute types not yet supported by the bundle inspector are silently ignored if isinstance(computed_value, (list, tuple)): if "__unsupported__" in computed_value: continue else: if computed_value == "__unsupported__": continue error_msg = f"Unexpected value on attribute {inspector_attributes[attribute_index + 2].get_name()}" ogts.verify_values(expected_attribute_values[attribute_index], computed_value, error_msg) # ====================================================================== @ogt.deprecated_function("Use omni.graph.nodes.test.verify_bundles_are_equal()") def compare_bundle_inspector_results( expected: BundleInspectorOutputType, actual: BundleInspectorOutputType, test: Optional[TestCase] = None ): """Helper to compare the expected outputs from a bundle inspector node This uses the unit test framework for the comparisons. Args: expected: Values expected to be retrieved from the bundle inspector's outputs actual: Outputs retrieved from the inspector test: If not None then use it to report errors found, otherwise use a locally constructed TestCase Raises: ValueError if any of the bundle output values do not match the expected ones """ if test is None: test = TestCase() # Breaking open the tuples helps to clarify the operation being performed ( expected_count, expected_names, expected_types, expected_roles, expected_array_depths, expected_tuple_counts, expected_values, ) = expected ( actual_count, actual_names, actual_types, actual_roles, actual_array_depths, actual_tuple_counts, actual_values, ) = actual test.assertEqual(actual_count, expected_count) test.assertCountEqual(actual_names, expected_names) test.assertCountEqual(actual_types, expected_types) test.assertCountEqual(actual_roles, expected_roles) test.assertCountEqual(actual_array_depths, expected_array_depths) test.assertCountEqual(actual_tuple_counts, expected_tuple_counts) for one_actual, one_expected in zip(actual_values, expected_values): if isinstance(one_actual, list): test.assertCountEqual(one_actual, one_expected) else: test.assertEqual(one_actual, one_expected) # ============================================================================================================== @ogt.deprecated_function("Use og.Controller.create_prim or og.Controller.edit for creating prims") def create_prim_with_everything(prim_path: Optional[str] = None) -> Tuple[Usd.Prim, Dict[str, Any]]: """Deprecated function; should no longer be called""" return (None, {})
24,152
Python
45.717601
120
0.611544
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_legacy_write_prims_node.py
r""" _____ ______ _____ _____ ______ _____ _______ ______ _____ | __ \ | ____|| __ \ | __ \ | ____|/ ____| /\ |__ __|| ____|| __ \ | | | || |__ | |__) || |__) || |__ | | / \ | | | |__ | | | | | | | || __| | ___/ | _ / | __| | | / /\ \ | | | __| | | | | | |__| || |____ | | | | \ \ | |____| |____ / ____ \ | | | |____ | |__| | |_____/ |______||_| |_| \_\|______|\_____|/_/ \_\|_| |______||_____/ OgnWritePrims is deprecated. Use WritePrimsV2 instead. Unit tests for the OgnWritePrims (Legacy) node, kept for maintaining backward compatibility. For updated tests for OgnWritePrimsV2, find test_write_prims_node.py. """ import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.commands import omni.kit.stage_templates import omni.kit.test import omni.timeline import omni.usd from pxr import Usd, UsdGeom from usdrt import Usd as UsdRT # ====================================================================== class TestLegacyWritePrimNodes(ogts.OmniGraphTestCase): TEST_GRAPH_PATH = "/World/TestGraph" # ---------------------------------------------------------------------- async def test_legacy_read_write_prims_mpib(self): """Test omni.graph.nodes.ReadPrims and WritePrims MPiB without bundle modification""" usd_context = omni.usd.get_context() stage: Usd.Stage = usd_context.get_stage() stage_rt = UsdRT.Stage.Attach(usd_context.get_stage_id()) controller = og.Controller() keys = og.Controller.Keys cube1_prim = ogts.create_cube(stage, "Cube1", (1, 0, 0)) cube2_prim = ogts.create_cube(stage, "Cube2", (0, 1, 0)) (graph, [read_prims_node, _], _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Read", "omni.graph.nodes.ReadPrims"), ("Write", "omni.graph.nodes.WritePrims"), ], keys.CONNECT: [ ("Read.outputs_primsBundle", "Write.inputs:primsBundle"), ], }, ) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"), target=cube1_prim.GetPath(), ) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"), target=cube2_prim.GetPath(), ) await self._evaluate_graph(graph, controller) self._assert_no_compute_messages(graph) # Reading the prim into a bundle again must leave the attributes intact, as we didn't modify anything await self._evaluate_graph(graph, controller) self._assert_no_compute_messages(graph) graph_context = graph.get_default_graph_context() output_prims_bundle = graph_context.get_output_bundle(read_prims_node, "outputs_primsBundle") self.assertTrue(output_prims_bundle.valid) child_bundles = output_prims_bundle.get_child_bundles() self.assertEqual(len(child_bundles), 2) expected_colors = { "/Cube1": [[1.0, 0.0, 0.0]], "/Cube2": [[0.0, 1.0, 0.0]], } for bundle in child_bundles: path = bundle.get_attribute_by_name("sourcePrimPath").get() expected_color = expected_colors[path] self.assertNotEqual(expected_color, None) # Check bundle values self.assertListEqual(bundle.get_attribute_by_name("primvars:displayColor").get().tolist(), expected_color) # Check USD prim values prim = stage.GetPrimAtPath(path) self.assertEqual([rgb[:] for rgb in prim.GetAttribute("primvars:displayColor").Get()], expected_color) # Check Fabric prim values prim_rt = stage_rt.GetPrimAtPath(path) self.assertEqual([rgb[:] for rgb in prim_rt.GetAttribute("primvars:displayColor").Get()], expected_color) # ---------------------------------------------------------------------- async def test_legacy_read_write_prims_spib(self): """Test omni.graph.nodes.ReadPrims and WritePrims SPiB without bundle modification""" usd_context = omni.usd.get_context() stage: Usd.Stage = usd_context.get_stage() stage_rt = UsdRT.Stage.Attach(usd_context.get_stage_id()) controller = og.Controller() keys = og.Controller.Keys cube1_prim = ogts.create_cube(stage, "Cube1", (1, 0, 0)) (graph, [read_prims_node, _, _], _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Read", "omni.graph.nodes.ReadPrims"), ("ExtractCube1", "omni.graph.nodes.ExtractPrim"), ("Write", "omni.graph.nodes.WritePrims"), ], keys.SET_VALUES: [ ("ExtractCube1.inputs:primPath", "/Cube1"), ], keys.CONNECT: [ ("Read.outputs_primsBundle", "ExtractCube1.inputs:prims"), ("ExtractCube1.outputs_primBundle", "Write.inputs:primsBundle"), ], }, ) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"), target=cube1_prim.GetPath(), ) await self._evaluate_graph(graph, controller) self._assert_no_compute_messages(graph) # Reading the prim into a bundle again must leave the attributes intact, as we didn't modify anything await self._evaluate_graph(graph, controller) self._assert_no_compute_messages(graph) graph_context = graph.get_default_graph_context() output_prims_bundle = graph_context.get_output_bundle(read_prims_node, "outputs_primsBundle") self.assertTrue(output_prims_bundle.valid) child_bundles = output_prims_bundle.get_child_bundles() self.assertEqual(len(child_bundles), 1) expected_colors = { "/Cube1": [[1.0, 0.0, 0.0]], } for bundle in child_bundles: path = bundle.get_attribute_by_name("sourcePrimPath").get() expected_color = expected_colors[path] self.assertNotEqual(expected_color, None) # Check bundle values self.assertListEqual(bundle.get_attribute_by_name("primvars:displayColor").get().tolist(), expected_color) # Check USD prim values prim = stage.GetPrimAtPath(path) self.assertEqual([rgb[:] for rgb in prim.GetAttribute("primvars:displayColor").Get()], expected_color) # Check Fabric prim values prim_rt = stage_rt.GetPrimAtPath(path) self.assertEqual([rgb[:] for rgb in prim_rt.GetAttribute("primvars:displayColor").Get()], expected_color) # ---------------------------------------------------------------------- async def test_legacy_read_write_prims_int_to_fabric(self): """Test omni.graph.nodes.ReadPrims and WritePrims for an integer attribute, Fabric only""" await self._read_write_prims_int(False) # ---------------------------------------------------------------------- async def test_legacy_read_write_prims_int_to_usd(self): """Test omni.graph.nodes.ReadPrims and WritePrims for an integer attribute, writing back to USD""" await self._read_write_prims_int(True) # ---------------------------------------------------------------------- async def _read_write_prims_int(self, usd_write_back: bool): usd_context = omni.usd.get_context() stage: Usd.Stage = usd_context.get_stage() stage_rt = UsdRT.Stage.Attach(usd_context.get_stage_id()) controller = og.Controller() keys = og.Controller.Keys cube1_prim = ogts.create_cube(stage, "Cube1", (1, 0, 0)) cube2_prim = ogts.create_cube(stage, "Cube2", (0, 1, 0)) (graph, [extract_cube1, extract_cube2, *_], _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("ExtractCube1", "omni.graph.nodes.ExtractPrim"), ("ExtractCube2", "omni.graph.nodes.ExtractPrim"), ("Read", "omni.graph.nodes.ReadPrims"), ("Write", "omni.graph.nodes.WritePrims"), ("SizeCube1", "omni.graph.nodes.ConstantDouble"), ("SizeCube2", "omni.graph.nodes.ConstantDouble"), ("InsertSizeCube1", "omni.graph.nodes.InsertAttribute"), ("InsertSizeCube2", "omni.graph.nodes.InsertAttribute"), ], keys.SET_VALUES: [ ("ExtractCube1.inputs:primPath", "/Cube1"), ("ExtractCube2.inputs:primPath", "/Cube2"), ("SizeCube1.inputs:value", 200), ("SizeCube2.inputs:value", 300), ("InsertSizeCube1.inputs:outputAttrName", "size"), ("InsertSizeCube2.inputs:outputAttrName", "size"), ("Write.inputs:usdWriteBack", usd_write_back), ], keys.CONNECT: [ ("Read.outputs_primsBundle", "ExtractCube1.inputs:prims"), ("Read.outputs_primsBundle", "ExtractCube2.inputs:prims"), ("SizeCube1.inputs:value", "InsertSizeCube1.inputs:attrToInsert"), ("SizeCube2.inputs:value", "InsertSizeCube2.inputs:attrToInsert"), ("ExtractCube1.outputs_primBundle", "InsertSizeCube1.inputs:data"), ("ExtractCube2.outputs_primBundle", "InsertSizeCube2.inputs:data"), ("InsertSizeCube1.outputs_data", "Write.inputs:primsBundle"), ("InsertSizeCube2.outputs_data", "Write.inputs:primsBundle"), ], }, ) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"), target=cube1_prim.GetPath(), ) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"), target=cube2_prim.GetPath(), ) await self._evaluate_graph(graph, controller) self._assert_no_compute_messages(graph) graph_context = graph.get_default_graph_context() # Because we have feedback, the extract_cube1 bundle should have picked up the written attributes. # TODO: Feedback will become optional one day! cube1_bundle = graph_context.get_output_bundle(extract_cube1, "outputs_primBundle") self.assertTrue(cube1_bundle.valid) self.assertEqual(cube1_bundle.get_attribute_by_name("size").get(), 200) # Because we have feedback, the extract_cube2 bundle should have picked up the written attributes. # TODO: Feedback will become optional one day! cube2_bundle = graph_context.get_output_bundle(extract_cube2, "outputs_primBundle") self.assertTrue(cube2_bundle.valid) self.assertEqual(cube2_bundle.get_attribute_by_name("size").get(), 300) # Check USD write-back self.assertEqual(cube1_prim.GetAttribute("size").Get(), 200 if usd_write_back else 1) self.assertEqual(cube2_prim.GetAttribute("size").Get(), 300 if usd_write_back else 1) # Check Fabric values self.assertEqual(stage_rt.GetPrimAtPath("/Cube1").GetAttribute("size").Get(), 200) self.assertEqual(stage_rt.GetPrimAtPath("/Cube2").GetAttribute("size").Get(), 300) # Make sure the prim-bundle internal attributes are not written to the USD prim for attr_name in ["sourcePrimPath", "sourcePrimType"]: self.assertEqual(cube1_prim.HasAttribute(attr_name), False) self.assertEqual(cube2_prim.HasAttribute(attr_name), False) # ---------------------------------------------------------------------- async def test_legacy_read_write_prims_translate_only(self): """Test omni.graph.nodes.ReadPrims and WritePrims using an attribute pattern to just translate""" await self._test_read_write_prims_patterns( "xformOp:trans*", None, None, [ [(1.0, 2.0, 3.0), (0.0, 0.0, 0.0)], [(4.0, 5.0, 6.0), (0.0, 0.0, 0.0)], ], ) # ---------------------------------------------------------------------- async def test_legacy_read_write_prims_rotate_only(self): """Test omni.graph.nodes.ReadPrims and WritePrims using an attribute pattern to just rotate""" await self._test_read_write_prims_patterns( "xformOp:rotate*", None, None, [ [(0.0, 0.0, 0.0), (7.0, 8.0, 9.0)], [(0.0, 0.0, 0.0), (10.0, 11.0, 12.0)], ], ) # ---------------------------------------------------------------------- async def test_legacy_read_write_prims_xform_only(self): """Test omni.graph.nodes.ReadPrims and WritePrims using an attribute pattern to translate and rotate""" await self._test_read_write_prims_patterns( "xformOp:*", None, None, [ [(1.0, 2.0, 3.0), (7.0, 8.0, 9.0)], [(4.0, 5.0, 6.0), (10.0, 11.0, 12.0)], ], ) # ---------------------------------------------------------------------- async def test_legacy_read_write_prims_shape1_only(self): """Test omni.graph.nodes.ReadPrims and WritePrims using an path pattern to limit writing to Shape1 only""" await self._test_read_write_prims_patterns( None, "/Shape1", None, [ [(1.0, 2.0, 3.0), (7.0, 8.0, 9.0)], [(0.0, 0.0, 0.0), (0.0, 0.0, 0.0)], ], ) # ---------------------------------------------------------------------- async def test_legacy_read_write_prims_shape2_only(self): """Test omni.graph.nodes.ReadPrims and WritePrims using an path pattern to limit writing to Shape2 only""" await self._test_read_write_prims_patterns( None, "/Shape2", None, [ [(0.0, 0.0, 0.0), (0.0, 0.0, 0.0)], [(4.0, 5.0, 6.0), (10.0, 11.0, 12.0)], ], ) # ---------------------------------------------------------------------- async def test_legacy_read_write_prims_both_shapes(self): """Test omni.graph.nodes.ReadPrims and WritePrims using an path pattern to write to both shapes""" await self._test_read_write_prims_patterns( None, "/Shape*", None, [ [(1.0, 2.0, 3.0), (7.0, 8.0, 9.0)], [(4.0, 5.0, 6.0), (10.0, 11.0, 12.0)], ], ) # ---------------------------------------------------------------------- async def test_legacy_read_write_prims_cube_only(self): """Test omni.graph.nodes.ReadPrims and WritePrims using an path pattern to limit writing to cubes only""" await self._test_read_write_prims_patterns( None, None, "Cube", [ [(1.0, 2.0, 3.0), (7.0, 8.0, 9.0)], [(0.0, 0.0, 0.0), (0.0, 0.0, 0.0)], ], ) # ---------------------------------------------------------------------- async def test_legacy_read_write_prims_cone_only(self): """Test omni.graph.nodes.ReadPrims and WritePrims using an type pattern to limit writing to cones only""" await self._test_read_write_prims_patterns( None, None, "Cone", [ [(0.0, 0.0, 0.0), (0.0, 0.0, 0.0)], [(4.0, 5.0, 6.0), (10.0, 11.0, 12.0)], ], ) # ---------------------------------------------------------------------- async def test_legacy_read_write_prims_cube_and_cone(self): """Test omni.graph.nodes.ReadPrims and WritePrims using an type pattern to write to both cubes and cones""" await self._test_read_write_prims_patterns( None, None, "Cone;Cube", [ [(1.0, 2.0, 3.0), (7.0, 8.0, 9.0)], [(4.0, 5.0, 6.0), (10.0, 11.0, 12.0)], ], ) # ---------------------------------------------------------------------- async def _test_read_write_prims_patterns(self, attr_pattern, path_pattern, type_pattern, expected_prim_values): # No need to test USD write back in this unit tests, other tests do this. usd_write_back = False usd_context = omni.usd.get_context() stage: Usd.Stage = usd_context.get_stage() stage_rt = UsdRT.Stage.Attach(usd_context.get_stage_id()) controller = og.Controller() keys = og.Controller.Keys cube_prim = ogts.create_cube(stage, "Shape1", (1, 0, 0)) cone_prim = ogts.create_cone(stage, "Shape2", (0, 1, 0)) # add transforms with double precision xform_precision = UsdGeom.XformOp.PrecisionDouble for prim in [cube_prim, cone_prim]: UsdGeom.Xformable(prim).AddTranslateOp(xform_precision).Set((0, 0, 0)) UsdGeom.Xformable(prim).AddRotateXYZOp(xform_precision).Set((0, 0, 0)) UsdGeom.Xformable(prim).AddScaleOp(xform_precision).Set((1, 1, 1)) set_values = [ ("ExtractCube.inputs:primPath", "/Shape1"), ("ExtractCone.inputs:primPath", "/Shape2"), ("TranslateCube.inputs:value", (1, 2, 3)), ("TranslateCone.inputs:value", (4, 5, 6)), ("RotateCube.inputs:value", (7, 8, 9)), ("RotateCone.inputs:value", (10, 11, 12)), ("InsertTranslateCube.inputs:outputAttrName", "xformOp:translate"), ("InsertTranslateCone.inputs:outputAttrName", "xformOp:translate"), ("InsertRotateCube.inputs:outputAttrName", "xformOp:rotateXYZ"), ("InsertRotateCone.inputs:outputAttrName", "xformOp:rotateXYZ"), ("Write.inputs:usdWriteBack", usd_write_back), ] if attr_pattern: set_values.append(("Write.inputs:attrNamesToExport", attr_pattern)) if path_pattern: set_values.append(("Write.inputs:pathPattern", path_pattern)) if type_pattern: set_values.append(("Write.inputs:typePattern", type_pattern)) (graph, [extract_cube, extract_cone, *_], _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("ExtractCube", "omni.graph.nodes.ExtractPrim"), ("ExtractCone", "omni.graph.nodes.ExtractPrim"), ("Read", "omni.graph.nodes.ReadPrims"), ("Write", "omni.graph.nodes.WritePrims"), ("TranslateCube", "omni.graph.nodes.ConstantDouble3"), ("TranslateCone", "omni.graph.nodes.ConstantDouble3"), ("RotateCube", "omni.graph.nodes.ConstantDouble3"), ("RotateCone", "omni.graph.nodes.ConstantDouble3"), ("InsertTranslateCube", "omni.graph.nodes.InsertAttribute"), ("InsertTranslateCone", "omni.graph.nodes.InsertAttribute"), ("InsertRotateCube", "omni.graph.nodes.InsertAttribute"), ("InsertRotateCone", "omni.graph.nodes.InsertAttribute"), ], keys.CONNECT: [ ("Read.outputs_primsBundle", "ExtractCube.inputs:prims"), ("Read.outputs_primsBundle", "ExtractCone.inputs:prims"), ("TranslateCube.inputs:value", "InsertTranslateCube.inputs:attrToInsert"), ("TranslateCone.inputs:value", "InsertTranslateCone.inputs:attrToInsert"), ("RotateCube.inputs:value", "InsertRotateCube.inputs:attrToInsert"), ("RotateCone.inputs:value", "InsertRotateCone.inputs:attrToInsert"), ("ExtractCube.outputs_primBundle", "InsertTranslateCube.inputs:data"), ("ExtractCone.outputs_primBundle", "InsertTranslateCone.inputs:data"), ("InsertTranslateCube.outputs_data", "InsertRotateCube.inputs:data"), ("InsertTranslateCone.outputs_data", "InsertRotateCone.inputs:data"), ("InsertRotateCube.outputs_data", "Write.inputs:primsBundle"), ("InsertRotateCone.outputs_data", "Write.inputs:primsBundle"), ], keys.SET_VALUES: set_values, }, ) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"), target=cube_prim.GetPath(), ) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"), target=cone_prim.GetPath(), ) await self._evaluate_graph(graph, controller) self._assert_no_compute_messages(graph) graph_context = graph.get_default_graph_context() cube_bundle = graph_context.get_output_bundle(extract_cube, "outputs_primBundle") cone_bundle = graph_context.get_output_bundle(extract_cone, "outputs_primBundle") prim_bundles = [cube_bundle, cone_bundle] prim_paths = ["/Shape1", "/Shape2"] # We will check these attributes attr_names = ["xformOp:translate", "xformOp:rotateXYZ"] # We need two lists of values, one for each prim self.assertEqual(len(expected_prim_values), 2) for prim_index, prim_bundle in enumerate(prim_bundles): expected_values = expected_prim_values[prim_index] # All attribute values must be passed self.assertEqual(len(expected_values), len(attr_names)) prim_rt = stage_rt.GetPrimAtPath(prim_paths[prim_index]) # Check attributes values in prim bundle for attr_index, expected_value in enumerate(expected_values): attr_name = attr_names[attr_index] # Because we have feedback, the bundle should have picked up the written attributes. # TODO: Feedback will become optional one day! actual_value = tuple(prim_bundle.get_attribute_by_name(attr_name).get()) self.assertEqual(actual_value, expected_value) # Check Fabric values actual_value_rt = tuple(prim_rt.GetAttribute(attr_name).Get()) self.assertEqual(actual_value_rt, expected_value) # Make sure the prim-bundle internal attributes are not written to the USD prim for attr_name in ["sourcePrimPath", "sourcePrimType"]: self.assertEqual(cube_prim.HasAttribute(attr_name), False) self.assertEqual(cone_prim.HasAttribute(attr_name), False) # ---------------------------------------------------------------------- async def test_legacy_read_write_prims_array_new_attr_to_fabric(self): """Test omni.graph.nodes.ReadPrims and WritePrims for a new array attribute, Fabric only""" await self._test_read_write_prims_vec3_array(False, False) # ---------------------------------------------------------------------- async def test_legacy_read_write_prims_array_new_attr_to_usd(self): """Test omni.graph.nodes.ReadPrims and WritePrims for a new array attribute, writing back to USD""" await self._test_read_write_prims_vec3_array(True, False) # ---------------------------------------------------------------------- async def test_legacy_read_write_prims_array_attr_to_fabric(self): """Test omni.graph.nodes.ReadPrims and WritePrims for an existing array attribute, Fabric only""" await self._test_read_write_prims_vec3_array(False, True) # ---------------------------------------------------------------------- async def test_legacy_read_write_prims_array_attr_to_usd(self): """Test omni.graph.nodes.ReadPrims and WritePrims for an existing array attribute, writing back to USD""" await self._test_read_write_prims_vec3_array(True, True) # ---------------------------------------------------------------------- async def _test_read_write_prims_vec3_array(self, usd_write_back: bool, add_new_attr: bool): usd_context = omni.usd.get_context() stage = usd_context.get_stage() stage_rt = UsdRT.Stage.Attach(usd_context.get_stage_id()) cube_prim = ogts.create_cube(stage, "Cube", (1, 0, 0)) controller = og.Controller() keys = og.Controller.Keys attr_name = "new_array_attr" if add_new_attr else "primvars:displayColor" (graph, nodes, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Read", "omni.graph.nodes.ReadPrims"), ("Write", "omni.graph.nodes.WritePrims"), ("ExtractCube", "omni.graph.nodes.ExtractPrim"), ("MakeArray", "omni.graph.nodes.ConstructArray"), ("InsertAttribute", "omni.graph.nodes.InsertAttribute"), ], keys.SET_VALUES: [ ("ExtractCube.inputs:primPath", "/Cube"), ("MakeArray.inputs:arraySize", 1), ("MakeArray.inputs:arrayType", "float[3][]"), ("MakeArray.inputs:input0", [0.25, 0.50, 0.75]), ("InsertAttribute.inputs:outputAttrName", attr_name), ("Write.inputs:usdWriteBack", usd_write_back), ], keys.CONNECT: [ ("Read.outputs_primsBundle", "ExtractCube.inputs:prims"), ("ExtractCube.outputs_primBundle", "InsertAttribute.inputs:data"), ("MakeArray.outputs:array", "InsertAttribute.inputs:attrToInsert"), ("InsertAttribute.outputs_data", "Write.inputs:primsBundle"), ], }, ) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"), target=cube_prim.GetPath(), ) await self._evaluate_graph(graph, controller) self._assert_no_compute_messages(graph) graph_context = graph.get_default_graph_context() cube_bundle = graph_context.get_output_bundle(nodes[2], "outputs_primBundle") self.assertTrue(cube_bundle.valid) # Because we have feedback, the bundle should have picked up the written attributes. # TODO: Feedback will become optional one day! feedback_values = cube_bundle.get_attribute_by_name(attr_name).get() self.assertEqual(len(feedback_values), 1) self.assertEqual(tuple(feedback_values[0]), (0.25, 0.50, 0.75)) # Check Fabric values fabric_values = stage_rt.GetPrimAtPath("/Cube").GetAttribute(attr_name).Get() self.assertEqual(len(fabric_values), 1) self.assertEqual(tuple(fabric_values[0]), (0.25, 0.50, 0.75)) if usd_write_back: # With USD write back, the existing attribute should be updated in USD usd_values = stage.GetPrimAtPath("/Cube").GetAttribute(attr_name).Get() self.assertEqual(len(usd_values), 1) self.assertEqual(tuple(usd_values[0]), (0.25, 0.50, 0.75)) elif add_new_attr: # Without USD write back, the new attribute should not exist in USD. self.assertFalse(stage.GetPrimAtPath("/Cube").HasAttribute(attr_name)) else: # Without USD write back, the existing attribute should not be updated in USD usd_values = stage.GetPrimAtPath("/Cube").GetAttribute(attr_name).Get() self.assertEqual(len(usd_values), 1) self.assertEqual(tuple(usd_values[0]), (1, 0, 0)) # ---------------------------------------------------------------------- # Helpers def _assert_no_compute_messages(self, graph): graph_nodes = graph.get_nodes() for severity in [og.WARNING, og.ERROR]: for node in graph_nodes: self.assertEqual(node.get_compute_messages(severity), []) async def _evaluate_graph(self, graph, controller): await omni.kit.app.get_app().next_update_async() await controller.evaluate(graph)
29,141
Python
44.820755
118
0.540887
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_write_prims_node.py
# noqa: PLC0302 """Unit tests for the OgnWritePrims node in this extension""" import fnmatch import os import tempfile import carb import omni.graph.core as og import omni.graph.core.autonode as oga import omni.graph.core.tests as ogts import omni.kit.commands import omni.kit.stage_templates import omni.kit.test import omni.timeline import omni.usd from pxr import Sdf, Usd, UsdGeom from usdrt import Sdf as SdfRT from usdrt import Usd as UsdRT # Define a test node that has one relationship in the bundle # This will be used to test WritePrimsV2 node's Relationship exporting REL_BUNDLE_TRL_NAME = "test_rel" REL_BUNDLE_TARGETS = [Sdf.Path("/Foo/bar"), Sdf.Path("/Foo/baz")] REL_BUNDLE_TARGETS_RT = [SdfRT.Path(path.pathString) for path in REL_BUNDLE_TARGETS] @oga.AutoFunc(module_name="__test_write_prims_v2__", pure=True) def relationship_bundle() -> og.Bundle: bundle = og.Bundle("return", False) bundle.create_attribute(REL_BUNDLE_TRL_NAME, og.Type(og.BaseDataType.RELATIONSHIP, 1, 1)).value = REL_BUNDLE_TARGETS return bundle # ====================================================================== # because the child bundle's order inside of bundle is non-deterministic, WritePrims node sort the bundle content # according to sourcePrimPath when scatter_under_targets mode is off def sort_child_bundles(child_bundles, scatter_under_targets: bool): # do not sort if scatter_under_targets if scatter_under_targets: return child_bundles child_bundles.sort(key=lambda x: x.get_attribute_by_name("sourcePrimPath").get()) return child_bundles # ====================================================================== class TestWritePrimNodes(ogts.OmniGraphTestCase): TEST_GRAPH_PATH = "/World/TestGraph" # ---------------------------------------------------------------------- async def test_read_write_prims_mpib(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims MPiB without bundle modification and output to targets""" await self._test_read_write_prims_mpib_impl(False) # ---------------------------------------------------------------------- async def test_read_write_prims_mpib_scatter(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims MPiB without bundle modification and scatter under targets""" await self._test_read_write_prims_mpib_impl(True) # ---------------------------------------------------------------------- async def _test_read_write_prims_mpib_impl(self, scatter_under_targets: bool): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims MPiB without bundle modification""" target_prim_paths = ["/target0", "/target1"] usd_context = omni.usd.get_context() stage: Usd.Stage = usd_context.get_stage() stage_rt = UsdRT.Stage.Attach(usd_context.get_stage_id()) controller = og.Controller() keys = og.Controller.Keys cube1_prim = ogts.create_cube(stage, "Cube1", (1, 0, 0)) cube2_prim = ogts.create_cube(stage, "Cube2", (0, 1, 0)) (graph, [read_prims_node, _], _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Read", "omni.graph.nodes.ReadPrimsV2"), ("Write", "omni.graph.nodes.WritePrimsV2"), ], keys.SET_VALUES: [ ("Write.inputs:scatterUnderTargets", scatter_under_targets), ], keys.CONNECT: [ ("Read.outputs_primsBundle", "Write.inputs:primsBundle"), ], }, ) omni.kit.commands.execute( "SetRelationshipTargets", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"), targets=[cube1_prim.GetPath(), cube2_prim.GetPath()], ) for target_path in target_prim_paths: target_xform = UsdGeom.Xform.Define(stage, target_path) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Write.inputs:prims"), target=target_xform.GetPrim().GetPath(), ) await self._evaluate_graph(graph, controller) self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR]) # Reading the prim into a bundle again must leave the attributes intact, as we didn't modify anything await self._evaluate_graph(graph, controller) self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR]) graph_context = graph.get_default_graph_context() output_prims_bundle = graph_context.get_output_bundle(read_prims_node, "outputs_primsBundle") self.assertTrue(output_prims_bundle.valid) child_bundles = output_prims_bundle.get_child_bundles() self.assertEqual(len(child_bundles), 2) expected_colors = { "/Cube1": [[1.0, 0.0, 0.0]], "/Cube2": [[0.0, 1.0, 0.0]], } child_bundles = sort_child_bundles(child_bundles, scatter_under_targets) for i, bundle in enumerate(child_bundles): path = bundle.get_attribute_by_name("sourcePrimPath").get() expected_color = expected_colors[path] self.assertNotEqual(expected_color, None) # Check bundle values self.assertListEqual(bundle.get_attribute_by_name("primvars:displayColor").get().tolist(), expected_color) def check_prim_values(source_prim_path, target_prim_path, expected_color): # Check USD prim values prim = stage.GetPrimAtPath(source_prim_path) self.assertEqual([rgb[:] for rgb in prim.GetAttribute("primvars:displayColor").Get()], expected_color) # Check Fabric prim values prim_rt = stage_rt.GetPrimAtPath(source_prim_path) self.assertTrue(prim_rt.IsValid()) self.assertEqual( [rgb[:] for rgb in prim_rt.GetAttribute("primvars:displayColor").Get()], expected_color ) # Check target Fabric prim values prim_rt = stage_rt.GetPrimAtPath(target_prim_path) self.assertTrue(prim_rt.IsValid()) self.assertEqual( [rgb[:] for rgb in prim_rt.GetAttribute("primvars:displayColor").Get()], expected_color ) if scatter_under_targets: for target_prim_path in target_prim_paths: check_prim_values(path, target_prim_path + path, expected_color) else: check_prim_values(path, target_prim_paths[i], expected_color) # ---------------------------------------------------------------------- async def test_read_write_prims_spib(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims SPiB without bundle modification and output to targets""" await self._test_read_write_prims_spib_impl(False) # ---------------------------------------------------------------------- async def test_read_write_prims_spib_no_source_prim_info(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims SPiB without bundle modification and output to targets""" await self._test_read_write_prims_spib_impl(False, True) # ---------------------------------------------------------------------- async def test_read_write_prims_spib_scatter(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims SPiB without bundle modification and scatter under targets""" await self._test_read_write_prims_spib_impl(True) # ---------------------------------------------------------------------- async def _test_read_write_prims_spib_impl( self, scatter_under_targets: bool, remove_source_prim_info: bool = False ): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims SPiB without bundle modification""" target_prim_paths = ["/target0", "/target1"] usd_context = omni.usd.get_context() stage: Usd.Stage = usd_context.get_stage() stage_rt = UsdRT.Stage.Attach(usd_context.get_stage_id()) controller = og.Controller() keys = og.Controller.Keys cube1_prim = ogts.create_cube(stage, "Cube1", (1, 0, 0)) (graph, [read_prims_node, *_], _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Read", "omni.graph.nodes.ReadPrimsV2"), ("ExtractCube1", "omni.graph.nodes.ExtractPrim"), ("RemoveAttrs", "omni.graph.nodes.RemoveAttribute"), ("Write", "omni.graph.nodes.WritePrimsV2"), ], keys.SET_VALUES: [ ("ExtractCube1.inputs:primPath", "/Cube1"), ("RemoveAttrs.inputs:allowRemovePrimInternal", True), ( "RemoveAttrs.inputs:attrNamesToRemove", "sourcePrimPath;sourcePrimType" if remove_source_prim_info else "", ), ("Write.inputs:scatterUnderTargets", scatter_under_targets), ], keys.CONNECT: [ ("Read.outputs_primsBundle", "ExtractCube1.inputs:prims"), ("ExtractCube1.outputs_primBundle", "RemoveAttrs.inputs:data"), ("RemoveAttrs.outputs_data", "Write.inputs:primsBundle"), ], }, ) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"), target=cube1_prim.GetPath(), ) for target_path in target_prim_paths: target_xform = UsdGeom.Xform.Define(stage, target_path) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Write.inputs:prims"), target=target_xform.GetPrim().GetPath(), ) await self._evaluate_graph(graph, controller) self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR]) # Reading the prim into a bundle again must leave the attributes intact, as we didn't modify anything await self._evaluate_graph(graph, controller) self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR]) graph_context = graph.get_default_graph_context() output_prims_bundle = graph_context.get_output_bundle(read_prims_node, "outputs_primsBundle") self.assertTrue(output_prims_bundle.valid) child_bundles = output_prims_bundle.get_child_bundles() self.assertEqual(len(child_bundles), 1) expected_colors = { "/Cube1": [[1.0, 0.0, 0.0]], } child_bundles = sort_child_bundles(child_bundles, scatter_under_targets) for i, bundle in enumerate(child_bundles): path = bundle.get_attribute_by_name("sourcePrimPath").get() expected_color = expected_colors[path] self.assertNotEqual(expected_color, None) # Check bundle values self.assertListEqual(bundle.get_attribute_by_name("primvars:displayColor").get().tolist(), expected_color) def check_prim_values(target_prim_path, expected_color): # Check Target USD prim values prim = stage.GetPrimAtPath(target_prim_path) # if source prim info is removed, the target prim type should not change. Otherwise it changes from Xform to Cube self.assertEqual(prim.GetTypeName(), "Xform" if remove_source_prim_info else "Cube") self.assertEqual([rgb[:] for rgb in prim.GetAttribute("primvars:displayColor").Get()], expected_color) # Check Target Fabric prim values prim_rt = stage_rt.GetPrimAtPath(target_prim_path) self.assertEqual( [rgb[:] for rgb in prim_rt.GetAttribute("primvars:displayColor").Get()], expected_color ) if scatter_under_targets: for target_prim_path in target_prim_paths: check_prim_values(target_prim_path + path, expected_color) else: check_prim_values(target_prim_paths[i], expected_color) # ---------------------------------------------------------------------- async def test_read_write_prims_int_to_fabric(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims for an integer attribute, Fabric only""" await self._read_write_prims_int(False, False) # ---------------------------------------------------------------------- async def test_read_write_prims_int_to_fabric_scatter(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims for an integer attribute, Fabric only""" await self._read_write_prims_int(False, True) # ---------------------------------------------------------------------- async def test_read_write_prims_int_to_usd(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims for an integer attribute, writing back to USD""" await self._read_write_prims_int(True, False) # ---------------------------------------------------------------------- async def test_read_write_prims_int_to_usd_scatter(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims for an integer attribute, writing back to USD""" await self._read_write_prims_int(True, True) # ---------------------------------------------------------------------- async def _read_write_prims_int(self, usd_write_back: bool, scatter_under_targets: bool): target_prim_paths = ["/target0", "/target1"] usd_context = omni.usd.get_context() stage: Usd.Stage = usd_context.get_stage() stage_rt = UsdRT.Stage.Attach(usd_context.get_stage_id()) controller = og.Controller() keys = og.Controller.Keys cube1_prim = ogts.create_cube(stage, "Cube1", (1, 0, 0)) cube2_prim = ogts.create_cube(stage, "Cube2", (0, 1, 0)) (graph, _, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("ExtractCube1", "omni.graph.nodes.ExtractPrim"), ("ExtractCube2", "omni.graph.nodes.ExtractPrim"), ("Read", "omni.graph.nodes.ReadPrimsV2"), ("Write", "omni.graph.nodes.WritePrimsV2"), ("SizeCube1", "omni.graph.nodes.ConstantDouble"), ("SizeCube2", "omni.graph.nodes.ConstantDouble"), ("InsertSizeCube1", "omni.graph.nodes.InsertAttribute"), ("InsertSizeCube2", "omni.graph.nodes.InsertAttribute"), ], keys.SET_VALUES: [ ("ExtractCube1.inputs:primPath", "/Cube1"), ("ExtractCube2.inputs:primPath", "/Cube2"), ("SizeCube1.inputs:value", 200), ("SizeCube2.inputs:value", 300), ("InsertSizeCube1.inputs:outputAttrName", "size"), ("InsertSizeCube2.inputs:outputAttrName", "size"), ("Write.inputs:usdWriteBack", usd_write_back), ("Write.inputs:scatterUnderTargets", scatter_under_targets), ], keys.CONNECT: [ ("Read.outputs_primsBundle", "ExtractCube1.inputs:prims"), ("Read.outputs_primsBundle", "ExtractCube2.inputs:prims"), ("SizeCube1.inputs:value", "InsertSizeCube1.inputs:attrToInsert"), ("SizeCube2.inputs:value", "InsertSizeCube2.inputs:attrToInsert"), ("ExtractCube1.outputs_primBundle", "InsertSizeCube1.inputs:data"), ("ExtractCube2.outputs_primBundle", "InsertSizeCube2.inputs:data"), ("InsertSizeCube1.outputs_data", "Write.inputs:primsBundle"), ("InsertSizeCube2.outputs_data", "Write.inputs:primsBundle"), ], }, ) omni.kit.commands.execute( "SetRelationshipTargets", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"), targets=[cube1_prim.GetPath(), cube2_prim.GetPath()], ) for target_path in target_prim_paths: target_xform = UsdGeom.Xform.Define(stage, target_path) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Write.inputs:prims"), target=target_xform.GetPrim().GetPath(), ) await self._evaluate_graph(graph, controller) self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR]) def check_prim_values(cube_1_path, cube_2_path): if usd_write_back: # Check USD write-back cube1_prim_target = stage.GetPrimAtPath(cube_1_path) cube2_prim_target = stage.GetPrimAtPath(cube_2_path) self.assertEqual(cube1_prim_target.GetAttribute("size").Get(), 200 if usd_write_back else 1) self.assertEqual(cube2_prim_target.GetAttribute("size").Get(), 300 if usd_write_back else 1) # Make sure the prim-bundle internal attributes are not written to the USD prim for attr_name in ["sourcePrimPath", "sourcePrimType"]: self.assertEqual(cube1_prim_target.HasAttribute(attr_name), False) self.assertEqual(cube2_prim_target.HasAttribute(attr_name), False) # Check Fabric values self.assertEqual(stage_rt.GetPrimAtPath(cube_1_path).GetAttribute("size").Get(), 200) self.assertEqual(stage_rt.GetPrimAtPath(cube_2_path).GetAttribute("size").Get(), 300) if scatter_under_targets: for target_prim_path in target_prim_paths: check_prim_values(target_prim_path + "/Cube1", target_prim_path + "/Cube2") else: check_prim_values(target_prim_paths[0], target_prim_paths[1]) # ---------------------------------------------------------------------- async def test_read_write_prims_translate_only(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an attribute pattern to just translate""" await self._test_read_write_prims_patterns( "xformOp:trans*", None, None, [ [(1.0, 2.0, 3.0), (0.0, 0.0, 0.0)], [(4.0, 5.0, 6.0), (0.0, 0.0, 0.0)], ], False, ) # ---------------------------------------------------------------------- async def test_read_write_prims_translate_only_scatter(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an attribute pattern to just translate""" await self._test_read_write_prims_patterns( "xformOp:trans*", None, None, [ [(1.0, 2.0, 3.0), (0.0, 0.0, 0.0)], [(4.0, 5.0, 6.0), (0.0, 0.0, 0.0)], ], True, ) # ---------------------------------------------------------------------- async def test_read_write_prims_rotate_only(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an attribute pattern to just rotate""" await self._test_read_write_prims_patterns( "xformOp:rotate*", None, None, [ [(0.0, 0.0, 0.0), (7.0, 8.0, 9.0)], [(0.0, 0.0, 0.0), (10.0, 11.0, 12.0)], ], False, ) # ---------------------------------------------------------------------- async def test_read_write_prims_rotate_only_scatter(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an attribute pattern to just rotate""" await self._test_read_write_prims_patterns( "xformOp:rotate*", None, None, [ [(0.0, 0.0, 0.0), (7.0, 8.0, 9.0)], [(0.0, 0.0, 0.0), (10.0, 11.0, 12.0)], ], True, ) # ---------------------------------------------------------------------- async def test_read_write_prims_xform_only(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an attribute pattern to translate and rotate""" await self._test_read_write_prims_patterns( "xformOp:*", None, None, [ [(1.0, 2.0, 3.0), (7.0, 8.0, 9.0)], [(4.0, 5.0, 6.0), (10.0, 11.0, 12.0)], ], False, ) # ---------------------------------------------------------------------- async def test_read_write_prims_xform_only_scatter(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an attribute pattern to translate and rotate""" await self._test_read_write_prims_patterns( "xformOp:*", None, None, [ [(1.0, 2.0, 3.0), (7.0, 8.0, 9.0)], [(4.0, 5.0, 6.0), (10.0, 11.0, 12.0)], ], True, ) # ---------------------------------------------------------------------- async def test_read_write_prims_shape1_only(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an path pattern to limit writing to Shape1 only""" await self._test_read_write_prims_patterns( None, "/Shape1", None, [ [(1.0, 2.0, 3.0), (7.0, 8.0, 9.0)], [(0.0, 0.0, 0.0), (0.0, 0.0, 0.0)], ], False, ) # ---------------------------------------------------------------------- async def test_read_write_prims_shape1_only_scatter(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an path pattern to limit writing to Shape1 only""" await self._test_read_write_prims_patterns( None, "/Shape1", None, [ [(1.0, 2.0, 3.0), (7.0, 8.0, 9.0)], [(0.0, 0.0, 0.0), (0.0, 0.0, 0.0)], ], True, ) # ---------------------------------------------------------------------- async def test_read_write_prims_shape2_only(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an path pattern to limit writing to Shape2 only""" await self._test_read_write_prims_patterns( None, "/Shape2", None, [ [(0.0, 0.0, 0.0), (0.0, 0.0, 0.0)], [(4.0, 5.0, 6.0), (10.0, 11.0, 12.0)], ], False, ) # ---------------------------------------------------------------------- async def test_read_write_prims_shape2_only_scatter(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an path pattern to limit writing to Shape2 only""" await self._test_read_write_prims_patterns( None, "/Shape2", None, [ [(0.0, 0.0, 0.0), (0.0, 0.0, 0.0)], [(4.0, 5.0, 6.0), (10.0, 11.0, 12.0)], ], True, ) # ---------------------------------------------------------------------- async def test_read_write_prims_both_shapes(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an path pattern to write to both shapes""" await self._test_read_write_prims_patterns( None, "/Shape*", None, [ [(1.0, 2.0, 3.0), (7.0, 8.0, 9.0)], [(4.0, 5.0, 6.0), (10.0, 11.0, 12.0)], ], False, ) # ---------------------------------------------------------------------- async def test_read_write_prims_both_shapes_scatter(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an path pattern to write to both shapes""" await self._test_read_write_prims_patterns( None, "/Shape*", None, [ [(1.0, 2.0, 3.0), (7.0, 8.0, 9.0)], [(4.0, 5.0, 6.0), (10.0, 11.0, 12.0)], ], True, ) # ---------------------------------------------------------------------- async def test_read_write_prims_cube_only(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an path pattern to limit writing to cubes only""" await self._test_read_write_prims_patterns( None, None, "Cube", [ [(1.0, 2.0, 3.0), (7.0, 8.0, 9.0)], [(0.0, 0.0, 0.0), (0.0, 0.0, 0.0)], ], False, ) # ---------------------------------------------------------------------- async def test_read_write_prims_cube_only_scatter(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an path pattern to limit writing to cubes only""" await self._test_read_write_prims_patterns( None, None, "Cube", [ [(1.0, 2.0, 3.0), (7.0, 8.0, 9.0)], [(0.0, 0.0, 0.0), (0.0, 0.0, 0.0)], ], True, ) # ---------------------------------------------------------------------- async def test_read_write_prims_cone_only(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an type pattern to limit writing to cones only""" await self._test_read_write_prims_patterns( None, None, "Cone", [ [(0.0, 0.0, 0.0), (0.0, 0.0, 0.0)], [(4.0, 5.0, 6.0), (10.0, 11.0, 12.0)], ], False, ) # ---------------------------------------------------------------------- async def test_read_write_prims_cone_only_scatter(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an type pattern to limit writing to cones only""" await self._test_read_write_prims_patterns( None, None, "Cone", [ [(0.0, 0.0, 0.0), (0.0, 0.0, 0.0)], [(4.0, 5.0, 6.0), (10.0, 11.0, 12.0)], ], True, ) # ---------------------------------------------------------------------- async def test_read_write_prims_cube_and_cone(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an type pattern to write to both cubes and cones""" await self._test_read_write_prims_patterns( None, None, "Cone;Cube", [ [(1.0, 2.0, 3.0), (7.0, 8.0, 9.0)], [(4.0, 5.0, 6.0), (10.0, 11.0, 12.0)], ], False, ) # ---------------------------------------------------------------------- async def test_read_write_prims_cube_and_cone_scatter(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims using an type pattern to write to both cubes and cones""" await self._test_read_write_prims_patterns( None, None, "Cone;Cube", [ [(1.0, 2.0, 3.0), (7.0, 8.0, 9.0)], [(4.0, 5.0, 6.0), (10.0, 11.0, 12.0)], ], True, ) # ---------------------------------------------------------------------- async def _test_read_write_prims_patterns( self, attr_pattern, path_pattern, type_pattern, expected_prim_values, scatter_under_targets: bool ): target_prim_paths = ["/target0", "/target1"] # test USD write back since it's the main workflow currently usd_write_back = True usd_context = omni.usd.get_context() stage: Usd.Stage = usd_context.get_stage() stage_rt = UsdRT.Stage.Attach(usd_context.get_stage_id()) controller = og.Controller() keys = og.Controller.Keys cube_prim = ogts.create_cube(stage, "Shape1", (1, 0, 0)) cone_prim = ogts.create_cone(stage, "Shape2", (0, 1, 0)) # add transforms with double precision xform_precision = UsdGeom.XformOp.PrecisionDouble for prim in [cube_prim, cone_prim]: UsdGeom.Xformable(prim).AddTranslateOp(xform_precision).Set((0, 0, 0)) UsdGeom.Xformable(prim).AddRotateXYZOp(xform_precision).Set((0, 0, 0)) UsdGeom.Xformable(prim).AddScaleOp(xform_precision).Set((1, 1, 1)) set_values = [ ("ExtractCube.inputs:primPath", "/Shape1"), ("ExtractCone.inputs:primPath", "/Shape2"), ("TranslateCube.inputs:value", (1, 2, 3)), ("TranslateCone.inputs:value", (4, 5, 6)), ("RotateCube.inputs:value", (7, 8, 9)), ("RotateCone.inputs:value", (10, 11, 12)), ("InsertTranslateCube.inputs:outputAttrName", "xformOp:translate"), ("InsertTranslateCone.inputs:outputAttrName", "xformOp:translate"), ("InsertRotateCube.inputs:outputAttrName", "xformOp:rotateXYZ"), ("InsertRotateCone.inputs:outputAttrName", "xformOp:rotateXYZ"), ("Write.inputs:usdWriteBack", usd_write_back), ("Write.inputs:scatterUnderTargets", scatter_under_targets), ] if attr_pattern: set_values.append(("Write.inputs:attrNamesToExport", attr_pattern)) if path_pattern: set_values.append(("Write.inputs:pathPattern", path_pattern)) if type_pattern: set_values.append(("Write.inputs:typePattern", type_pattern)) (graph, [extract_cube, extract_cone, *_], _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("ExtractCube", "omni.graph.nodes.ExtractPrim"), ("ExtractCone", "omni.graph.nodes.ExtractPrim"), ("Read", "omni.graph.nodes.ReadPrimsV2"), ("Write", "omni.graph.nodes.WritePrimsV2"), ("TranslateCube", "omni.graph.nodes.ConstantDouble3"), ("TranslateCone", "omni.graph.nodes.ConstantDouble3"), ("RotateCube", "omni.graph.nodes.ConstantDouble3"), ("RotateCone", "omni.graph.nodes.ConstantDouble3"), ("InsertTranslateCube", "omni.graph.nodes.InsertAttribute"), ("InsertTranslateCone", "omni.graph.nodes.InsertAttribute"), ("InsertRotateCube", "omni.graph.nodes.InsertAttribute"), ("InsertRotateCone", "omni.graph.nodes.InsertAttribute"), ], keys.CONNECT: [ ("Read.outputs_primsBundle", "ExtractCube.inputs:prims"), ("Read.outputs_primsBundle", "ExtractCone.inputs:prims"), ("TranslateCube.inputs:value", "InsertTranslateCube.inputs:attrToInsert"), ("TranslateCone.inputs:value", "InsertTranslateCone.inputs:attrToInsert"), ("RotateCube.inputs:value", "InsertRotateCube.inputs:attrToInsert"), ("RotateCone.inputs:value", "InsertRotateCone.inputs:attrToInsert"), ("ExtractCube.outputs_primBundle", "InsertTranslateCube.inputs:data"), ("ExtractCone.outputs_primBundle", "InsertTranslateCone.inputs:data"), ("InsertTranslateCube.outputs_data", "InsertRotateCube.inputs:data"), ("InsertTranslateCone.outputs_data", "InsertRotateCone.inputs:data"), ("InsertRotateCube.outputs_data", "Write.inputs:primsBundle"), ("InsertRotateCone.outputs_data", "Write.inputs:primsBundle"), ], keys.SET_VALUES: set_values, }, ) omni.kit.commands.execute( "SetRelationshipTargets", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"), targets=[cube_prim.GetPath(), cone_prim.GetPath()], ) for target_path in target_prim_paths: target_xform = UsdGeom.Xform.Define(stage, target_path) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Write.inputs:prims"), target=target_xform.GetPrim().GetPath(), ) await self._evaluate_graph(graph, controller) self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR]) graph_context = graph.get_default_graph_context() cube_bundle = graph_context.get_output_bundle(extract_cube, "outputs_primBundle") cone_bundle = graph_context.get_output_bundle(extract_cone, "outputs_primBundle") prim_bundles = [cube_bundle, cone_bundle] prim_paths = ["/Shape1", "/Shape2"] prim_types = ["Cube", "Cone"] # We will check these attributes attr_names = ["xformOp:translate", "xformOp:rotateXYZ"] # We need two lists of values, one for each prim self.assertEqual(len(expected_prim_values), 2) attr_pattern_tokens = attr_pattern.split(";") if attr_pattern else [] path_pattern_tokens = path_pattern.split(";") if path_pattern else [] type_pattern_tokens = type_pattern.split(";") if type_pattern else [] for prim_index, _prim_bundle in enumerate(prim_bundles): expected_values = expected_prim_values[prim_index] # All attribute values must be passed self.assertEqual(len(expected_values), len(attr_names)) # Check attributes values in prim bundle for attr_index, expected_value in enumerate(expected_values): attr_name = attr_names[attr_index] def check_prim_values(source_prim_path, target_prim_path, prim_type, attr_name, expected_value): if usd_write_back: prim = stage.GetPrimAtPath(target_prim_path) else: prim = stage_rt.GetPrimAtPath(target_prim_path) # to emulate matcher behavior attr_matched = True if attr_pattern_tokens: attr_matched = False for token in attr_pattern_tokens: attr_matched |= fnmatch.fnmatch(attr_name, token) if attr_matched: break prim_matched = True if path_pattern_tokens: path_matched = False for token in path_pattern_tokens: path_matched |= fnmatch.fnmatch(source_prim_path, token) prim_matched &= path_matched if type_pattern_tokens: type_matched = False for token in type_pattern_tokens: type_matched |= fnmatch.fnmatch(prim_type, token) prim_matched &= type_matched # Check values if prim_matched: if usd_write_back: # usdrt syncs usd prim type if only change the type in fabric self.assertEqual(prim.GetTypeName(), prim_type) if attr_matched: actual_value_rt = tuple(prim.GetAttribute(attr_name).Get()) self.assertEqual(actual_value_rt, expected_value) else: # if attribute does not match, it won't be exported self.assertFalse(prim.GetAttribute(attr_name).IsValid()) else: if scatter_under_targets: # if unmatched, the target prim won't exist if filter failed self.assertFalse(prim.IsValid()) else: # if unmatched, the prim type won't change from xform to cube/cone self.assertTrue(prim.IsValid()) self.assertEqual(prim.GetTypeName(), "Xform") if scatter_under_targets: for target_prim_path in target_prim_paths: check_prim_values( prim_paths[prim_index], target_prim_path + prim_paths[prim_index], prim_types[prim_index], attr_name, expected_value, ) else: check_prim_values( prim_paths[prim_index], target_prim_paths[prim_index], prim_types[prim_index], attr_name, expected_value, ) # ---------------------------------------------------------------------- async def test_read_write_prims_array_new_attr_to_fabric(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims for a new array attribute, Fabric only""" await self._test_read_write_prims_vec3_array(False, False, False) # ---------------------------------------------------------------------- async def test_read_write_prims_array_new_attr_to_fabric_scatter(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims for a new array attribute, Fabric only""" await self._test_read_write_prims_vec3_array(False, False, True) # ---------------------------------------------------------------------- async def test_read_write_prims_array_new_attr_to_usd(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims for a new array attribute, writing back to USD""" await self._test_read_write_prims_vec3_array(True, False, False) # ---------------------------------------------------------------------- async def test_read_write_prims_array_new_attr_to_usd_scatter(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims for a new array attribute, writing back to USD""" await self._test_read_write_prims_vec3_array(True, False, True) # ---------------------------------------------------------------------- async def test_read_write_prims_array_attr_to_fabric(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims for an existing array attribute, Fabric only""" await self._test_read_write_prims_vec3_array(False, True, False) # ---------------------------------------------------------------------- async def test_read_write_prims_array_attr_to_fabric_scatter(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims for an existing array attribute, Fabric only""" await self._test_read_write_prims_vec3_array(False, True, True) # ---------------------------------------------------------------------- async def test_read_write_prims_array_attr_to_usd(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims for an existing array attribute, writing back to USD""" await self._test_read_write_prims_vec3_array(True, True, False) # ---------------------------------------------------------------------- async def test_read_write_prims_array_attr_to_usd_scatter(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims for an existing array attribute, writing back to USD""" await self._test_read_write_prims_vec3_array(True, True, True) # ---------------------------------------------------------------------- async def _test_read_write_prims_vec3_array( self, usd_write_back: bool, add_new_attr: bool, scatter_under_targets: bool ): target_prim_paths = ["/target0", "/target1"] usd_context = omni.usd.get_context() stage = usd_context.get_stage() stage_rt = UsdRT.Stage.Attach(usd_context.get_stage_id()) cube_prim = ogts.create_cube(stage, "Cube", (1, 0, 0)) attr_name = "new_array_attr" if not add_new_attr: # if graph is not going to add a new attr, make the attr now with USD API so it exists before graph execution. # Cannot reuse primvars:displayColor because it's a color3f[], not a strict float3[], and ConstructArray node # cannot set role. cube_prim.CreateAttribute(attr_name, Sdf.ValueTypeNames.Float3Array).Set([(1, 0, 0)]) controller = og.Controller() keys = og.Controller.Keys (graph, nodes, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Read", "omni.graph.nodes.ReadPrimsV2"), ("Write", "omni.graph.nodes.WritePrimsV2"), ("ExtractCube", "omni.graph.nodes.ExtractPrim"), ("MakeArray", "omni.graph.nodes.ConstructArray"), ("InsertAttribute", "omni.graph.nodes.InsertAttribute"), ], keys.SET_VALUES: [ ("ExtractCube.inputs:primPath", "/Cube"), ("MakeArray.inputs:arraySize", 1), ("MakeArray.inputs:arrayType", "float[3][]"), ("MakeArray.inputs:input0", [0.25, 0.50, 0.75]), ("InsertAttribute.inputs:outputAttrName", attr_name), ("Write.inputs:usdWriteBack", usd_write_back), ("Write.inputs:scatterUnderTargets", scatter_under_targets), ], keys.CONNECT: [ ("Read.outputs_primsBundle", "ExtractCube.inputs:prims"), ("ExtractCube.outputs_primBundle", "InsertAttribute.inputs:data"), ("MakeArray.outputs:array", "InsertAttribute.inputs:attrToInsert"), ("InsertAttribute.outputs_data", "Write.inputs:primsBundle"), ], }, ) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"), target=cube_prim.GetPath(), ) for target_path in target_prim_paths: target_xform = UsdGeom.Xform.Define(stage, target_path) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Write.inputs:prims"), target=target_xform.GetPrim().GetPath(), ) await self._evaluate_graph(graph, controller) self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR]) graph_context = graph.get_default_graph_context() cube_bundle = graph_context.get_output_bundle(nodes[2], "outputs_primBundle") self.assertTrue(cube_bundle.valid) cube_path = "/Cube" def check_prim_values(source_prim_path, target_prim_path): # Check Fabric values fabric_values = stage_rt.GetPrimAtPath(target_prim_path).GetAttribute(attr_name).Get() self.assertEqual(len(fabric_values), 1) self.assertEqual(tuple(fabric_values[0]), (0.25, 0.50, 0.75)) if usd_write_back: # With USD write back, the existing attribute should be updated in USD usd_values = stage.GetPrimAtPath(target_prim_path).GetAttribute(attr_name).Get() self.assertEqual(len(usd_values), 1) self.assertEqual(tuple(usd_values[0]), (0.25, 0.50, 0.75)) else: if scatter_under_targets: self.assertFalse(stage.GetPrimAtPath(target_prim_path).IsValid()) if scatter_under_targets: for target_prim_path in target_prim_paths: check_prim_values(cube_path, target_prim_path + cube_path) else: # only one source check_prim_values(cube_path, target_prim_paths[0]) async def test_read_write_prims_remove_missing_to_usd(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims MPiB with remove missing attributes and prims matching to USD""" await self._test_read_write_prims_remove_missing(True, False) async def test_read_write_prims_remove_missing_to_usd_scatter(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims MPiB with remove missing attributes and prims matching to USD""" await self._test_read_write_prims_remove_missing(True, True) async def test_read_write_prims_remove_missing_to_fabric(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims MPiB with remove missing attributes and prims matching to Fabric""" await self._test_read_write_prims_remove_missing(False, False) async def test_read_write_prims_remove_missing_to_fabric_scatter(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims MPiB with remove missing attributes and prims matching to Fabric""" await self._test_read_write_prims_remove_missing(False, True) # ---------------------------------------------------------------------- async def _test_read_write_prims_remove_missing(self, usd_write_back: bool, scatter_under_targets: bool): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims MPiB with exact attributes and prims matching""" usd_context = omni.usd.get_context() stage_usd: Usd.Stage = usd_context.get_stage() stage_rt = UsdRT.Stage.Attach(usd_context.get_stage_id()) controller = og.Controller() keys = og.Controller.Keys # Stage hierarchy: # # /Xform # /Xform # /Cube2 # /Cube1 # /target0 # /target1 stage_usd.DefinePrim("/Xform", "Xform") stage_usd.DefinePrim("/Xform/Xform", "Xform") cube1_prim = stage_usd.DefinePrim("/Xform/Cube1", "Cube") cube2_prim = stage_usd.DefinePrim("/Xform/Xform/Cube2", "Cube") test_attr_name = "test_attr" test_target_existing_attr_name = "test_attr2" test_both_existing_attr_name = "test_attr3" cube1_prim.CreateAttribute(test_attr_name, Sdf.ValueTypeNames.Float3) cube2_prim.CreateAttribute(test_attr_name, Sdf.ValueTypeNames.Float3) (graph, _, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Read", "omni.graph.nodes.ReadPrimsV2"), ("Write", "omni.graph.nodes.WritePrimsV2"), ], keys.SET_VALUES: [ ("Write.inputs:usdWriteBack", usd_write_back), ("Write.inputs:scatterUnderTargets", scatter_under_targets), ], keys.CONNECT: [ ("Read.outputs_primsBundle", "Write.inputs:primsBundle"), ], }, ) omni.kit.commands.execute( "SetRelationshipTargets", relationship=stage_usd.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"), targets=[cube1_prim.GetPath(), cube2_prim.GetPath()], ) target_prim_paths = ["/target0", "/target1"] for target_path in target_prim_paths: target_xform = UsdGeom.Cube.Define(stage_usd, target_path) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage_usd.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Write.inputs:prims"), target=target_xform.GetPrim().GetPath(), ) # put a Sphere under the target. This should NOT be removed by removeMissingPrims later, as it doesn't exist in the upstream bundle stage_usd.DefinePrim(target_path + "/Sphere", "Sphere") await self._evaluate_graph(graph, controller) self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR]) # check attributes are exported correctly and setup the test scenario for removeMissingAttrs # Add test_target_existing_attr_name to target prims only # Add test_both_existing_attr_name to both source and target prims for i, path in enumerate([cube1_prim.GetPath(), cube2_prim.GetPath()]): def check_initial_prim(target_prim_path): for stage in [stage_rt, stage_usd]: # Check prim prim = stage.GetPrimAtPath(target_prim_path) self.assertTrue(prim.IsValid()) # Check attribute attr = prim.GetAttribute(test_attr_name) self.assertTrue(attr.IsValid()) # skip stage_usd check if usd_write_back is off if not usd_write_back: break def add_attribute_to_source(source_prim_path): # creates additional attributes on output prims. # these attribute should not be removed, as there did not exist in upstream bundle for stage, sdf in [(stage_rt, SdfRT), (stage_usd, Sdf)]: prim = stage.GetPrimAtPath(source_prim_path) prim.CreateAttribute(test_both_existing_attr_name, sdf.ValueTypeNames.Float2, True) if not usd_write_back: break def add_attribute_to_target_output(target_prim_path): # creates additional attributes on output prims. # these attribute should not be removed, as there did not exist in upstream bundle for stage, sdf in [(stage_rt, SdfRT), (stage_usd, Sdf)]: prim = stage.GetPrimAtPath(target_prim_path) prim.CreateAttribute(test_target_existing_attr_name, sdf.ValueTypeNames.Float2, True) prim.CreateAttribute(test_both_existing_attr_name, sdf.ValueTypeNames.Float2, True) if not usd_write_back: break if scatter_under_targets: for target_prim_path in target_prim_paths: check_initial_prim(target_prim_path + path.pathString) add_attribute_to_target_output(target_prim_path + path.pathString) else: check_initial_prim(target_prim_paths[i]) add_attribute_to_target_output(target_prim_paths[i]) add_attribute_to_source(path.pathString) await self._evaluate_graph(graph, controller) self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR]) # --------------------------- test removeMissingAttrs ----------------------------------------- # remove the test_attr from source and tick the graph, it must be removed from target too cube1_prim.RemoveProperty(test_attr_name) cube2_prim.RemoveProperty(test_attr_name) # remove the test_attr from source and tick the graph, it must be removed from target too cube1_prim.RemoveProperty(test_both_existing_attr_name) cube2_prim.RemoveProperty(test_both_existing_attr_name) # TODO ReadPrims node won't clear the attributes from output bundle due to lack of USD change tracking, # has to set attrNamesToImport to force a re-evaluation # FIXME when ReadPrims node properly tracks USD changes. controller.edit( self.TEST_GRAPH_PATH, { keys.SET_VALUES: [ # changing filter from '*' to '**' applies same filter but forces node to re-evaluate to remove deleted attributes ("Read.inputs:attrNamesToImport", "**"), ], }, ) await self._evaluate_graph(graph, controller) self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR]) for i, path in enumerate([cube1_prim.GetPath(), cube2_prim.GetPath()]): def check_prim_attr_matched(source_prim_path, target_prim_path): for stage in [stage_rt, stage_usd]: prim = stage.GetPrimAtPath(target_prim_path) self.assertTrue(prim.IsValid()) # Check attribute, it should be gone attr = prim.GetAttribute(test_attr_name) self.assertFalse(attr.IsValid()) # Check pre-existing attribute that has not been written to, it should stay attr = prim.GetAttribute(test_target_existing_attr_name) self.assertTrue(attr.IsValid()) # Check pre-existing attribute that has been written to, it should stay attr = prim.GetAttribute(test_both_existing_attr_name) self.assertTrue(attr.IsValid()) # skip stage_usd check if usd_write_back is off if not usd_write_back: break if scatter_under_targets: for target_prim_path in target_prim_paths: check_prim_attr_matched(path, target_prim_path + path.pathString) else: check_prim_attr_matched(path, target_prim_paths[i]) # ------------------------- test removeMissingPrims --------------------------------- # remove the /Cube1 from source and tick the graph, it must be removed from target too omni.kit.commands.execute( "RemoveRelationshipTarget", relationship=stage_usd.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"), target=cube2_prim.GetPath(), ) await self._evaluate_graph(graph, controller) self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR]) def check_prim_matched(target_root_path, prim_path, valid: bool): # Check USD and fabric prim, "Cube2" should be removed, "Cube1" stays target_prim_path = target_root_path + prim_path for stage in [stage_rt, stage_usd]: prim = stage.GetPrimAtPath(target_prim_path) self.assertEqual(prim.IsValid(), valid) # The pre-existing Sphere prim should still exist self.assertTrue(stage.GetPrimAtPath(target_root_path + "/Sphere").IsValid()) # The stub prim /targetN/Xform/Xform should also be removed self.assertFalse(stage.GetPrimAtPath(target_root_path + "/Xform/Xform").IsValid()) # skip stage_usd check if usd_write_back is off if not usd_write_back: break if scatter_under_targets: for i, path in enumerate([cube1_prim.GetPath(), cube2_prim.GetPath()]): for target_prim_path in target_prim_paths: check_prim_matched(target_prim_path, path.pathString, i == 0) else: check_prim_matched(target_prim_paths[0], "", True) # test removeMissingPrims with no prim input # remove all prims from ReadPrims node, and the target should be empty omni.kit.commands.execute( "SetRelationshipTargets", relationship=stage_usd.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"), targets=[], ) await self._evaluate_graph(graph, controller) self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR]) # target prims should have only the "Sphere" prim as child for target_prim_path in target_prim_paths: target_prim = stage_usd.GetPrimAtPath(target_prim_path) self.assertEqual(target_prim.GetAllChildrenNames(), ["Sphere"]) async def test_read_write_prims_remove_schema_properties(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims MPiB that removes attributes defined within schema""" await self._test_read_write_prims_remove_schema_properties(False) async def test_read_write_prims_remove_schema_properties_scatter(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims MPiB that removes attributes defined within schema""" await self._test_read_write_prims_remove_schema_properties(True) # ---------------------------------------------------------------------- async def _test_read_write_prims_remove_schema_properties(self, scatter_under_targets: bool): """ Test omni.graph.nodes.ReadPrimsV2 and WritePrims MPiB that removes attributes defined within schema This is a USD-only test as Fabric doesn't have the schema concept yet """ usd_context = omni.usd.get_context() stage: Usd.Stage = usd_context.get_stage() controller = og.Controller() keys = og.Controller.Keys # Stage hierarchy: # # /Xform # /target xform_prim = stage.DefinePrim("/Xform", "Xform") # both are schema properties of Xformable test_attr_name = UsdGeom.Tokens.visibility test_rel_name = UsdGeom.Tokens.proxyPrim xform_prim.GetAttribute(UsdGeom.Tokens.visibility).Set(UsdGeom.Tokens.invisible) xform_prim.GetRelationship(test_rel_name).AddTarget("/Foo/bar") (graph, _, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Read", "omni.graph.nodes.ReadPrimsV2"), ("Write", "omni.graph.nodes.WritePrimsV2"), ], keys.SET_VALUES: [ ("Write.inputs:usdWriteBack", True), ("Write.inputs:scatterUnderTargets", scatter_under_targets), ], keys.CONNECT: [ ("Read.outputs_primsBundle", "Write.inputs:primsBundle"), ], }, ) omni.kit.commands.execute( "SetRelationshipTargets", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"), targets=[xform_prim.GetPath()], ) target_xform = UsdGeom.Xform.Define(stage, "/target") omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Write.inputs:prims"), target=target_xform.GetPrim().GetPath(), ) await self._evaluate_graph(graph, controller) self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR]) def check_initial_prim(target_prim_path): # Check prim prim = stage.GetPrimAtPath(target_prim_path) self.assertTrue(prim.IsValid()) # Check attribute # It should be both valid and authored for target prim attr = prim.GetAttribute(test_attr_name) self.assertTrue(attr.IsAuthored()) self.assertEqual(attr.Get(), UsdGeom.Tokens.invisible) # Check relationship # It should be both valid and authored for target prim rel = prim.GetRelationship(test_rel_name) self.assertTrue(rel.IsAuthored()) self.assertListEqual(rel.GetTargets(), ["/Foo/bar"]) if scatter_under_targets: check_initial_prim("/target/Xform") else: check_initial_prim("/target") # Remove spec for both properties # XXX cannot use RemoveProperty due to change tracking not working properly in ReadPrimsV2 node # set attrNamesToImport to empty instead to clear the attributes from ReadPrimsV2 output bundle # xform_prim.RemoveProperty(test_attr_name) # xform_prim.RemoveProperty(test_rel_name) controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: ("Read.inputs:attrNamesToImport", "")}) await self._evaluate_graph(graph, controller) self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR]) def check_ticked_prim(target_prim_path): # Check prim prim = stage.GetPrimAtPath(target_prim_path) self.assertTrue(prim.IsValid()) # Check attribute # It should still exits but be reverted to unauthored schema value attr = prim.GetAttribute(test_attr_name) self.assertTrue(attr.IsValid()) self.assertFalse(attr.IsAuthored()) self.assertEqual(attr.Get(), UsdGeom.Tokens.inherited) # Check relationship # It should still exits but be reverted to unauthored schema value rel = prim.GetRelationship(test_rel_name) self.assertTrue(rel.IsValid()) self.assertFalse(rel.IsAuthored()) self.assertListEqual(rel.GetTargets(), []) if scatter_under_targets: check_ticked_prim("/target/Xform") else: check_ticked_prim("/target") # ---------------------------------------------------------------------- async def test_read_write_prims_fill_usd_hierarchy_gap(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims when some prim along target hierarchy does not fully exist""" usd_context = omni.usd.get_context() stage: Usd.Stage = usd_context.get_stage() controller = og.Controller() keys = og.Controller.Keys UsdGeom.Xform.Define(stage, "/Xform") scope = UsdGeom.Scope.Define(stage, "/Xform/Scope") cube = UsdGeom.Cube.Define(stage, "/Xform/Scope/Cube") target_xform = UsdGeom.Xform.Define(stage, "/Target") (graph, [_, _], _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Read", "omni.graph.nodes.ReadPrimsV2"), ("Write", "omni.graph.nodes.WritePrimsV2"), ], keys.SET_VALUES: [ ("Write.inputs:usdWriteBack", True), ("Write.inputs:scatterUnderTargets", True), ], keys.CONNECT: [ ("Read.outputs_primsBundle", "Write.inputs:primsBundle"), ], }, ) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"), target=cube.GetPrim().GetPath(), ) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Write.inputs:prims"), target=target_xform.GetPrim().GetPath(), ) await self._evaluate_graph(graph, controller) self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR]) # check the target hierarchy was created, all missing prims has the type Xform self.assertTrue(UsdGeom.Xform.Get(stage, "/Target/Xform")) self.assertTrue(UsdGeom.Xform.Get(stage, "/Target/Xform/Scope")) self.assertTrue(UsdGeom.Cube.Get(stage, "/Target/Xform/Scope/Cube")) # add /Xform/Scope to import targets omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"), target=scope.GetPrim().GetPath(), ) await self._evaluate_graph(graph, controller) self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR]) # check the target hierarchy was created, because "/Xform/Scope" is also exported, # the type should be changed from Xform to Scope self.assertTrue(UsdGeom.Xform.Get(stage, "/Target/Xform")) self.assertTrue(UsdGeom.Scope.Get(stage, "/Target/Xform/Scope")) self.assertFalse(UsdGeom.Xform.Get(stage, "/Target/Xform/Scope")) self.assertTrue(UsdGeom.Cube.Get(stage, "/Target/Xform/Scope/Cube")) # ---------------------------------------------------------------------- async def test_read_write_prims_find_prims_loop_guard(self): await self._test_read_write_prims_find_prims_loop_guard(False) # ---------------------------------------------------------------------- async def test_read_write_prims_find_prims_loop_guard_scatter(self): await self._test_read_write_prims_find_prims_loop_guard(True) # ---------------------------------------------------------------------- async def _test_read_write_prims_find_prims_loop_guard(self, scatter_under_targets: bool): """Test omni.graph.nodes.ReadPrimsV2 find prims tracker and WritePrims that loop can be detect and prevented""" logging = carb.logging.acquire_logging() usd_context = omni.usd.get_context() stage: Usd.Stage = usd_context.get_stage() controller = og.Controller() keys = og.Controller.Keys xform = UsdGeom.Xform.Define(stage, "/Xform") xform_xform = UsdGeom.Xform.Define(stage, "/Xform/Xform") xform2 = UsdGeom.Xform.Define(stage, "/Xform2") xform2_xform = UsdGeom.Xform.Define(stage, "/Xform2/Xform") (graph, _, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Read", "omni.graph.nodes.ReadPrimsV2"), ("Read2", "omni.graph.nodes.ReadPrimsV2"), ("Write", "omni.graph.nodes.WritePrimsV2"), ], keys.SET_VALUES: [ ("Read.inputs:pathPattern", "*"), ("Write.inputs:usdWriteBack", True), ("Write.inputs:scatterUnderTargets", scatter_under_targets), ], keys.CONNECT: [ ("Read.outputs_primsBundle", "Write.inputs:primsBundle"), ], }, ) # ------------ test path tracker on connected Read node ------------ omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"), target=xform.GetPrim().GetPath(), ) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Write.inputs:prims"), target=xform_xform.GetPrim().GetPath(), ) log_was_enabled = logging.is_log_enabled() # turn off carb logging so the error does not trigger test failure # og logging still works and logs node error message. logging.set_log_enabled(False) await self._evaluate_graph(graph, controller) error_message = self._get_node_messages(graph, og.ERROR) # check the error is logged self.assertEqual( error_message, [ "[/World/TestGraph] Target prim '/Xform/Xform' is a descendant of FindPrims/ReadPrims source '/Xform', writing to the target may mutate the input state. Please choose a different target" ], ) # check the target prim is NOT created if scatter_under_targets: self.assertFalse(stage.GetPrimAtPath("/Xform/Xform/Xform").IsValid()) # ------------ test path tracker on unconnected Read node ------------ controller.edit( self.TEST_GRAPH_PATH, { keys.SET_VALUES: [ ("Read2.inputs:pathPattern", "*"), ] }, ) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read2.inputs:prims"), target=xform2.GetPrim().GetPath(), ) omni.kit.commands.execute( "SetRelationshipTargets", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Write.inputs:prims"), targets=[xform2_xform.GetPrim().GetPath()], ) await self._evaluate_graph(graph, controller) error_message = self._get_node_messages(graph, og.ERROR) # check the error is logged self.assertEqual( error_message, [ "[/World/TestGraph] Target prim '/Xform2/Xform' is a descendant of FindPrims/ReadPrims source '/Xform2', writing to the target may mutate the input state. Please choose a different target" ], ) # check the target prim is NOT created if scatter_under_targets: self.assertFalse(stage.GetPrimAtPath("/Xform2/Xform/Xform").IsValid()) logging.set_log_enabled(log_was_enabled) # ---------------------------------------------------------------------- async def test_write_prims_empty_bundle(self): """Test warnings and errors issued by omni.graph.nodes.WritePrimsV2 when its input bundle is empty""" controller = og.Controller() keys = og.Controller.Keys (graph, _, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("bundle_ctor", "omni.graph.nodes.BundleConstructor"), ("write_prims", "omni.graph.nodes.WritePrimsV2"), ], keys.CONNECT: [ ("bundle_ctor.outputs_bundle", "write_prims.inputs:primsBundle"), ], }, ) with self.CarbLogSuppressor(): await self._evaluate_graph(graph, controller) # no warning or errors messages are expected self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR]) # ---------------------------------------------------------------------- async def test_write_prims_source_prim_path_validation_str(self): """Test warnings and errors issued by omni.graph.nodes.WritePrimsV2 when a string sourcePrimPath is detected""" await self._test_write_prims_attribute_validation_impl( "sourcePrimPath", "foo", "String", "sourcePrimPath attribute must hold a token" ) async def test_write_prims_source_prim_path_validation_int(self): """Test warnings and errors issued by omni.graph.nodes.WritePrimsV2 when an integer sourcePrimPath is detected""" await self._test_write_prims_attribute_validation_impl( "sourcePrimPath", 42, "Int", "sourcePrimPath attribute must hold a token" ) async def test_write_prims_source_prim_type_validation_str(self): """Test warnings and errors issued by omni.graph.nodes.WritePrimsV2 when a string sourcePrimType is detected""" await self._test_write_prims_attribute_validation_impl( "sourcePrimType", "bar", "String", "sourcePrimType attribute must hold a token" ) async def test_write_prims_source_prim_type_validation_int(self): """Test warnings and errors issued by omni.graph.nodes.WritePrimsV2 when an integer rsourcePrimType is detected""" await self._test_write_prims_attribute_validation_impl( "sourcePrimType", 42, "Int", "sourcePrimType attribute must hold a token" ) async def _test_write_prims_attribute_validation_impl( self, attr_name, attr_value, attr_type, expected_error_message ): usd_context = omni.usd.get_context() stage: Usd.Stage = usd_context.get_stage() controller = og.Controller() keys = og.Controller.Keys ogts.create_cube(stage, "Cube", (1, 0, 0)) (graph, _, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("CreateEmptyBundle", "omni.graph.nodes.BundleConstructor"), ("WritePrims", "omni.graph.nodes.WritePrimsV2"), ("ConstSourcePrimPath", f"omni.graph.nodes.Constant{attr_type}"), ("InsertSourcePrimPath", "omni.graph.nodes.InsertAttribute"), ], keys.SET_VALUES: [ ("ConstSourcePrimPath.inputs:value", attr_value), ("InsertSourcePrimPath.inputs:outputAttrName", attr_name), ], keys.CONNECT: [ ("ConstSourcePrimPath.inputs:value", "InsertSourcePrimPath.inputs:attrToInsert"), ("CreateEmptyBundle.outputs_bundle", "InsertSourcePrimPath.inputs:data"), ("InsertSourcePrimPath.outputs_data", "WritePrims.inputs:primsBundle"), ], }, ) target_xform = UsdGeom.Xform.Define(stage, "/Targets") omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/WritePrims.inputs:prims"), target=target_xform.GetPrim().GetPath(), ) with self.CarbLogSuppressor(): await self._evaluate_graph(graph, controller) # check the error is logged expected_message = f"[{self.TEST_GRAPH_PATH}] Bundle '{self.TEST_GRAPH_PATH}/__runtime_data/InsertSourcePrimPath_outputs_data' was skipped because it was invalid! {expected_error_message}" self.assertEqual(self._get_node_messages(graph, og.WARNING), [expected_message]) # no warning message is expected self._assert_no_compute_messages(graph, [og.ERROR]) # ---------------------------------------------------------------------- async def test_read_write_prims_to_layer(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrims MPiB to a different layer""" usd_context = omni.usd.get_context() stage: Usd.Stage = usd_context.get_stage() controller = og.Controller() keys = og.Controller.Keys session_layer = stage.GetSessionLayer() sub_layer = Sdf.Layer.CreateAnonymous() sub_layer2 = Sdf.Layer.CreateAnonymous() root_layer = stage.GetRootLayer() root_layer.subLayerPaths.append(sub_layer.identifier) root_layer.subLayerPaths.append(sub_layer2.identifier) test_layers = [session_layer, sub_layer, sub_layer2, root_layer] # switch edit target to sub_layer2 with Usd.EditContext(stage, sub_layer2): def create_scope_with_test_attrs(prim_path: str): scope = UsdGeom.Scope.Define(stage, prim_path) scope_prim = scope.GetPrim() scope_prim.CreateAttribute("test_attr_0", Sdf.ValueTypeNames.Bool).Set(True) scope_prim.CreateAttribute("test_attr_1", Sdf.ValueTypeNames.Bool).Set(True) scope_prim.CreateAttribute("test_attr_2", Sdf.ValueTypeNames.Bool).Set(True) scope_prim.CreateAttribute("test_attr_3", Sdf.ValueTypeNames.Bool).Set(True) return scope_prim test_layer_count = len(test_layers) source_prims = [] for i in range(test_layer_count): source_prims.append(create_scope_with_test_attrs(f"/Scope{i}")) # make a graph to Read from scope_prim_N, Write to scope_N_out prim with only test_attr_N to layer index N (graph, _, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Read0", "omni.graph.nodes.ReadPrimsV2"), ("Read1", "omni.graph.nodes.ReadPrimsV2"), ("Read2", "omni.graph.nodes.ReadPrimsV2"), ("Read3", "omni.graph.nodes.ReadPrimsV2"), ("Write0", "omni.graph.nodes.WritePrimsV2"), ("Write1", "omni.graph.nodes.WritePrimsV2"), ("Write2", "omni.graph.nodes.WritePrimsV2"), ("Write3", "omni.graph.nodes.WritePrimsV2"), ], keys.SET_VALUES: [ ("Write0.inputs:layerIdentifier", "<Session Layer>"), ("Write1.inputs:layerIdentifier", sub_layer.identifier), ("Write2.inputs:layerIdentifier", ""), # write to current edit target (sub_layer2 in this case) ("Write3.inputs:layerIdentifier", "<Root Layer>"), ("Write0.inputs:attrNamesToExport", "test_attr_0"), ("Write1.inputs:attrNamesToExport", "test_attr_1"), ("Write2.inputs:attrNamesToExport", "test_attr_2"), ("Write3.inputs:attrNamesToExport", "test_attr_3"), ], keys.CONNECT: [ ("Read0.outputs_primsBundle", "Write0.inputs:primsBundle"), ("Read1.outputs_primsBundle", "Write1.inputs:primsBundle"), ("Read2.outputs_primsBundle", "Write2.inputs:primsBundle"), ("Read3.outputs_primsBundle", "Write3.inputs:primsBundle"), ], }, ) for i in range(test_layer_count): omni.kit.commands.execute( "SetRelationshipTargets", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read{i}.inputs:prims"), targets=[source_prims[i].GetPath()], ) omni.kit.commands.execute( "SetRelationshipTargets", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Write{i}.inputs:prims"), targets=[f"/Scope_{i}_out"], ) await self._evaluate_graph(graph, controller) self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR]) # Scope_0_out should only exist on test_layers[0] with test_attr_0 # Scope_1_out should only exist on test_layers[1] with test_attr_1 # Scope_2_out should only exist on test_layers[2] with test_attr_2 # Scope_3_out should only exist on test_layers[3] with test_attr_3 for layer_idx, layer in enumerate(test_layers): for prim_idx in range(test_layer_count): prim_out_spec = layer.GetPrimAtPath(f"/Scope_{prim_idx}_out") if prim_idx == layer_idx: self.assertTrue(prim_out_spec) self.assertEqual(prim_out_spec.specifier, Sdf.SpecifierDef) for attr_idx in range(test_layer_count): attr_out_spec = layer.GetAttributeAtPath(f"/Scope_{prim_idx}_out.test_attr_{attr_idx}") if attr_idx == layer_idx: self.assertTrue(attr_out_spec) self.assertTrue(attr_out_spec.default) else: self.assertFalse(attr_out_spec) else: self.assertFalse(prim_out_spec) ############################################################# # Change the target to session layer and check `over` spec test_layer_index = 2 # change value from True to False source_prims[test_layer_index].GetAttribute(f"test_attr_{test_layer_index}").Set(False) controller.edit( self.TEST_GRAPH_PATH, { keys.SET_VALUES: [ (f"Write{test_layer_index}.inputs:layerIdentifier", "<Session Layer>"), ], }, ) await self._evaluate_graph(graph, controller) self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR]) prim_out_spec = session_layer.GetPrimAtPath(f"/Scope_{test_layer_index}_out") self.assertTrue(prim_out_spec) self.assertEqual(prim_out_spec.specifier, Sdf.SpecifierOver) attr_out_spec = session_layer.GetAttributeAtPath( f"/Scope_{test_layer_index}_out.test_attr_{test_layer_index}" ) self.assertTrue(attr_out_spec) self.assertFalse(attr_out_spec.default) # value should be set to False because we changed it prev_attr_out_spec = test_layers[test_layer_index].GetAttributeAtPath( f"/Scope_{test_layer_index}_out.test_attr_{test_layer_index}" ) self.assertTrue(prev_attr_out_spec) self.assertTrue( prev_attr_out_spec.default ) # the value should still be True as it should not be written to anymore # ---------------------------------------------------------------------- async def test_read_write_prims_layer_identifier_resolver(self): """ Test omni.graph.nodes.ReadPrimsV2 and WritePrimsV2 layer identifier resolver Construct file hierarchy like this: /Ref/ref.usda /Ref/ref_sublayer.usda /main.usda /Ref/ref_sublayer.usda is a sublayer of /Ref/ref.usda A graph with WritePrimsV2 node is in /Ref/ref.usda, with a layerIdentifier to ./ref_sublayer.usda If /Ref/ref.usda is opened in Kit and graph executes, the output should be written to /Ref/ref_sublayer.usda /Ref/ref_sublayer.usda is also a sublayer of /main.usda /main.usda also references /Ref/ref.usda If /main.usda is opened in Kit and graph executes, the relative layerIdentifier of ./ref_sublayer.usda should still be resolved to /Ref/ref_sublayer.usda, but not /ref_sublayer.usda, and graph out put on that layer. """ with tempfile.TemporaryDirectory() as tmpdirname: usd_context = omni.usd.get_context() controller = og.Controller() keys = og.Controller.Keys ref_dir = os.path.join(tmpdirname, "Ref") ref_sublayer_fn = os.path.join(ref_dir, "ref_sub_layer.usda") ref_sublayer = Sdf.Layer.CreateNew(ref_sublayer_fn) ref_sublayer.Save() ref_fn = os.path.join(ref_dir, "ref.usda") Sdf.Layer.CreateNew(ref_fn).Save() success, error = await usd_context.open_stage_async(str(ref_fn)) self.assertTrue(success, error) stage = usd_context.get_stage() root_layer = stage.GetRootLayer() root_layer.subLayerPaths.append("./ref_sub_layer.usda") world = UsdGeom.Xform.Define(stage, "/World") stage.SetDefaultPrim(world.GetPrim()) source = UsdGeom.Scope.Define(stage, "/World/Source") source_prim = source.GetPrim() source_prim.CreateAttribute("test_attr", Sdf.ValueTypeNames.Bool).Set(True) (graph, _, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Read", "omni.graph.nodes.ReadPrimsV2"), ("Write", "omni.graph.nodes.WritePrimsV2"), ], keys.SET_VALUES: [ ("Write.inputs:layerIdentifier", "./ref_sub_layer.usda"), ("Write.inputs:attrNamesToExport", "test_attr"), ], keys.CONNECT: [ ("Read.outputs_primsBundle", "Write.inputs:primsBundle"), ], }, ) omni.kit.commands.execute( "SetRelationshipTargets", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"), targets=["/World/Source"], ) omni.kit.commands.execute( "SetRelationshipTargets", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Write.inputs:prims"), targets=["/World/Target"], ) # Block saving the stage first before graph ticking. The ticked result should not be saved and discard later result = usd_context.save_stage() self.assertTrue(result) # Tick the graph to make sure the layerIdentifier is resolved correctly within /Ref/ref.usda stage await self._evaluate_graph(graph, controller) self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR]) prim_out_spec = ref_sublayer.GetPrimAtPath("/World/Target") self.assertTrue(prim_out_spec) self.assertEqual(prim_out_spec.specifier, Sdf.SpecifierDef) attr_out_spec = ref_sublayer.GetAttributeAtPath("/World/Target.test_attr") self.assertTrue(attr_out_spec) self.assertTrue(attr_out_spec.default) prim_out_spec = root_layer.GetPrimAtPath("/World/Target") self.assertFalse(prim_out_spec) # close the stage and release layer ref to discard all temporary changes. await omni.usd.get_context().close_stage_async() ref_sublayer = None # Now make the main.usda, add Ref/ref.usda as a reference and tick graph main_fn = os.path.join(tmpdirname, "main.usda") Sdf.Layer.CreateNew(main_fn).Save() success, error = await usd_context.open_stage_async(str(main_fn)) self.assertTrue(success, error) stage = usd_context.get_stage() # Add "./Ref/ref_sub_layer.usda" again as a local sublayer so graph can resolve and write to it on this new stage root_layer = stage.GetRootLayer() root_layer.subLayerPaths.append("./Ref/ref_sub_layer.usda") # For whatever reason need to make an empty graph otherwise test crashes when referencing in "./Ref/ref.usda" # same code does NOT crash while executed within Kit Script Editor without the dummy graph controller.edit("/dummy", {}) ref_prim = stage.DefinePrim("/Ref") refs = ref_prim.GetReferences() refs.AddReference("./Ref/ref.usda") # reopen Ref/ref_sublayer.usda ref_sublayer = Sdf.Layer.FindOrOpen(ref_sublayer_fn) self.assertTrue(ref_sublayer) # double check the target spec does not exist before tick the graph self.assertFalse(ref_sublayer.GetPrimAtPath("/Ref/Target")) # let OG populate the referenced graph await omni.kit.app.get_app().next_update_async() # Tick the graph to make sure the layerIdentifier is resolved correctly when referencing /Ref/ref.usda graph = og.get_graph_by_path("/Ref/TestGraph") await self._evaluate_graph(graph, controller) self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR]) # the references graph should be able to resolve layerIdentifier even if the relative path anchors differently prim_out_spec = ref_sublayer.GetPrimAtPath("/Ref/Target") self.assertTrue(prim_out_spec) self.assertEqual(prim_out_spec.specifier, Sdf.SpecifierDef) attr_out_spec = ref_sublayer.GetAttributeAtPath("/Ref/Target.test_attr") self.assertTrue(attr_out_spec) self.assertTrue(attr_out_spec.default) prim_out_spec = root_layer.GetPrimAtPath("/Ref/Target") self.assertFalse(prim_out_spec) # ---------------------------------------------------------------------- async def test_write_prims_relationship(self): """Test WritePrims MPiB to export a relationship""" usd_context = omni.usd.get_context() stage: Usd.Stage = usd_context.get_stage() stage_rt = UsdRT.Stage.Attach(usd_context.get_stage_id()) controller = og.Controller() keys = og.Controller.Keys (graph, _, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("RelBundle", "__test_write_prims_v2__.relationship_bundle"), ("Write", "omni.graph.nodes.WritePrimsV2"), ], keys.CONNECT: [ ("RelBundle.outputs_out_0", "Write.inputs:primsBundle"), ], }, ) target_path = "/Target" target_xform = UsdGeom.Xform.Define(stage, target_path) omni.kit.commands.execute( "SetRelationshipTargets", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Write.inputs:prims"), targets=[target_xform.GetPrim().GetPath()], ) await self._evaluate_graph(graph, controller) self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR]) # Check USD prim relationship prim = stage.GetPrimAtPath(target_path) rel = prim.GetRelationship(REL_BUNDLE_TRL_NAME) self.assertTrue(rel) self.assertListEqual(REL_BUNDLE_TARGETS, rel.GetTargets()) # Check Fabric prim relationship prim_rt = stage_rt.GetPrimAtPath(target_path) rel_rt = prim_rt.GetRelationship(REL_BUNDLE_TRL_NAME) self.assertTrue(rel_rt) self.assertListEqual(REL_BUNDLE_TARGETS_RT, rel_rt.GetTargets()) # ---------------------------------------------------------------------- async def test_write_prims_interpolation(self): """Test writing interpolation metadata through omni.graph.nodes.WritePrimsV2""" target_prim_path = "/target" usd_context = omni.usd.get_context() stage: Usd.Stage = usd_context.get_stage() controller = og.Controller() keys = og.Controller.Keys xform_prim = UsdGeom.Xform.Define(stage, target_prim_path) cube_prim = ogts.create_cube(stage, "Cube1", (1, 0, 0)) (graph, [_, _], _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Read", "omni.graph.nodes.ReadPrimsV2"), ("Write", "omni.graph.nodes.WritePrimsV2"), ], keys.SET_VALUES: [ ("Write.inputs:scatterUnderTargets", True), ], keys.CONNECT: [ ("Read.outputs_primsBundle", "Write.inputs:primsBundle"), ], }, ) omni.kit.commands.execute( "SetRelationshipTargets", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"), targets=[cube_prim.GetPath()], ) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Write.inputs:prims"), target=xform_prim.GetPrim().GetPath(), ) # Set the interpolation on a primvar interpolation = "uniform" primvar = UsdGeom.Primvar(cube_prim.GetAttribute("primvars:displayColor")) self.assertTrue(primvar) primvar.SetInterpolation(interpolation) await self._evaluate_graph(graph, controller) self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR]) target_prim_path = xform_prim.GetPath().AppendPath( cube_prim.GetPath().MakeRelativePath(Sdf.Path.absoluteRootPath) ) target_prim = stage.GetPrimAtPath(target_prim_path) self.assertTrue(target_prim) attr = target_prim.GetAttribute("primvars:displayColor") self.assertTrue(attr) primvar = UsdGeom.Primvar(attr) self.assertTrue(primvar) self.assertEqual(primvar.GetInterpolation(), interpolation) # Change the interpolation of the input prim, then evaluate the graph again... interpolation = "constant" primvar = UsdGeom.Primvar(cube_prim.GetAttribute("primvars:displayColor")) self.assertTrue(primvar) primvar.SetInterpolation(interpolation) await self._evaluate_graph(graph, controller) self._assert_no_compute_messages(graph, [og.WARNING, og.ERROR]) target_prim = stage.GetPrimAtPath(target_prim_path) self.assertTrue(target_prim) attr = target_prim.GetAttribute("primvars:displayColor") self.assertTrue(attr) primvar = UsdGeom.Primvar(attr) self.assertTrue(primvar) self.assertEqual(primvar.GetInterpolation(), interpolation) # Finally, clear the metadata on the input prim and ensure that the metadata is cleared on the output prim attr = cube_prim.GetAttribute("primvars:displayColor") attr.ClearMetadata("interpolation") await self._evaluate_graph(graph, controller) # Just check for errors here; we do expect to get a warning that the metadata field no longer exists self._assert_no_compute_messages(graph, [og.ERROR]) target_prim = stage.GetPrimAtPath(target_prim_path) self.assertTrue(target_prim) attr = target_prim.GetAttribute("primvars:displayColor") self.assertTrue(attr) self.assertFalse(attr.HasMetadata("interpolation")) # ---------------------------------------------------------------------- # Helpers def _assert_no_compute_messages(self, graph, severity_list): graph_nodes = graph.get_nodes() for severity in severity_list: for node in graph_nodes: self.assertEqual(node.get_compute_messages(severity), []) async def _evaluate_graph(self, graph, controller): await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() def _get_node_messages(self, graph, severity): error_message = [] graph_nodes = graph.get_nodes() for node in graph_nodes: error = node.get_compute_messages(severity) if error: error_message += error return error_message class CarbLogSuppressor: def __init__(self): self.logging = carb.logging.acquire_logging() self.log_was_enabled = self.logging.is_log_enabled() def __enter__(self): # turn off carb logging so the error does not trigger test failure # og logging still works and logs node error message. self.logging.set_log_enabled(False) return self def __exit__(self, *_): # restore carb logging self.logging.set_log_enabled(self.log_was_enabled)
94,944
Python
44.51534
204
0.552441
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_read_prim_node.py
# noqa: PLC0302 from math import isnan import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.test from pxr import Sdf, Usd, UsdGeom # Tests for ReadPrim (singular) node class TestReadPrimNode(ogts.OmniGraphTestCase): """Unit tests for ReadPrim node in this extension""" async def test_read_prim_node_v1(self): """Validate backward compatibility for legacy versions of ReadPrim node.""" # load the test scene which contains a ReadPrim V1 node (result, error) = await ogts.load_test_file("TestReadPrimNode_v1.usda", use_caller_subdirectory=True) self.assertTrue(result, error) test_graph_path = "/World/TestGraph" test_graph = og.get_graph_by_path(test_graph_path) read_prim_node = test_graph.get_node(test_graph_path + "/read_prim") self.assertTrue(read_prim_node.is_valid()) # validate new attributes can be automatically created with their default value set. self.assertTrue(read_prim_node.get_attribute_exists("inputs:computeBoundingBox")) self.assertFalse(read_prim_node.get_attribute("inputs:computeBoundingBox").get()) self.assertTrue(read_prim_node.get_attribute_exists("inputs:usdTimecode")) self.assertTrue(isnan(read_prim_node.get_attribute("inputs:usdTimecode").get())) # Tests for ReadPrimBundle node class TestReadPrimsBundle(ogts.OmniGraphTestCase): """Unit tests for ReadPrimBundle node in this extension""" async def test_read_prims_bundle_node_target_mpib(self): """Validate backward compatibility for legacy versions of ReadPrim node.""" (result, error) = await ogts.load_test_file("TestReadPrimNode_targetMPiB.usda", use_caller_subdirectory=True) self.assertTrue(result, error) test_graph_path = "/TestGraph" test_graph = og.get_graph_by_path(test_graph_path) test_context = test_graph.get_default_graph_context() read_prim_bundle_node = test_graph.get_node(test_graph_path + "/read_prims_into_bundle") self.assertTrue(read_prim_bundle_node.is_valid()) factory = og.IBundleFactory.create() output_bundle = test_context.get_output_bundle(read_prim_bundle_node, "outputs_primsBundle") output_bundle2 = factory.get_bundle(test_context, output_bundle) self.assertTrue(output_bundle2.valid) self.assertTrue(output_bundle2.get_child_bundle_count(), 2) child0 = output_bundle2.get_child_bundle(0) child1 = output_bundle2.get_child_bundle(1) self.assertTrue(child0.valid) self.assertTrue(child1.valid) self.assertTrue("size" in child0.get_attribute_names()) self.assertTrue("size" in child1.get_attribute_names()) async def test_read_prims_bundle_node_path_mpib(self): """Load multiple primitives into a bundle through input path""" (result, error) = await ogts.load_test_file("TestReadPrimNode_pathMPiB.usda", use_caller_subdirectory=True) self.assertTrue(result, error) test_graph_path = "/TestGraph" test_graph = og.get_graph_by_path(test_graph_path) test_context = test_graph.get_default_graph_context() read_prim_bundle_node = test_graph.get_node(test_graph_path + "/read_prims_into_bundle") self.assertTrue(read_prim_bundle_node.is_valid()) factory = og.IBundleFactory.create() output_bundle = test_context.get_output_bundle(read_prim_bundle_node, "outputs_primsBundle") output_bundle2 = factory.get_bundle(test_context, output_bundle) self.assertTrue(output_bundle2.valid) self.assertTrue(output_bundle2.get_child_bundle_count(), 2) child0 = output_bundle2.get_child_bundle(0) child1 = output_bundle2.get_child_bundle(1) self.assertTrue(child0.valid) self.assertTrue(child1.valid) self.assertTrue("size" in child0.get_attribute_names()) self.assertTrue("size" in child1.get_attribute_names()) # Tests for both ReadPrims (legacy) and ReadPrimsV2 node # Must be inherited by a child test class to be tested class TestReadPrimsCommon: """Unit tests for both ReadPrims (legacy) and ReadPrimsV2 node in this extension""" def __init__(self, read_prims_node_type): self._read_prims_node_type = read_prims_node_type async def test_import_matrix_and_bbox(self): """Verify that bounding box and matrix are correctly computed by ReadPrim.""" controller = og.Controller() keys = og.Controller.Keys usd_context = omni.usd.get_context() stage = usd_context.get_stage() # create 500 cubes to feed ReadPrims and trigger its concurrent collection of prims cube_paths = [] cubes = [] for i in range(500): cube_path = "/World/Cube" + str(i) cube = ogts.create_cube(stage, cube_path[1:], (1, 1, 1)) UsdGeom.Xformable(cube).AddTranslateOp() cube_paths.append(cube_path) cubes.append(cube) self.assertEqual(cube.GetPath(), cube_path) # noqa: PLE1101 (_, nodes, _, _) = controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("ReadPrims", self._read_prims_node_type), ("ExtractPrim", "omni.graph.nodes.ExtractPrim"), ("ExtractBundle", "omni.graph.nodes.ExtractBundle"), ("Inv", "omni.graph.nodes.OgnInvertMatrix"), ("Const0", "omni.graph.nodes.ConstantDouble3"), ("Const1", "omni.graph.nodes.ConstantDouble3"), ], keys.SET_VALUES: [ ("ExtractPrim.inputs:primPath", cube_paths[0]), ], keys.CONNECT: [ ("ReadPrims.outputs_primsBundle", "ExtractPrim.inputs:prims"), ("ExtractPrim.outputs_primBundle", "ExtractBundle.inputs:bundle"), ], }, ) # add target prim omni.kit.commands.execute( "SetRelationshipTargets", relationship=stage.GetPropertyAtPath("/TestGraph/ReadPrims.inputs:prims"), targets=cube_paths, ) # get initial output attributes await controller.evaluate() # connect the matrix controller.edit("/TestGraph", {keys.CONNECT: ("ExtractBundle.outputs:worldMatrix", "Inv.inputs:matrix")}) await controller.evaluate() read_prims_node = nodes[0] extract_bundle = nodes[2] # We did not ask for BBox self.assertFalse(read_prims_node.get_attribute_exists("outputs:bboxMinCorner")) # noqa: PLE1101 self.assertFalse(read_prims_node.get_attribute_exists("outputs:bboxMaxCorner")) # noqa: PLE1101 self.assertFalse(read_prims_node.get_attribute_exists("outputs:bboxTransform")) # noqa: PLE1101 # but we should have the default matrix mat_attr = extract_bundle.get_attribute("outputs:worldMatrix") mat = mat_attr.get() self.assertTrue((mat == [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]).all()) # noqa: PLE1101 # move the cube, check the new matrix pos = cubes[0].GetAttribute("xformOp:translate") pos.Set((2, 2, 2)) await controller.evaluate() mat = mat_attr.get() self.assertTrue((mat == [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 2, 2, 2, 1]).all()) # noqa: PLE1101 # now ask for bbox, and check its value controller.edit( "/TestGraph", { keys.SET_VALUES: ("ReadPrims.inputs:computeBoundingBox", True), }, ) await controller.evaluate() self.assertTrue(extract_bundle.get_attribute_exists("outputs:bboxMinCorner")) # noqa: PLE1101 self.assertTrue(extract_bundle.get_attribute_exists("outputs:bboxMaxCorner")) # noqa: PLE1101 self.assertTrue(extract_bundle.get_attribute_exists("outputs:bboxTransform")) # noqa: PLE1101 # connect the bbox controller.edit( "/TestGraph", { keys.CONNECT: [ ("ExtractBundle.outputs:bboxMinCorner", "Const0.inputs:value"), ("ExtractBundle.outputs:bboxMaxCorner", "Const1.inputs:value"), ] }, ) await controller.evaluate() bbox_min = extract_bundle.get_attribute("outputs:bboxMinCorner") bbox_max = extract_bundle.get_attribute("outputs:bboxMaxCorner") bbox_min_val = bbox_min.get() bbox_max_val = bbox_max.get() self.assertTrue((bbox_min_val == [-0.5, -0.5, -0.5]).all()) # noqa: PLE1101 self.assertTrue((bbox_max_val == [0.5, 0.5, 0.5]).all()) # noqa: PLE1101 # then resize the cube, and check new bbox ext = cubes[0].GetAttribute("extent") ext.Set([(-10, -10, -10), (10, 10, 10)]) await controller.evaluate() bbox_min_val = bbox_min.get() bbox_max_val = bbox_max.get() self.assertTrue((bbox_min_val == [-10, -10, -10]).all()) # noqa: PLE1101 self.assertTrue((bbox_max_val == [10, 10, 10]).all()) # noqa: PLE1101 async def _test_apply_skel_binding_on_skinned_model(self, test_scene): """shared function to validate applying skel binding on a model which has SkelBindingAPI schema.""" # load test scene which contains a mesh that is bound with a skeleton and a skel animation (result, error) = await ogts.load_test_file(test_scene, use_caller_subdirectory=True) self.assertTrue(result, error) # noqa: PLE1101 controller = og.Controller() keys = og.Controller.Keys usd_context = omni.usd.get_context() stage = usd_context.get_stage() bundle_factory = og.IBundleFactory.create() # create a ReadPrims node (test_graph, [read_prims_node], _, _) = controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("read_prims", self._read_prims_node_type), ], }, ) # add target prim cylinder_path = "/Root/group1/pCylinder1_Skinned" omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath("/TestGraph/read_prims.inputs:prims"), target=cylinder_path, ) await controller.evaluate() # validate a single child bundle is created when applySkelBinding is not enabled yet. test_context = test_graph.get_default_graph_context() output_bundle = test_context.get_output_bundle(read_prims_node, "outputs_primsBundle") output_bundle = bundle_factory.get_bundle(test_context, output_bundle) self.assertTrue(output_bundle.valid) # noqa: PLE1101 child_bundles = output_bundle.get_child_bundles() self.assertTrue(len(child_bundles), 1) # noqa: PLE1101 single_prim_in_bundle = child_bundles[0] self.assertTrue(single_prim_in_bundle.valid) # noqa: PLE1101 source_prim_path_str = "sourcePrimPath" source_prim_path_attr = single_prim_in_bundle.get_attribute_by_name(source_prim_path_str) self.assertTrue(source_prim_path_attr.is_valid()) # noqa: PLE1101 self.assertEqual(source_prim_path_attr.get(), cylinder_path) # noqa: PLE1101 attributes_without_skel_binding = set(single_prim_in_bundle.get_attribute_names()) self.assertTrue("points" in attributes_without_skel_binding) # noqa: PLE1101 self.assertTrue("normals" in attributes_without_skel_binding) # noqa: PLE1101 # apply skel binding controller.edit( "/TestGraph", { keys.SET_VALUES: ("read_prims.inputs:applySkelBinding", True), }, ) await controller.evaluate() # validate child bundles are created for cylinder, skeleton and skel animation. child_bundles = output_bundle.get_child_bundles() self.assertEqual(len(child_bundles), 3) # noqa: PLE1101 cylinder_bundle = None skeleton_bundle = None skelanim_bundle = None for child_bundle in child_bundles: source_prim_path_attr = child_bundle.get_attribute_by_name(source_prim_path_str) if source_prim_path_attr.get() == cylinder_path: cylinder_bundle = child_bundle else: source_prim_type_attr = child_bundle.get_attribute_by_name("sourcePrimType") source_prim_type = source_prim_type_attr.get() if source_prim_type == "Skeleton": skeleton_bundle = child_bundle elif source_prim_type == "SkelAnimation": skelanim_bundle = child_bundle self.assertIsNotNone(cylinder_bundle) # noqa: PLE1101 self.assertIsNotNone(skeleton_bundle) # noqa: PLE1101 self.assertIsNotNone(skelanim_bundle) # noqa: PLE1101 # the cylinder bundle has the skel:skeleton attribute that stores the link to the Skeleton bundle skeleton_path_attr = cylinder_bundle.get_attribute_by_name("skel:skeleton") self.assertTrue(skeleton_path_attr.is_valid()) # noqa: PLE1101 source_prim_path_attr = skeleton_bundle.get_attribute_by_name(source_prim_path_str) self.assertTrue(source_prim_path_attr.is_valid()) # noqa: PLE1101 skeleton_path = skeleton_path_attr.get() self.assertEqual(source_prim_path_attr.get(), skeleton_path) # noqa: PLE1101 # the skeleton bundle has the skel:animationSource attribute that stores the link to the SkelAnimation bundle skelanim_path_attr = skeleton_bundle.get_attribute_by_name("skel:animationSource") self.assertTrue(skelanim_path_attr.is_valid()) # noqa: PLE1101 source_prim_path_attr = skelanim_bundle.get_attribute_by_name(source_prim_path_str) self.assertTrue(source_prim_path_attr.is_valid()) # noqa: PLE1101 skelanim_path = skelanim_path_attr.get() self.assertEqual(source_prim_path_attr.get(), skelanim_path) # noqa: PLE1101 # validate additional skel attributes added to the cylinder bundle attributes_with_skel_binding = set(cylinder_bundle.get_attribute_names()) self.assertTrue(attributes_without_skel_binding.issubset(attributes_with_skel_binding)) # noqa: PLE1101 additional_skel_attributes = attributes_with_skel_binding.difference(attributes_without_skel_binding) self.assertTrue("points:default" in additional_skel_attributes) # noqa: PLE1101 self.assertTrue("normals:default" in additional_skel_attributes) # noqa: PLE1101 # validate the joints attribute joints_attr = skeleton_bundle.get_attribute_by_name("joints") self.assertTrue(joints_attr.is_valid()) # noqa: PLE1101 num_joints = joints_attr.size() # validate the rest pose matrix_attr_type = og.Type(og.BaseDataType.DOUBLE, 16, 1, og.AttributeRole.MATRIX) rest_transforms_attr = skeleton_bundle.get_attribute_by_name("restTransforms") self.assertTrue(rest_transforms_attr.is_valid()) # noqa: PLE1101 self.assertEqual(rest_transforms_attr.get_type(), matrix_attr_type) # noqa: PLE1101 self.assertEqual(rest_transforms_attr.size(), num_joints) # noqa: PLE1101 # validate the animated pose which is stored at the "jointLocalTransforms" attribute joint_local_transforms_attr = skeleton_bundle.get_attribute_by_name("jointLocalTransforms") self.assertTrue(joint_local_transforms_attr.is_valid()) # noqa: PLE1101 self.assertEqual(joint_local_transforms_attr.get_type(), matrix_attr_type) # noqa: PLE1101 self.assertEqual(joint_local_transforms_attr.size(), num_joints) # noqa: PLE1101 async def test_apply_skel_binding_on_authored_skeletal_relationships(self): """validate applying skel binding on a prim that has SkelBindingAPI schema and authored skeletal relationships.""" await self._test_apply_skel_binding_on_skinned_model("skelcylinder.usda") async def test_apply_skel_binding_on_inherited_skeletal_relationships(self): """validate applying skel binding on a prim that has SkelBindingAPI schema and inherited skeletal relationships.""" await self._test_apply_skel_binding_on_skinned_model("skelcylinder_inherited_skeleton.usda") async def test_apply_skel_binding_on_model_without_normals(self): """validate applying skel binding on a model which has SkelBindingAPI schema and no normals.""" # load test scene which contains a mesh that is bound with a skeleton and a skel animation (result, error) = await ogts.load_test_file("skel_model_without_normals.usda", use_caller_subdirectory=True) self.assertTrue(result, error) # noqa: PLE1101 controller = og.Controller() keys = og.Controller.Keys usd_context = omni.usd.get_context() stage = usd_context.get_stage() bundle_factory = og.IBundleFactory.create() # create a ReadPrims node (test_graph, [read_prims_node], _, _) = controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("read_prims", self._read_prims_node_type), ], keys.SET_VALUES: [ # Remove the normals attribute from the list of attributes to import, because ReadPrims # imports normals by default, and we want to test the SkelBinding when the normals are not # imported. ("read_prims.inputs:attrNamesToImport", "* ^normals") ], }, ) # add target prim mesh_path = "/Model/Arm" omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath("/TestGraph/read_prims.inputs:prims"), target=mesh_path, ) await controller.evaluate() # validate a single child bundle is created when applySkelBinding is not enabled yet. test_context = test_graph.get_default_graph_context() output_bundle = test_context.get_output_bundle(read_prims_node, "outputs_primsBundle") output_bundle = bundle_factory.get_bundle(test_context, output_bundle) self.assertTrue(output_bundle.valid) # noqa: PLE1101 child_bundles = output_bundle.get_child_bundles() self.assertTrue(len(child_bundles), 1) # noqa: PLE1101 mesh_bundle = child_bundles[0] self.assertTrue(mesh_bundle.valid) # noqa: PLE1101 # the mesh bundle has points but no normals attributes_without_skel_binding = set(mesh_bundle.get_attribute_names()) self.assertTrue("points" in attributes_without_skel_binding) # noqa: PLE1101 self.assertFalse("normals" in attributes_without_skel_binding) # noqa: PLE1101 # apply skel binding controller.edit( "/TestGraph", { keys.SET_VALUES: ("read_prims.inputs:applySkelBinding", True), }, ) await controller.evaluate() # there will be three bundles and we need to get the mesh bundles child_bundles = output_bundle.get_child_bundles() self.assertEqual(len(child_bundles), 3) # noqa: PLE1101 mesh_bundle = None for child_bundle in child_bundles: source_prim_path_attr = child_bundle.get_attribute_by_name("sourcePrimPath") if source_prim_path_attr.get() == mesh_path: mesh_bundle = child_bundle break self.assertIsNotNone(mesh_bundle) # noqa: PLE1101 # validate additional skel attributes added to the cylinder bundle attributes_with_skel_binding = set(mesh_bundle.get_attribute_names()) self.assertTrue(attributes_without_skel_binding.issubset(attributes_with_skel_binding)) # noqa: PLE1101 additional_skel_attributes = attributes_with_skel_binding.difference(attributes_without_skel_binding) self.assertTrue("points:default" in additional_skel_attributes) # noqa: PLE1101 self.assertFalse("normals:default" in additional_skel_attributes) # noqa: PLE1101 async def test_apply_skel_binding_on_prim_without_required_schema(self): """validate applying skel binding to a simple cube which has no SkelBindingAPI schema.""" controller = og.Controller() keys = og.Controller.Keys usd_context = omni.usd.get_context() stage = usd_context.get_stage() bundle_factory = og.IBundleFactory.create() # create a ReadPrims node (test_graph, [read_prims_node], _, _) = controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("read_prims", self._read_prims_node_type), ], }, ) # add target prim cube = ogts.create_cube(stage, "World/Cube", (1, 1, 1)) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath("/TestGraph/read_prims.inputs:prims"), target=cube.GetPath(), ) await controller.evaluate() # validate a single child bundle is created before applying skel binding. test_context = test_graph.get_default_graph_context() output_bundle = test_context.get_output_bundle(read_prims_node, "outputs_primsBundle") output_bundle = bundle_factory.get_bundle(test_context, output_bundle) self.assertTrue(output_bundle.valid) # noqa: PLE1101 child_bundles = output_bundle.get_child_bundles() self.assertTrue(len(child_bundles), 1) # noqa: PLE1101 child_bundle_before_skel_binding = child_bundles[0] self.assertTrue(child_bundle_before_skel_binding.valid) # noqa: PLE1101 source_prim_path_str = "sourcePrimPath" source_prim_path_attr = child_bundle_before_skel_binding.get_attribute_by_name(source_prim_path_str) self.assertTrue(source_prim_path_attr.is_valid()) # noqa: PLE1101 self.assertEqual(source_prim_path_attr.get(), cube.GetPath()) # noqa: PLE1101 attributes_before_skel_binding = set(child_bundle_before_skel_binding.get_attribute_names()) # apply skel binding controller.edit( "/TestGraph", { keys.SET_VALUES: ("read_prims.inputs:applySkelBinding", True), }, ) await controller.evaluate() # validate no additional child bundle is created after applying skel binding. child_bundles = output_bundle.get_child_bundles() self.assertEqual(len(child_bundles), 1) # noqa: PLE1101 child_bundle_after_skel_binding = child_bundles[0] self.assertTrue(child_bundle_after_skel_binding.valid) # noqa: PLE1101 source_prim_path_attr = child_bundle_after_skel_binding.get_attribute_by_name(source_prim_path_str) self.assertTrue(source_prim_path_attr.is_valid()) # noqa: PLE1101 self.assertEqual(source_prim_path_attr.get(), cube.GetPath()) # noqa: PLE1101 # validate no additional attributes have been added to the bundle attributes_after_skel_binding = set(child_bundle_after_skel_binding.get_attribute_names()) self.assertEqual(attributes_before_skel_binding, attributes_after_skel_binding) # noqa: PLE1101 async def _test_apply_skel_binding_on_joint_ordering(self, test_scene, path_skinned_mesh, path_baked_mesh): """shared function to validate applying skel binding on joint ordering.""" test_graph_path = "/TestGraph" time_code_range = range(1, 30) # load test scene which contains a mesh that is bound with a skeleton and a skel animation (result, error) = await ogts.load_test_file(test_scene, use_caller_subdirectory=True) self.assertTrue(result, error) # noqa: PLE1101 controller = og.Controller() keys = og.Controller.Keys usd_context = omni.usd.get_context() stage = usd_context.get_stage() bundle_factory = og.IBundleFactory.create() (test_graph, (_, extracter_0, extracter_1), _, _) = controller.edit( test_graph_path, { keys.CREATE_NODES: [ ("ReadPrims", self._read_prims_node_type), ("ExtractPrim_SkelBinding", "omni.graph.nodes.ExtractPrim"), ("ExtractPrim_BakeSkinning", "omni.graph.nodes.ExtractPrim"), ], keys.SET_VALUES: [ ("ReadPrims.inputs:applySkelBinding", True), ("ExtractPrim_SkelBinding.inputs:primPath", path_skinned_mesh), ("ExtractPrim_BakeSkinning.inputs:primPath", path_baked_mesh), ], keys.CONNECT: [ ("ReadPrims.outputs_primsBundle", "ExtractPrim_SkelBinding.inputs:prims"), ("ReadPrims.outputs_primsBundle", "ExtractPrim_BakeSkinning.inputs:prims"), ], }, ) # Assign the target prims to the import node. cylinder_paths = [path_skinned_mesh, path_baked_mesh] omni.kit.commands.execute( "SetRelationshipTargets", relationship=stage.GetPropertyAtPath(test_graph_path + "/ReadPrims.inputs:prims"), targets=cylinder_paths, ) # get initial output attributes await controller.evaluate() # fetch skinned points test_context = test_graph.get_default_graph_context() output_bundle = test_context.get_output_bundle(extracter_0, "outputs_primBundle") bundle = bundle_factory.get_bundle(test_context, output_bundle) self.assertTrue(bundle.valid) # noqa: PLE1101 skinned_points_attr = bundle.get_attribute_by_name("points") self.assertTrue(skinned_points_attr.is_valid()) # noqa: PLE1101 # fetch baked points test_context = test_graph.get_default_graph_context() output_bundle = test_context.get_output_bundle(extracter_1, "outputs_primBundle") bundle = bundle_factory.get_bundle(test_context, output_bundle) self.assertTrue(bundle.valid) # noqa: PLE1101 baked_points_attr = bundle.get_attribute_by_name("points") self.assertTrue(baked_points_attr.is_valid()) # noqa: PLE1101 # playback and compare the two lists of points for time_code in time_code_range: controller.edit( test_graph_path, {keys.SET_VALUES: ("ReadPrims.inputs:usdTimecode", time_code)}, ) await og.Controller.evaluate(test_graph) skinned_points = skinned_points_attr.get().tolist() self.assertTrue(isinstance(skinned_points, list)) # noqa: PLE1101 self.assertTrue(len(skinned_points) != 0) # noqa: PLE1101 baked_points = baked_points_attr.get().tolist() self.assertTrue(isinstance(baked_points, list)) # noqa: PLE1101 self.assertTrue(len(baked_points) != 0) # noqa: PLE1101 self.assertTrue(skinned_points == baked_points) # noqa: PLE1101 async def test_apply_skel_binding_on_joint_ordering(self): """validate applying skel binding on joint ordering which is defined on skeleton but may or may not be overridden by skinned mesh""" # The skinned meshes are baked offline with the following script. Then we can compare the computation result of the # `ReadPrims` node with the baked meshes. # # from pxr import Gf, Usd, UsdSkel # # testFile = "lbs.usda" # stage = Usd.Stage.Open(testFile) # # UsdSkel.BakeSkinning(stage.Traverse()) # # stage.GetRootLayer().Export("lbs.baked.usda") # Each tuple is (test_scene, path_skinned_mesh, path_baked_mesh) test_cases = [ ("lbs.usda", "/Root/Mesh_Skinned", "/Root/Mesh_Baked"), ("lbs_custom_joint_ordering.usda", "/Root/Mesh_Skinned", "/Root/Mesh_Baked"), ("skelcylinder.usda", "/Root/group1/pCylinder1_Skinned", "/Root/group1/pCylinder1_Baked"), ( "skelcylinder_custom_joint_ordering.usda", "/Root/group1/pCylinder1_Skinned", "/Root/group1/pCylinder1_Baked", ), ] for test_case in test_cases: await self._test_apply_skel_binding_on_joint_ordering(*test_case) async def test_read_prims_attribute_filter(self): """Validate the attribute filter functionality of ReadPrim.""" await self._test_attribute_filter(self._read_prims_node_type) async def _test_attribute_filter(self, node_type): """Shared function to validate the attribute filter functionality of ReadPrimBundle and ReadPrim.""" controller = og.Controller() keys = og.Controller.Keys test_graph_path = "/TestGraph" (test_graph, [read_prims_node], _, _) = controller.edit( test_graph_path, { keys.CREATE_NODES: [("read_prims_node", node_type)], }, ) # Create a cube and connect it as the input prim. stage = omni.usd.get_context().get_stage() cube = ogts.create_cube(stage, "World/Cube", (1, 1, 1)) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(test_graph_path + "/read_prims_node.inputs:prims"), target=cube.GetPath(), ) await controller.evaluate() # Get the output bundle. test_context = test_graph.get_default_graph_context() output_bundle = test_context.get_output_bundle(read_prims_node, "outputs_primsBundle") bundle_factory = og.IBundleFactory.create() output_bundle = bundle_factory.get_bundle(test_context, output_bundle) self.assertTrue(output_bundle.valid) # noqa: PLE1101 self.assertEqual(output_bundle.get_child_bundle_count(), 1) # noqa: PLE1101 # Get the only child bundle. child_bundle = output_bundle.get_child_bundle(0) self.assertTrue(child_bundle.valid) # noqa: PLE1101 # The "size" attribute is expected for a cube by default. default_attribute_names = child_bundle.get_attribute_names() self.assertTrue("size" in default_attribute_names) # noqa: PLE1101 # The filtered attribute names will be the same as the default. attr_filters = ["*", "* dummy", "dummy *"] for attr_filter in attr_filters: controller.edit( test_graph_path, { keys.SET_VALUES: ("read_prims_node.inputs:attrNamesToImport", attr_filter), }, ) await controller.evaluate() self.assertEqual(set(child_bundle.get_attribute_names()), set(default_attribute_names)) # noqa: PLE1101 # The filtered attribute names will contain "size" only. attr_filters = [ "size", "size dummy", "dummy size", "????", "s???", "?ize", "?i?e", "*z?", "?im* ?ix* ?iz*", "???? dummy", "dummy ????", ] # "sourcePrimPath", "sourcePrimType" and "worldMatrix" are additional attributes created by the node. expected_attribute_names = {"sourcePrimPath", "sourcePrimType", "worldMatrix", "size"} for attr_filter in attr_filters: controller.edit( test_graph_path, { keys.SET_VALUES: ("read_prims_node.inputs:attrNamesToImport", attr_filter), }, ) await controller.evaluate() self.assertEqual(set(child_bundle.get_attribute_names()), expected_attribute_names) # noqa: PLE1101 # The filtered attribute names will not contain "size". attr_filters = [ " ", "Size", "SIZE", "dummy", "sizedummy", "dummysize", "size:dummy", "dummy:size", "size&dummy", "dummy&size", "*:dummy", "dummy:*", "???", "??", "?", "????:dummy", "dummy:????", ] # "sourcePrimPath", "sourcePrimType" and "worldMatrix" are additional attributes created by the node. expected_attribute_names = {"sourcePrimPath", "sourcePrimType", "worldMatrix"} for attr_filter in attr_filters: controller.edit( test_graph_path, { keys.SET_VALUES: ("read_prims_node.inputs:attrNamesToImport", attr_filter), }, ) await controller.evaluate() self.assertEqual(set(child_bundle.get_attribute_names()), expected_attribute_names) # noqa: PLE1101 async def test_read_prims_time_code_mpib(self): """Test whether points and normals keep consistent after modifying time code.""" controller = og.Controller() keys = og.Controller.Keys bundle_factory = og.IBundleFactory.create() stage = omni.usd.get_context().get_stage() # Create two cubes, whose types are Mesh and Cube respectively. cube_paths = ["/cube_mesh", "/cube_shape"] _, default_cube_mesh_path = omni.kit.commands.execute("CreateMeshPrim", prim_type="Cube") omni.kit.commands.execute("MovePrim", path_from=default_cube_mesh_path, path_to=cube_paths[0]) og.Controller.create_prim(cube_paths[1], {}, "Cube") # Create a graph that reads the two prims and extract the bundle of the cube mesh test_graph_path = "/TestGraph" (test_graph, [_, extract_prim_node], _, _,) = controller.edit( test_graph_path, { keys.CREATE_NODES: [ ("read_prims", self._read_prims_node_type), ("extract_prim", "omni.graph.nodes.ExtractPrim"), ], keys.SET_VALUES: [ ("extract_prim.inputs:primPath", cube_paths[0]), ], keys.CONNECT: [ ("read_prims.outputs_primsBundle", "extract_prim.inputs:prims"), ], }, ) # Assign the target prims to the import node. omni.kit.commands.execute( "SetRelationshipTargets", relationship=stage.GetPropertyAtPath(test_graph_path + "/read_prims.inputs:prims"), targets=cube_paths, ) await og.Controller.evaluate(test_graph) # Get output bundle. test_context = test_graph.get_default_graph_context() output_bundle = test_context.get_output_bundle(extract_prim_node, "outputs_primBundle") bundle = bundle_factory.get_bundle(test_context, output_bundle) self.assertTrue(bundle.valid) # noqa: PLE1101 # Get points points_attr = bundle.get_attribute_by_name("points") self.assertTrue(points_attr.is_valid()) # noqa: PLE1101 points = points_attr.get().tolist() self.assertTrue(isinstance(points, list)) # noqa: PLE1101 self.assertTrue(len(points) != 0) # noqa: PLE1101 # Get normals normals_attr = bundle.get_attribute_by_name("normals") self.assertTrue(normals_attr.is_valid()) # noqa: PLE1101 normals = normals_attr.get().tolist() self.assertTrue(isinstance(normals, list)) # noqa: PLE1101 self.assertTrue(len(normals) != 0) # noqa: PLE1101 # Modify timecode and trigger evaluation. Run 60 times to eliminate random factor. for timecode in range(60): controller.edit( test_graph_path, {keys.SET_VALUES: ("read_prims.inputs:usdTimecode", timecode)}, ) await og.Controller.evaluate(test_graph) # Test whether the points data keep consistent points_attr = bundle.get_attribute_by_name("points") self.assertTrue(points_attr.is_valid()) # noqa: PLE1101 self.assertSequenceEqual(points_attr.get().tolist(), points) # noqa: PLE1101 # Test whether the points data keep consistent normals_attr = bundle.get_attribute_by_name("normals") self.assertTrue(normals_attr.is_valid()) # noqa: PLE1101 self.assertSequenceEqual(normals_attr.get().tolist(), normals) # noqa: PLE1101 async def test_read_prims_attribute_interpolation(self): controller = og.Controller() keys = og.Controller.Keys usd_context = omni.usd.get_context() stage = usd_context.get_stage() # Create Mesh and Primvar with interpolation mesh = ogts.create_grid_mesh(stage, "/Mesh") sts_primvar = UsdGeom.PrimvarsAPI(mesh).CreatePrimvar("st", Sdf.ValueTypeNames.Float2Array) sts_primvar.SetInterpolation("faceVarying") # Create Read Prim with test node to test if interpolation was read test_graph_path = "/TestGraph" (test_graph, [_, attr_interp], _, _,) = controller.edit( test_graph_path, { keys.CREATE_NODES: [ ("read_prims", self._read_prims_node_type), ("attr_interp", "omni.graph.test.TestBundleAttributeInterpolation"), ], keys.SET_VALUES: ("attr_interp.inputs:attribute", "primvars:st"), keys.CONNECT: ("read_prims.outputs_primsBundle", "attr_interp.inputs:prims"), }, ) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(test_graph_path + "/read_prims.inputs:prims"), target=mesh.GetPath(), ) await og.Controller.evaluate(test_graph) # Confirm the interpolation is carried properly from Read Prims and Bundle Prims self.assertEqual(attr_interp.get_attribute("outputs:interpolation").get(), "faceVarying") # noqa: PLE1101 async def test_read_prim_nodes_have_nan_defaults(self): """Validates that manually created prim nodes have nan as default""" controller = og.Controller() keys = og.Controller.Keys test_graph_path = "/TestGraph" (_, nodes, _, _) = controller.edit( test_graph_path, { keys.CREATE_NODES: [ ("ReadPrims", self._read_prims_node_type), ("ReadPrimAttr", "omni.graph.nodes.ReadPrimAttribute"), ("ReadPrimAttrs", "omni.graph.nodes.ReadPrimAttributes"), ("ReadPrimsBundle", "omni.graph.nodes.ReadPrimsBundle"), ], }, ) for node in nodes: self.assertTrue(isnan(node.get_attribute("inputs:usdTimecode").get())) # noqa: PLE1101 async def test_read_prim_have_no_errors_on_creation(self): """Validates that creating ReadPrimAttribute nodes with default values doesn't throw errors""" controller = og.Controller() keys = og.Controller.Keys test_graph_path = "/TestGraph" (test_graph, nodes, _, _) = controller.edit( {"graph_path": test_graph_path}, { keys.CREATE_NODES: [ ("ReadPrimAttr", "omni.graph.nodes.ReadPrimAttribute"), ], keys.SET_VALUES: [ ("ReadPrimAttr.inputs:name", ""), ], }, ) self.assertEqual(len(nodes[0].get_compute_messages(og.ERROR)), 0) # noqa: PLE1101 nodes[0].clear_old_compute_messages() with ogts.ExpectedError(): await og.Controller.evaluate(test_graph) self.assertEqual(len(nodes[0].get_compute_messages(og.ERROR)), 1) # noqa: PLE1101 # Tests for ReadPrims (legacy) node only + all tests in TestReadPrimsCommon class TestReadPrimsNode(ogts.OmniGraphTestCase, TestReadPrimsCommon): """ Unit tests for ReadPrims (legacy) node in this extension It also inherits all tests from TestReadPrimsCommon unless explicitly opted out """ def __init__(self, *args, **kwargs): ogts.OmniGraphTestCase.__init__(self, *args, **kwargs) TestReadPrimsCommon.__init__(self, read_prims_node_type="omni.graph.nodes.ReadPrims") async def test_read_prims_node_v1(self): """Validate backward compatibility for legacy versions of ReadPrims node.""" # load the test scene which contains a ReadPrims V1 node (result, error) = await ogts.load_test_file("TestReadPrimsNode_v1.usda", use_caller_subdirectory=True) self.assertTrue(result, error) test_graph_path = "/World/TestGraph" test_graph = og.get_graph_by_path(test_graph_path) read_prim_node = test_graph.get_node(test_graph_path + "/read_prims") self.assertTrue(read_prim_node.is_valid()) # validate new attributes can be automatically created with their default value set. attr_names_and_values = [ ("inputs:applySkelBinding", False), ] for attr_name, attr_value in attr_names_and_values: self.assertTrue(read_prim_node.get_attribute_exists(attr_name)) self.assertTrue(read_prim_node.get_attribute(attr_name).get() == attr_value) # this is a test for ReadPrimBundle, to utilize _test_attribute_filter, thus it is not in TestReadPrimsBundle async def test_read_prims_bundle_attribute_filter(self): """Validate the attribute filter functionality of ReadPrimBundle.""" await self._test_attribute_filter("omni.graph.nodes.ReadPrimsBundle") # Tests for ReadPrimsV2 node only + all tests in TestReadPrimsCommon class TestReadPrimsV2Node(ogts.OmniGraphTestCase, TestReadPrimsCommon): """ Unit tests for ReadPrimsV2 node in this extension It also inherits all tests from TestReadPrimsCommon unless explicitly opted out """ def __init__(self, *args, **kwargs): ogts.OmniGraphTestCase.__init__(self, *args, **kwargs) TestReadPrimsCommon.__init__(self, read_prims_node_type="omni.graph.nodes.ReadPrimsV2") async def test_read_prims_root_prims_targets(self): """Test omni.graph.nodes.ReadPrims with rootPrims targets""" usd_context = omni.usd.get_context() stage: Usd.Stage = usd_context.get_stage() test_graph_path = "/World/TestGraph" controller = og.Controller() keys = og.Controller.Keys root1 = stage.DefinePrim("/Root1", "Xform") stage.DefinePrim("/Root1/Xform", "Xform") stage.DefinePrim("/Root1/Xform/Cube", "Cube") stage.DefinePrim("/Root2", "Xform") stage.DefinePrim("/Root2/Xform", "Xform") stage.DefinePrim("/Root2/Xform/Sphere", "Sphere") root3 = stage.DefinePrim("/Root3", "Xform") stage.DefinePrim("/Root3/Xform", "Xform") stage.DefinePrim("/Root3/Xform/Cone", "Cone") (graph, [read_prims_node], _, _) = controller.edit( test_graph_path, { keys.CREATE_NODES: [ ("Read", self._read_prims_node_type), ], keys.SET_VALUES: [ ("Read.inputs:pathPattern", "*"), ], }, ) # connect /Root1 and /Root3 to inputs:rootPrims # The node should find all prims under them, but not /Root2 omni.kit.commands.execute( "SetRelationshipTargets", relationship=stage.GetPropertyAtPath(f"{test_graph_path}/Read.inputs:prims"), targets=[root1.GetPath(), root3.GetPath()], ) await controller.evaluate() graph_context = graph.get_default_graph_context() output_prims_bundle = graph_context.get_output_bundle(read_prims_node, "outputs_primsBundle") self.assertTrue(output_prims_bundle.valid) expected_matched_prim_paths = { "/Root1", "/Root1/Xform", "/Root1/Xform/Cube", "/Root3", "/Root3/Xform", "/Root3/Xform/Cone", } child_bundles = output_prims_bundle.get_child_bundles() self.assertEqual(len(child_bundles), len(expected_matched_prim_paths)) for bundle in child_bundles: path = bundle.get_attribute_by_name("sourcePrimPath").get() expected_matched_prim_paths.remove(path) # no exception should raise when remove a path in the loop above # after the loop, all paths should have been removed self.assertEqual(len(expected_matched_prim_paths), 0)
45,040
Python
42.64438
140
0.61714
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_timeline_nodes.py
"""Unit tests for the timeline playback nodes in this extension""" import carb.events import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.commands import omni.kit.stage_templates import omni.kit.test import omni.timeline import omni.usd # ====================================================================== class TestTimelineNodes(ogts.OmniGraphTestCase): TEST_GRAPH_PATH = "/World/TestGraph" FRAME_RATE = 64 # power of two so that FRAME_DURATION is an exact binary number FRAME_DURATION = 1.0 / FRAME_RATE START_FRAME = 10 END_FRAME = 20 START_TIME = START_FRAME * FRAME_DURATION END_TIME = END_FRAME * FRAME_DURATION TEST_MESSAGE_NAME = "omni.graph.nodes/triggerTimelineNode" TEST_MESSAGE_EVENT = carb.events.type_from_string(TEST_MESSAGE_NAME) def flush(self): # The timeline is async, we need to commit any pending changes before we can read its last state. self._timeline.commit() def current_time(self): self.flush() return self._timeline.get_current_time() def current_frame(self): return self._timeline.time_to_time_code(self.current_time()) def assert_from_start(self, frame: int, message: str): self.assertEqual(self.current_frame(), self.START_FRAME + frame, message) def is_playing(self): self.flush() return self._timeline.is_playing() def is_looping(self): self.flush() return self._timeline.is_looping() def dump(self, header=""): self.flush() tl = self._timeline print( f""" Timeline {header} tick:{tl.get_current_tick()} time:{tl.get_current_time()} start:{tl.get_start_time()} end:{tl.get_end_time()} playing:{tl.is_playing()} looping:{tl.is_looping()} """ ) async def tick(self): await omni.kit.app.get_app().next_update_async() async def fire(self): app = omni.kit.app.get_app() message_bus = app.get_message_bus_event_stream() message_bus.push(self.TEST_MESSAGE_EVENT) await self.tick() # ---------------------------------------------------------------------- async def setUp(self): """Set up test environment, to be torn down when done""" await super().setUp() fps = self.FRAME_RATE # make sure we put the global timeline in the same initial state self._timeline = omni.timeline.get_timeline_interface() self._timeline.stop() self._timeline.set_current_time(0) self._timeline.set_end_time(self.END_TIME) self._timeline.set_start_time(self.START_TIME) self._timeline.set_time_codes_per_second(fps) self._timeline.set_looping(False) self._timeline.set_fast_mode(False) self._timeline.set_prerolling(True) self._timeline.set_auto_update(True) self._timeline.set_play_every_frame(True) self._timeline.set_ticks_per_frame(1) self._timeline.set_target_framerate(fps) self._timeline.commit() # ---------------------------------------------------------------------- async def test_timeline_start_node(self): """Test OgnTimelineStart node""" # convert to action graph og.Controller.edit({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"}) controller = og.Controller() keys = og.Controller.Keys controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("OnMessage", "omni.graph.action.OnMessageBusEvent"), ("StartTimeline", "omni.graph.nodes.StartTimeline"), ], keys.CONNECT: [ ("OnMessage.outputs:execOut", "StartTimeline.inputs:execIn"), ], keys.SET_VALUES: [ ("OnMessage.inputs:onlyPlayback", False), ("OnMessage.inputs:eventName", self.TEST_MESSAGE_NAME), ], }, ) # Initialize await self.tick() self.assertFalse(self.is_playing(), "Should not have started yet") # Trigger the node await self.fire() self.assertTrue(self.is_playing(), "Should have started") self.assert_from_start(0, "Should have started at frame 0 from start") await self.tick() self.assert_from_start(1, "Should have advanced one frame after starting") # Trigger the node again await self.fire() self.assert_from_start(2, "Should not have restarted after starting twice") # Pause the timeline self._timeline.pause() self._timeline.commit() await self.tick() self.assert_from_start(2, "Should have been paused at frame 2") # Start again await self.fire() self.assert_from_start(2, "Should be at frame 2 after paused and starting again") await self.tick() self.assert_from_start(3, "Should be at frame 3 after paused and playing for one frame") # ---------------------------------------------------------------------- async def test_timeline_stop_node(self): """Test OgnTimelineStop node""" # convert to action graph og.Controller.edit({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"}) controller = og.Controller() keys = og.Controller.Keys controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("OnMessage", "omni.graph.action.OnMessageBusEvent"), ("StopTimeline", "omni.graph.nodes.StopTimeline"), ], keys.CONNECT: [ ("OnMessage.outputs:execOut", "StopTimeline.inputs:execIn"), ], keys.SET_VALUES: [ ("OnMessage.inputs:onlyPlayback", False), ("OnMessage.inputs:eventName", self.TEST_MESSAGE_NAME), ], }, ) # Initialize await self.tick() self.assertFalse(self.is_playing(), "Should not have started") # Trigger the node await self.fire() await self.tick() # Stopping a stopped timeline has no effect self.assertTrue(self.current_frame() == 0, "Should not have started when stopping") # Start the timeline self._timeline.play() self.assertTrue(self.is_playing(), "Should have started") play_frames = 5 # Advance the timeline N frames for _ in range(play_frames): await self.tick() self.assert_from_start(play_frames, f"Should have played {play_frames} frames") # Trigger the node await self.fire() stop_frame = play_frames + 1 self.assertFalse(self.is_playing(), "Should have stopped") self.assert_from_start(stop_frame, f"Should have stopped at frame {stop_frame}") await self.tick() self.assert_from_start( stop_frame, f"Should still be at frame {stop_frame} after stopped one frame", ) # Trigger the node again await self.fire() # Should still be at the current frame self.assert_from_start( stop_frame, f"Should still be at frame {stop_frame} after stopping twice", ) # ---------------------------------------------------------------------- async def test_timeline_loop_node(self): """Test OgnTimelineLoop node""" # convert to action graph og.Controller.edit({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"}) controller = og.Controller() keys = og.Controller.Keys controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("OnMessage", "omni.graph.action.OnMessageBusEvent"), ("LoopTimeline", "omni.graph.nodes.LoopTimeline"), ], keys.CONNECT: [ ("OnMessage.outputs:execOut", "LoopTimeline.inputs:execIn"), ], keys.SET_VALUES: [ ("OnMessage.inputs:onlyPlayback", False), ("OnMessage.inputs:eventName", self.TEST_MESSAGE_NAME), ], }, ) def set_looping(value): controller.edit( self.TEST_GRAPH_PATH, { keys.SET_VALUES: [ ("LoopTimeline.inputs:loop", value), ], }, ) # Initialize await self.tick() self.assertFalse(self.is_looping(), "Should not be looping yet") # Enable looping set_looping(True) await self.fire() self.assertTrue(self.is_looping(), "Should be looping") # Disable looping set_looping(False) await self.fire() self.assertFalse(self.is_looping(), "Should not be looping") # ---------------------------------------------------------------------- async def test_timeline_get_node(self): """Test OgnTimelineGet node""" # convert to push graph og.Controller.edit({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "push"}) controller = og.Controller() keys = og.Controller.Keys (_, [node], _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("GetTimeline", "omni.graph.nodes.GetTimeline"), ], }, ) def get_attr_value(name): attr = og.Controller.attribute(f"outputs:{name}", node) return og.Controller(attr).get() def assert_attr_value(name, value): self.assertEqual(get_attr_value(name), value, name) async def assert_node_values(playing, looping): await self.tick() assert_attr_value("time", self._timeline.get_current_time()) assert_attr_value("frame", self.current_frame()) assert_attr_value("startTime", self.START_TIME) assert_attr_value("startFrame", self.START_FRAME) assert_attr_value("endTime", self.END_TIME) assert_attr_value("endFrame", self.END_FRAME) assert_attr_value("framesPerSecond", self.FRAME_RATE) assert_attr_value("isPlaying", playing) assert_attr_value("isLooping", looping) await assert_node_values(playing=False, looping=False) self._timeline.pause() await assert_node_values(playing=False, looping=False) self._timeline.play() await assert_node_values(playing=True, looping=False) await assert_node_values(playing=True, looping=False) self._timeline.set_looping(True) await assert_node_values(playing=True, looping=True) await assert_node_values(playing=True, looping=True) # ---------------------------------------------------------------------- async def test_timeline_set_node(self): """Test OgnTimelineSet node""" # convert to push graph og.Controller.edit({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "push"}) controller = og.Controller() keys = og.Controller.Keys (_, [node], _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("SetTimeline", "omni.graph.nodes.SetTimeline"), ], }, ) def get_attr_value(name): attr = og.Controller.attribute(f"outputs:{name}", node) return og.Controller(attr).get() async def set_node_property(property_name, property_value): attr = og.Controller.attribute("inputs:propName", node) attr.set(property_name) attr = og.Controller.attribute("inputs:propValue", node) attr.set(property_value) await self.tick() self.flush() async def assert_set_position(target_frame, expected_frame, clamped): await set_node_property("Frame", target_frame) self.assertEqual(self.current_frame(), expected_frame, "Wrong Frame") self.assertEqual(get_attr_value("clamped"), clamped, "Wrong clamping") target_time = target_frame * self.FRAME_DURATION expected_time = expected_frame * self.FRAME_DURATION await set_node_property("Time", target_time) self.assertEqual(self.current_time(), expected_time, "Wrong Time") self.assertEqual(get_attr_value("clamped"), clamped, "Wrong clamping") for f in range(self.START_FRAME, self.END_FRAME): await assert_set_position(f, f, False) await assert_set_position(self.START_FRAME - 1, self.START_FRAME, True) await assert_set_position(self.END_FRAME + 1, self.END_FRAME, True) await set_node_property("StartTime", 0) self.assertEqual(self._timeline.get_start_time(), 0, "Wrong StartTime") await set_node_property("StartFrame", 1) self.assertEqual(self._timeline.get_start_time(), self.FRAME_DURATION, "Wrong StartFrame") await set_node_property("EndTime", 10) self.assertEqual(self._timeline.get_end_time(), 10, "Wrong EndTime") await set_node_property("EndFrame", 2) self.assertEqual(self._timeline.get_end_time(), 2 * self.FRAME_DURATION, "Wrong EndFrame") await set_node_property("FramesPerSecond", 30) self.assertEqual(self._timeline.get_time_codes_per_seconds(), 30, "Wrong FramesPerSecond") # ----------------------------------------------------------------------
13,858
Python
33.135468
105
0.558161
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_bundle_inspector.py
"""Test the node that inspects attribute bundles""" import omni.graph.core as og import omni.graph.core.tests as ogts from .bundle_test_utils import ( bundle_inspector_results, get_bundle_with_all_results, prim_with_everything_definition, verify_bundles_are_equal, ) # ====================================================================== class TestBundleInspector(ogts.test_case_class()): """Run a simple unit test that exercises graph functionality""" # ---------------------------------------------------------------------- async def test_node_with_contents(self): """Test the node with some pre-made input bundle contents""" prim_definition = prim_with_everything_definition() keys = og.Controller.Keys (_, [inspector_node, _], [prim], _) = og.Controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("Inspector", "omni.graph.nodes.BundleInspector"), ], keys.CREATE_PRIMS: ("TestPrim", prim_definition), keys.EXPOSE_PRIMS: (og.Controller.PrimExposureType.AS_BUNDLE, "/TestPrim", "TestPrimExtract"), keys.CONNECT: [ ("TestPrimExtract.outputs_primBundle", "Inspector.inputs:bundle"), ], }, ) await og.Controller.evaluate() results = bundle_inspector_results(inspector_node) expected_values = get_bundle_with_all_results(str(prim.GetPrimPath()), prim_source_type=str(prim.GetTypeName())) try: verify_bundles_are_equal(results, expected_values) except ValueError as error: self.assertTrue(False, error) async def test_bundle_inspector_node_v2(self): """Validate backward compatibility for legacy versions of BundleInspector node.""" # load the test scene which contains a ReadPrim V1 node (result, error) = await ogts.load_test_file("TestBundleInspectorNode_v2.usda", use_caller_subdirectory=True) self.assertTrue(result, error) test_graph_path = "/TestGraph" test_graph = og.get_graph_by_path(test_graph_path) read_prim_node = test_graph.get_node(test_graph_path + "/Inspector") self.assertTrue(read_prim_node.is_valid()) # validate new attributes can be automatically created with their default value set. attr_names_and_values = [ ("inputs:inspectDepth", 1), ] for (attr_name, attr_value) in attr_names_and_values: self.assertTrue(read_prim_node.get_attribute_exists(attr_name)) self.assertTrue(read_prim_node.get_attribute(attr_name).get() == attr_value)
2,707
Python
41.984126
120
0.596601
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_variant_nodes.py
"""Testing the stability of the API in this module""" import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.test import omni.usd from pxr import Sdf # ====================================================================== class TestVariantNodes(ogts.OmniGraphTestCase): def __init__(self, arg): super().__init__(arg) self.usda_file = "variant_sets.usda" self.input_prim = "/InputPrim" @staticmethod def set_variant_selection(prim_path, variant_set_name, variant_name): # noqa: C901 stage = omni.usd.get_context().get_stage() prim = stage.GetPrimAtPath(prim_path) variant_set = prim.GetVariantSet(variant_set_name) variant_names = variant_set.GetVariantNames() if variant_name not in variant_names: variant_set.AddVariant(variant_name) variant_set.SetVariantSelection(variant_name) def set_up_variant_sets(self): for prim_path in [self.input_prim]: stage = omni.usd.get_context().get_stage() prim = stage.DefinePrim(prim_path, "Xform") attr = prim.CreateAttribute("primvars:displayColor", Sdf.ValueTypeNames.Color3f) variant_set_name = "color" variant_sets = prim.GetVariantSets() variant_set = variant_sets.GetVariantSet(variant_set_name) variant_set.AddVariant("red") variant_set.AddVariant("green") variant_set.AddVariant("blue") variant_set.SetVariantSelection("red") with variant_set.GetVariantEditContext(): attr.Set((1, 0, 0)) variant_set.SetVariantSelection("green") with variant_set.GetVariantEditContext(): attr.Set((0, 1, 0)) variant_set.SetVariantSelection("blue") with variant_set.GetVariantEditContext(): attr.Set((0, 0, 1)) variant_set.SetVariantSelection("default_color") variant_set_name = "size" variant_sets = prim.GetVariantSets() variant_set = variant_sets.GetVariantSet(variant_set_name) variant_set.AddVariant("small") variant_set.AddVariant("medium") variant_set.AddVariant("large") variant_set.SetVariantSelection("default_size") def get_variant_selection(self, prim_path, variant_set_name): stage = omni.usd.get_context().get_stage() prim = stage.GetPrimAtPath(prim_path) variant_set = prim.GetVariantSet(variant_set_name) return variant_set.GetVariantSelection() async def _test_variant_node( self, node_type, node_attrs, expected_values, expected_variants=None, expected_attr_values=None, read_file=True, use_connected_prim=False, variant_selection=None, ): await omni.usd.get_context().new_stage_async() if read_file: (result, error) = await ogts.load_test_file(self.usda_file, use_caller_subdirectory=True) self.assertTrue(result, error) else: self.set_up_variant_sets() if variant_selection: prim_path, variant_set_name, variant_name = variant_selection self.set_variant_selection(prim_path, variant_set_name, variant_name) keys = og.Controller.Keys controller = og.Controller() graph = "/TestGraph" variant_node = "VariantNode" values = [(f"{variant_node}.{key}", value) for key, value in node_attrs.items()] controller.edit( graph, { keys.CREATE_NODES: [ (variant_node, node_type), ], keys.SET_VALUES: values, }, ) stage = omni.usd.get_context().get_stage() # use a prim path connection instead of setting the value directly if use_connected_prim: (_, (_prim_at_path, _), _, _) = controller.edit( graph, { keys.CREATE_NODES: [ ("GetPrimAtPath", "omni.graph.nodes.GetPrimsAtPath"), ("ConstToken", "omni.graph.nodes.ConstantToken"), ], keys.CONNECT: [ ("ConstToken.inputs:value", "GetPrimAtPath.inputs:path"), ("GetPrimAtPath.outputs:prims", f"{variant_node}.inputs:prim"), ], keys.SET_VALUES: [ ("ConstToken.inputs:value", self.input_prim), ], }, ) else: omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{graph}/{variant_node}.inputs:prim"), target=self.input_prim, ) await controller.evaluate() for output in expected_values.keys(): test_attribute = controller.attribute(output, f"{graph}/{variant_node}") actual_value = controller.get(attribute=test_attribute) if isinstance(expected_values[output], list): actual_value = list(actual_value) self.assertTrue( actual_value == expected_values[output], f"actual_value: {actual_value}, expected_value: {expected_values[output]}", ) if expected_variants: for prim_path, variant_set_name, expected_variant_name in expected_variants: actual_value = self.get_variant_selection(prim_path, variant_set_name) self.assertTrue( actual_value == expected_variant_name, f"actual_value: {actual_value}, expected_value: {expected_variant_name}", ) if expected_attr_values: for prim_path, attr_name, expected_value in expected_attr_values: test_attribute = stage.GetPropertyAtPath(f"{prim_path}.{attr_name}") actual_value = test_attribute.Get() self.assertTrue( actual_value == expected_value, f"actual_value: {actual_value}, expected_value: {expected_value}", ) async def test_get_variant_names_1(self): node_type = "omni.graph.nodes.GetVariantNames" node_attrs = { "inputs:variantSetName": "color", } expected_values = {"outputs:variantNames": ["blue", "green", "red"]} await self._test_variant_node(node_type, node_attrs, expected_values) async def test_get_variant_names_2(self): node_type = "omni.graph.nodes.GetVariantNames" node_attrs = { "inputs:variantSetName": "color", } expected_values = {"outputs:variantNames": ["blue", "green", "red"]} await self._test_variant_node(node_type, node_attrs, expected_values, use_connected_prim=False) await self._test_variant_node(node_type, node_attrs, expected_values, use_connected_prim=True) async def test_get_variant_selection(self): node_type = "omni.graph.nodes.GetVariantSelection" node_attrs = { "inputs:variantSetName": "color", } expected_values = {"outputs:variantName": "default_color"} await self._test_variant_node(node_type, node_attrs, expected_values) async def test_get_variant_selection_2(self): node_type = "omni.graph.nodes.GetVariantSelection" node_attrs = { "inputs:variantSetName": "color", } expected_values = {"outputs:variantName": "green"} variant_selection = (self.input_prim, "color", "green") await self._test_variant_node( node_type, node_attrs, expected_values, variant_selection=variant_selection, use_connected_prim=False, ) await self._test_variant_node( node_type, node_attrs, expected_values, variant_selection=variant_selection, use_connected_prim=True, ) async def test_get_variant_set_names(self): node_type = "omni.graph.nodes.GetVariantSetNames" node_attrs = {} expected_values = {"outputs:variantSetNames": ["color", "size"]} await self._test_variant_node(node_type, node_attrs, expected_values) async def test_get_variant_set_names_2(self): node_type = "omni.graph.nodes.GetVariantSetNames" node_attrs = {} expected_values = {"outputs:variantSetNames": ["color", "size"]} await self._test_variant_node(node_type, node_attrs, expected_values, use_connected_prim=False) await self._test_variant_node(node_type, node_attrs, expected_values, use_connected_prim=True) async def test_has_variant_set_1(self): node_type = "omni.graph.nodes.HasVariantSet" node_attrs = { "inputs:variantSetName": "color", } expected_values = {"outputs:exists": True} await self._test_variant_node(node_type, node_attrs, expected_values) async def test_has_variant_set_2(self): node_type = "omni.graph.nodes.HasVariantSet" node_attrs = { "inputs:variantSetName": "flavor", } expected_values = {"outputs:exists": False} await self._test_variant_node(node_type, node_attrs, expected_values) async def test_has_variant_set_3(self): node_type = "omni.graph.nodes.HasVariantSet" node_attrs = { "inputs:variantSetName": "flavor", } expected_values = {"outputs:exists": False} await self._test_variant_node(node_type, node_attrs, expected_values, use_connected_prim=False) await self._test_variant_node(node_type, node_attrs, expected_values, use_connected_prim=True) async def test_clear_variant_set_with_default(self): node_type = "omni.graph.nodes.ClearVariantSelection" node_attrs = { "inputs:variantSetName": "color", } expected_values = {} expected_variants = [(self.input_prim, "color", "default_color")] await self._test_variant_node(node_type, node_attrs, expected_values, expected_variants) async def test_clear_variant_set(self): node_type = "omni.graph.nodes.ClearVariantSelection" node_attrs = { "inputs:variantSetName": "color", } expected_values = {} expected_variants = [(self.input_prim, "color", "default_color")] await self._test_variant_node(node_type, node_attrs, expected_values, expected_variants, read_file=False) async def test_clear_variant_set_2(self): node_type = "omni.graph.nodes.ClearVariantSelection" node_attrs = { "inputs:variantSetName": "color", } expected_values = {} expected_variants = [(self.input_prim, "color", "default_color")] await self._test_variant_node( node_type, node_attrs, expected_values, expected_variants, read_file=False, use_connected_prim=False, ) await self._test_variant_node( node_type, node_attrs, expected_values, expected_variants, read_file=False, use_connected_prim=True, ) async def test_set_variant_selection(self): node_type = "omni.graph.nodes.SetVariantSelection" node_attrs = { "inputs:setVariant": True, "inputs:variantSetName": "color", "inputs:variantName": "red", } expected_values = {} expected_variants = [(self.input_prim, "color", "red")] await self._test_variant_node(node_type, node_attrs, expected_values, expected_variants) async def test_set_variant_selection_2(self): node_type = "omni.graph.nodes.SetVariantSelection" node_attrs = { "inputs:setVariant": True, "inputs:variantSetName": "color", "inputs:variantName": "red", } expected_values = {} expected_variants = [(self.input_prim, "color", "red")] await self._test_variant_node( node_type, node_attrs, expected_values, expected_variants, use_connected_prim=False, ) await self._test_variant_node( node_type, node_attrs, expected_values, expected_variants, use_connected_prim=True, ) async def test_blend_variants(self): node_type = "omni.graph.nodes.BlendVariants" node_attrs = { "inputs:variantSetName": "color", "inputs:blend": 0.5, "inputs:variantNameA": "red", "inputs:variantNameB": "green", } expected_values = {} expected_variants = [] expected_attr_values = [(self.input_prim, "primvars:displayColor", [0.5, 0.5, 0.0])] await self._test_variant_node( node_type, node_attrs, expected_values, expected_variants, expected_attr_values, read_file=False, )
13,333
Python
35.531507
113
0.572114
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_timer_node.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. # import asyncio from pathlib import Path from typing import Tuple import omni.graph.core as og import omni.kit.app import omni.kit.commands import omni.kit.test import omni.kit.ui_test as ui_test import omni.usd from carb.input import KeyboardInput as Key class TestTimerNode(omni.kit.test.AsyncTestCase): async def setUp(self): extension_root_folder = Path( omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) ) self._test_files = extension_root_folder.joinpath("data/tests/usd") await self._load_stage() async def tearDown(self): await omni.usd.get_context().close_stage_async() async def test_timer_node(self): await self._test_timer_node_impl() async def _load_stage(self): usd_context = omni.usd.get_context() filename = "timer.usda" test_file_path = self._test_files.joinpath(filename).absolute() await usd_context.open_stage_async(str(test_file_path)) print(f"Loaded: {test_file_path}") self._stage = usd_context.get_stage() async def _test_timer_node_impl(self): node = self._stage.GetPrimAtPath("/World/ActionGraph/Timer") graph = self._stage.GetPrimAtPath("/World/ActionGraph") self.assertEqual(graph.GetTypeName(), "OmniGraph") await ui_test.emulate_keyboard_press(Key.A) await omni.kit.app.get_app().next_update_async() await self._test_time_and_range(node, [(0, (0, 0.1)), (1, (0.4, 0.6)), (2.5, (1, 1))]) async def _test_time_and_range(self, node: og.Node, time_range: Tuple[float, Tuple[float, float]]): for (time, (min_value, max_value)) in time_range: print("Time: ", time, "Range: ", min_value, max_value) if time > 0: print("sleeping for ", time, " seconds") await asyncio.sleep(time) print("sleeping done") self._test_y_within_range(node, min_value, max_value) # because asyncio.sleep(1) does not sleep for exactly that amount of time, check the result in an range def _test_y_within_range(self, node: og.Node, min_value: float, max_value: float): actual_value = og.Controller.get(f"{node.GetPath()}.outputs:value") print(f"min_value: {min_value}, max_value: {max_value} actual_value: {actual_value}") self.assertGreaterEqual(actual_value, min_value) self.assertLessEqual(actual_value, max_value)
2,905
Python
38.808219
107
0.667814
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_read_prims_incremental.py
# noqa: PLC0302 from typing import List import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.test from pxr import Sdf, Usd, UsdGeom _debug = False class TestReadPrimsIncremental(ogts.OmniGraphTestCase): """Unit tests for incremental behavior of the ReadPrimsV2 node in this extension""" async def test_read_prims_change_tracking_path_targets(self): """Test change tracking of omni.graph.nodes.ReadPrimsV2 using path targets""" await self._test_read_prims_change_tracking_impl(False) async def test_read_prims_change_tracking_path_pattern(self): """Test change tracking of omni.graph.nodes.ReadPrimsV2 using path pattern""" await self._test_read_prims_change_tracking_impl(True) async def _test_read_prims_change_tracking_impl(self, use_path_pattern): usd_context = omni.usd.get_context() stage: Usd.Stage = usd_context.get_stage() test_graph_path = "/World/TestGraph" controller = og.Controller() keys = og.Controller.Keys xcube = UsdGeom.Xform.Define(stage, "/XCube") UsdGeom.Xform.Define(stage, "/XCone") cube = ogts.create_cube(stage, "XCube/Cube", (1, 0, 0)) cone = ogts.create_cone(stage, "XCone/Cone", (0, 1, 0)) cube.GetAttribute("size").Set(100) cone.GetAttribute("radius").Set(50) cone.GetAttribute("height").Set(10) cube_path = str(cube.GetPath()) cone_path = str(cone.GetPath()) (graph, [read_prims_node, _], _, _) = controller.edit( test_graph_path, { keys.CREATE_NODES: [ ("Read", "omni.graph.nodes.ReadPrimsV2"), ("Inspector", "omni.graph.nodes.BundleInspector"), ], keys.CONNECT: [ ("Read.outputs_primsBundle", "Inspector.inputs:bundle"), ], keys.SET_VALUES: [ ("Inspector.inputs:print", False), ], }, ) if use_path_pattern: controller.edit( test_graph_path, { keys.SET_VALUES: [ ("Read.inputs:pathPattern", "/X*/C*"), ], }, ) else: omni.kit.commands.execute( "SetRelationshipTargets", relationship=stage.GetPropertyAtPath(f"{test_graph_path}/Read.inputs:prims"), targets=[cube_path, cone_path], ) def get_attr(bundle, name): return bundle.get_attribute_by_name(name) def get_attr_value(bundle, name): return get_attr(bundle, name).get() def assert_attr_value(bundle, name, value): if isinstance(value, list): self.assertEqual(get_attr_value(bundle, name).tolist(), value) else: self.assertEqual(get_attr_value(bundle, name), value) def assert_attr_missing(bundle, name): self.assertFalse(get_attr(bundle, name).is_valid()) def assert_stamp(bundle, stamp): assert_attr_value(bundle, "_debugStamp", stamp) def assert_stamp_missing(bundle): assert_attr_missing(bundle, "_debugStamp") def set_stamp(stamp): if _debug: print(f"### Setting debug stamp to {stamp}") controller.edit(test_graph_path, {keys.SET_VALUES: ("Read.inputs:_debugStamp", stamp)}) def set_change_tracking(enable): controller.edit(test_graph_path, {keys.SET_VALUES: ("Read.inputs:enableChangeTracking", enable)}) def get_expected_prim_attributes_count(prim, debug_stamp=False, bbox=False): n = len(prim.GetPropertyNames()) n += 3 # sourcePrimPath, sourcePrimType, worldMatrix n -= 1 # remove "proxyPrim" which is skipped unless it has targets if debug_stamp: n += 1 # _debugStamp if bbox: n += 3 # bboxTransform, bboxCenter, bboxSize return n id_mat = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] # initial update set_stamp(10) await controller.evaluate() graph_context = graph.get_default_graph_context() container_rwbundle = graph_context.get_output_bundle(read_prims_node, "outputs_primsBundle") self.assertTrue(container_rwbundle.valid) self.assertFalse(container_rwbundle.is_read_only()) bundle_factory = og.IBundleFactory.create() container = bundle_factory.get_const_bundle_from_path(graph_context, container_rwbundle.get_path()) self.assertTrue(container.is_read_only()) child_bundles = container.get_child_bundles() self.assertEqual(len(child_bundles), 2) # check initial bundle output # full updates will have negative debug stamps on the container bundle assert_stamp(container, -10) cube_bundle = None cone_bundle = None for bundle in child_bundles: # reading attribute values from writable bundle will bump dirty ids, so make sure it is a read-only bundle. self.assertTrue(bundle.is_read_only()) assert_stamp_missing(bundle) assert_attr_missing(bundle, "bboxMaxCorner") assert_attr_missing(bundle, "bboxMinCorner") assert_attr_missing(bundle, "bboxTransform") assert_attr_value(bundle, "worldMatrix", id_mat) path = get_attr_value(bundle, "sourcePrimPath") if path == cube_path: cube_bundle = bundle n_attrs = get_expected_prim_attributes_count(cube) self.assertEqual(bundle.get_attribute_count(), n_attrs) assert_attr_value(bundle, "sourcePrimType", "Cube") assert_attr_value(bundle, "size", 100) assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 0]]) elif path == cone_path: cone_bundle = bundle n_attrs = get_expected_prim_attributes_count(cone) self.assertEqual(bundle.get_attribute_count(), n_attrs) assert_attr_value(bundle, "sourcePrimType", "Cone") assert_attr_value(bundle, "radius", 50) assert_attr_value(bundle, "height", 10) assert_attr_value(bundle, "primvars:displayColor", [[0, 1, 0]]) else: self.fail(path) self.assertIsNotNone(cube_bundle) self.assertIsNotNone(cone_bundle) # empty update set_stamp(15) await controller.evaluate() # nothing should have been updated. assert_stamp(container, -10) container_bundle_name = container.get_name() cube_bundle_name = cube_bundle.get_name() cone_bundle_name = cone_bundle.get_name() dirtyid_interface = og._og_unstable.IDirtyID2.create(graph_context) # noqa: PLW0212 self.assertIsNotNone(dirtyid_interface) # dirty tracking is not activated for the output bundle entries = [container] entry_names = [container_bundle_name] for bundle in child_bundles: bundle_name = bundle.get_name() attrs = bundle.get_attributes() entries.append(bundle) entries.extend(attrs) entry_names.append(bundle_name) entry_names.extend([bundle_name + "." + attr.get_name() for attr in attrs]) # invalid dirty ids expected curr_dirtyids = dirtyid_interface.get(entries) self.assert_dirtyid_validity(dirtyid_interface, entry_names, curr_dirtyids, False) # activate dirty tracking controller.edit( test_graph_path, { keys.SET_VALUES: [ ("Read.inputs:enableBundleChangeTracking", True), ], }, ) await controller.evaluate() # valid dirty ids expected curr_dirtyids = dirtyid_interface.get(entries) self.assert_dirtyid_validity(dirtyid_interface, entry_names, curr_dirtyids, True) for bundle in child_bundles: assert_stamp_missing(bundle) assert_attr_missing(bundle, "bboxMaxCorner") assert_attr_missing(bundle, "bboxMinCorner") assert_attr_missing(bundle, "bboxTransform") assert_attr_value(bundle, "worldMatrix", id_mat) path = get_attr_value(bundle, "sourcePrimPath") if path == cube_path: n_attrs = get_expected_prim_attributes_count(cube) self.assertEqual(bundle.get_attribute_count(), n_attrs) assert_attr_value(bundle, "sourcePrimType", "Cube") assert_attr_value(bundle, "size", 100) assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 0]]) elif path == cone_path: n_attrs = get_expected_prim_attributes_count(cone) self.assertEqual(bundle.get_attribute_count(), n_attrs) assert_attr_value(bundle, "sourcePrimType", "Cone") assert_attr_value(bundle, "radius", 50) assert_attr_value(bundle, "height", 10) assert_attr_value(bundle, "primvars:displayColor", [[0, 1, 0]]) else: self.fail(path) # no change before this evaluation await controller.evaluate() # the dirty ids shouldn't be bumped when there is no change prev_dirtyids = curr_dirtyids curr_dirtyids = dirtyid_interface.get(entries) self.assert_dirtyid(dirtyid_interface, entry_names, curr_dirtyids, prev_dirtyids, []) # change just the cube size set_stamp(20) cube.GetAttribute("size").Set(200) await controller.evaluate() # check that only the cube bundle was updated assert_stamp(container, 20) child_bundles = container.get_child_bundles() self.assertEqual(len(child_bundles), 2) for bundle in child_bundles: path = get_attr_value(bundle, "sourcePrimPath") assert_attr_missing(bundle, "bboxMaxCorner") assert_attr_missing(bundle, "bboxMinCorner") assert_attr_missing(bundle, "bboxTransform") assert_attr_value(bundle, "worldMatrix", id_mat) if path == cube_path: n_attrs = get_expected_prim_attributes_count(cube, debug_stamp=True) self.assertEqual(bundle.get_attribute_count(), n_attrs) assert_attr_value(bundle, "sourcePrimType", "Cube") assert_attr_value(bundle, "size", 200) assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 0]]) elif path == cone_path: n_attrs = get_expected_prim_attributes_count(cone) self.assertEqual(bundle.get_attribute_count(), n_attrs) assert_stamp_missing(bundle) assert_attr_value(bundle, "sourcePrimType", "Cone") assert_attr_value(bundle, "radius", 50) assert_attr_value(bundle, "height", 10) assert_attr_value(bundle, "primvars:displayColor", [[0, 1, 0]]) else: self.fail(path) # only the changed entries will have the dirty ids bumped prev_dirtyids = curr_dirtyids curr_dirtyids = dirtyid_interface.get(entries) changed_entry_names = [container_bundle_name, cube_bundle_name, cube_bundle_name + ".size"] self.assert_dirtyid(dirtyid_interface, entry_names, curr_dirtyids, prev_dirtyids, changed_entry_names) # change just the cone radius and height set_stamp(30) cone.GetAttribute("radius").Set(300) cone.GetAttribute("height").Set(20) await controller.evaluate() # check that only the cone bundle was updated assert_stamp(container, 30) for bundle in child_bundles: assert_attr_missing(bundle, "bboxMaxCorner") assert_attr_missing(bundle, "bboxMinCorner") assert_attr_missing(bundle, "bboxTransform") assert_attr_value(bundle, "worldMatrix", id_mat) path = get_attr_value(bundle, "sourcePrimPath") if path == cube_path: n_attrs = get_expected_prim_attributes_count(cube, debug_stamp=True) self.assertEqual(bundle.get_attribute_count(), n_attrs) assert_stamp(bundle, 20) assert_attr_value(bundle, "sourcePrimType", "Cube") assert_attr_value(bundle, "size", 200) assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 0]]) elif path == cone_path: n_attrs = get_expected_prim_attributes_count(cone, debug_stamp=True) self.assertEqual(bundle.get_attribute_count(), n_attrs) assert_stamp(bundle, 30) assert_attr_value(bundle, "sourcePrimType", "Cone") assert_attr_value(bundle, "radius", 300) assert_attr_value(bundle, "height", 20) assert_attr_value(bundle, "primvars:displayColor", [[0, 1, 0]]) else: self.fail(path) # only the changed entries will have the dirty ids bumped prev_dirtyids = curr_dirtyids curr_dirtyids = dirtyid_interface.get(entries) changed_entry_names = [ container_bundle_name, cone_bundle_name, cone_bundle_name + ".radius", cone_bundle_name + ".height", ] self.assert_dirtyid(dirtyid_interface, entry_names, curr_dirtyids, prev_dirtyids, changed_entry_names) # delete the cone, full update will be triggered for now set_stamp(40) removed_entries = [] removed_entry_names = [] for bundle in child_bundles: bundle_path = get_attr_value(bundle, "sourcePrimPath") if bundle_path == cone_path: bundle_name = bundle.get_name() attrs = bundle.get_attributes() removed_entries.append(bundle) removed_entries.extend(attrs) removed_entry_names.append(bundle_name) removed_entry_names.extend([bundle_name + "." + attr.get_name() for attr in attrs]) stage.RemovePrim(cone_path) await controller.evaluate() # for now, deleting does a full update assert_stamp(container, -40) child_bundles = container.get_child_bundles() self.assertEqual(len(child_bundles), 1) for bundle in child_bundles: n_attrs = get_expected_prim_attributes_count(cube) self.assertEqual(bundle.get_attribute_count(), n_attrs) assert_stamp_missing(bundle) assert_attr_value(bundle, "sourcePrimPath", cube_path) assert_attr_value(bundle, "sourcePrimType", "Cube") assert_attr_missing(bundle, "bboxMaxCorner") assert_attr_missing(bundle, "bboxMinCorner") assert_attr_missing(bundle, "bboxTransform") assert_attr_value(bundle, "worldMatrix", id_mat) assert_attr_value(bundle, "size", 200) assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 0]]) # invalid dirty ids expected for removed entries self.assert_dirtyid_validity( dirtyid_interface, removed_entry_names, dirtyid_interface.get(removed_entries), False ) # the dirty ids should be bumped for all remaining entries remaining_prev_dirtyids = [] remaining_entries = [] remaining_entry_names = [] num_entries = len(entries) for i in range(num_entries): if entry_names[i] not in removed_entry_names: remaining_prev_dirtyids.append(curr_dirtyids[i]) remaining_entries.append(entries[i]) remaining_entry_names.append(entry_names[i]) remaining_curr_dirtyids = dirtyid_interface.get(remaining_entries) self.assert_dirtyid( dirtyid_interface, remaining_entry_names, remaining_curr_dirtyids, remaining_prev_dirtyids, remaining_entry_names, ) # create the cone again, using blue color now set_stamp(50) cone = ogts.create_cone(stage, "XCone/Cone", (0, 0, 1)) cone.GetAttribute("radius").Set(400) cone.GetAttribute("height").Set(40) await controller.evaluate() # for now, creation does a full update assert_stamp(container, -50) child_bundles = container.get_child_bundles() self.assertEqual(len(child_bundles), 2) for bundle in child_bundles: assert_stamp_missing(bundle) assert_attr_missing(bundle, "bboxMaxCorner") assert_attr_missing(bundle, "bboxMinCorner") assert_attr_missing(bundle, "bboxTransform") assert_attr_value(bundle, "worldMatrix", id_mat) path = get_attr_value(bundle, "sourcePrimPath") if path == cube_path: n_attrs = get_expected_prim_attributes_count(cube) self.assertEqual(bundle.get_attribute_count(), n_attrs) assert_attr_value(bundle, "size", 200) assert_attr_value(bundle, "sourcePrimType", "Cube") assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 0]]) elif path == cone_path: n_attrs = get_expected_prim_attributes_count(cone) self.assertEqual(bundle.get_attribute_count(), n_attrs) assert_attr_value(bundle, "radius", 400) assert_attr_value(bundle, "height", 40) assert_attr_value(bundle, "sourcePrimType", "Cone") assert_attr_value(bundle, "primvars:displayColor", [[0, 0, 1]]) else: self.fail(path) # for now, creation does a full update prev_dirtyids = curr_dirtyids curr_dirtyids = dirtyid_interface.get(entries) self.assert_dirtyid(dirtyid_interface, entry_names, curr_dirtyids, prev_dirtyids, entry_names) # create a new cube attribute set_stamp(60) dummy_attr_name = "dummy" cube.CreateAttribute(dummy_attr_name, Sdf.ValueTypeNames.Float3Array).Set([(1, 2, 3)]) await controller.evaluate() # only the cube should update, and should contain the new attribute assert_stamp(container, 60) child_bundles = container.get_child_bundles() self.assertEqual(len(child_bundles), 2) for bundle in child_bundles: assert_attr_missing(bundle, "bboxMaxCorner") assert_attr_missing(bundle, "bboxMinCorner") assert_attr_missing(bundle, "bboxTransform") assert_attr_value(bundle, "worldMatrix", id_mat) path = get_attr_value(bundle, "sourcePrimPath") if path == cube_path: n_attrs = get_expected_prim_attributes_count(cube, debug_stamp=True) self.assertEqual(bundle.get_attribute_count(), n_attrs) assert_stamp(bundle, 60) assert_attr_value(bundle, "size", 200) assert_attr_value(bundle, "sourcePrimType", "Cube") assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 0]]) self.assertListEqual(get_attr_value(bundle, dummy_attr_name).tolist(), [[1, 2, 3]]) elif path == cone_path: n_attrs = get_expected_prim_attributes_count(cone) self.assertEqual(bundle.get_attribute_count(), n_attrs) assert_stamp_missing(bundle) assert_attr_value(bundle, "radius", 400) assert_attr_value(bundle, "height", 40) assert_attr_value(bundle, "sourcePrimType", "Cone") assert_attr_value(bundle, "primvars:displayColor", [[0, 0, 1]]) else: self.fail(path) dummy_attr = get_attr(cube_bundle, dummy_attr_name) self.assertTrue(dummy_attr.is_valid()) dummy_entry_name = cube_bundle_name + "." + dummy_attr_name dummy_dirtyids = dirtyid_interface.get([dummy_attr]) self.assert_dirtyid_validity(dirtyid_interface, [dummy_entry_name], dummy_dirtyids, True) dummy_entries = entries + [dummy_attr] dummy_entry_names = entry_names + [dummy_entry_name] dummy_prev_dirtyids = curr_dirtyids + dummy_dirtyids dummy_curr_dirtyids = dirtyid_interface.get(dummy_entries) self.assert_dirtyid( dirtyid_interface, dummy_entry_names, dummy_curr_dirtyids, dummy_prev_dirtyids, [container_bundle_name, cube_bundle_name], ) # clear new cube attribute set_stamp(70) cube.GetAttribute(dummy_attr_name).Clear() await controller.evaluate() # only the cube should update, and should contain the cleared attribute assert_stamp(container, 70) child_bundles = container.get_child_bundles() self.assertEqual(len(child_bundles), 2) for bundle in child_bundles: assert_attr_missing(bundle, "bboxMaxCorner") assert_attr_missing(bundle, "bboxMinCorner") assert_attr_missing(bundle, "bboxTransform") assert_attr_value(bundle, "worldMatrix", id_mat) path = get_attr_value(bundle, "sourcePrimPath") if path == cube_path: n_attrs = get_expected_prim_attributes_count(cube, debug_stamp=True) self.assertEqual(bundle.get_attribute_count(), n_attrs) assert_stamp(bundle, 70) assert_attr_value(bundle, "size", 200) assert_attr_value(bundle, "sourcePrimType", "Cube") assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 0]]) self.assertListEqual(get_attr_value(bundle, dummy_attr_name).tolist(), []) elif path == cone_path: n_attrs = get_expected_prim_attributes_count(cone) self.assertEqual(bundle.get_attribute_count(), n_attrs) assert_stamp_missing(bundle) assert_attr_value(bundle, "radius", 400) assert_attr_value(bundle, "height", 40) assert_attr_value(bundle, "sourcePrimType", "Cone") assert_attr_value(bundle, "primvars:displayColor", [[0, 0, 1]]) else: self.fail(path) dummy_attr = get_attr(cube_bundle, dummy_attr_name) self.assertTrue(dummy_attr.is_valid()) dummy_prev_dirtyids = curr_dirtyids + dummy_dirtyids dummy_curr_dirtyids = dirtyid_interface.get(dummy_entries) self.assert_dirtyid( dirtyid_interface, dummy_entry_names, dummy_curr_dirtyids, dummy_prev_dirtyids, [container_bundle_name, cube_bundle_name, dummy_entry_name], ) # remove the new cube attribute set_stamp(80) cube.RemoveProperty(dummy_attr_name) await controller.evaluate() # only the cube should update, and should not contain the new attribute anymore assert_stamp(container, 80) child_bundles = container.get_child_bundles() self.assertEqual(len(child_bundles), 2) for bundle in child_bundles: assert_attr_missing(bundle, "bboxMaxCorner") assert_attr_missing(bundle, "bboxMinCorner") assert_attr_missing(bundle, "bboxTransform") assert_attr_value(bundle, "worldMatrix", id_mat) path = get_attr_value(bundle, "sourcePrimPath") if path == cube_path: n_attrs = get_expected_prim_attributes_count(cube, debug_stamp=True) self.assertEqual(bundle.get_attribute_count(), n_attrs) assert_stamp(bundle, 80) assert_attr_value(bundle, "size", 200) assert_attr_value(bundle, "sourcePrimType", "Cube") assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 0]]) assert_attr_missing(bundle, dummy_attr_name) elif path == cone_path: n_attrs = get_expected_prim_attributes_count(cone) self.assertEqual(bundle.get_attribute_count(), n_attrs) assert_stamp_missing(bundle) assert_attr_value(bundle, "radius", 400) assert_attr_value(bundle, "height", 40) assert_attr_value(bundle, "sourcePrimType", "Cone") assert_attr_value(bundle, "primvars:displayColor", [[0, 0, 1]]) else: self.fail(path) dummy_attr = get_attr(cube_bundle, dummy_attr_name) self.assertFalse(dummy_attr.is_valid()) prev_dirtyids = dummy_prev_dirtyids[:-1] curr_dirtyids = dirtyid_interface.get(entries) self.assert_dirtyid( dirtyid_interface, entry_names, curr_dirtyids, prev_dirtyids, [container_bundle_name, cube_bundle_name] ) curr_dummy_dirtyids = dirtyid_interface.get([dummy_attr]) self.assert_dirtyid_validity(dirtyid_interface, [dummy_entry_name], curr_dummy_dirtyids, False) # remove the cone from the input paths if use_path_pattern: controller.edit( test_graph_path, { keys.SET_VALUES: [ ("Read.inputs:pathPattern", cube_path), ], }, ) else: omni.kit.commands.execute( "SetRelationshipTargets", relationship=stage.GetPropertyAtPath(f"{test_graph_path}/Read.inputs:prims"), targets=[cube.GetPath()], ) set_stamp(90) await controller.evaluate() # for now, changing inputs:prims does a full update assert_stamp(container, -90) child_bundles = container.get_child_bundles() self.assertEqual(len(child_bundles), 1) for bundle in child_bundles: n_attrs = get_expected_prim_attributes_count(cube) self.assertEqual(bundle.get_attribute_count(), n_attrs) assert_stamp_missing(bundle) assert_attr_missing(bundle, "bboxMaxCorner") assert_attr_missing(bundle, "bboxMinCorner") assert_attr_missing(bundle, "bboxTransform") assert_attr_value(bundle, "worldMatrix", id_mat) assert_attr_value(bundle, "sourcePrimPath", cube_path) assert_attr_value(bundle, "sourcePrimType", "Cube") assert_attr_value(bundle, "size", 200) assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 0]]) # invalid dirty ids expected for removed entries self.assert_dirtyid_validity( dirtyid_interface, removed_entry_names, dirtyid_interface.get(removed_entries), False ) # the dirty ids should be bumped for all remaining entries remaining_prev_dirtyids = [] remaining_entries = [] remaining_entry_names = [] num_entries = len(entries) for i in range(num_entries): if entry_names[i] not in removed_entry_names: remaining_prev_dirtyids.append(curr_dirtyids[i]) remaining_entries.append(entries[i]) remaining_entry_names.append(entry_names[i]) remaining_curr_dirtyids = dirtyid_interface.get(remaining_entries) self.assert_dirtyid( dirtyid_interface, remaining_entry_names, remaining_curr_dirtyids, remaining_prev_dirtyids, remaining_entry_names, ) # add the cone again to the input paths if use_path_pattern: controller.edit( test_graph_path, { keys.SET_VALUES: [ ("Read.inputs:pathPattern", "/X*/C*"), ], }, ) else: omni.kit.commands.execute( "SetRelationshipTargets", relationship=stage.GetPropertyAtPath(f"{test_graph_path}/Read.inputs:prims"), targets=[cube.GetPath(), cone.GetPath()], ) set_stamp(100) await controller.evaluate() # for now, changing inputs:prims does a full update assert_stamp(container, -100) child_bundles = container.get_child_bundles() self.assertEqual(len(child_bundles), 2) for bundle in child_bundles: assert_attr_missing(bundle, "bboxMaxCorner") assert_attr_missing(bundle, "bboxMinCorner") assert_attr_missing(bundle, "bboxTransform") assert_attr_value(bundle, "worldMatrix", id_mat) path = get_attr_value(bundle, "sourcePrimPath") if path == cube_path: n_attrs = get_expected_prim_attributes_count(cube) self.assertEqual(bundle.get_attribute_count(), n_attrs) assert_stamp_missing(bundle) assert_attr_value(bundle, "size", 200) assert_attr_value(bundle, "sourcePrimType", "Cube") elif path == cone_path: n_attrs = get_expected_prim_attributes_count(cone) self.assertEqual(bundle.get_attribute_count(), n_attrs) assert_stamp_missing(bundle) assert_attr_value(bundle, "radius", 400) assert_attr_value(bundle, "height", 40) assert_attr_value(bundle, "sourcePrimType", "Cone") # for now, changing inputs:prims does a full update prev_dirtyids = curr_dirtyids curr_dirtyids = dirtyid_interface.get(entries) self.assert_dirtyid(dirtyid_interface, entry_names, curr_dirtyids, prev_dirtyids, entry_names) # modify, delete and create again, but don't evaluate the graph yet. set_stamp(110) cube.GetAttribute("size").Set(1000) cone.GetAttribute("height").Set(10) stage.RemovePrim(cube_path) cone.GetAttribute("radius").Set(10) stage.RemovePrim(cone_path) cube = ogts.create_cube(stage, "XCube/Cube", (0, 1, 1)) cube.GetAttribute("size").Set(100) removed_entries = [] removed_entry_names = [] for bundle in child_bundles: bundle_path = get_attr_value(bundle, "sourcePrimPath") if bundle_path == cone_path: bundle_name = bundle.get_name() attrs = bundle.get_attributes() removed_entries.append(bundle) removed_entries.extend(attrs) removed_entry_names.append(bundle_name) removed_entry_names.extend([bundle_name + "." + attr.get_name() for attr in attrs]) await controller.evaluate() # the multiple changes should have be collected together # but for now, deleting and creation does a full update unfortunately assert_stamp(container, -110) child_bundles = container.get_child_bundles() self.assertEqual(len(child_bundles), 1) for bundle in child_bundles: n_attrs = get_expected_prim_attributes_count(cube) self.assertEqual(bundle.get_attribute_count(), n_attrs) assert_stamp_missing(bundle) assert_attr_missing(bundle, "bboxMaxCorner") assert_attr_missing(bundle, "bboxMinCorner") assert_attr_missing(bundle, "bboxTransform") assert_attr_value(bundle, "worldMatrix", id_mat) assert_attr_value(bundle, "sourcePrimPath", cube_path) assert_attr_value(bundle, "sourcePrimType", "Cube") assert_attr_value(bundle, "size", 100) assert_attr_value(bundle, "primvars:displayColor", [[0, 1, 1]]) # invalid dirty ids expected for removed entries self.assert_dirtyid_validity( dirtyid_interface, removed_entry_names, dirtyid_interface.get(removed_entries), False ) # the dirty ids should be bumped for all remaining entries remaining_prev_dirtyids = [] remaining_entries = [] remaining_entry_names = [] num_entries = len(entries) for i in range(num_entries): if entry_names[i] not in removed_entry_names: remaining_prev_dirtyids.append(curr_dirtyids[i]) remaining_entries.append(entries[i]) remaining_entry_names.append(entry_names[i]) remaining_curr_dirtyids = dirtyid_interface.get(remaining_entries) self.assert_dirtyid( dirtyid_interface, remaining_entry_names, remaining_curr_dirtyids, remaining_prev_dirtyids, remaining_entry_names, ) # remove the Cube parent xform # this should remove the Cube from the bundle set_stamp(120) stage.RemovePrim("/XCube") await controller.evaluate() if use_path_pattern: # The path pattern matcher will not find any prim matches, # so the input paths will be empty. # In this case, the output bundle is just cleared. assert_stamp_missing(container) else: # The relationship still has a path to the delete cone # So the input paths won't change, but the deletion # will be detected by the change tracker assert_stamp(container, -120) child_bundles = container.get_child_bundles() self.assertEqual(len(child_bundles), 0) container_prev_dirtyids = [remaining_curr_dirtyids[0]] container_curr_dirtyids = dirtyid_interface.get([container]) self.assert_dirtyid( dirtyid_interface, [container_bundle_name], container_curr_dirtyids, container_prev_dirtyids, [container_bundle_name], ) # create the cube again set_stamp(130) xcube = UsdGeom.Xform.Define(stage, "/XCube") cube = ogts.create_cube(stage, "XCube/Cube", (1, 0, 1)) cube.GetAttribute("size").Set(100) await controller.evaluate() # for now creation of prims results in a full update assert_stamp(container, -130) child_bundles = container.get_child_bundles() self.assertEqual(len(child_bundles), 1) for bundle in child_bundles: n_attrs = get_expected_prim_attributes_count(cube) self.assertEqual(bundle.get_attribute_count(), n_attrs) assert_stamp_missing(bundle) assert_attr_missing(bundle, "bboxMaxCorner") assert_attr_missing(bundle, "bboxMinCorner") assert_attr_missing(bundle, "bboxTransform") assert_attr_value(bundle, "worldMatrix", id_mat) assert_attr_value(bundle, "sourcePrimPath", cube_path) assert_attr_value(bundle, "sourcePrimType", "Cube") assert_attr_value(bundle, "size", 100) assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 1]]) remaining_prev_dirtyids = remaining_curr_dirtyids remaining_curr_dirtyids = dirtyid_interface.get(remaining_entries) self.assert_dirtyid( dirtyid_interface, remaining_entry_names, remaining_curr_dirtyids, remaining_prev_dirtyids, remaining_entry_names, ) # translate the cube through its parent xform set_stamp(140) UsdGeom.XformCommonAPI(xcube).SetTranslate((10.0, 10.0, 10.0)) await controller.evaluate() # the cube bundle wordMatrix should have updated assert_stamp(container, 140) child_bundles = container.get_child_bundles() self.assertEqual(len(child_bundles), 1) for bundle in child_bundles: n_attrs = get_expected_prim_attributes_count(cube, debug_stamp=True) self.assertEqual(bundle.get_attribute_count(), n_attrs) assert_stamp(bundle, 10000140) # 1e7 means only world matrix was updated assert_attr_value(bundle, "sourcePrimPath", cube_path) assert_attr_value(bundle, "sourcePrimType", "Cube") assert_attr_missing(bundle, "bboxMaxCorner") assert_attr_missing(bundle, "bboxMinCorner") assert_attr_missing(bundle, "bboxTransform") assert_attr_value(bundle, "worldMatrix", [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 10, 10, 1]) assert_attr_value(bundle, "size", 100) assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 1]]) remaining_prev_dirtyids = remaining_curr_dirtyids remaining_curr_dirtyids = dirtyid_interface.get(remaining_entries) self.assert_dirtyid( dirtyid_interface, remaining_entry_names, remaining_curr_dirtyids, remaining_prev_dirtyids, [container_bundle_name, cube_bundle_name, cube_bundle_name + ".worldMatrix"], ) # request bounding boxes set_stamp(150) controller.edit( test_graph_path, { keys.SET_VALUES: ("Read.inputs:computeBoundingBox", True), }, ) await controller.evaluate() # changing the computeBoundingBox causes a full update assert_stamp(container, -150) child_bundles = container.get_child_bundles() self.assertEqual(len(child_bundles), 1) for bundle in child_bundles: n_attrs = get_expected_prim_attributes_count(cube, bbox=True) self.assertEqual(bundle.get_attribute_count(), n_attrs) assert_stamp_missing(bundle) assert_attr_value(bundle, "sourcePrimPath", cube_path) assert_attr_value(bundle, "sourcePrimType", "Cube") assert_attr_value(bundle, "bboxMaxCorner", [50, 50, 50]) assert_attr_value(bundle, "bboxMinCorner", [-50, -50, -50]) assert_attr_value(bundle, "bboxTransform", id_mat) assert_attr_value(bundle, "worldMatrix", [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 10, 10, 1]) assert_attr_value(bundle, "size", 100) assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 1]]) remaining_prev_dirtyids = remaining_curr_dirtyids remaining_curr_dirtyids = dirtyid_interface.get(remaining_entries) self.assert_dirtyid( dirtyid_interface, remaining_entry_names, remaining_curr_dirtyids, remaining_prev_dirtyids, remaining_entry_names, ) bbox_entries = [ get_attr(cube_bundle, "bboxMaxCorner"), get_attr(cube_bundle, "bboxMinCorner"), get_attr(cube_bundle, "bboxTransform"), ] bbox_entry_names = [ cube_bundle_name + ".bboxMaxCorner", cube_bundle_name + ".bboxMinCorner", cube_bundle_name + ".bboxTransform", ] bbox_curr_dirtyids = dirtyid_interface.get(bbox_entries) self.assert_dirtyid_validity(dirtyid_interface, bbox_entry_names, bbox_curr_dirtyids, True) # modify bounding box set_stamp(160) cube.GetAttribute("size").Set(200) await controller.evaluate() # check incremental update assert_stamp(container, 160) child_bundles = container.get_child_bundles() self.assertEqual(len(child_bundles), 1) for bundle in child_bundles: n_attrs = get_expected_prim_attributes_count(cube, debug_stamp=True, bbox=True) self.assertEqual(bundle.get_attribute_count(), n_attrs) assert_stamp(bundle, 160) assert_attr_value(bundle, "sourcePrimPath", cube_path) assert_attr_value(bundle, "sourcePrimType", "Cube") assert_attr_value(bundle, "bboxMaxCorner", [100, 100, 100]) assert_attr_value(bundle, "bboxMinCorner", [-100, -100, -100]) assert_attr_value(bundle, "bboxTransform", id_mat) assert_attr_value(bundle, "worldMatrix", [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 10, 10, 1]) assert_attr_value(bundle, "size", 200) assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 1]]) entries = remaining_entries + bbox_entries entry_names = remaining_entry_names + bbox_entry_names prev_dirtyids = remaining_curr_dirtyids + bbox_curr_dirtyids curr_dirtyids = dirtyid_interface.get(entries) self.assert_dirtyid( dirtyid_interface, entry_names, curr_dirtyids, prev_dirtyids, [ container_bundle_name, cube_bundle_name, cube_bundle_name + ".size", cube_bundle_name + ".bboxMaxCorner", cube_bundle_name + ".bboxMinCorner", ], ) # evaluate bbox without modification set_stamp(170) await controller.evaluate() # check nothing was updated assert_stamp(container, 160) child_bundles = container.get_child_bundles() self.assertEqual(len(child_bundles), 1) for bundle in child_bundles: n_attrs = get_expected_prim_attributes_count(cube, debug_stamp=True, bbox=True) self.assertEqual(bundle.get_attribute_count(), n_attrs) assert_stamp(bundle, 160) assert_attr_value(bundle, "sourcePrimPath", cube_path) assert_attr_value(bundle, "sourcePrimType", "Cube") assert_attr_value(bundle, "bboxMaxCorner", [100, 100, 100]) assert_attr_value(bundle, "bboxMinCorner", [-100, -100, -100]) assert_attr_value(bundle, "bboxTransform", id_mat) assert_attr_value(bundle, "worldMatrix", [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 10, 10, 1]) assert_attr_value(bundle, "size", 200) assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 1]]) prev_dirtyids = curr_dirtyids curr_dirtyids = dirtyid_interface.get(entries) self.assert_dirtyid(dirtyid_interface, entry_names, curr_dirtyids, prev_dirtyids, []) # animate for timecode in range(10): set_stamp(180 + timecode) controller.edit(test_graph_path, {keys.SET_VALUES: ("Read.inputs:usdTimecode", timecode)}) await controller.evaluate() # check a full update is done assert_stamp(container, -(180 + timecode)) child_bundles = container.get_child_bundles() self.assertEqual(len(child_bundles), 1) for bundle in child_bundles: n_attrs = get_expected_prim_attributes_count(cube, bbox=True) self.assertEqual(bundle.get_attribute_count(), n_attrs) assert_stamp_missing(bundle) assert_attr_value(bundle, "sourcePrimPath", cube_path) assert_attr_value(bundle, "sourcePrimType", "Cube") assert_attr_value(bundle, "bboxMaxCorner", [100, 100, 100]) assert_attr_value(bundle, "bboxMinCorner", [-100, -100, -100]) assert_attr_value(bundle, "bboxTransform", id_mat) assert_attr_value(bundle, "worldMatrix", [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 10, 10, 1]) assert_attr_value(bundle, "size", 200) assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 1]]) prev_dirtyids = curr_dirtyids curr_dirtyids = dirtyid_interface.get(entries) self.assert_dirtyid(dirtyid_interface, entry_names, curr_dirtyids, prev_dirtyids, entry_names) # switch back to non-animating set_stamp(200) controller.edit(test_graph_path, {keys.SET_VALUES: ("Read.inputs:usdTimecode", float("nan"))}) # changes to the cube should not trigger an incremental update when switching cube.GetAttribute("size").Set(100) await controller.evaluate() # check a full update is done assert_stamp(container, -200) child_bundles = container.get_child_bundles() self.assertEqual(len(child_bundles), 1) for bundle in child_bundles: n_attrs = get_expected_prim_attributes_count(cube, bbox=True) self.assertEqual(bundle.get_attribute_count(), n_attrs) assert_stamp_missing(bundle) assert_attr_value(bundle, "sourcePrimPath", cube_path) assert_attr_value(bundle, "sourcePrimType", "Cube") assert_attr_value(bundle, "bboxMaxCorner", [50, 50, 50]) assert_attr_value(bundle, "bboxMinCorner", [-50, -50, -50]) assert_attr_value(bundle, "bboxTransform", id_mat) assert_attr_value(bundle, "worldMatrix", [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 10, 10, 1]) assert_attr_value(bundle, "size", 100) assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 1]]) prev_dirtyids = curr_dirtyids curr_dirtyids = dirtyid_interface.get(entries) self.assert_dirtyid(dirtyid_interface, entry_names, curr_dirtyids, prev_dirtyids, entry_names) # change the cube again set_stamp(210) # changes to the cube should now trigger an incremental update cube.GetAttribute("size").Set(200) await controller.evaluate() # an incremental update should be done assert_stamp(container, 210) child_bundles = container.get_child_bundles() self.assertEqual(len(child_bundles), 1) for bundle in child_bundles: n_attrs = get_expected_prim_attributes_count(cube, debug_stamp=True, bbox=True) self.assertEqual(bundle.get_attribute_count(), n_attrs) assert_stamp(bundle, 210) assert_attr_value(bundle, "sourcePrimPath", cube_path) assert_attr_value(bundle, "sourcePrimType", "Cube") assert_attr_value(bundle, "bboxMaxCorner", [100, 100, 100]) assert_attr_value(bundle, "bboxMinCorner", [-100, -100, -100]) assert_attr_value(bundle, "bboxTransform", id_mat) assert_attr_value(bundle, "worldMatrix", [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 10, 10, 1]) assert_attr_value(bundle, "size", 200) assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 1]]) # disable change tracking set_change_tracking(False) set_stamp(220) await controller.evaluate() # the input change should trigger a full update assert_stamp(container, -220) for bundle in child_bundles: n_attrs = get_expected_prim_attributes_count(cube, bbox=True) self.assertEqual(bundle.get_attribute_count(), n_attrs) assert_stamp_missing(bundle) assert_attr_value(bundle, "sourcePrimPath", cube_path) assert_attr_value(bundle, "sourcePrimType", "Cube") assert_attr_value(bundle, "bboxMaxCorner", [100, 100, 100]) assert_attr_value(bundle, "bboxMinCorner", [-100, -100, -100]) assert_attr_value(bundle, "bboxTransform", id_mat) assert_attr_value(bundle, "worldMatrix", [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 10, 10, 1]) assert_attr_value(bundle, "size", 200) assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 1]]) prev_dirtyids = curr_dirtyids curr_dirtyids = dirtyid_interface.get(entries) self.assert_dirtyid(dirtyid_interface, entry_names, curr_dirtyids, prev_dirtyids, entry_names) # change the cube again, with change tracking disabled set_stamp(230) # changes to the cube should now trigger a full update cube.GetAttribute("size").Set(100) await controller.evaluate() assert_stamp(container, -230) for bundle in child_bundles: n_attrs = get_expected_prim_attributes_count(cube, bbox=True) self.assertEqual(bundle.get_attribute_count(), n_attrs) assert_stamp_missing(bundle) assert_attr_value(bundle, "sourcePrimPath", cube_path) assert_attr_value(bundle, "sourcePrimType", "Cube") assert_attr_value(bundle, "bboxMaxCorner", [50, 50, 50]) assert_attr_value(bundle, "bboxMinCorner", [-50, -50, -50]) assert_attr_value(bundle, "bboxTransform", id_mat) assert_attr_value(bundle, "worldMatrix", [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 10, 10, 1]) assert_attr_value(bundle, "size", 100) assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 1]]) prev_dirtyids = curr_dirtyids curr_dirtyids = dirtyid_interface.get(entries) self.assert_dirtyid(dirtyid_interface, entry_names, curr_dirtyids, prev_dirtyids, entry_names) # enable change tracking again set_change_tracking(True) set_stamp(250) await controller.evaluate() # the input change should trigger a full update assert_stamp(container, -250) for bundle in child_bundles: n_attrs = get_expected_prim_attributes_count(cube, bbox=True) self.assertEqual(bundle.get_attribute_count(), n_attrs) assert_stamp_missing(bundle) assert_attr_value(bundle, "sourcePrimPath", cube_path) assert_attr_value(bundle, "sourcePrimType", "Cube") assert_attr_value(bundle, "bboxMaxCorner", [50, 50, 50]) assert_attr_value(bundle, "bboxMinCorner", [-50, -50, -50]) assert_attr_value(bundle, "bboxTransform", id_mat) assert_attr_value(bundle, "worldMatrix", [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 10, 10, 1]) assert_attr_value(bundle, "size", 100) assert_attr_value(bundle, "primvars:displayColor", [[1, 0, 1]]) prev_dirtyids = curr_dirtyids curr_dirtyids = dirtyid_interface.get(entries) self.assert_dirtyid(dirtyid_interface, entry_names, curr_dirtyids, prev_dirtyids, entry_names) # create, remove and create the cone, in one go set_stamp(260) cone = ogts.create_cube(stage, "XCone/Cone", (1, 1, 1)) stage.RemovePrim(cone_path) cone = ogts.create_cube(stage, "XCone/Cone", (1, 1, 1)) await controller.evaluate() # the second removal should not cancel the last creation assert_stamp(container, -260) child_bundles = container.get_child_bundles() self.assertEqual(len(child_bundles), 2) prev_dirtyids = curr_dirtyids curr_dirtyids = dirtyid_interface.get(entries) self.assert_dirtyid(dirtyid_interface, entry_names, curr_dirtyids, prev_dirtyids, entry_names) async def test_read_prims_change_tracking_no_debug_stamps(self): """omni.graph.nodes.ReadPrimsV2 change tracking should not add debug stamps unless requested""" usd_context = omni.usd.get_context() stage: Usd.Stage = usd_context.get_stage() test_graph_path = "/World/TestGraph" controller = og.Controller() keys = og.Controller.Keys xcube = UsdGeom.Xform.Define(stage, "/XCube") cube = ogts.create_cube(stage, "XCube/Cube", (1, 0, 0)) cube.GetAttribute("size").Set(100) (graph, [read_prims_node, _], _, _) = controller.edit( test_graph_path, { keys.CREATE_NODES: [ ("Read", "omni.graph.nodes.ReadPrimsV2"), ("Inspector", "omni.graph.nodes.BundleInspector"), ], keys.CONNECT: [ ("Read.outputs_primsBundle", "Inspector.inputs:bundle"), ], keys.SET_VALUES: [ ("Inspector.inputs:print", False), ], }, ) omni.kit.commands.execute( "SetRelationshipTargets", relationship=stage.GetPropertyAtPath(f"{test_graph_path}/Read.inputs:prims"), targets=[cube.GetPath()], ) def get_attr(bundle, name): return bundle.get_attribute_by_name(name) def assert_attr_missing(bundle, name): self.assertFalse(get_attr(bundle, name).is_valid()) def assert_stamp_missing(bundle): assert_attr_missing(bundle, "_debugStamp") # initial update await controller.evaluate() graph_context = graph.get_default_graph_context() container = graph_context.get_output_bundle(read_prims_node, "outputs_primsBundle") self.assertTrue(container.valid) # no stamps should be added assert_stamp_missing(container) child_bundles = container.get_child_bundles() self.assertEqual(len(child_bundles), 1) for bundle in child_bundles: assert_stamp_missing(bundle) # trigger incremental empty update await controller.evaluate() # no stamps should be added assert_stamp_missing(container) child_bundles = container.get_child_bundles() self.assertEqual(len(child_bundles), 1) for bundle in child_bundles: assert_stamp_missing(bundle) # move the xform UsdGeom.XformCommonAPI(xcube).SetTranslate((10.0, 10.0, 10.0)) # trigger incremental update, world matrices should be updated await controller.evaluate() # but no stamps should be added assert_stamp_missing(container) child_bundles = container.get_child_bundles() self.assertEqual(len(child_bundles), 1) for bundle in child_bundles: assert_stamp_missing(bundle) def assert_dirtyid_validity( self, dirtyid_interface: og._og_unstable.IDirtyID2, entry_names: List[str], curr_dirtyids: list, is_valid: bool ): self.assertEqual(len(entry_names), len(curr_dirtyids)) if _debug: print() for entry_name, curr_dirty_id in zip(entry_names, curr_dirtyids): print(entry_name, curr_dirty_id) for entry_name, curr_dirty_id in zip(entry_names, curr_dirtyids): self.assertEqual(dirtyid_interface.is_valid(curr_dirty_id), is_valid, entry_name) def assert_dirtyid( self, dirtyid_interface: og._og_unstable.IDirtyID2, entry_names: List[str], curr_dirtyids: list, prev_dirtyids: list, changed_entry_names: List[str], ): self.assertEqual(len(entry_names), len(curr_dirtyids)) self.assertEqual(len(entry_names), len(prev_dirtyids)) if _debug: print() for entry_name, curr_dirty_id, prev_dirty_id in zip(entry_names, curr_dirtyids, prev_dirtyids): print(entry_name, curr_dirty_id, prev_dirty_id) for entry_name, curr_dirty_id, prev_dirty_id in zip(entry_names, curr_dirtyids, prev_dirtyids): self.assertTrue(dirtyid_interface.is_valid(curr_dirty_id), entry_name) self.assertTrue(dirtyid_interface.is_valid(prev_dirty_id), entry_name) if entry_name in changed_entry_names: self.assertGreater(curr_dirty_id, prev_dirty_id, entry_name) else: self.assertEqual(curr_dirty_id, prev_dirty_id, entry_name)
55,642
Python
41.281915
119
0.593257
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_dynamic_nodes.py
"""Tests for nodes with dynamic attributes""" # noqa: PLC0302 import unittest from typing import Any, Dict import omni.graph.core as og import omni.graph.core.tests as ogts import omni.usd from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene, _test_verify_scene, _TestGraphAndNode from pxr import OmniGraphSchemaTools DYN_ATTRIBUTE_FORMAT = "inputs:" # ====================================================================== class TestDynamicNodes(ogts.OmniGraphTestCase): """Unit tests for nodes with dynamic attributes""" PERSISTENT_SETTINGS_PREFIX = "/persistent" TEST_GRAPH_PATH = "/World/TestGraph" # This method is copied from the module omnigraph_test_utils and is modified to support the "dynamicInputs" keyword # in test data. Once the dynamic inputs can directly be tested in .ogn files, this implementation should be replaced # with the standard implementation. async def _test_setup_scene( tc: unittest.TestCase, # noqa: N805 controller: og.Controller, test_graph_name: str, test_node_name: str, test_node_type: str, test_run: Dict[str, Any], last_test_info: _TestGraphAndNode, instance_count=0, ) -> _TestGraphAndNode: """Setup the scene based on given test run dictionary Args: tc: Unit test case executing this method. Used to raise errors controller: Controller object to use when constructing the scene (e.g. may have undo support disabled) test_graph_name: Graph name to use when constructing the scene test_node_name: Node name to use when constructing the scene without "setup" explicitly provided in test_run test_node_type: Node type to use when constructing the scene without "setup" explicitly provided in test_run test_run: Dictionary of consist of four sub-lists and a dictionary: - values for input attributes, set before the test starts - values for output attributes, checked after the test finishes - initial values for state attributes, set before the test starts - final values for state attributes, checked after the test finishes - setup to be used for populating the scene via controller For complete implementation see generate_user_test_data. last_test_info: When executing multiple tests cases for the same node, this represents graph and node used in previous run instance_count: number of instances to create assotiated to this graph, in order to test vectorized compute Returns: Graph and node to use in current execution of the test """ test_info = last_test_info setup = test_run.get("setup", None) if setup: (test_info.graph, test_nodes, _, _) = controller.edit(test_graph_name, setup) tc.assertTrue(test_nodes) test_info.node = test_nodes[0] elif setup is None: test_info.graph = controller.create_graph(test_graph_name) test_info.node = controller.create_node((test_node_name, test_info.graph), test_node_type) else: tc.assertTrue( test_info.graph is not None and test_info.graph.is_valid(), "Test is misconfigured - empty setup cannot be in the first test", ) tc.assertTrue(test_info.graph is not None and test_info.graph.is_valid(), "Test graph invalid") tc.assertTrue(test_info.node is not None and test_info.node.is_valid(), "Test node invalid") await controller.evaluate(test_info.graph) inputs = test_run.get("inputs", []) state_set = test_run.get("state_set", []) values_to_set = inputs + state_set if values_to_set: for attribute_name, attribute_value, _ in values_to_set: controller.set(attribute=(attribute_name, test_info.node), value=attribute_value) dynamic_inputs = test_run.get("dynamicInputs", []) if dynamic_inputs: for attribute_name, attribute_value, _ in dynamic_inputs: controller.create_attribute( test_info.node, attribute_name, attribute_value["type"], og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, attribute_value["value"], ) # create some instance prims, and apply the graph on it if instance_count != 0: stage = omni.usd.get_context().get_stage() for i in range(instance_count): prim_name = f"/World/Test_Instance_Prim_{i}" stage.DefinePrim(prim_name) OmniGraphSchemaTools.applyOmniGraphAPI(stage, prim_name, test_graph_name) return test_info async def test_node_is_updated_when_dynamic_attributes_are_added_or_removed(self): """Tests that the node database is notified and updated when dynamic attributes are added or removed""" # Arrange: create an Add node and add two dynamic attributes on it controller = og.Controller() keys = og.Controller.Keys (graph, (add_node, _, _), _, _,) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Add", "omni.graph.nodes.Add"), ("Const1", "omni.graph.nodes.ConstantFloat"), ("Const2", "omni.graph.nodes.ConstantFloat"), ], keys.CONNECT: [ ("Const1.inputs:value", "Add.inputs:a"), ("Const2.inputs:value", "Add.inputs:b"), ], keys.SET_VALUES: [ ("Const1.inputs:value", 2.0), ("Const2.inputs:value", 3.0), ], }, ) # Evaluate the graph once to ensure the node has a Database created await controller.evaluate(graph) controller.create_attribute( add_node, "inputs:input0", og.Type(og.BaseDataType.FLOAT), og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, 5, # the default value will be applied in the computation ) controller.create_attribute( add_node, "inputs:input1", og.Type(og.BaseDataType.FLOAT), og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, 7, # the default value will be applied in the computation ) # Act: evaluate the graph await controller.evaluate(graph) # Assert: read the sum output and test that the dynamic attributes were included in the computation sum_attr = controller.attribute("outputs:sum", add_node) self.assertEqual(17, controller.get(sum_attr), "The dynamic attributes were not included in the computation") # Arrange 2: remove one of the dynamic inputs input0_attr = controller.attribute("inputs:input0", add_node) controller.remove_attribute(input0_attr) # Act 2: evaluate the graph await controller.evaluate(graph) # Assert 2: assert that only one of the dynamic inputs were used in the computation sum_attr = controller.attribute("outputs:sum", add_node) self.assertEqual( 12, og.Controller.get(sum_attr), "The node was not notified of the removal of a dynamic attribute" ) TEST_DATA_ADD = [ { "inputs": [ ["inputs:a", {"type": "float[2]", "value": [1.0, 2.0]}, False], ["inputs:b", {"type": "float[2]", "value": [0.5, 1.0]}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "float[2]", "value": [3.0, 4.0]}, False], ["inputs:d", {"type": "float[2]", "value": [0.1, 0.1]}, False], ], "outputs": [ ["outputs:sum", {"type": "float[2]", "value": [4.6, 7.1]}, False], ], }, { "inputs": [ ["inputs:a", {"type": "int64", "value": 10}, False], ["inputs:b", {"type": "int64", "value": 6}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "int64", "value": 4}, False], ["inputs:d", {"type": "int64", "value": 20}, False], ], "outputs": [ ["outputs:sum", {"type": "int64", "value": 40}, False], ], }, { "inputs": [ ["inputs:a", {"type": "double[2][]", "value": [[10, 5], [1, 1]]}, False], ["inputs:b", {"type": "double[2]", "value": [5, 5]}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "double[2]", "value": [5, 5]}, False], ["inputs:d", {"type": "double[2][]", "value": [[10, 5], [1, 1]]}, False], ], "outputs": [ ["outputs:sum", {"type": "double[2][]", "value": [[30, 20], [12, 12]]}, False], ], }, { "inputs": [ ["inputs:a", {"type": "double[2][]", "value": [[10, 5], [1, 1]]}, False], ["inputs:b", {"type": "double", "value": 5}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "double[2]", "value": [5, 5]}, False], ["inputs:d", {"type": "double[2][]", "value": [[10, 5], [1, 1]]}, False], ], "outputs": [ ["outputs:sum", {"type": "double[2][]", "value": [[30, 20], [12, 12]]}, False], ], }, ] async def test_add(self): """Validates the node OgnAdd with dynamic inputs""" test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA_ADD): await _test_clear_scene(self, test_run) test_info = await self._test_setup_scene( controller, "/TestGraph", "TestNode_omni_graph_nodes_Add", "omni.graph.nodes.Add", test_run, test_info ) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.Add User test case #{i+1}") async def test_add_vectorized(self): """Validates the node OgnAdd with dynamic inputs - vectorized computation""" test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA_ADD): await _test_clear_scene(self, test_run) test_info = await self._test_setup_scene( controller, "/TestGraph", "TestNode_omni_graph_nodes_Add", "omni.graph.nodes.Add", test_run, test_info, 16, ) await controller.evaluate(test_info.graph) _test_verify_scene(self, controller, test_run, test_info, f"omni.graph.nodes.Add User test case #{i+1}", 16) TEST_DATA_SUBTRACT = [ { # 1 "inputs": [ ["inputs:a", {"type": "double", "value": 10.0}, False], ["inputs:b", {"type": "double", "value": 0.5}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "double", "value": 1.0}, False], ["inputs:d", {"type": "double", "value": 0.5}, False], ], "outputs": [ ["outputs:difference", {"type": "double", "value": 8}, False], ], }, { # 2 "inputs": [ ["inputs:a", {"type": "float", "value": 10.0}, False], ["inputs:b", {"type": "float", "value": 0.5}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "float", "value": 1.0}, False], ["inputs:d", {"type": "float", "value": 0.5}, False], ], "outputs": [ ["outputs:difference", {"type": "float", "value": 8}, False], ], }, { # 3 "inputs": [ ["inputs:a", {"type": "half", "value": 10.0}, False], ["inputs:b", {"type": "half", "value": 0.5}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "half", "value": 1.0}, False], ["inputs:d", {"type": "half", "value": 0.5}, False], ], "outputs": [ ["outputs:difference", {"type": "half", "value": 8.0}, False], ], }, { # 4 "inputs": [ ["inputs:a", {"type": "int", "value": 10}, False], ["inputs:b", {"type": "int", "value": 6}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "int", "value": 1}, False], ["inputs:d", {"type": "int", "value": 2}, False], ], "outputs": [ ["outputs:difference", {"type": "int", "value": 1}, False], ], }, { # 5 "inputs": [ ["inputs:a", {"type": "int64", "value": 10}, False], ["inputs:b", {"type": "int64", "value": 6}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "int64", "value": 1}, False], ["inputs:d", {"type": "int64", "value": 2}, False], ], "outputs": [ ["outputs:difference", {"type": "int64", "value": 1}, False], ], }, { # 6 "inputs": [ ["inputs:a", {"type": "uchar", "value": 10}, False], ["inputs:b", {"type": "uchar", "value": 6}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "uchar", "value": 1}, False], ["inputs:d", {"type": "uchar", "value": 2}, False], ], "outputs": [ ["outputs:difference", {"type": "uchar", "value": 1}, False], ], }, { # 7 "inputs": [ ["inputs:a", {"type": "uint", "value": 10}, False], ["inputs:b", {"type": "uint", "value": 6}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "uint", "value": 1}, False], ["inputs:d", {"type": "uint", "value": 2}, False], ], "outputs": [ ["outputs:difference", {"type": "uint", "value": 1}, False], ], }, { # 8 "inputs": [ ["inputs:a", {"type": "uint64", "value": 10}, False], ["inputs:b", {"type": "uint64", "value": 6}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "uint64", "value": 1}, False], ["inputs:d", {"type": "uint64", "value": 2}, False], ], "outputs": [ ["outputs:difference", {"type": "uint64", "value": 1}, False], ], }, { # 9 "inputs": [ ["inputs:a", {"type": "float[2]", "value": [10.0, 20.0]}, False], ["inputs:b", {"type": "float[2]", "value": [0.5, 1.0]}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "float[2]", "value": [1.0, 2.0]}, False], ["inputs:d", {"type": "float[2]", "value": [3.0, 4.0]}, False], ], "outputs": [ ["outputs:difference", {"type": "float[2]", "value": [5.5, 13.0]}, False], ], }, { # 10 "inputs": [ ["inputs:a", {"type": "float[3]", "value": [10.0, 20.0, 30.0]}, False], ["inputs:b", {"type": "float[3]", "value": [0.5, 1.0, 1.5]}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "float[3]", "value": [1.0, 2.0, 3.0]}, False], ["inputs:d", {"type": "float[3]", "value": [0.5, 1.0, 1.5]}, False], ], "outputs": [ ["outputs:difference", {"type": "float[3]", "value": [8.0, 16.0, 24.0]}, False], ], }, { # 11 "inputs": [ ["inputs:a", {"type": "float[4]", "value": [10.0, 20.0, 30.0, 40.0]}, False], ["inputs:b", {"type": "float[4]", "value": [0.5, 1.0, 1.5, 2.0]}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "float[4]", "value": [1.0, 2.0, 3.0, 4.0]}, False], ["inputs:d", {"type": "float[4]", "value": [0.5, 0.5, 0.5, 0.5]}, False], ], "outputs": [ ["outputs:difference", {"type": "float[4]", "value": [8.0, 16.5, 25.0, 33.5]}, False], ], }, { # 12 "inputs": [ ["inputs:a", {"type": "float[2]", "value": [2.0, 3.0]}, False], ["inputs:b", {"type": "float", "value": 1.0}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "float[2]", "value": [0.5, 0.5]}, False], ["inputs:d", {"type": "float", "value": 1.0}, False], ], "outputs": [ ["outputs:difference", {"type": "float[2]", "value": [-0.5, 0.5]}, False], ], }, { # 13 "inputs": [ ["inputs:a", {"type": "float", "value": 1.0}, False], ["inputs:b", {"type": "float[2]", "value": [1.0, 2.0]}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "float", "value": 1.0}, False], ["inputs:d", {"type": "float[2]", "value": [1.0, 2.0]}, False], ], "outputs": [ ["outputs:difference", {"type": "float[2]", "value": [-2.0, -4.0]}, False], ], }, { # 14 "inputs": [ ["inputs:a", {"type": "float[]", "value": [2.0, 3.0]}, False], ["inputs:b", {"type": "float", "value": 1.0}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "float[]", "value": [2.0, 3.0]}, False], ["inputs:d", {"type": "float", "value": 1.0}, False], ], "outputs": [ ["outputs:difference", {"type": "float[]", "value": [-2.0, -2.0]}, False], ], }, { # 15 "inputs": [ ["inputs:a", {"type": "float", "value": 1.0}, False], ["inputs:b", {"type": "float[]", "value": [1.0, 2.0]}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "float", "value": 1.0}, False], ["inputs:d", {"type": "float[]", "value": [1.0, 2.0]}, False], ], "outputs": [ ["outputs:difference", {"type": "float[]", "value": [-2.0, -4.0]}, False], ], }, { # 16 "inputs": [ ["inputs:a", {"type": "int64[]", "value": [10]}, False], ["inputs:b", {"type": "int64[]", "value": [5]}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "int64[]", "value": [1]}, False], ["inputs:d", {"type": "int64[]", "value": [2]}, False], ], "outputs": [ ["outputs:difference", {"type": "int64[]", "value": [2]}, False], ], }, { # 17 "inputs": [ ["inputs:a", {"type": "int64[]", "value": [10, 20]}, False], ["inputs:b", {"type": "int64[]", "value": [5, 10]}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "int64[]", "value": [1, 2]}, False], ["inputs:d", {"type": "int64[]", "value": [3, 4]}, False], ], "outputs": [ ["outputs:difference", {"type": "int64[]", "value": [1, 4]}, False], ], }, { # 18 "inputs": [ ["inputs:a", {"type": "int64[]", "value": [10, 20, 30]}, False], ["inputs:b", {"type": "int64[]", "value": [5, 10, 15]}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "int64[]", "value": [10, 20, 30]}, False], ["inputs:d", {"type": "int64[]", "value": [5, 10, 15]}, False], ], "outputs": [ ["outputs:difference", {"type": "int64[]", "value": [-10, -20, -30]}, False], ], }, { # 19 "inputs": [ ["inputs:a", {"type": "int64[]", "value": [10, 20, 30, 40]}, False], ["inputs:b", {"type": "int64[]", "value": [5, 10, 15, 20]}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "int64[]", "value": [10, 20, 30, 40]}, False], ["inputs:d", {"type": "int64[]", "value": [5, 10, 15, 20]}, False], ], "outputs": [ ["outputs:difference", {"type": "int64[]", "value": [-10, -20, -30, -40]}, False], ], }, { # 20 "inputs": [ ["inputs:a", {"type": "int[3][]", "value": [[10, 20, 30], [40, 50, 60]]}, False], ["inputs:b", {"type": "int[3]", "value": [5, 10, 15]}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "int[3][]", "value": [[10, 20, 30], [40, 50, 60]]}, False], ["inputs:d", {"type": "int[3]", "value": [5, 10, 15]}, False], ], "outputs": [ [ "outputs:difference", {"type": "int[3][]", "value": [[-10, -20, -30], [-10, -20, -30]]}, False, ], # output an array with a single int3 element ], }, { # 21 dynamic arrays mirror the default attributes - should give the same result as previous test "inputs": [ ["inputs:a", {"type": "int[3][]", "value": [[10, 20, 30], [40, 50, 60]]}, False], ["inputs:b", {"type": "int[3]", "value": [5, 10, 15]}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "int[3]", "value": [5, 10, 15]}, False], ["inputs:d", {"type": "int[3][]", "value": [[10, 20, 30], [40, 50, 60]]}, False], ], "outputs": [ ["outputs:difference", {"type": "int[3][]", "value": [[-10, -20, -30], [-10, -20, -30]]}, False], ], }, { # 22 "inputs": [ ["inputs:a", {"type": "int[3]", "value": [5, 10, 15]}, False], ["inputs:b", {"type": "int[3][]", "value": [[10, 20, 30], [40, 50, 60]]}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "int[3]", "value": [5, 10, 15]}, False], ["inputs:d", {"type": "int[3][]", "value": [[10, 20, 30], [40, 50, 60]]}, False], ], "outputs": [ ["outputs:difference", {"type": "int[3][]", "value": [[-20, -40, -60], [-80, -100, -120]]}, False], ], }, { # 23 "inputs": [ ["inputs:a", {"type": "int[2][]", "value": [[10, 20], [30, 40], [50, 60]]}, False], ["inputs:b", {"type": "int[2]", "value": [5, 10]}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "int[2][]", "value": [[10, 20], [30, 40], [50, 60]]}, False], ["inputs:d", {"type": "int[2]", "value": [5, 10]}, False], ], "outputs": [ ["outputs:difference", {"type": "int[2][]", "value": [[-10, -20], [-10, -20], [-10, -20]]}, False], ], }, { # 24 "inputs": [ ["inputs:a", {"type": "int[2]", "value": [5, 10]}, False], ["inputs:b", {"type": "int[2][]", "value": [[10, 20], [30, 40], [50, 60]]}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "int[2]", "value": [5, 10]}, False], ["inputs:d", {"type": "int[2][]", "value": [[10, 20], [30, 40], [50, 60]]}, False], ], "outputs": [ ["outputs:difference", {"type": "int[2][]", "value": [[-20, -40], [-60, -80], [-100, -120]]}, False], ], }, ] async def test_subtract(self): """Validates the node OgnSubtract with dynamic inputs""" test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA_SUBTRACT): await _test_clear_scene(self, test_run) test_info = await self._test_setup_scene( controller, "/TestGraph", "TestNode_omni_graph_nodes_Subtract", "omni.graph.nodes.Subtract", test_run, test_info, ) await controller.evaluate(test_info.graph) _test_verify_scene( self, controller, test_run, test_info, f"omni.graph.nodes.Subtract User test case #{i+1}" ) async def test_subtract_vectorized(self): """Validates the node OgnSubtract with dynamic inputs - vectorized computation""" test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA_SUBTRACT): await _test_clear_scene(self, test_run) test_info = await self._test_setup_scene( controller, "/TestGraph", "TestNode_omni_graph_nodes_Subtract", "omni.graph.nodes.Subtract", test_run, test_info, 16, ) await controller.evaluate(test_info.graph) _test_verify_scene( self, controller, test_run, test_info, f"omni.graph.nodes.Subtract User test case #{i+1}", 16 ) TEST_DATA_MULTIPLY = [ { "inputs": [ ["inputs:a", {"type": "float", "value": 42.0}, False], ["inputs:b", {"type": "float", "value": 2.0}, False], ], "outputs": [ ["outputs:product", {"type": "float", "value": 84.0}, False], ], }, { "inputs": [ ["inputs:a", {"type": "double[2]", "value": [1.0, 42.0]}, False], ["inputs:b", {"type": "double[2]", "value": [2.0, 1.0]}, False], ], "outputs": [ ["outputs:product", {"type": "double[2]", "value": [2.0, 42.0]}, False], ], }, { "inputs": [ ["inputs:a", {"type": "double[]", "value": [1.0, 42.0]}, False], ["inputs:b", {"type": "double", "value": 2.0}, False], ], "outputs": [ ["outputs:product", {"type": "double[]", "value": [2.0, 84.0]}, False], ], }, { "inputs": [ ["inputs:a", {"type": "double[2][]", "value": [[10, 5], [1, 1]]}, False], ["inputs:b", {"type": "double[2]", "value": [5, 5]}, False], ], "outputs": [ ["outputs:product", {"type": "double[2][]", "value": [[50, 25], [5, 5]]}, False], ], }, { "inputs": [ ["inputs:a", {"type": "double[2][]", "value": [[10, 5], [1, 1]]}, False], ["inputs:b", {"type": "double", "value": 2}, False], ], "outputs": [ ["outputs:product", {"type": "double[2][]", "value": [[20, 10], [2, 2]]}, False], ], }, { "inputs": [ ["inputs:a", {"type": "double[2]", "value": [10, 5]}, False], ["inputs:b", {"type": "double", "value": 2}, False], ], "outputs": [ ["outputs:product", {"type": "double[2]", "value": [20, 10]}, False], ], }, ] async def test_multiply(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA_MULTIPLY): await _test_clear_scene(self, test_run) test_info = await self._test_setup_scene( controller, "/TestGraph", "TestNode_omni_graph_nodes_Multiply", "omni.graph.nodes.Multiply", test_run, test_info, ) await controller.evaluate(test_info.graph) _test_verify_scene( self, controller, test_run, test_info, f"omni.graph.nodes.Multiply User test case #{i+1}" ) async def test_multiply_vectorized(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA_MULTIPLY): await _test_clear_scene(self, test_run) test_info = await self._test_setup_scene( controller, "/TestGraph", "TestNode_omni_graph_nodes_Multiply", "omni.graph.nodes.Multiply", test_run, test_info, 16, ) await controller.evaluate(test_info.graph) _test_verify_scene( self, controller, test_run, test_info, f"omni.graph.nodes.Multiply User test case #{i+1}", 16 ) TEST_DATA_AND = [ { "inputs": [ ["inputs:a", {"type": "bool", "value": False}, False], ["inputs:b", {"type": "bool", "value": True}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "bool", "value": False}, False], ["inputs:d", {"type": "bool", "value": True}, False], ], "outputs": [ ["outputs:result", False, False], ], }, { "inputs": [ ["inputs:a", {"type": "bool", "value": True}, False], ["inputs:b", {"type": "bool", "value": True}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "bool", "value": True}, False], ["inputs:d", {"type": "bool", "value": True}, False], ], "outputs": [ ["outputs:result", True, False], ], }, { "inputs": [ ["inputs:a", {"type": "bool[]", "value": [False, False, True, True]}, False], ["inputs:b", {"type": "bool[]", "value": [False, True, False, True]}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "bool", "value": True}, False], ["inputs:d", {"type": "bool[]", "value": [False, True, False, True]}, False], ], "outputs": [ ["outputs:result", [False, False, False, True], False], ], }, { "inputs": [ ["inputs:a", {"type": "bool", "value": False}, False], ["inputs:b", {"type": "bool[]", "value": [False, True]}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "bool", "value": False}, False], ["inputs:d", {"type": "bool[]", "value": [False, True]}, False], ], "outputs": [ ["outputs:result", [False, False], False], ], }, { "inputs": [ ["inputs:a", {"type": "bool[]", "value": [False, True]}, False], ["inputs:b", {"type": "bool", "value": False}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "bool[]", "value": [False, True]}, False], ["inputs:d", {"type": "bool", "value": False}, False], ], "outputs": [ ["outputs:result", [False, False], False], ], }, { "inputs": [ ["inputs:a", {"type": "bool[]", "value": [False, True]}, False], ["inputs:b", {"type": "bool", "value": True}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "bool[]", "value": [False, True]}, False], ["inputs:d", {"type": "bool", "value": True}, False], ], "outputs": [ ["outputs:result", [False, True], False], ], }, ] async def test_boolean_and(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA_AND): await _test_clear_scene(self, test_run) test_info = await self._test_setup_scene( controller, "/TestGraph", "TestNode_omni_graph_nodes_BooleanAnd", "omni.graph.nodes.BooleanAnd", test_run, test_info, ) await controller.evaluate(test_info.graph) _test_verify_scene( self, controller, test_run, test_info, f"omni.graph.nodes.BooleanAnd User test case #{i+1}" ) async def test_boolean_and_vectorized(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA_AND): await _test_clear_scene(self, test_run) test_info = await self._test_setup_scene( controller, "/TestGraph", "TestNode_omni_graph_nodes_BooleanAnd", "omni.graph.nodes.BooleanAnd", test_run, test_info, 16, ) await controller.evaluate(test_info.graph) _test_verify_scene( self, controller, test_run, test_info, f"omni.graph.nodes.BooleanAnd User test case #{i+1}", 16 ) TEST_DATA_OR = [ { "inputs": [ ["inputs:a", {"type": "bool", "value": False}, False], ["inputs:b", {"type": "bool", "value": True}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "bool", "value": False}, False], ["inputs:d", {"type": "bool", "value": True}, False], ], "outputs": [ ["outputs:result", True, False], ], }, { "inputs": [ ["inputs:a", {"type": "bool[]", "value": [False, False, True, True]}, False], ["inputs:b", {"type": "bool[]", "value": [False, True, False, True]}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "bool", "value": False}, False], ["inputs:d", {"type": "bool", "value": True}, False], ], "outputs": [ ["outputs:result", {"type": "bool[]", "value": [True, True, True, True]}, False], ], }, { "inputs": [ ["inputs:a", {"type": "bool", "value": False}, False], ["inputs:b", {"type": "bool[]", "value": [False, True]}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "bool", "value": False}, False], ["inputs:d", {"type": "bool", "value": True}, False], ], "outputs": [ ["outputs:result", [True, True], False], ], }, { "inputs": [ ["inputs:a", {"type": "bool[]", "value": [False, True]}, False], ["inputs:b", {"type": "bool", "value": False}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "bool", "value": False}, False], ["inputs:d", {"type": "bool[]", "value": [False, True]}, False], ], "outputs": [ ["outputs:result", [False, True], False], ], }, { "inputs": [ ["inputs:a", {"type": "bool[]", "value": [False, True]}, False], ["inputs:b", {"type": "bool", "value": False}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "bool", "value": False}, False], ["inputs:d", {"type": "bool[]", "value": [False, True]}, False], ], "outputs": [ ["outputs:result", {"type": "bool[]", "value": [False, True]}, False], ], }, ] async def test_boolean_or(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA_OR): await _test_clear_scene(self, test_run) test_info = await self._test_setup_scene( controller, "/TestGraph", "TestNode_omni_graph_nodes_BooleanOr", "omni.graph.nodes.BooleanOr", test_run, test_info, ) await controller.evaluate(test_info.graph) _test_verify_scene( self, controller, test_run, test_info, f"omni.graph.nodes.BooleanOr User test case #{i+1}" ) async def test_boolean_or_vectorized(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA_OR): await _test_clear_scene(self, test_run) test_info = await self._test_setup_scene( controller, "/TestGraph", "TestNode_omni_graph_nodes_BooleanOr", "omni.graph.nodes.BooleanOr", test_run, test_info, 16, ) await controller.evaluate(test_info.graph) _test_verify_scene( self, controller, test_run, test_info, f"omni.graph.nodes.BooleanOr User test case #{i+1}", 16 ) TEST_DATA_NAND = [ { "inputs": [ ["inputs:a", {"type": "bool", "value": False}, False], ["inputs:b", {"type": "bool", "value": True}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "bool", "value": False}, False], ["inputs:d", {"type": "bool", "value": True}, False], ], "outputs": [ ["outputs:result", True, False], ], }, { "inputs": [ ["inputs:a", {"type": "bool[]", "value": [False, False, True, True]}, False], ["inputs:b", {"type": "bool[]", "value": [False, True, False, True]}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "bool[]", "value": [False, False, True, True]}, False], ["inputs:d", {"type": "bool[]", "value": [False, True, False, True]}, False], ], "outputs": [ ["outputs:result", [True, True, True, False], False], ], }, { "inputs": [ ["inputs:a", {"type": "bool", "value": False}, False], ["inputs:b", {"type": "bool[]", "value": [False, True]}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "bool", "value": False}, False], ["inputs:d", {"type": "bool[]", "value": [False, True]}, False], ], "outputs": [ ["outputs:result", [True, True], False], ], }, { "inputs": [ ["inputs:a", {"type": "bool", "value": False}, False], ["inputs:b", {"type": "bool[]", "value": [False, True]}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "bool[]", "value": [False, True]}, False], ["inputs:d", {"type": "bool", "value": False}, False], ], "outputs": [ ["outputs:result", [True, True], False], ], }, { "inputs": [ ["inputs:a", {"type": "bool[]", "value": [False, True]}, False], ["inputs:b", {"type": "bool", "value": True}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "bool[]", "value": [False, True]}, False], ["inputs:d", {"type": "bool[]", "value": [False, True]}, False], ], "outputs": [ ["outputs:result", [True, False], False], ], }, ] async def test_boolean_nand(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA_NAND): await _test_clear_scene(self, test_run) test_info = await self._test_setup_scene( controller, "/TestGraph", "TestNode_omni_graph_nodes_BooleanNand", "omni.graph.nodes.BooleanNand", test_run, test_info, ) await controller.evaluate(test_info.graph) _test_verify_scene( self, controller, test_run, test_info, f"omni.graph.nodes.BooleanNand User test case #{i+1}" ) async def test_boolean_nand_vectorized(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA_NAND): await _test_clear_scene(self, test_run) test_info = await self._test_setup_scene( controller, "/TestGraph", "TestNode_omni_graph_nodes_BooleanNand", "omni.graph.nodes.BooleanNand", test_run, test_info, 16, ) await controller.evaluate(test_info.graph) _test_verify_scene( self, controller, test_run, test_info, f"omni.graph.nodes.BooleanNand User test case #{i+1}", 16 ) TEST_DATA_NOR = [ { "inputs": [ ["inputs:a", {"type": "bool", "value": False}, False], ["inputs:b", {"type": "bool", "value": True}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "bool", "value": False}, False], ["inputs:d", {"type": "bool", "value": True}, False], ], "outputs": [ ["outputs:result", False, False], ], }, { "inputs": [ ["inputs:a", {"type": "bool", "value": False}, False], ["inputs:b", {"type": "bool", "value": False}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "bool", "value": False}, False], ], "outputs": [ ["outputs:result", True, False], ], }, { "inputs": [ ["inputs:a", {"type": "bool[]", "value": [False, False, True, True]}, False], ["inputs:b", {"type": "bool[]", "value": [False, True, False, True]}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "bool[]", "value": [False, False, True, True]}, False], ["inputs:d", {"type": "bool[]", "value": [False, True, False, True]}, False], ], "outputs": [ ["outputs:result", [True, False, False, False], False], ], }, { "inputs": [ ["inputs:a", {"type": "bool[]", "value": [False, False, True, True]}, False], ["inputs:b", {"type": "bool[]", "value": [False, True, False, True]}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "bool[]", "value": [False, True, False, True]}, False], ["inputs:d", {"type": "bool[]", "value": [False, False, True, True]}, False], ], "outputs": [ ["outputs:result", [True, False, False, False], False], ], }, { "inputs": [ ["inputs:a", {"type": "bool", "value": False}, False], ["inputs:b", {"type": "bool[]", "value": [False, True]}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "bool", "value": False}, False], ["inputs:d", {"type": "bool[]", "value": [False, True]}, False], ], "outputs": [ ["outputs:result", [True, False], False], ], }, { "inputs": [ ["inputs:a", {"type": "bool[]", "value": [False, True]}, False], ["inputs:b", {"type": "bool", "value": False}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "bool[]", "value": [False, True]}, False], ["inputs:d", {"type": "bool", "value": False}, False], ], "outputs": [ ["outputs:result", [True, False], False], ], }, ] async def test_boolean_nor(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA_NOR): await _test_clear_scene(self, test_run) test_info = await self._test_setup_scene( controller, "/TestGraph", "TestNode_omni_graph_nodes_BooleanNor", "omni.graph.nodes.BooleanNor", test_run, test_info, ) await controller.evaluate(test_info.graph) _test_verify_scene( self, controller, test_run, test_info, f"omni.graph.nodes.BooleanNor User test case #{i+1}" ) async def test_boolean_nor_vectorized(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA_NOR): await _test_clear_scene(self, test_run) test_info = await self._test_setup_scene( controller, "/TestGraph", "TestNode_omni_graph_nodes_BooleanNor", "omni.graph.nodes.BooleanNor", test_run, test_info, 16, ) await controller.evaluate(test_info.graph) _test_verify_scene( self, controller, test_run, test_info, f"omni.graph.nodes.BooleanNor User test case #{i+1}", 16 ) TEST_DATA_APPEND_STRING = [ { "inputs": [ ["inputs:a", {"type": "token", "value": "/"}, False], ["inputs:b", {"type": "token", "value": "foo"}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "token", "value": "/"}, False], ["inputs:d", {"type": "token", "value": "bar"}, False], ], "outputs": [ ["outputs:value", {"type": "token", "value": "/foo/bar"}, False], ], }, { "inputs": [ ["inputs:a", {"type": "token[]", "value": ["/World", "/World2"]}, False], ["inputs:b", {"type": "token", "value": "/foo"}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "token", "value": "/"}, False], ["inputs:d", {"type": "token", "value": "bar"}, False], ], "outputs": [ ["outputs:value", {"type": "token[]", "value": ["/World/foo/bar", "/World2/foo/bar"]}, False], ], }, { "inputs": [ ["inputs:a", {"type": "token[]", "value": ["/World", "/World2"]}, False], ["inputs:b", {"type": "token[]", "value": ["/foo", "/bar"]}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "token[]", "value": ["/", "baz"]}, False], ["inputs:d", {"type": "token[]", "value": ["/", "biz"]}, False], ], "outputs": [ ["outputs:value", {"type": "token[]", "value": ["/World/foo//", "/World2/barbazbiz"]}, False], ], }, { "inputs": [ ["inputs:a", {"type": "string", "value": "/"}, False], ["inputs:b", {"type": "string", "value": "foo"}, False], ], "dynamicInputs": [ ["inputs:c", {"type": "string", "value": "/"}, False], ["inputs:d", {"type": "string", "value": "bar"}, False], ], "outputs": [ ["outputs:value", {"type": "string", "value": "/foo/bar"}, False], ], }, ] async def test_append_string(self): test_info = _TestGraphAndNode() controller = og.Controller() for i, test_run in enumerate(self.TEST_DATA_APPEND_STRING): await _test_clear_scene(self, test_run) test_info = await self._test_setup_scene( controller, "/TestGraph", "AppendString", "omni.graph.nodes.BuildString", test_run, test_info ) await controller.evaluate(test_info.graph) _test_verify_scene( self, controller, test_run, test_info, f"omni.graph.nodes.BuildString User test case #{i+1}" )
50,042
Python
40.187654
134
0.430878
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_nodes.py
# noqa: PLC0302 """Misc collection of tests for nodes in this extension""" import math import os from functools import partial from math import isnan from typing import Callable, Set import carb import carb.settings import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.commands import omni.kit.stage_templates import omni.kit.test import omni.timeline import omni.usd import usdrt from omni.graph.core import ThreadsafetyTestUtils from pxr import Gf, OmniGraphSchemaTools, Sdf, Usd, UsdGeom, UsdShade # ====================================================================== class TestNodes(ogts.OmniGraphTestCase): """Unit tests nodes in this extension""" PERSISTENT_SETTINGS_PREFIX = "/persistent" TEST_GRAPH_PATH = "/World/TestGraph" async def setUp(self): """Set up test environment, to be torn down when done""" await super().setUp() # Ensure that Xform prims are created with the full set of xformOp attributes with consistent behavior. settings = carb.settings.get_settings() settings.set(self.PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/PrimCreationWithDefaultXformOps", True) settings.set( self.PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpType", "Scale, Rotate, Translate" ) settings.set(self.PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultRotationOrder", "XYZ") settings.set( self.PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpOrder", "xformOp:translate, xformOp:rotate, xformOp:scale", ) settings.set(self.PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpPrecision", "Double") # ---------------------------------------------------------------------- async def test_getprimrelationship(self): """Test GetPrimRelationship node""" usd_context = omni.usd.get_context() stage = usd_context.get_stage() controller = og.Controller() keys = og.Controller.Keys (graph, (get_node,), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: ("Get", "omni.graph.nodes.GetPrimRelationship"), keys.CREATE_PRIMS: [("RelHolder", {}), ("TestPrimA", {}), ("TestPrimB", {})], keys.SET_VALUES: [("Get.inputs:name", "test_rel"), ("Get.inputs:usePath", False)], }, ) await controller.evaluate(graph) prim = stage.GetPrimAtPath("/RelHolder") rel = prim.CreateRelationship("test_rel") for prim_path in ("/TestPrimA", "/TestPrimB"): omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target=Sdf.Path(prim_path)) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Get.inputs:prim"), target=prim.GetPath(), ) await controller.evaluate(graph) rel_paths = og.Controller.get(controller.attribute("outputs:paths", get_node)) self.assertEqual(rel_paths, rel.GetTargets()) controller.edit( self.TEST_GRAPH_PATH, {keys.SET_VALUES: [("Get.inputs:path", "/RelHolder"), ("Get.inputs:usePath", True)]}, ) await controller.evaluate(graph) rel_paths = og.Controller.get(controller.attribute("outputs:paths", get_node)) self.assertEqual(rel_paths, rel.GetTargets()) # ---------------------------------------------------------------------- @ThreadsafetyTestUtils.make_threading_test def test_get_prim_path(self, test_instance_id: int = 0): """Test GetPrimPath node""" usd_context = omni.usd.get_context() stage = usd_context.get_stage() graph_path = self.TEST_GRAPH_PATH + str(test_instance_id) prim_path = "/World/TestPrim" ThreadsafetyTestUtils.add_to_threading_cache(test_instance_id, stage.DefinePrim(prim_path)) controller = og.Controller() keys = og.Controller.Keys (_, (get_node,), _, _) = controller.edit( graph_path, {keys.CREATE_NODES: ("GetPrimPath", "omni.graph.nodes.GetPrimPath")}, ) rel = stage.GetPropertyAtPath(f"{graph_path}/GetPrimPath.inputs:prim") omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target=prim_path) yield ThreadsafetyTestUtils.EVALUATION_ALL_GRAPHS rel_paths = og.Controller.get(controller.attribute("outputs:primPath", get_node)) self.assertEqual(rel_paths, prim_path) ThreadsafetyTestUtils.single_evaluation_last_test_instance( test_instance_id, lambda: stage.RemovePrim(prim_path) ) # ---------------------------------------------------------------------- @ThreadsafetyTestUtils.make_threading_test def test_get_prim_paths(self, test_instance_id: int = 0): """Test GetPrimPaths node""" usd_context = omni.usd.get_context() stage = usd_context.get_stage() graph_path = self.TEST_GRAPH_PATH + str(test_instance_id) prim_paths = ["/World/TestPrim1", "/World/TestPrim2"] ThreadsafetyTestUtils.add_to_threading_cache(test_instance_id, stage.DefinePrim(prim_paths[0])) ThreadsafetyTestUtils.add_to_threading_cache(test_instance_id, stage.DefinePrim(prim_paths[1])) controller = og.Controller() keys = og.Controller.Keys (_, (get_node,), _, _) = controller.edit( graph_path, {keys.CREATE_NODES: ("GetPrimPaths", "omni.graph.nodes.GetPrimPaths")}, ) rel = stage.GetPropertyAtPath(f"{graph_path}/GetPrimPaths.inputs:prims") omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target=prim_paths[0]) omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target=prim_paths[1]) yield ThreadsafetyTestUtils.EVALUATION_ALL_GRAPHS rel_paths = og.Controller.get(controller.attribute("outputs:primPaths", get_node)) self.assertEqual(rel_paths, prim_paths) ThreadsafetyTestUtils.single_evaluation_last_test_instance( test_instance_id, lambda: stage.RemovePrim(prim_paths[0]) ) ThreadsafetyTestUtils.single_evaluation_last_test_instance( test_instance_id, lambda: stage.RemovePrim(prim_paths[1]) ) # ---------------------------------------------------------------------- @ThreadsafetyTestUtils.make_threading_test def test_get_prims_at_path(self, test_instance_id: int = 0): """Test GetPrimAtPath node""" graph_path = self.TEST_GRAPH_PATH + str(test_instance_id) controller = og.Controller() prim_path = "/World/foo/bar" keys = og.Controller.Keys (_, (get_prim_at_path, get_prims_at_path, _, _), _, _) = controller.edit( graph_path, { keys.CREATE_NODES: [ ("GetPrimAtPath", "omni.graph.nodes.GetPrimsAtPath"), ("GetPrimsAtPath", "omni.graph.nodes.GetPrimsAtPath"), ("MakeArray", "omni.graph.nodes.ConstructArray"), ("ConstToken", "omni.graph.nodes.ConstantToken"), ], keys.CONNECT: [ ("ConstToken.inputs:value", "GetPrimAtPath.inputs:path"), ("MakeArray.outputs:array", "GetPrimsAtPath.inputs:path"), ], keys.SET_VALUES: [ ("MakeArray.inputs:arraySize", 3), ("MakeArray.inputs:arrayType", "token[]"), ("MakeArray.inputs:input0", prim_path), ("ConstToken.inputs:value", prim_path), ], }, ) yield ThreadsafetyTestUtils.EVALUATION_ALL_GRAPHS out_path = og.Controller.get(controller.attribute("outputs:prims", get_prim_at_path)) self.assertEqual(out_path, [usdrt.Sdf.Path(prim_path)]) out_paths = og.Controller.get(controller.attribute("outputs:prims", get_prims_at_path)) self.assertEqual(out_paths, [usdrt.Sdf.Path(prim_path)] * 3) # ---------------------------------------------------------------------- @ThreadsafetyTestUtils.make_threading_test def test_constant_prims(self, test_instance_id: int = 0): """Test ConstantPrims node""" usd_context = omni.usd.get_context() stage = usd_context.get_stage() graph_path = self.TEST_GRAPH_PATH + str(test_instance_id) prim_paths = ["/World/TestPrim1", "/World/TestPrim2"] for prim_path in prim_paths: ThreadsafetyTestUtils.add_to_threading_cache(test_instance_id, stage.DefinePrim(prim_path)) controller = og.Controller() keys = og.Controller.Keys (_, (_const_prims, prim_paths_node), _, _) = controller.edit( graph_path, { keys.CREATE_NODES: [ ("ConstantPrims", "omni.graph.nodes.ConstantPrims"), ("GetPrimPath", "omni.graph.nodes.GetPrimPaths"), ], keys.CONNECT: [("ConstantPrims.inputs:value", "GetPrimPath.inputs:prims")], }, ) rel = stage.GetPropertyAtPath(f"{graph_path}/ConstantPrims.inputs:value") for prim_path in prim_paths: omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target=prim_path) yield ThreadsafetyTestUtils.EVALUATION_ALL_GRAPHS out_paths = og.Controller.get(controller.attribute("outputs:primPaths", prim_paths_node)) self.assertEqual(out_paths, prim_paths) for prim_path in prim_paths: ThreadsafetyTestUtils.single_evaluation_last_test_instance( test_instance_id, partial(stage.RemovePrim, prim_path) ) # ---------------------------------------------------------------------- async def test_constant_prims_loads_from_file(self): """ Validation that connections are maintained when loading a graph from a file which uses ConstantPrims - which uses a target input attribute as its output """ await ogts.load_test_file("TestConstantPrims.usda", use_caller_subdirectory=True) self.assertTrue(og.Controller.graph("/World/PushGraph").is_valid()) self.assertTrue(og.Controller.node("/World/PushGraph/constant_prims").is_valid()) self.assertTrue(og.Controller.node("/World/PushGraph/get_prim_paths").is_valid()) attr_dst = og.Controller.attribute("/World/PushGraph/get_prim_paths.inputs:prims") attr_src = og.Controller.attribute("/World/PushGraph/constant_prims.inputs:value") self.assertTrue(attr_dst.is_valid()) self.assertTrue(attr_src.is_valid()) self.assertTrue(attr_dst.is_connected(attr_src)) self.assertEqual(attr_dst.get_upstream_connection_count(), 1) self.assertEqual(attr_dst.get_upstream_connections()[0].get_path(), attr_src.get_path()) actual_result = og.Controller.get(attr_dst) expected_result = [usdrt.Sdf.Path("/Environment"), usdrt.Sdf.Path("/Environment/defaultLight")] self.assertEqual(expected_result, actual_result) # ---------------------------------------------------------------------- @ThreadsafetyTestUtils.make_threading_test def test_get_parent_prims(self, test_instance_id: int = 0): """Test ConstantPrims node""" usd_context = omni.usd.get_context() stage = usd_context.get_stage() graph_path = self.TEST_GRAPH_PATH + str(test_instance_id) prim_paths = ["/World/Test", "/World/Test/Test"] prim_parents = ["/World", "/World/Test"] for prim_path in prim_paths: ThreadsafetyTestUtils.add_to_threading_cache(test_instance_id, stage.DefinePrim(prim_path)) controller = og.Controller() keys = og.Controller.Keys (_, (get_parent_prims,), _, _) = controller.edit( graph_path, {keys.CREATE_NODES: ("GetParentPrims", "omni.graph.nodes.GetParentPrims")} ) rel = stage.GetPropertyAtPath(f"{graph_path}/GetParentPrims.inputs:prims") for prim_path in prim_paths: omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target=prim_path) yield ThreadsafetyTestUtils.EVALUATION_ALL_GRAPHS out_paths = og.Controller.get(controller.attribute("outputs:parentPrims", get_parent_prims)) self.assertEqual(out_paths, [usdrt.Sdf.Path(p) for p in prim_parents]) for prim_path in prim_paths: ThreadsafetyTestUtils.single_evaluation_last_test_instance( test_instance_id, partial(stage.RemovePrim, prim_path) ) # ---------------------------------------------------------------------- async def test_prim_relationship_load(self): """Test that a prim relationship when loading does not create OgnPrim node""" async def do_test(): await ogts.load_test_file("TestPrimRelationshipLoad.usda", use_caller_subdirectory=True) # Cube and Capsule are driving Sphere, Cylinder, Cone by various methods usd_context = omni.usd.get_context() stage = usd_context.get_stage() graph = og.get_graph_by_path("/World/PushGraph") controller = og.Controller() nodes = graph.get_nodes() node_paths = [n.get_prim_path() for n in nodes] # These prims are only connected by relationship, so should not show up in OG self.assertNotIn("/World/Cube", node_paths) self.assertNotIn("/World/Sphere", node_paths) self.assertNotIn("/World/Cylinder", node_paths) self.assertNotIn("/World/Cone", node_paths) # Sanity check that the rotate connections are working for p in ("Sphere", "Capsule", "Cylinder", "Cone"): rotate_xyz = stage.GetPrimAtPath("/World/" + p).GetAttribute("xformOp:rotateXYZ").Get() self.assertEqual(rotate_xyz[0], 0) self.assertEqual(rotate_xyz[1], 0) stage.GetPrimAtPath("/World/Cube").GetAttribute("xformOp:rotateXYZ").Set((100, 0, 0)) stage.GetPrimAtPath("/World/Capsule").GetAttribute("xformOp:rotateXYZ").Set((100, 0, 0)) await controller.evaluate(graph) for p in ("Sphere", "Cylinder", "Cone"): rotate_xyz = stage.GetPrimAtPath("/World/" + p).GetAttribute("xformOp:rotateXYZ").Get() if p == "Cone": # /World/Cone is not loaded into Flatcache, so we expect this part of the # graph to be non-functional (Cone will not change) self.assertEqual(rotate_xyz[0], 0) self.assertEqual(rotate_xyz[1], 0) await do_test() # ---------------------------------------------------------------------- @staticmethod def _get_expected_read_prims_property_names(prim) -> Set[str]: properties = set(prim.GetAuthoredPropertyNames()) properties.update({"worldMatrix", "sourcePrimPath", "sourcePrimType"}) return properties # ---------------------------------------------------------------------- @staticmethod def _get_expected_read_prims_v2_property_names(prim) -> Set[str]: properties = set(prim.GetPropertyNames()) properties.remove("proxyPrim") # remove "proxyPrim" which is skipped unless it has targets properties.update({"worldMatrix", "sourcePrimPath", "sourcePrimType"}) return properties # ---------------------------------------------------------------------- async def test_read_prims_write_prim(self): """Test omni.graph.nodes.ReadPrims and WritePrim""" await self._read_prims_write_prim( "omni.graph.nodes.ReadPrims", False, compute_expected_property_names=self._get_expected_read_prims_property_names, ) # ---------------------------------------------------------------------- async def test_read_prims_write_prim_with_target(self): await self._read_prims_write_prim( "omni.graph.nodes.ReadPrims", True, compute_expected_property_names=self._get_expected_read_prims_property_names, ) # ---------------------------------------------------------------------- async def test_read_prims_v2_write_prim(self): """Test omni.graph.nodes.ReadPrimsV2 and WritePrim""" await self._read_prims_write_prim( "omni.graph.nodes.ReadPrimsV2", False, compute_expected_property_names=self._get_expected_read_prims_v2_property_names, ) # ---------------------------------------------------------------------- async def test_read_prims_v2_write_prim_with_target(self): await self._read_prims_write_prim( "omni.graph.nodes.ReadPrimsV2", True, compute_expected_property_names=self._get_expected_read_prims_v2_property_names, ) # ---------------------------------------------------------------------- async def test_read_prims_bundle_write_prim(self): """Test omni.graph.nodes.ReadPrimsBundle and WritePrim""" await self._read_prims_write_prim( "omni.graph.nodes.ReadPrimsBundle", False, compute_expected_property_names=self._get_expected_read_prims_property_names, ) # ---------------------------------------------------------------------- async def test_read_prims_bundle_write_prim_with_target(self): await self._read_prims_write_prim( "omni.graph.nodes.ReadPrimsBundle", True, compute_expected_property_names=self._get_expected_read_prims_property_names, ) # ---------------------------------------------------------------------- async def _read_prims_write_prim( self, read_prims_type, use_target_inputs, compute_expected_property_names: Callable ): """ use_target_inputs will use the prim target input for the ExtractPrim nodes rather than the prim path input """ usd_context = omni.usd.get_context() stage = usd_context.get_stage() controller = og.Controller() keys = og.Controller.Keys cube_prim = ogts.create_cube(stage, "Cube", (1, 1, 1)) (graph, (read_node, write_node, _, _, extract_bundle_node), _, _,) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Read", read_prims_type), ("Write", "omni.graph.nodes.WritePrim"), ("Add", "omni.graph.nodes.Add"), ("ExtractPrim", "omni.graph.nodes.ExtractPrim"), ("ExtractBundle", "omni.graph.nodes.ExtractBundle"), ], keys.SET_VALUES: [ ("ExtractPrim.inputs:primPath", "/Cube"), ], keys.CONNECT: [ ("Read.outputs_primsBundle", "ExtractPrim.inputs:prims"), ("ExtractPrim.outputs_primBundle", "ExtractBundle.inputs:bundle"), ], }, ) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"), target=cube_prim.GetPath(), ) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Write.inputs:prim"), target=cube_prim.GetPath(), ) await controller.evaluate(graph) if use_target_inputs: omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetRelationshipAtPath(f"{self.TEST_GRAPH_PATH}/ExtractPrim.inputs:prim"), target=cube_prim.GetPath(), ) await controller.evaluate(graph) factory = og.IBundleFactory.create() # Check MPiB output for Read bundle = graph.get_default_graph_context().get_output_bundle(read_node, "outputs_primsBundle") output_bundle2 = factory.get_bundle(graph.get_default_graph_context(), bundle) self.assertEqual(output_bundle2.get_child_bundle_count(), 1) # Attribute Count: # 2 - node: type, typeVersion, # 3 - inputs: bundle # 2 - outputs: passThrough, n_static_attribs_extract_bundle = 4 # Attribute Count: # 2 - node: type, typeVersion, # 3 - inputs: prim, execIn, usdWriteBack # 1 - outputs: execOut, n_static_attribs_write = 6 extract_bundle_name = "outputs_passThrough" attribs = extract_bundle_node.get_attributes() found_size_attrib = False for attrib in attribs: if attrib.get_name() == "outputs:size" and attrib.get_resolved_type().base_type == og.BaseDataType.DOUBLE: found_size_attrib = True self.assertTrue(found_size_attrib) expected_property_names = compute_expected_property_names(cube_prim) bundle = graph.get_default_graph_context().get_output_bundle(extract_bundle_node, extract_bundle_name) attribute_names = set(bundle.get_attribute_names()) self.assertEqual(attribute_names, expected_property_names) # Check we have the expected bundle attributes self.assertIn("size", attribute_names) self.assertIn("sourcePrimPath", attribute_names) self.assertIn("sourcePrimType", attribute_names) self.assertIn("worldMatrix", attribute_names) self.assertIn("primvars:displayColor", attribute_names) attribute_datas = bundle.get_attribute_data(False) self.assertEqual( next((a for a in attribute_datas if a.get_name() == "sourcePrimPath")).get(), cube_prim.GetPath().pathString, ) # Check we have the expected dynamic attrib on WritePrim attribs = write_node.get_attributes() found_size_attrib = False for attrib in attribs: if attrib.get_name() == "inputs:size" and attrib.get_resolved_type().base_type == og.BaseDataType.DOUBLE: found_size_attrib = True self.assertTrue(found_size_attrib) # check that evaluations propagate in a read/write cycle as expected controller.edit( self.TEST_GRAPH_PATH, { keys.CONNECT: [ ("ExtractBundle.outputs:size", "Add.inputs:a"), ("ExtractBundle.outputs:size", "Add.inputs:b"), ("Add.outputs:sum", "Write.inputs:size"), ] }, ) await controller.evaluate(graph) attr = controller.attribute("outputs:size", extract_bundle_node) # it is now 2 on prim, but read node as not been executed after the write, so still has the old value self.assertEqual(og.Controller.get(attr), 1) await controller.evaluate(graph) # now it is 4 on the prim, and /Read as 2 self.assertEqual(og.Controller.get(attr), 2) await controller.evaluate(graph) # now it is 8 on the prim, and /Read as 4 self.assertEqual(og.Controller.get(attr), 4) # ReadPrim: Clear the inputs:prim attribute to trigger a reset of the ReadPrim node omni.kit.commands.execute( "RemoveRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prims"), target=cube_prim.GetPath(), ) await controller.evaluate(graph) # Verify that the stale dynamic and bundle attributes have been removed attribs = extract_bundle_node.get_attributes() self.assertEqual(len(attribs), n_static_attribs_extract_bundle) bundle = graph.get_default_graph_context().get_output_bundle(extract_bundle_node, extract_bundle_name) self.assertEqual(bundle.get_attribute_data_count(), 0) # WritePrim: Clear the inputs:prim attribute to trigger a reset of the WritePrim node omni.kit.commands.execute( "RemoveRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/Write.inputs:prim"), target=cube_prim.GetPath(), ) await controller.evaluate(graph) # Verify that the stale dynamic and bundle attributes have been removed attribs = write_node.get_attributes() self.assertEqual(len(attribs), n_static_attribs_write) # Set it up again and re-verify things work omni.kit.undo.undo() # Undo remove target from Write Prim # Following step is to undo disconnected and removed dynamic attributes inside of Extract Bundle. # When Extract Bundle's input change or recompute is called, we record omni.kit.undo.undo() # Call to undo dynamic attribute removal and disconnection on read prim (compute) omni.kit.undo.undo() # Call to undo dynamic attribute removal and disconnection on read prim (compute) omni.kit.undo.undo() # Call to undo dynamic attribute removal and disconnection on read prim into bundle (compute) omni.kit.undo.undo() # Call to undo dynamic attribute removal and disconnection on read prim into bundle (compute) await controller.evaluate(graph) # Check if MPiB is back to the output of ReadPrimIntoBundle bundle = graph.get_default_graph_context().get_output_bundle(read_node, "outputs_primsBundle") output_bundle2 = factory.get_bundle(graph.get_default_graph_context(), bundle) self.assertEqual(output_bundle2.get_child_bundle_count(), 1) # Verify we have the size attribute back and our bundle attribs attribs = write_node.get_attributes() found_size_attrib = False for attrib in attribs: if attrib.get_name() == "inputs:size" and attrib.get_resolved_type().base_type == og.BaseDataType.DOUBLE: found_size_attrib = True self.assertTrue(found_size_attrib) # Check output bundle attributes of ExtractBundle bundle = graph.get_default_graph_context().get_output_bundle(extract_bundle_node, extract_bundle_name) attribute_datas = bundle.get_attribute_data(False) attribute_names = [a.get_name() for a in attribute_datas] self.assertIn("size", attribute_names) self.assertIn("sourcePrimPath", attribute_names) self.assertIn("worldMatrix", attribute_names) self.assertIn("primvars:displayColor", attribute_names) attribs = extract_bundle_node.get_attributes() self.assertEqual(len(attribs) - n_static_attribs_extract_bundle, len(attribute_datas)) # Reset the underlying prim attrib value and check the plumbing is still working cube_prim.GetAttribute("size").Set(1) await controller.evaluate(graph) attr = controller.attribute("outputs:size", extract_bundle_node) self.assertEqual(og.Controller.get(attr), 1) await controller.evaluate(graph) self.assertEqual(og.Controller.get(attr), 2) await controller.evaluate(graph) self.assertEqual(og.Controller.get(attr), 4) # ---------------------------------------------------------------------- async def test_findprims(self): """Test omni.graph.nodes.FindPrims corner cases""" usd_context = omni.usd.get_context() stage = usd_context.get_stage() controller = og.Controller() keys = og.Controller.Keys cube_prim = ogts.create_cube(stage, "Cube1", (1, 1, 1)) cube_prim2 = ogts.create_cube(stage, "Cube2", (1, 1, 1)) cube_prim3 = ogts.create_cube(stage, "Cube3", (1, 1, 1)) cube_prim3.CreateRelationship("test_rel").AddTarget(cube_prim.GetPrimPath()) (graph, (read_node,), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: ("FindPrims", "omni.graph.nodes.FindPrims"), keys.SET_VALUES: ("FindPrims.inputs:namePrefix", "Cube"), }, ) await controller.evaluate(graph) paths_attr = controller.attribute("outputs:primPaths", read_node) paths = og.Controller.get(paths_attr) self.assertListEqual(paths, [p.GetPrimPath() for p in (cube_prim, cube_prim2, cube_prim3)]) # set cube to inactive and verify it doesn't show up in the list cube_prim.SetActive(False) await controller.evaluate(graph) paths = og.Controller.get(paths_attr) self.assertListEqual(paths, [p.GetPrimPath() for p in (cube_prim2, cube_prim3)]) # Test the relationship requirement works controller.edit( self.TEST_GRAPH_PATH, { keys.SET_VALUES: [ ("FindPrims.inputs:requiredRelationship", "test_rel"), # Not the right target ("FindPrims.inputs:requiredRelationshipTarget", cube_prim2.GetPrimPath().pathString), ] }, ) await controller.evaluate(graph) paths = og.Controller.get(paths_attr) self.assertTrue(len(paths) == 0) controller.edit( self.TEST_GRAPH_PATH, { keys.SET_VALUES: [ # The right target ("FindPrims.inputs:requiredRelationshipTarget", cube_prim.GetPrimPath().pathString), ] }, ) await controller.evaluate(graph) paths = og.Controller.get(paths_attr) self.assertListEqual(paths, [p.GetPrimPath() for p in (cube_prim3,)]) # ---------------------------------------------------------------------- async def test_findprims_path_pattern(self): usd_context = omni.usd.get_context() stage = usd_context.get_stage() ogts.create_cube(stage, "Cube1", (1, 1, 1)) ogts.create_cube(stage, "Cube2", (1, 1, 1)) ogts.create_cube(stage, "Cube3", (1, 1, 1)) ogts.create_cube(stage, "Cube44", (1, 1, 1)) ogts.create_cube(stage, "AnotherCube1", (1, 1, 1)) ogts.create_cube(stage, "AnotherCube2", (1, 1, 1)) ogts.create_cube(stage, "AnotherCube3", (1, 1, 1)) controller = og.Controller() keys = og.Controller.Keys (graph, (find_prims,), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: ("FindPrims", "omni.graph.nodes.FindPrims"), keys.SET_VALUES: [ ("FindPrims.inputs:recursive", True), ("FindPrims.inputs:pathPattern", "/Cube?"), ], }, ) await controller.evaluate(graph) outputs_prim_paths = find_prims.get_attribute("outputs:primPaths") value = outputs_prim_paths.get() self.assertEqual(len(value), 3) # Cube1, Cube2, Cube3 but not Cube44 self.assertTrue(all(item in ["/Cube1", "/Cube2", "/Cube3"] for item in value)) (graph, _, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.SET_VALUES: ("FindPrims.inputs:pathPattern", "/*Cube?"), }, ) await controller.evaluate(graph) value = outputs_prim_paths.get() self.assertEqual(len(value), 6) # AnotherCube1,2,3 and Cube1,2,3, but not Cube44 required_cubes = ["/Cube1", "/Cube2", "/Cube3", "/AnotherCube1", "/AnotherCube2", "/AnotherCube3"] self.assertTrue(all(item in required_cubes for item in value)) # get all /Cube?, but exclude /Cube2 (graph, _, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.SET_VALUES: ("FindPrims.inputs:pathPattern", "/Cube? ^/Cube2"), }, ) await controller.evaluate(graph) value = outputs_prim_paths.get() self.assertEqual(len(value), 2) # Cube1,3, but not Cube2 required_cubes = ["/Cube1", "/Cube3"] self.assertTrue(all(item in required_cubes for item in value)) # get all /Cube? but exclude /Cube1 and /Cube2 (graph, _, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.SET_VALUES: ("FindPrims.inputs:pathPattern", "/Cube? ^/Cube1 ^/Cube2"), }, ) await controller.evaluate(graph) value = outputs_prim_paths.get() self.assertEqual(len(value), 1) # Cube3, but not Cube1,2 required_cubes = ["/Cube3"] self.assertTrue(all(item in required_cubes for item in value)) # get all Cubes, but exclude all cubes that end with single digit (graph, _, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.SET_VALUES: ("FindPrims.inputs:pathPattern", "*Cube* ^*Cube?"), }, ) await controller.evaluate(graph) value = outputs_prim_paths.get() self.assertEqual(len(value), 1) # only Cube44 required_cubes = ["/Cube44"] self.assertTrue(all(item in required_cubes for item in value)) # get all Cubes, and exclude all cubes to produce empty set (graph, _, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.SET_VALUES: ("FindPrims.inputs:pathPattern", "*Cube* ^*Cube*"), }, ) await controller.evaluate(graph) value = outputs_prim_paths.get() self.assertEqual(len(value), 0) # ---------------------------------------------------------------------- async def test_getprims_path_pattern(self): """Test the path pattern matching feature of the GetPrims node.""" usd_context = omni.usd.get_context() stage = usd_context.get_stage() controller = og.Controller() keys = og.Controller.Keys (graph, (_, get_prims_node), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("ReadPrimsBundle", "omni.graph.nodes.ReadPrimsBundle"), ("GetPrims", "omni.graph.nodes.GetPrims"), ], keys.CONNECT: [("ReadPrimsBundle.outputs_primsBundle", "GetPrims.inputs:bundle")], }, ) cube_paths = {"/Cube1", "/Cube2", "/Cube3", "/Cube44", "/AnotherCube1", "/AnotherCube2", "/AnotherCube3"} for cube_path in cube_paths: cube_name = cube_path.split("/")[-1] ogts.create_cube(stage, cube_name, (1, 1, 1)) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/ReadPrimsBundle.inputs:prims"), target=cube_path, ) await controller.evaluate(graph) # Dictionary from each path pattern to its expected prim paths path_pattern_dict = { "*": cube_paths, "": set(), "/Cube?": {"/Cube1", "/Cube2", "/Cube3"}, "/*Cube?": {"/Cube1", "/Cube2", "/Cube3", "/AnotherCube1", "/AnotherCube2", "/AnotherCube3"}, "/* ^/Another*": {"/Cube1", "/Cube2", "/Cube3", "/Cube44"}, } bundle_factory = og.IBundleFactory.create() bundle = graph.get_default_graph_context().get_output_bundle(get_prims_node, "outputs_bundle") output_bundle2 = bundle_factory.get_bundle(graph.get_default_graph_context(), bundle) for path_pattern, expected_prim_paths in path_pattern_dict.items(): # Test path patterns with the "inverse" option off (by default) (graph, _, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.SET_VALUES: [ ("GetPrims.inputs:pathPattern", path_pattern), ("GetPrims.inputs:inverse", False), ] }, ) await controller.evaluate(graph) child_bundle_paths = set() child_bundle_count = output_bundle2.get_child_bundle_count() for i in range(child_bundle_count): child_bundle = output_bundle2.get_child_bundle(i) attr = child_bundle.get_attribute_by_name("sourcePrimPath") child_bundle_paths.add(attr.get()) self.assertEqual(child_bundle_paths, expected_prim_paths) # Test path patterns with the "inverse" option on (graph, _, _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.SET_VALUES: [ ("GetPrims.inputs:inverse", True), ] }, ) await controller.evaluate(graph) child_bundle_paths = set() child_bundle_count = output_bundle2.get_child_bundle_count() for i in range(child_bundle_count): child_bundle = output_bundle2.get_child_bundle(i) attr = child_bundle.get_attribute_by_name("sourcePrimPath") child_bundle_paths.add(attr.get()) self.assertEqual(child_bundle_paths, cube_paths.difference(expected_prim_paths)) # ---------------------------------------------------------------------- async def test_readtime(self): """Test omni.graph.nodes.ReadTime""" app = omni.kit.app.get_app() timeline = omni.timeline.get_timeline_interface() time_node_name = "Time" # setup initial timeline state and avoid possibility that running this test twice will give different results timeline.set_fast_mode(True) fps = 24.0 timeline.set_time_codes_per_second(fps) timeline.set_start_time(-1.0) timeline.set_end_time(0.0) timeline.set_current_time(0.0) await app.next_update_async() keys = og.Controller.Keys (_, (time_node,), _, _) = og.Controller.edit( self.TEST_GRAPH_PATH, {keys.CREATE_NODES: [(time_node_name, "omni.graph.nodes.ReadTime")]} ) await app.next_update_async() await og.Controller.evaluate() self.assertGreater(og.Controller(og.Controller.attribute("outputs:deltaSeconds", time_node)).get(), 0.0) self.assertGreater(og.Controller(og.Controller.attribute("outputs:timeSinceStart", time_node)).get(), 0.0) self.assertFalse(og.Controller(og.Controller.attribute("outputs:isPlaying", time_node)).get()) self.assertEqual(og.Controller(og.Controller.attribute("outputs:time", time_node)).get(), 0.0) self.assertEqual(og.Controller(og.Controller.attribute("outputs:frame", time_node)).get(), 0.0) timeline.set_start_time(1.0) timeline.set_end_time(10.0) timeline.play() await app.next_update_async() await app.next_update_async() await og.Controller.evaluate() # graph has been reloaded as a result of the fps change: we need re refetch the node time_node = og.get_node_by_path(self.TEST_GRAPH_PATH + "/" + time_node_name) self.assertTrue(og.Controller(og.Controller.attribute("outputs:isPlaying", time_node)).get()) animation_time = og.Controller(og.Controller.attribute("outputs:time", time_node)).get() self.assertGreater(animation_time, 0.0) self.assertAlmostEqual( og.Controller(og.Controller.attribute("outputs:frame", time_node)).get(), fps * animation_time, places=2 ) timeline.stop() await app.next_update_async() # ---------------------------------------------------------------------- async def test_read_and_write_prim_material(self): await self._read_and_write_prim_material(False) async def test_read_and_write_prim_material_with_target(self): await self._read_and_write_prim_material(True) async def _read_and_write_prim_material(self, use_target_inputs): """ Test ReadPrimMaterial and WritePrimMaterial node. If use_target_inputs is true, use the prim target input rather than the prim path input """ usd_context = omni.usd.get_context() stage = usd_context.get_stage() controller = og.Controller() keys = og.Controller.Keys mat_path = "/TestMaterial" prim_path_a = "/TestPrimA" prim_path_b = "/TestPrimB" (graph, (read_node, _), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Read", "omni.graph.nodes.ReadPrimMaterial"), ("Write", "omni.graph.nodes.WritePrimMaterial"), ], keys.CREATE_PRIMS: [(mat_path, "Material"), (prim_path_a, "Cube"), (prim_path_b, "Cube")], keys.SET_VALUES: [ ("Read.inputs:primPath", prim_path_a), ("Write.inputs:primPath", prim_path_b), ("Write.inputs:materialPath", mat_path), ], }, ) await controller.evaluate(graph) if use_target_inputs: omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetRelationshipAtPath(f"{self.TEST_GRAPH_PATH}/Read.inputs:prim"), target=prim_path_a, ) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetRelationshipAtPath(f"{self.TEST_GRAPH_PATH}/Write.inputs:prim"), target=prim_path_b, ) omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetRelationshipAtPath(f"{self.TEST_GRAPH_PATH}/Write.inputs:material"), target=mat_path, ) await controller.evaluate(graph) prim_a = stage.GetPrimAtPath(prim_path_a) rel_a = prim_a.CreateRelationship("material:binding") omni.kit.commands.execute("AddRelationshipTarget", relationship=rel_a, target=Sdf.Path(mat_path)) await controller.evaluate(graph) read_output = og.Controller.get(controller.attribute("outputs:material", read_node)) self.assertEqual(read_output, mat_path) prim_b = stage.GetPrimAtPath(prim_path_b) mat_b, _ = UsdShade.MaterialBindingAPI(prim_b).ComputeBoundMaterial() write_output = mat_b.GetPath().pathString self.assertEqual(write_output, mat_path) # ---------------------------------------------------------------------- async def test_read_prim_material_with_target_connections(self): """Test ReadPrimMaterial and WritePrimMaterial node""" usd_context = omni.usd.get_context() stage = usd_context.get_stage() controller = og.Controller() keys = og.Controller.Keys mat_path = "/TestMaterial" prim_path_a = "/TestPrimA" (graph, (_, _, prim_node, _), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Read", "omni.graph.nodes.ReadPrimMaterial"), ("GetPrimAtPath", "omni.graph.nodes.GetPrimsAtPath"), ("GetPrimPath", "omni.graph.nodes.GetPrimPath"), ("ConstToken", "omni.graph.nodes.ConstantToken"), ], keys.CREATE_PRIMS: [(mat_path, "Material"), (prim_path_a, "Cube")], keys.SET_VALUES: [("ConstToken.inputs:value", prim_path_a)], keys.CONNECT: [ ("Read.outputs:materialPrim", "GetPrimPath.inputs:prim"), ("GetPrimAtPath.outputs:prims", "Read.inputs:prim"), ("ConstToken.inputs:value", "GetPrimAtPath.inputs:path"), ], }, ) prim_a = stage.GetPrimAtPath(prim_path_a) rel_a = prim_a.CreateRelationship("material:binding") omni.kit.commands.execute("AddRelationshipTarget", relationship=rel_a, target=Sdf.Path(mat_path)) await controller.evaluate(graph) mat_output = og.Controller.get(("outputs:primPath", prim_node)) self.assertEqual(mat_output, mat_path) # ---------------------------------------------------------------------- async def test_read_and_write_settings(self): """Test ReadSetting and WriteSetting node""" controller = og.Controller() keys = og.Controller.Keys settings = carb.settings.get_settings() setting_path = self.PERSISTENT_SETTINGS_PREFIX + "/omnigraph/deprecationsAreErrors" default_value = settings.get(setting_path) sample_value = not default_value (graph, (read_node, _, _), _, _) = og.Controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Read", "omni.graph.nodes.ReadSetting"), ("Write", "omni.graph.nodes.WriteSetting"), ("ConstBool", "omni.graph.nodes.ConstantBool"), ], keys.CONNECT: [("ConstBool.inputs:value", "Write.inputs:value")], keys.SET_VALUES: [ ("Read.inputs:settingPath", setting_path), ("Write.inputs:settingPath", setting_path), ("ConstBool.inputs:value", sample_value), ], }, ) await controller.evaluate(graph) await omni.kit.app.get_app().next_update_async() output_value = og.Controller.get(controller.attribute("outputs:value", read_node)) self.assertEqual(output_value, sample_value) settings.set(setting_path, default_value) # ---------------------------------------------------------------------- async def test_get_look_at_rotation(self): """Test GetLookAtRotation node""" usd_context = omni.usd.get_context() stage = usd_context.get_stage() # Get the scene up-vector. stage_up_axis = stage.GetMetadata("upAxis") if stage_up_axis.lower() == "x": up_vec = Gf.Vec3d.XAxis() fwd_vec = -Gf.Vec3d.ZAxis() right_vec = -Gf.Vec3d.YAxis() is_y_up = False elif stage_up_axis.lower() == "z": up_vec = Gf.Vec3d.ZAxis() fwd_vec = -Gf.Vec3d.XAxis() right_vec = Gf.Vec3d.YAxis() is_y_up = False else: up_vec = Gf.Vec3d.YAxis() fwd_vec = -Gf.Vec3d.ZAxis() right_vec = Gf.Vec3d.XAxis() is_y_up = True # Create a prim driven by a GetLookAtRotation node to always face its fwd_vec toward # the origin. distance_from_origin = 750.0 # It's important that the up component be non-zero as that creates a difference between the local and # and world up-vectors, which is where problems can occur. up_offset = 100.0 position = up_vec * up_offset - fwd_vec * distance_from_origin xform_path = "/World/xform" controller = og.Controller() keys = og.Controller.Keys (graph, (lookat_node, *_), (xform_prim, *_), _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("lookat", "omni.graph.nodes.GetLookAtRotation"), ("write", "omni.graph.nodes.WritePrimAttribute"), ], keys.CREATE_PRIMS: [(xform_path, "Xform")], keys.CONNECT: [("lookat.outputs:rotateXYZ", "write.inputs:value")], keys.SET_VALUES: [ ("lookat.inputs:forward", fwd_vec), ("lookat.inputs:start", position), ("write.inputs:name", "xformOp:rotateXYZ"), ("write.inputs:primPath", xform_path), ("write.inputs:usePath", True), ], }, ) await controller.evaluate(graph) start_attr = lookat_node.get_attribute("inputs:start") fwd_attr = lookat_node.get_attribute("inputs:forward") up_attr = lookat_node.get_attribute("inputs:up") for _ in range(2): # Move the transform in a circle around the origin, keeping the up component constant. for angle in range(0, 360, 45): rad = math.radians(angle) position = right_vec * math.sin(rad) * distance_from_origin position -= fwd_vec * math.cos(rad) * distance_from_origin position += up_vec * up_offset start_attr.set(position) await controller.evaluate(graph) # Get the normalized vector from the current position to the origin. pos_vec = -Gf.Vec3d(position).GetNormalized() # The forward vector in world space should match the position vector. cache = UsdGeom.XformCache() xform = cache.GetLocalToWorldTransform(xform_prim) ws_fwd = xform.TransformDir(fwd_vec).GetNormalized() diff = Gf.Rotation(pos_vec, ws_fwd).GetAngle() self.assertAlmostEqual( diff, 0.0, msg=f"at {angle} degree position, forward vector does not point at origin." ) # The local and world up-vectors should remain within 8 degrees of each other. ws_up = xform.TransformDir(up_vec).GetNormalized() diff = Gf.Rotation(up_vec, ws_up).GetAngle() self.assertLess(abs(diff), 8.0, f"at {angle} degree position, up-vector has drifted too far") # The first pass used scene-up. # For the second pass we set an explicit up-vector, different from scene-up. if is_y_up: up_vec = Gf.Vec3d.ZAxis() fwd_vec = -Gf.Vec3d.XAxis() right_vec = Gf.Vec3d.YAxis() else: up_vec = Gf.Vec3d.YAxis() fwd_vec = -Gf.Vec3d.ZAxis() right_vec = Gf.Vec3d.XAxis() fwd_attr.set(fwd_vec) up_attr.set(up_vec) async def test_selection_nodes(self): """Test ReadStageSelection, IsPrimSelected nodes""" usd_context = omni.usd.get_context() stage = usd_context.get_stage() controller = og.Controller() keys = og.Controller.Keys (graph, (read_node, check_node, check_target), _, _) = og.Controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Read", "omni.graph.nodes.ReadStageSelection"), ("IsSelected", "omni.graph.nodes.IsPrimSelected"), ("IsSelectedWithTarget", "omni.graph.nodes.IsPrimSelected"), ], keys.SET_VALUES: [("IsSelected.inputs:primPath", f"{self.TEST_GRAPH_PATH}/Read")], }, ) await controller.evaluate(graph) rel = stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/IsSelectedWithTarget.inputs:prim") omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target=f"{self.TEST_GRAPH_PATH}/Read") selection = usd_context.get_selection() self.assertFalse(og.Controller.get(controller.attribute("outputs:isSelected", check_node))) self.assertFalse(og.Controller.get(controller.attribute("outputs:isSelected", check_target))) selection.set_selected_prim_paths( [read_node.get_prim_path()], False, ) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() selected_paths = og.Controller.get(controller.attribute("outputs:selectedPrims", read_node)) self.assertListEqual(selected_paths, selection.get_selected_prim_paths()) self.assertTrue(og.Controller.get(controller.attribute("outputs:isSelected", check_node))) self.assertTrue(og.Controller.get(controller.attribute("outputs:isSelected", check_target))) selection.clear_selected_prim_paths() await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() selected_paths = og.Controller.get(controller.attribute("outputs:selectedPrims", read_node)) self.assertListEqual(selected_paths, selection.get_selected_prim_paths()) self.assertFalse(og.Controller.get(controller.attribute("outputs:isSelected", check_node))) self.assertFalse(og.Controller.get(controller.attribute("outputs:isSelected", check_target))) # ---------------------------------------------------------------------- async def test_parallel_read_write_prim_attribute(self): """Attempt to read and write prim attributes in parallel""" # ReadIndex -> Multiply # / \ # 10 ------x--------> MakeTranslate -> WriteTranslate # / # ReadTranslate -> BreakTranslate -yz- keys = og.Controller.Keys index_name = "testIndex" attr_name = "xformOp:translate" scale = 10 cubes = [] for i in range(64): graph_name = f"/graph{i}" obj_name = f"/obj{i}" controller = og.Controller() (graph, _, prims, _) = controller.edit( graph_name, { keys.CREATE_NODES: [ ("ReadIndex", "omni.graph.nodes.ReadPrimAttribute"), ("ReadTranslate", "omni.graph.nodes.ReadPrimAttribute"), ("BreakTranslate", "omni.graph.nodes.BreakVector3"), ("Multiply", "omni.graph.nodes.Multiply"), ("MakeTranslate", "omni.graph.nodes.MakeVector3"), ("WriteTranslate", "omni.graph.nodes.WritePrimAttribute"), ], keys.CREATE_PRIMS: [ (obj_name, "Cube"), ], }, ) # we want to test parallel execution: prevent any merging graph.set_auto_instancing_allowed(False) attr = prims[0].CreateAttribute(index_name, Sdf.ValueTypeNames.Double) attr.Set(i) cubes.append(prims[0]) controller.edit( graph_name, { keys.SET_VALUES: [ ("ReadIndex.inputs:name", index_name), ("ReadIndex.inputs:usePath", True), ("ReadIndex.inputs:primPath", obj_name), ("ReadTranslate.inputs:name", attr_name), ("ReadTranslate.inputs:usePath", True), ("ReadTranslate.inputs:primPath", obj_name), ("WriteTranslate.inputs:name", attr_name), ("WriteTranslate.inputs:usePath", True), ("WriteTranslate.inputs:primPath", obj_name), ("Multiply.inputs:b", scale, "double"), ], }, ) controller.edit( graph_name, { keys.CONNECT: [ ("ReadIndex.outputs:value", "Multiply.inputs:a"), ("ReadTranslate.outputs:value", "BreakTranslate.inputs:tuple"), ("Multiply.outputs:product", "MakeTranslate.inputs:x"), ("BreakTranslate.outputs:y", "MakeTranslate.inputs:y"), ("BreakTranslate.outputs:z", "MakeTranslate.inputs:z"), ("MakeTranslate.outputs:tuple", "WriteTranslate.inputs:value"), ], }, ) # cubes[0].GetStage().Export("c:/tmp/test.usda") for cube in cubes: translate = cube.GetAttribute(attr_name).Get() self.assertEqual(translate[0], 0) await og.Controller.evaluate() for cube in cubes: index = cube.GetAttribute(index_name).Get() translate = cube.GetAttribute(attr_name).Get() self.assertEqual(translate[0], index * scale) # ---------------------------------------------------------------------- async def test_read_prim_node_default_time_code_upgrades(self): """ Tests that read prim node variants property upgrade their time code property to use NAN as a default """ app = omni.kit.app.get_app() nodes = [ "ReadPrim", "ReadPrims", "ReadPrimAttribute", "ReadPrimAttributes", "ReadPrimBundle", "ReadPrimsBundle", ] # testing under different frame rates to validate the upgrade is correctly detected frame_rates = [12, 24, 30, 60] for frame_rate in frame_rates: with self.subTest(frame_rate=frame_rate): timeline = omni.timeline.get_timeline_interface() timeline.set_time_codes_per_second(frame_rate) await app.next_update_async() file_path = os.path.join(os.path.dirname(__file__), "data", "TestReadPrimNodeVariants.usda") stage = omni.usd.get_context().get_stage() # create a prim and add a file reference prim = stage.DefinePrim("/Ref") # when we make the references, there will be deprecation warnings prim.GetReferences().AddReference(file_path) self.assertEqual(stage.GetTimeCodesPerSecond(), frame_rate) await omni.kit.app.get_app().next_update_async() for node in nodes: attr = og.Controller.attribute(f"/Ref/ActionGraph/{node}.inputs:usdTimecode") self.assertTrue(isnan(attr.get())) await omni.usd.get_context().new_stage_async() # ---------------------------------------------------------------------- async def test_is_prim_active(self): usd_context = omni.usd.get_context() stage = usd_context.get_stage() contents = Usd.Stage.CreateInMemory("payload.usd") contents.DefinePrim("/payload/A", "Xform") payload = stage.DefinePrim("/payload", "Xform") payload.GetPayloads().AddPayload(Sdf.Payload(contents.GetRootLayer().identifier, "/payload")) keys = og.Controller.Keys controller = og.Controller() (graph, (node,), _, _) = controller.edit( "/TestGraph", { keys.CREATE_NODES: [("IsActive", "omni.graph.nodes.IsPrimActive")], }, ) await controller.evaluate(graph) rel = stage.GetRelationshipAtPath("/TestGraph/IsActive.inputs:primTarget") omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/payload/A") await controller.evaluate(graph) out = node.get_attribute("outputs:active") self.assertEqual(out.get(), True) # Note: currently the node will raise an error if the prim isn't in the stage as well as set active to false payload.Unload() with ogts.ExpectedError(): await controller.evaluate(graph) out = node.get_attribute("outputs:active") self.assertEqual(out.get(), False) # ------------------------------------------------------------------------------- async def test_get_graph_target_prim(self): """Test that the GetGraphTargetPrim node outputs the expected graph target prim""" usd_context = omni.usd.get_context() stage = usd_context.get_stage() controller = og.Controller() keys = og.Controller.Keys (graph, (_graph_target_node, path_node), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("GetGraphTargetPrim", "omni.graph.nodes.GetGraphTargetPrim"), ("GetPrimPath", "omni.graph.nodes.GetPrimPath"), ], keys.CONNECT: [("GetGraphTargetPrim.outputs:prim", "GetPrimPath.inputs:prim")], }, ) # no instances, it should return the graph prim await og.Controller.evaluate(graph) self.assertEqual(self.TEST_GRAPH_PATH, path_node.get_attribute("outputs:primPath").get()) num_instances = 5 # create instances for i in range(0, num_instances): prim_name = f"/World/Prim_{i}" stage.DefinePrim(prim_name) OmniGraphSchemaTools.applyOmniGraphAPI(stage, prim_name, self.TEST_GRAPH_PATH) # rerun the graph, this time evaluating instances await og.Controller.evaluate(graph) for i in range(0, num_instances): self.assertEqual(f"/World/Prim_{i}", path_node.get_attribute("outputs:primPath").get(instance=i)) async def test_construct_array_invalid_array_size(self): """Test that setting an invalid value on OgnConstructArray.arraySize does not crash""" # Ideally this would be done with the following test in the .ogn file, but the node parser # applies the minimum / maximum attribute limits when parsing the tests, which means that # we cannot define tests for invalid inputs in the .ogn file # { # "inputs:arraySize": -1, "inputs:arrayType": "Int64", # "outputs:array": {"type": "int64[]", "value": []} # } controller = og.Controller() keys = og.Controller.Keys (graph, nodes, _, _,) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [("ConstructArray", "omni.graph.nodes.ConstructArray")], keys.SET_VALUES: [ ("ConstructArray.inputs:arraySize", -1), ("ConstructArray.inputs:arrayType", "int[]"), ], }, ) # Evaluate the graph once to ensure the node has a Database created await controller.evaluate(graph) result = nodes[0].get_attribute("outputs:array").get() expected: [int] = [] self.assertListEqual(expected, list(result)) async def test_get_prim_local_to_world_empty(self): """Regression test for GetPrimLocalToWorldTransform""" controller = og.Controller() keys = og.Controller.Keys (graph, _, _, _,) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [("TestWorld", "omni.graph.nodes.GetPrimLocalToWorldTransform")], keys.SET_VALUES: [ ("TestWorld.inputs:usePath", False), ], }, ) with ogts.ExpectedError(): await controller.evaluate(graph)
63,239
Python
43.162011
123
0.568178
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_find_prims_node.py
import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.test class TestFindPrimsNode(ogts.OmniGraphTestCase): """Unit tests for Find Prims node in this extension""" # ---------------------------------------------------------------------- async def test_find_prims_node_type_attribute_v1(self): """First version of Find Prims node did not use pattern matching. Attribute 'type' needs to be automatically updated to support pattern matching. """ # load the test scene which contains a ReadPrim V1 node (result, error) = await ogts.load_test_file("TestFindPrimsNode_v1.usda", use_caller_subdirectory=True) self.assertTrue(result, error) test_graph_path = "/World/TestGraph" test_graph = og.get_graph_by_path(test_graph_path) find_prims_empty = test_graph.get_node(test_graph_path + "/find_prims_empty") self.assertTrue(find_prims_empty.is_valid()) find_prims_types = test_graph.get_node(test_graph_path + "/find_prims_types") self.assertTrue(find_prims_types.is_valid()) self.assertEqual(find_prims_empty.get_attribute("inputs:type").get(), "*") self.assertEqual(find_prims_types.get_attribute("inputs:type").get(), "Mesh") # ---------------------------------------------------------------------- async def test_add_target_input(self): """ Test target input type and that path input is still used if target prim has not been selected """ keys = og.Controller.Keys controller = og.Controller() (graph, (node,), _, _) = controller.edit( "/TestGraph", { keys.CREATE_NODES: [("FindPrims", "omni.graph.nodes.FindPrims")], keys.CREATE_PRIMS: [ ("/World/A", "Xform"), ("/World/B", "Xform"), ("/World/A/Cone", "Cone"), ("/World/B/Cone", "Cone"), ("/World/B/Cube", "Cube"), ("/World/B/Sphere", "Sphere"), ], keys.SET_VALUES: [("FindPrims.inputs:rootPrimPath", "/World/A")], }, ) # If no target input is specified, fallback to path input await controller.evaluate(graph) out = node.get_attribute("outputs:primPaths") self.assertEqual(out.get(), ["/World/A/Cone"]) usd_context = omni.usd.get_context() stage = usd_context.get_stage() rel = stage.GetRelationshipAtPath("/TestGraph/FindPrims.inputs:rootPrim") omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/B") await controller.evaluate(graph) out = node.get_attribute("outputs:primPaths") self.assertEqual(out.get(), ["/World/B/Cone", "/World/B/Cube", "/World/B/Sphere"]) # Test with a required relationship cone = stage.GetPrimAtPath("/World/B/Cone") cube = stage.GetPrimAtPath("/World/B/Cube") omni.kit.commands.execute( "AddRelationshipTarget", relationship=cone.CreateRelationship("test_rel"), target="/World/A" ) omni.kit.commands.execute( "AddRelationshipTarget", relationship=cube.CreateRelationship("test_rel"), target="/World/B" ) rel_attr = node.get_attribute("inputs:requiredRelationship") rel_attr.set("test_rel") rel = stage.GetRelationshipAtPath("/TestGraph/FindPrims.inputs:requiredTarget") omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/B") await controller.evaluate(graph) self.assertEqual(out.get(), ["/World/B/Cube"])
3,708
Python
44.231707
116
0.587109
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_api.py
"""Testing the stability of the API in this module""" import omni.graph.core.tests as ogts import omni.graph.nodes as ognd from omni.graph.tools.tests.internal_utils import _check_module_api_consistency, _check_public_api_contents # ====================================================================== class _TestOmniGraphNodesApi(ogts.OmniGraphTestCase): _UNPUBLISHED = ["bindings", "ogn", "tests"] async def test_api(self): _check_module_api_consistency(ognd, self._UNPUBLISHED) # noqa: PLW0212 _check_module_api_consistency( # noqa: PLW0212 ognd.tests, ["create_prim_with_everything", "bundle_test_utils"], is_test_module=True ) async def test_api_features(self): """Test that the known public API features continue to exist""" _check_public_api_contents(ognd, [], self._UNPUBLISHED, only_expected_allowed=True) # noqa: PLW0212 _check_public_api_contents( # noqa: PLW0212 ognd.tests, [ "BundleInspectorResults_t", "BundleResultKeys", "bundle_inspector_results", "enable_debugging", "filter_bundle_inspector_results", "get_bundle_with_all_results", "prim_with_everything_definition", "verify_bundles_are_equal", ], [], only_expected_allowed=False, )
1,430
Python
39.885713
108
0.576224
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_auto_conv_on_load.py
"""Test the node that inspects attribute bundles""" import omni.graph.core as og ogts = og.tests # ====================================================================== class TestConversion(ogts.test_case_class()): """Run simple unit tests that exercises auto conversion of attribute""" # ---------------------------------------------------------------------- async def test_auto_conv_on_load(self): # This file contains a graph which has a chain of nodes connected through extented attributes # The begining of this chain forces type resolution to double, but a float is required at the end of the chain # The test makes sure that the type is correctly resolved/restored on this final attribute (result, error) = await ogts.load_test_file("TestConversionOnLoad.usda", use_caller_subdirectory=True) self.assertTrue(result, f"{error}") await og.Controller.evaluate() easing_node = og.Controller.node("/World/PushGraph/easing_function") attr = og.Controller.attribute("inputs:alpha", easing_node) attr_type = attr.get_resolved_type() self.assertTrue(attr_type.base_type == og.BaseDataType.FLOAT)
1,195
Python
43.296295
118
0.620084
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_prim_relationship_nodes.py
import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.commands import omni.kit.test from pxr import OmniGraphSchemaTools # ====================================================================== class TestPrimRelationshipNodes(ogts.OmniGraphTestCase): """Tests read and write prim relationship nodes""" TEST_GRAPH_PATH = "/World/TestGraph" # ---------------------------------------------------------------------- async def test_read_prim_relationships(self): """Test the read prim relationship nodes that use the new target input/output types""" usd_context = omni.usd.get_context() stage = usd_context.get_stage() controller = og.Controller() keys = og.Controller.Keys # For the instanced test, setup a graph like this so that each graph instance looks at the material on a # different cube # # read_var -> to_token -> build_string -> find_prims -> read_prim_relationship (graph, (read, read_test_rel, _, _, _, _), (cone,), _,) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Read", "omni.graph.nodes.ReadPrimRelationship"), ("ReadTestRel", "omni.graph.nodes.ReadPrimRelationship"), ("ReadVar", "omni.graph.core.ReadVariable"), ("ToToken", "omni.graph.nodes.ToToken"), ("BuildString", "omni.graph.nodes.BuildString"), ("FindPrims", "omni.graph.nodes.FindPrims"), ], keys.CREATE_PRIMS: [ ("/World/Cone", "Cone"), ], keys.SET_VALUES: [ ("Read.inputs:name", "material:binding"), ("ReadTestRel.inputs:name", "test_rel"), ("BuildString.inputs:a", "Cube_", og.Type(og.BaseDataType.TOKEN)), ("ReadVar.inputs:variableName", "suffix"), ("FindPrims.inputs:recursive", True), ], keys.CONNECT: [ ("ReadVar.outputs:value", "ToToken.inputs:value"), ("ToToken.outputs:converted", "BuildString.inputs:b"), ("BuildString.outputs:value", "FindPrims.inputs:namePrefix"), ("FindPrims.outputs:prims", "Read.inputs:prim"), ], }, ) await og.Controller.evaluate(graph) var = graph.create_variable("suffix", og.Type(og.BaseDataType.INT)) # Assign materials for instanced example num_instances = 3 for i in range(0, num_instances): prim = stage.DefinePrim(f"/World/Cube_{i}", "Cube") mat = stage.DefinePrim(f"/World/Material_{i}", "Material") omni.kit.commands.execute( "AddRelationshipTarget", relationship=prim.CreateRelationship("material:binding"), target=mat.GetPath() ) # Setup example with more than one relationship target rel = cone.CreateRelationship("test_rel") omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(f"{self.TEST_GRAPH_PATH}/ReadTestRel.inputs:prim"), target=cone.GetPath(), ) omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/Material_0") omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/Cube_0") await controller.evaluate(graph) # verify that this works without instancing self.assertEqual(read.get_attribute("outputs:value").get(), ["/World/Material_0"]) self.assertEqual(read_test_rel.get_attribute("outputs:value").get(), ["/World/Material_0", "/World/Cube_0"]) # create instances for i in range(0, num_instances): prim_name = f"/World/Instance_{i}" stage.DefinePrim(prim_name) OmniGraphSchemaTools.applyOmniGraphAPI(stage, prim_name, self.TEST_GRAPH_PATH) await og.Controller.evaluate(graph) for i in range(0, num_instances): var.set(graph.get_default_graph_context(), value=i, instance_path=f"/World/Instance_{i}") await og.Controller.evaluate(graph) # rerun the graph, this time evaluating instances for i in range(0, num_instances): self.assertEqual(read.get_attribute("outputs:value").get(instance=i), [f"/World/Material_{i}"]) # ---------------------------------------------------------------------- async def test_basic_write_prim_relationships(self): """Basic test of write prim relationship node""" usd_context = omni.usd.get_context() stage = usd_context.get_stage() controller = og.Controller() keys = og.Controller.Keys # To deterministically schedule write-read operation nodes are split # into separate graphs: write and read. # That gives control over scheduling writing before reading. write_graph_path = "/World/TestGraphWrite" read_graph_path = "/World/TestGraphRead" (write_graph, (write,), (cone, cube), _,) = controller.edit( write_graph_path, { keys.CREATE_NODES: [ ("Write", "omni.graph.nodes.WritePrimRelationship"), ], keys.CREATE_PRIMS: [ ("/World/Cone", "Cone"), ("/World/Cube", "Cube"), ], keys.SET_VALUES: [ ("Write.inputs:name", "test_rel"), ("Write.inputs:usdWriteBack", False), ], }, ) (read_graph, (read,), _, _,) = controller.edit( read_graph_path, { keys.CREATE_NODES: [ ("Read", "omni.graph.nodes.ReadPrimRelationship"), ], keys.SET_VALUES: [ ("Read.inputs:name", "test_rel"), ], }, ) # Setup Write rel = stage.GetPropertyAtPath(f"{write_graph_path}/Write.inputs:prim") omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target=cone.GetPath()) rel = stage.GetPropertyAtPath(f"{write_graph_path}/Write.inputs:value") omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target=cube.GetPath()) # Setup Read rel = stage.GetPropertyAtPath(f"{read_graph_path}/Read.inputs:prim") omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target=cone.GetPath()) # Evaluate write, then read await og.Controller.evaluate(write_graph) await og.Controller.evaluate(read_graph) out = read.get_attribute("outputs:value") self.assertEqual(out.get(), ["/World/Cube"]) # usd write back is false, so this should fail self.assertEqual(cone.HasRelationship("test_rel"), False) # verify usd write back write.get_attribute("inputs:usdWriteBack").set(True) await og.Controller.evaluate(write_graph) await og.Controller.evaluate(read_graph) self.assertEqual(cone.HasRelationship("test_rel"), True) # test that relationship is cleared if value is empty rel = stage.GetPropertyAtPath(f"{write_graph_path}/Write.inputs:value") omni.kit.commands.execute("RemoveRelationshipTarget", relationship=rel, target=cube.GetPath()) await og.Controller.evaluate(write_graph) await og.Controller.evaluate(read_graph) self.assertEqual(out.get(), []) # ---------------------------------------------------------------------- async def test_write_prim_relationships_with_instancing(self): """Test the write prim relationship nodes wth instancing""" usd_context = omni.usd.get_context() stage = usd_context.get_stage() controller = og.Controller() keys = og.Controller.Keys (graph, (write, read, _, _, _, _, _, _), _, _,) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Write", "omni.graph.nodes.WritePrimRelationship"), ("Read", "omni.graph.nodes.ReadPrimRelationship"), ("ReadVar", "omni.graph.core.ReadVariable"), ("ToToken", "omni.graph.nodes.ToToken"), ("BuildStringCone", "omni.graph.nodes.BuildString"), ("BuildStringCube", "omni.graph.nodes.BuildString"), ("FindPrimsCone", "omni.graph.nodes.FindPrims"), ("FindPrimsCube", "omni.graph.nodes.FindPrims"), ], keys.SET_VALUES: [ ("Write.inputs:name", "test_rel"), ("Write.inputs:usdWriteBack", False), ("Read.inputs:name", "test_rel"), ("BuildStringCone.inputs:a", "Cone_", og.Type(og.BaseDataType.TOKEN)), ("BuildStringCube.inputs:a", "Cube_", og.Type(og.BaseDataType.TOKEN)), ("ReadVar.inputs:variableName", "suffix"), ("FindPrimsCone.inputs:recursive", True), ("FindPrimsCube.inputs:recursive", True), ], keys.CONNECT: [ ("ReadVar.outputs:value", "ToToken.inputs:value"), ("ToToken.outputs:converted", "BuildStringCone.inputs:b"), ("ToToken.outputs:converted", "BuildStringCube.inputs:b"), ("BuildStringCone.outputs:value", "FindPrimsCone.inputs:namePrefix"), ("BuildStringCube.outputs:value", "FindPrimsCube.inputs:namePrefix"), ("FindPrimsCone.outputs:prims", "Write.inputs:prim"), ("FindPrimsCube.outputs:prims", "Write.inputs:value"), ("FindPrimsCone.outputs:prims", "Read.inputs:prim"), ], }, ) await og.Controller.evaluate(graph) var = graph.create_variable("suffix", og.Type(og.BaseDataType.INT)) # create targets for instanced example num_instances = 3 for i in range(0, num_instances): stage.DefinePrim(f"/World/Cone_{i}", "Cone") stage.DefinePrim(f"/World/Cube_{i}", "Cube") await og.Controller.evaluate(graph) # Setting the name input to something else and then back again is needed to trigger the prefetch of the prim # correctly. See OM-93232 for more details. Once we get to the bottom of what's going on there, this should be # removed. I'm not entirely sure why this workaround is also not needed in test_basic_write_prim_relationships. # And the issue also doesn't happen when this code is run in Kit GUI via the script editor. read.get_attribute("inputs:name").set("foo") await og.Controller.evaluate(graph) read.get_attribute("inputs:name").set("test_rel") await og.Controller.evaluate(graph) # test without instancing... self.assertEqual(read.get_attribute("outputs:value").get(), ["/World/Cube_0"]) # usd write back is false, so this should fail cone = stage.GetPrimAtPath("/World/Cone_0") self.assertEqual(cone.HasRelationship("test_rel"), False) # verify usd write back write.get_attribute("inputs:usdWriteBack").set(True) await og.Controller.evaluate(graph) self.assertEqual(cone.HasRelationship("test_rel"), True) # create instances for i in range(0, num_instances): prim_name = f"/World/Instance_{i}" stage.DefinePrim(prim_name) OmniGraphSchemaTools.applyOmniGraphAPI(stage, prim_name, self.TEST_GRAPH_PATH) await og.Controller.evaluate(graph) for i in range(0, num_instances): var.set(graph.get_default_graph_context(), value=i, instance_path=f"/World/Instance_{i}") await og.Controller.evaluate(graph) # Workaround. See OM-93232 read.get_attribute("inputs:name").set("foo") await og.Controller.evaluate(graph) read.get_attribute("inputs:name").set("test_rel") await og.Controller.evaluate(graph) # rerun the graph, this time evaluating instances for i in range(0, num_instances): self.assertEqual(read.get_attribute("outputs:value").get(instance=i), [f"/World/Cube_{i}"])
12,576
Python
44.734545
119
0.569418
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/__init__.py
""" Explicitly import the test utilities that will be part of the public interface This way you can do things like: import omni.graph.nodes.tests as ognt new_prim = ognt.bundle_inspector_output() """ from .bundle_test_utils import ( BundleInspectorResults_t, BundleResultKeys, bundle_inspector_results, enable_debugging, filter_bundle_inspector_results, get_bundle_with_all_results, prim_with_everything_definition, verify_bundles_are_equal, ) __all__ = [ "BundleInspectorResults_t", "BundleResultKeys", "bundle_inspector_results", "enable_debugging", "filter_bundle_inspector_results", "get_bundle_with_all_results", "prim_with_everything_definition", "verify_bundles_are_equal", ] scan_for_test_modules = True """The presence of this object causes the test runner to automatically scan the directory for unit test cases"""
900
Python
27.156249
112
0.716667
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_nodes_with_prim_connection.py
import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.commands import omni.kit.stage_templates import omni.kit.test import omni.timeline import omni.usd from pxr import Gf, Sdf, UsdGeom # ====================================================================== class TestNodesWithPrimConnection(ogts.OmniGraphTestCase): """Tests node using a target connection to a prim""" TEST_GRAPH_PATH = "/World/TestGraph" # ----------------------------------------------------------------------------------- async def setUp(self): await super().setUp() omni.timeline.get_timeline_interface().set_start_time(1.0) omni.timeline.get_timeline_interface().set_end_time(100000) omni.timeline.get_timeline_interface().set_play_every_frame(True) # ----------------------------------------------------------------------------------- async def tearDown(self): omni.timeline.get_timeline_interface().stop() omni.timeline.get_timeline_interface().set_play_every_frame(False) await super().tearDown() # ----------------------------------------------------------------------------------- async def test_read_prim_attribute_with_connected_prims(self): """ Tests that ReadPrimAttributes nodes works correctly with their prim attribute is connected using a target attribute port """ node = "omni.graph.nodes.ReadPrimAttribute" usd_context = omni.usd.get_context() stage = usd_context.get_stage() controller = og.Controller() keys = og.Controller.Keys (graph, (read_prim, _, _), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("ReadNode", node), ("GetPrimAtPath", "omni.graph.nodes.GetPrimsAtPath"), ("ConstToken", "omni.graph.nodes.ConstantToken"), ], keys.CONNECT: [("ConstToken.inputs:value", "GetPrimAtPath.inputs:path")], keys.CREATE_PRIMS: [ ("/World/Cube1", {"dummy_prop": ("float", 1)}, "Cube"), ("/World/Cube2", {"dummy_prop": ("float", 2)}, "Cube"), ], keys.SET_VALUES: [("ReadNode.inputs:name", "dummy_prop"), ("ConstToken.inputs:value", "/World/Cube2")], }, ) rel = stage.GetRelationshipAtPath(f"{self.TEST_GRAPH_PATH}/ReadNode.inputs:prim") omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/Cube1") # evaluate the unconnected graph with the first cube set directly await og.Controller.evaluate(graph) self.assertEquals(1, read_prim.get_attribute("outputs:value").get()) # connect the PrimPathNode, which is set to the second cube controller.edit(self.TEST_GRAPH_PATH, {keys.CONNECT: [("GetPrimAtPath.outputs:prims", "ReadNode.inputs:prim")]}) # validate the prim attribute is read from the correct attribute await og.Controller.evaluate(graph) self.assertEquals(2, read_prim.get_attribute("outputs:value").get()) # ----------------------------------------------------------------------------------- async def test_read_prim_attributes_with_connected_prims(self): """ Tests that ReadPrimAttributes nodes works correctly with their prim attribute is connected using a target attribute port """ node = "omni.graph.nodes.ReadPrimAttributes" usd_context = omni.usd.get_context() stage = usd_context.get_stage() controller = og.Controller() keys = og.Controller.Keys (graph, (_, _, _, to_string), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("ReadNode", node), ("GetPrimAtPath", "omni.graph.nodes.GetPrimsAtPath"), ("ConstToken", "omni.graph.nodes.ConstantToken"), ("ToString", "omni.graph.nodes.ToString"), # the output needs to be connected ], keys.CREATE_PRIMS: [ ("/World/Cube1", "Cube"), ("/World/Cube2", "Cube"), ], keys.CONNECT: [ ("ConstToken.inputs:value", "GetPrimAtPath.inputs:path"), ], keys.SET_VALUES: [ ("ReadNode.inputs:attrNamesToImport", "**"), ("ConstToken.inputs:value", "/World/Cube2"), ], }, ) rel = stage.GetRelationshipAtPath(f"{self.TEST_GRAPH_PATH}/ReadNode.inputs:prim") omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/Cube1") # evaluate the unconnected graph with the first cube set directly await og.Controller.evaluate(graph) # ReadPrimAttribute only copies values on connected values controller.edit( self.TEST_GRAPH_PATH, {keys.CONNECT: [("ReadNode.outputs:sourcePrimPath", "ToString.inputs:value")]} ) # run the graph again await og.Controller.evaluate(graph) self.assertEquals("/World/Cube1", og.Controller.get(("outputs:converted", to_string))) # connect the PrimPathNode, which is set to the second cube controller.edit(self.TEST_GRAPH_PATH, {keys.CONNECT: [("GetPrimAtPath.outputs:prims", "ReadNode.inputs:prim")]}) await og.Controller.evaluate(graph) # reconnect the output (a change in prims changes the outputs) controller.edit( self.TEST_GRAPH_PATH, {keys.CONNECT: [("ReadNode.outputs:sourcePrimPath", "ToString.inputs:value")]} ) await og.Controller.evaluate(graph) # validate the prim attribute is read from the correct attribute self.assertEquals("/World/Cube2", og.Controller.get(("outputs:converted", to_string))) # ----------------------------------------------------------------------------------- async def _test_read_prim_node_with_connected_prims(self, node): usd_context = omni.usd.get_context() stage = usd_context.get_stage() controller = og.Controller() keys = og.Controller.Keys (graph, (_read_prim, _, _, extract_node, _extract_bundle, _extract_prim), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("ReadNode", node), ("GetPrimAtPath", "omni.graph.nodes.GetPrimsAtPath"), ("ConstToken", "omni.graph.nodes.ConstantToken"), ("ExtractAttr", "omni.graph.nodes.ExtractAttribute"), ("ExtractBundle", "omni.graph.nodes.ExtractBundle"), ("ExtractPrim", "omni.graph.nodes.ExtractPrim"), ], keys.CONNECT: [ ("ConstToken.inputs:value", "GetPrimAtPath.inputs:path"), ("ReadNode.outputs_primsBundle", "ExtractPrim.inputs:prims"), ("ExtractPrim.outputs_primBundle", "ExtractBundle.inputs:bundle"), ("ExtractBundle.outputs_passThrough", "ExtractAttr.inputs:data"), ], keys.CREATE_PRIMS: [ ("/World/Cube1", {"dummy_prop": ("float", 1)}, "Cube"), ("/World/Cube2", {"dummy_prop": ("float", 2)}, "Cube"), ], keys.SET_VALUES: [ ("ReadNode.inputs:attrNamesToImport", "dummy_prop"), ("ExtractAttr.inputs:attrName", "dummy_prop"), ("ExtractPrim.inputs:primPath", "/World/Cube1"), ("ConstToken.inputs:value", "/World/Cube2"), ], }, ) rel = stage.GetRelationshipAtPath(f"{self.TEST_GRAPH_PATH}/ReadNode.inputs:prims") omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/Cube1") # evaluate the unconnected graph with the first cube set directly await og.Controller.evaluate(graph) self.assertEquals(1, og.Controller.get(("outputs:output", extract_node))) # connect the PrimPathNode, which is set to the second cube controller.edit( self.TEST_GRAPH_PATH, { keys.CONNECT: [("GetPrimAtPath.outputs:prims", "ReadNode.inputs:prims")], keys.SET_VALUES: [("ExtractPrim.inputs:primPath", "/World/Cube2")], }, ) # validate the prim attribute is read from the correct attribute await og.Controller.evaluate(graph) self.assertEquals(2, og.Controller.get(("outputs:output", extract_node))) # ----------------------------------------------------------------------------------- async def test_read_prims_with_connected_prims(self): """Tests that ReadPrims node can be connected at the prim port""" await self._test_read_prim_node_with_connected_prims("omni.graph.nodes.ReadPrims") # ----------------------------------------------------------------------------------- async def test_read_prims_bundle_with_connected_prims(self): """Tests that ReadPrims node can be connected at the prim port""" await self._test_read_prim_node_with_connected_prims("omni.graph.nodes.ReadPrimsBundle") # ----------------------------------------------------------------------------------- async def test_write_prim_attribute_with_connected_prim(self): """Test that WritePrimAttribute can be connected at the prim port""" node = "omni.graph.nodes.WritePrimAttribute" usd_context = omni.usd.get_context() stage = usd_context.get_stage() controller = og.Controller() keys = og.Controller.Keys (graph, (_write_prim, _, _, _), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("WriteNode", node), ("GetPrimAtPath", "omni.graph.nodes.GetPrimsAtPath"), ("ConstToken", "omni.graph.nodes.ConstantToken"), ("ConstValue", "omni.graph.nodes.ConstantFloat"), ], keys.CONNECT: [ ("ConstToken.inputs:value", "GetPrimAtPath.inputs:path"), ("ConstValue.inputs:value", "WriteNode.inputs:value"), ], keys.CREATE_PRIMS: [ ("/World/Cube1", {"dummy_prop": ("float", 1)}, "Cube"), ("/World/Cube2", {"dummy_prop": ("float", 2)}, "Cube"), ], keys.SET_VALUES: [ ("WriteNode.inputs:name", "dummy_prop"), ("ConstToken.inputs:value", "/World/Cube2"), ("ConstValue.inputs:value", 3.0), ("WriteNode.inputs:usdWriteBack", True), ], }, ) rel = stage.GetRelationshipAtPath(f"{self.TEST_GRAPH_PATH}/WriteNode.inputs:prim") omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/Cube1") # evaluate the unconnected graph with the first cube set directly await og.Controller.evaluate(graph) self.assertEquals(3, stage.GetAttributeAtPath("/World/Cube1.dummy_prop").Get()) # connect the PrimPathNode, which is set to the second cube controller.edit( self.TEST_GRAPH_PATH, {keys.CONNECT: [("GetPrimAtPath.outputs:prims", "WriteNode.inputs:prim")]} ) # validate the prim attribute is read from the correct attribute await og.Controller.evaluate(graph) self.assertEquals(3, stage.GetAttributeAtPath("/World/Cube2.dummy_prop").Get()) # -------------------------------------------------------------------------------------- async def _test_generic_with_connected_prim_setup(self, node_name, prim_input="prim", use_path="usePath"): """Creates a graph set with the given node, two prims (cubes) and sets the path to first prim""" usd_context = omni.usd.get_context() stage = usd_context.get_stage() controller = og.Controller() keys = og.Controller.Keys (graph, (node, _, _), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("Node", node_name), ("GetPrimAtPath", "omni.graph.nodes.GetPrimsAtPath"), ("ConstToken", "omni.graph.nodes.ConstantToken"), ], keys.CONNECT: [ ("ConstToken.inputs:value", "GetPrimAtPath.inputs:path"), ], keys.CREATE_PRIMS: [ ("/World/Cube1", "Cube"), ("/World/Cube2", "Cube"), ], keys.SET_VALUES: [ (f"Node.inputs:{use_path}", False), ("ConstToken.inputs:value", "/World/Cube2"), ], }, ) # make sure the prims have the correct transform attributes for prim_path in ["/World/Cube1", "/World/Cube2"]: prim = stage.GetPrimAtPath(prim_path) prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) prim.CreateAttribute("xformOp:rotateXYZ", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(1.0, 1.0, 1.0)) prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] ) rel = stage.GetRelationshipAtPath(f"{self.TEST_GRAPH_PATH}/Node.inputs:{prim_input}") omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/Cube1") omni.timeline.get_timeline_interface().play() return (controller, graph, node) def _connect_prim_path_node(self, controller): """ Helper to connect the prim path node from the graph created in _test_generic_with_connected_prim_setup """ controller.edit( self.TEST_GRAPH_PATH, { og.Controller.Keys.CONNECT: [("GetPrimAtPath.outputs:prims", "Node.inputs:prim")], }, ) # -------------------------------------------------------------------------------------- async def _advance(self, graph, delta_time=0.01): """ Helper routine to wait for minimum amount of time to pass Requires the timeline to be playing """ timeline = omni.timeline.get_timeline_interface() t = timeline.get_current_time() + delta_time await og.Controller.evaluate(graph) while timeline.get_current_time() < t: await omni.kit.app.get_app().next_update_async() if not timeline.is_playing(): raise og.OmniGraphError("_advance expected the timeline to be playing") # -------------------------------------------------------------------------------------- async def test_get_prim_direction_vector_with_connected_prim(self): """Test GetPrimDirectorVector works with a connected prim""" (controller, graph, node) = await self._test_generic_with_connected_prim_setup( "omni.graph.nodes.GetPrimDirectionVector" ) # rotate the second cube stage = omni.usd.get_context().get_stage() stage.GetAttributeAtPath("/World/Cube2.xformOp:rotateXYZ").Set(Gf.Vec3d(0, 180, 0)) # evaluate the unconnected graph with the first cube set directly await og.Controller.evaluate(graph) self.assertListEqual([0, 0, -1], list(og.Controller.get(("outputs:forwardVector", node)))) # connect the PrimPathNode, which is set to the second cube self._connect_prim_path_node(controller) # connect the PrimPathNode, which is set to the second cube # validate the prim attribute is read from the correct attribute await og.Controller.evaluate(graph) vec = og.Controller.get(("outputs:forwardVector", node)) self.assertAlmostEqual(0, vec[0]) self.assertAlmostEqual(0, vec[1]) self.assertAlmostEqual(1, vec[2]) # -------------------------------------------------------------------------------------- async def test_get_prim_local_to_world_with_connected_prim(self): """Test GetPrimLocalToWorldTransform works with a connected prim""" (controller, graph, node) = await self._test_generic_with_connected_prim_setup( "omni.graph.nodes.GetPrimLocalToWorldTransform" ) # rotate the second cube stage = omni.usd.get_context().get_stage() stage.GetAttributeAtPath("/World/Cube2.xformOp:rotateXYZ").Set(Gf.Vec3d(0, 180, 0)) # evaluate the unconnected graph with the first cube set directly await og.Controller.evaluate(graph) matrix = og.Controller.get(("outputs:localToWorldTransform", node)) matrix = [round(i) for i in matrix] self.assertListEqual([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], matrix) # connect the PrimPathNode, which is set to the second cube self._connect_prim_path_node(controller) # validate the prim attribute is read from the correct attribute await og.Controller.evaluate(graph) matrix = og.Controller.get(("outputs:localToWorldTransform", node)) matrix = [round(i) for i in matrix] self.assertListEqual([-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1], matrix) # -------------------------------------------------------------------------------------- async def test_get_prim_relationship_with_connected_prim(self): """Test GetPrimRelationship works with a connected prim""" (controller, graph, node) = await self._test_generic_with_connected_prim_setup( "omni.graph.nodes.GetPrimRelationship" ) self._connect_prim_path_node(controller) # set up a relationship from the connected to cube stage = omni.usd.get_context().get_stage() stage.GetPrimAtPath("/World/Cube2").CreateRelationship("dummy_rel").AddTarget("/World/Cube1") # mark the attribute og.Controller.set(("inputs:name", node), "dummy_rel") await og.Controller.evaluate(graph) self.assertEqual(["/World/Cube1"], og.Controller.get(("outputs:paths", node))) # -------------------------------------------------------------------------------------- async def test_move_to_target_with_connected_prim(self): """Test MoveToTarget works with a connected prim""" (_controller, graph, node) = await self._test_generic_with_connected_prim_setup( "omni.graph.nodes.MoveToTarget", "sourcePrim", "useSourcePath" ) # connect the destination stage = omni.usd.get_context().get_stage() rel = stage.GetRelationshipAtPath(f"{self.TEST_GRAPH_PATH}/Node.inputs:targetPrim") omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/Cube2") stage.GetAttributeAtPath("/World/Cube1.xformOp:translate").Set(Gf.Vec3d(1, 0, 0)) stage.GetAttributeAtPath("/World/Cube2.xformOp:translate").Set(Gf.Vec3d(1000, 0, 0)) og.Controller.set(("inputs:speed", node), 0.1) # validate the source cube is moving away from the source last_x = 0.99 # first frame is 1 for _ in range(0, 5): await self._advance(graph) xform_cache = UsdGeom.XformCache() cube1 = xform_cache.GetLocalToWorldTransform(stage.GetPrimAtPath("/World/Cube1")) x = cube1.ExtractTranslation()[0] self.assertGreater(x, last_x) last_x = x # -------------------------------------------------------------------------------------- async def test_move_to_transform_with_connected_prim(self): """Test MoveToTransform works with a connected prim""" (_controller, graph, node) = await self._test_generic_with_connected_prim_setup( "omni.graph.nodes.MoveToTransform" ) # connect the destination stage = omni.usd.get_context().get_stage() stage.GetAttributeAtPath("/World/Cube1.xformOp:translate").Set(Gf.Vec3d(1, 0, 0)) stage.GetPrimAtPath("/World/Cube1").CreateAttribute("xformOp:orient", Sdf.ValueTypeNames.Quatd, False).Set( Gf.Quatd(0) ) stage.GetPrimAtPath("/World/Cube1").CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:orient"] ) og.Controller.set(("inputs:speed", node), 0.1) og.Controller.set(("inputs:target", node), Gf.Matrix4d(1).SetTranslate(Gf.Vec3d(1000, 0, 0))) # validate the source cube is moving away from the source last_x = 0.99 # first frame is 1 for _ in range(0, 5): await self._advance(graph) xform_cache = UsdGeom.XformCache() cube1 = xform_cache.GetLocalToWorldTransform(stage.GetPrimAtPath("/World/Cube1")) x = cube1.ExtractTranslation()[0] self.assertGreater(x, last_x) last_x = x # -------------------------------------------------------------------------------------- async def test_rotate_to_target_with_connected_prim(self): """Test RotateToTarget works with a connected prim""" (_controller, graph, node) = await self._test_generic_with_connected_prim_setup( "omni.graph.nodes.RotateToTarget", "sourcePrim", "useSourcePath" ) # connect the destination stage = omni.usd.get_context().get_stage() rel = stage.GetRelationshipAtPath(f"{self.TEST_GRAPH_PATH}/Node.inputs:targetPrim") omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/Cube2") quat1 = Gf.Rotation().SetIdentity().GetQuat() quat2 = Gf.Rotation().SetAxisAngle(Gf.Vec3d.YAxis(), 180).GetQuat() stage.GetAttributeAtPath("/World/Cube1.xformOp:translate").Set(Gf.Vec3d(0, 0, 0)) stage.GetAttributeAtPath("/World/Cube2.xformOp:translate").Set(Gf.Vec3d(0, 0, 0)) stage.GetPrimAtPath("/World/Cube1").CreateAttribute("xformOp:orient", Sdf.ValueTypeNames.Quatd, False).Set( quat1 ) stage.GetPrimAtPath("/World/Cube2").CreateAttribute("xformOp:orient", Sdf.ValueTypeNames.Quatd, False).Set( quat2 ) stage.GetPrimAtPath("/World/Cube1").CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:orient", "xformOp:scale"] ) stage.GetPrimAtPath("/World/Cube2").CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:orient", "xformOp:scale"] ) og.Controller.set(("inputs:speed", node), 0.02) # very slow moving last_rot = quat2 for _ in range(0, 5): await self._advance(graph) xform_cache = UsdGeom.XformCache() cube1 = xform_cache.GetLocalToWorldTransform(stage.GetPrimAtPath("/World/Cube1")) rot = cube1.ExtractRotation() self.assertNotEqual(rot, last_rot) last_rot = rot # -------------------------------------------------------------------------------------- async def test_rotate_to_orientation_with_connected_prim(self): """Test RotateToOrientation works with a connected prim""" (_controller, graph, node) = await self._test_generic_with_connected_prim_setup( "omni.graph.nodes.RotateToOrientation" ) # connect the destination stage = omni.usd.get_context().get_stage() quat1 = Gf.Rotation().SetIdentity().GetQuat() stage.GetAttributeAtPath("/World/Cube1.xformOp:translate").Set(Gf.Vec3d(0, 0, 0)) stage.GetPrimAtPath("/World/Cube1").CreateAttribute("xformOp:orient", Sdf.ValueTypeNames.Quatd, False).Set( quat1 ) stage.GetPrimAtPath("/World/Cube1").CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:orient", "xformOp:scale"] ) og.Controller.set(("inputs:speed", node), 0.02) # very slow moving og.Controller.set(("inputs:target", node), (0, 180, 0)) last_rot = Gf.Rotation().SetAxisAngle(Gf.Vec3d.YAxis(), 180).GetQuat() for _ in range(0, 5): await self._advance(graph) xform_cache = UsdGeom.XformCache() cube1 = xform_cache.GetLocalToWorldTransform(stage.GetPrimAtPath("/World/Cube1")) rot = cube1.ExtractRotation() self.assertNotEqual(rot, last_rot) last_rot = rot # -------------------------------------------------------------------------------------- async def test_scale_to_size_with_connected_prim(self): """Test ScaleToSize works with a connected prim""" (_controller, graph, node) = await self._test_generic_with_connected_prim_setup("omni.graph.nodes.ScaleToSize") # connect the destination stage = omni.usd.get_context().get_stage() stage.GetAttributeAtPath("/World/Cube1.xformOp:scale").Set(Gf.Vec3d(1, 1, 1)) og.Controller.set(("inputs:speed", node), 0.1) og.Controller.set(("inputs:target", node), (1000, 1000, 1000)) # validate the source cube is moving away from the source last_x = 0.99 # first frame is 1 for _ in range(0, 5): await self._advance(graph) xform_cache = UsdGeom.XformCache() cube1 = xform_cache.GetLocalToWorldTransform(stage.GetPrimAtPath("/World/Cube1")) x = cube1[0][0] self.assertGreater(x, last_x) last_x = x # -------------------------------------------------------------------------------------- async def test_translate_to_target_with_connected_prim(self): """Test TranslateToTarget works with a connected prim""" (_controller, graph, node) = await self._test_generic_with_connected_prim_setup( "omni.graph.nodes.TranslateToTarget", "sourcePrim", "useSourcePath" ) # connect the destination stage = omni.usd.get_context().get_stage() rel = stage.GetRelationshipAtPath(f"{self.TEST_GRAPH_PATH}/Node.inputs:targetPrim") omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/World/Cube2") stage.GetAttributeAtPath("/World/Cube1.xformOp:translate").Set(Gf.Vec3d(1, 0, 0)) stage.GetAttributeAtPath("/World/Cube2.xformOp:translate").Set(Gf.Vec3d(1000, 0, 0)) og.Controller.set(("inputs:speed", node), 0.1) # validate the source cube is moving away from the source last_x = 0.99 # first frame is 1 for _ in range(0, 5): await self._advance(graph) xform_cache = UsdGeom.XformCache() cube1 = xform_cache.GetLocalToWorldTransform(stage.GetPrimAtPath("/World/Cube1")) x = cube1.ExtractTranslation()[0] self.assertGreater(x, last_x) last_x = x # -------------------------------------------------------------------------------------- async def test_translate_to_location_with_connected_prim(self): """Test TranslateToLocation works with a connected prim""" (_controller, graph, node) = await self._test_generic_with_connected_prim_setup( "omni.graph.nodes.TranslateToLocation" ) # connect the destination stage = omni.usd.get_context().get_stage() stage.GetAttributeAtPath("/World/Cube1.xformOp:translate").Set(Gf.Vec3d(1, 0, 0)) stage.GetPrimAtPath("/World/Cube1").CreateAttribute("xformOp:orient", Sdf.ValueTypeNames.Quatd, False).Set( Gf.Quatd(0) ) stage.GetPrimAtPath("/World/Cube1").CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:orient"] ) og.Controller.set(("inputs:speed", node), 0.1) og.Controller.set(("inputs:target", node), Gf.Vec3d(1000, 0, 0)) # validate the source cube is moving away from the source last_x = 0.99 # first frame is 1 for _ in range(0, 5): await self._advance(graph) xform_cache = UsdGeom.XformCache() cube1 = xform_cache.GetLocalToWorldTransform(stage.GetPrimAtPath("/World/Cube1")) x = cube1.ExtractTranslation()[0] self.assertGreater(x, last_x) last_x = x
28,915
Python
46.637562
120
0.565416
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_omnigraph_builtins.py
"""Basic tests of the compute graph""" from unittest import skip import numpy import omni.graph.core as og import omni.graph.core.tests as ogts import omni.graph.tools as ogt import omni.kit.stage_templates import omni.kit.test import omni.usd from omni.graph.core.tests.omnigraph_test_utils import create_scope_node from pxr import Sdf # ====================================================================== # Set of attribute types that can have default values set ATTR_INT = Sdf.ValueTypeNames.Int ATTR_BOOL = Sdf.ValueTypeNames.Bool ATTR_FLOAT = Sdf.ValueTypeNames.Float ATTR_DOUBLE = Sdf.ValueTypeNames.Double ATTR_INT_ARRAY = Sdf.ValueTypeNames.IntArray ATTR_FLOAT_ARRAY = Sdf.ValueTypeNames.FloatArray ATTR_DOUBLE_ARRAY = Sdf.ValueTypeNames.DoubleArray ATTR_FLOAT2_ARRAY = Sdf.ValueTypeNames.Float2Array ATTR_FLOAT3_ARRAY = Sdf.ValueTypeNames.Float3Array ATTR_STRING = Sdf.ValueTypeNames.String ATTR_TOKEN = Sdf.ValueTypeNames.Token ATTR_DEFAULTS = { ATTR_INT: 0, ATTR_BOOL: False, ATTR_FLOAT: 0.0, ATTR_DOUBLE: 0.0, ATTR_INT_ARRAY: [], ATTR_FLOAT_ARRAY: [], ATTR_DOUBLE_ARRAY: [], ATTR_FLOAT2_ARRAY: [], ATTR_FLOAT3_ARRAY: [], ATTR_STRING: "", ATTR_TOKEN: "", } # ====================================================================== def initialize_attribute(prim, attribute_name, attribute_type): """Set up an attribute named "attribute_name" on the given prim with a default value of the specified type""" ogt.dbg(f" Initialize {attribute_name} with value {ATTR_DEFAULTS[attribute_type]}") prim.CreateAttribute(attribute_name, attribute_type).Set(ATTR_DEFAULTS[attribute_type]) # ====================================================================== def float3_array_of(array_order: int): """ Returns an array of float3 the size of the array_order, with values equal to it e.g. array_order(1) = [[1.0, 1.0, 1.0]] e.g. array_order(2) = [[2.0, 2.0, 2.0], [2.0, 2.0, 2.0]] """ return [[float(array_order)] * 3] * array_order # ====================================================================== def generate_results(array_order1: int, array_order2: int): """ Returns expected test data for the concatenate node consisting of: - an array of float3, in a sequence of "array_order1" elements with values (array_order1, array_order1, array_order1) followed by a similar sequence for "array_order2" e.g. values 1 and 2 would yield: [[1.0,1.0,1.0],[2.0,2.0,2.0],[2.0,2.0,2.0]] """ return float3_array_of(array_order1) + float3_array_of(array_order2) # ====================================================================== class TestOmniGraphBuiltins(ogts.OmniGraphTestCase): """Run a simple unit test that exercises graph functionality""" # ---------------------------------------------------------------------- def compare_values(self, expected_value, actual_value, error_message): """Generic assert comparison which uses introspection to choose the correct method to compare the data values""" ogt.dbg(f"----Comparing {actual_value} with expected {expected_value} as '{error_message}'") if isinstance(expected_value, (list, tuple)): # If the numpy module is not available array values cannot be tested so silently succeed if numpy is None: return # Values are returned as numpy arrays so convert the expected value and use numpy to do the comparison numpy.testing.assert_almost_equal( actual_value, numpy.array(expected_value), decimal=3, err_msg=error_message ) elif isinstance(expected_value, float): self.assertAlmostEqual(actual_value, expected_value, error_message) else: self.assertEqual(actual_value, expected_value, error_message) # ---------------------------------------------------------------------- @skip("TODO: Enable when gather nodes are fully supported") async def test_concat_node(self): """ Run evaluation tests on the builtin math concat node. This node has its own test because it cannot be tested in isolation, it requires a gather node to provide a meaningful input. """ concat_node = "ConcatFloat3Arrays" gather_node = "GatherFloat3Arrays" scope_node1 = "ScopeWithArrays1" scope_node2 = "ScopeWithArrays2" gather_output = f"/World/{gather_node}.createdOutput" cached_prims = {} scene_data = { # The concatFloat3Arrays node flattens and array of arrays of float3 "omni.graph.nodes.ConcatenateFloat3Arrays": { "name": [concat_node], "inputs": [["inputs:inputArrays", Sdf.ValueTypeNames.Float3Array]], "outputs": [ ["outputs:outputArray", Sdf.ValueTypeNames.Float3Array, [[-1.0, -1.0, -1.0]]], ["outputs:arraySizes", Sdf.ValueTypeNames.IntArray, [-1]], ], }, # The gather node concatenates lists of inputs together so that a node can process them on mass "Gather": { "name": [gather_node], "inputs": [], "outputs": [["createdOutput", Sdf.ValueTypeNames.Float3Array, [[-1.0, -1.0, -1.0]]]], }, # Generic scope nodes to supply the float3 arrays to the gather node "Scope": { "name": [scope_node1, scope_node2], "inputs": [], "outputs": [["createdOutput", Sdf.ValueTypeNames.Float3Array, [[-1.0, -1.0, -1.0]]]], }, } # Create a stage consisting of one of each type of node to be tested with their attributes for node_type, node_configuration in scene_data.items(): for node_name in node_configuration["name"]: if node_type == "Scope": prim = create_scope_node(node_name) else: stage = omni.usd.get_context().get_stage() path = omni.usd.get_stage_next_free_path(stage, "/" + node_name, True) _ = og.GraphController.create_node(path, node_type) prim = stage.GetPrimAtPath(path) cached_prims[node_name] = prim for attribute_name, attribute_type in node_configuration["inputs"]: prim.CreateAttribute(attribute_name, attribute_type) for attribute_name, attribute_type, _ in node_configuration["outputs"]: prim.CreateAttribute(attribute_name, attribute_type) # Create the connections that get gathered arrays to the concat node cached_prims[concat_node].GetAttribute("inputs:inputArrays").AddConnection(gather_output) cached_prims[scope_node1].GetAttribute("createdOutput").Set([[1.0, 1.0, 1.0]]) cached_prims[scope_node2].GetAttribute("createdOutput").Set([[2.0, 2.0, 2.0], [2.0, 2.0, 2.0]]) # Pairs of inputs for the create nodes to generate results (extracted from generated_results()) test_data = [[1, 1], [1, 2], [1, 3], [3, 1], [3, 3]] await omni.kit.app.get_app().next_update_async() graph = omni.graph.core.get_current_graph() # Get the attributes that will be used for the computations concat_compute = graph.get_node("/World/" + concat_node) output_attr_array = concat_compute.get_attribute("outputs:outputArray") output_attr_counts = concat_compute.get_attribute("outputs:arraySizes") for test_values in test_data: # Set the test inputs cached_prims[scope_node1].GetAttribute("createdOutput").Set(float3_array_of(test_values[0])) cached_prims[scope_node2].GetAttribute("createdOutput").Set(float3_array_of(test_values[1])) # Run the compute await omni.kit.app.get_app().next_update_async() # Check the contents of the flattened array expected_output = generate_results(test_values[0], test_values[1]) output_array_value = og.Controller.get(output_attr_array) self.compare_values( expected_output, output_array_value, "ConcatNode test - outputArray attribute value error" ) # Check the contents of the array size counts output_counts_value = og.Controller.get(output_attr_counts) self.compare_values(test_values, output_counts_value, "ConcatNode test - arraySizes attribute value error")
8,602
Python
46.530386
120
0.595559
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/bundle_test_utils.py
"""Collection of utilities to help with testing bundled attributes on OmniGraph nodes""" import ast from dataclasses import dataclass from typing import Any, Dict, List, Optional, Tuple, Union import omni.graph.core as og import omni.graph.core.tests as ogts import omni.graph.tools.ogn as ogn from omni.graph.core.typing import Node_t, PrimAttrs_t __all__ = [ "bundle_inspector_results", "BundleInspectorResults_t", "BundleResultKeys", "enable_debugging", "filter_bundle_inspector_results", "get_bundle_with_all_results", "prim_with_everything_definition", "verify_bundles_are_equal", ] # ============================================================================================================== @dataclass class BundleResultKeys: """Container for the keys used in the bundle result values and the index in the return tuple that each one uses""" COUNT = "outputs:count" NAME = "outputs:names" TYPE = "outputs:types" TYPE_IDX = 0 TUPLE_COUNT = "outputs:tupleCounts" TUPLE_COUNT_IDX = 1 ARRAY_DEPTH = "outputs:arrayDepths" ARRAY_DEPTH_IDX = 2 ROLE = "outputs:roles" ROLE_IDX = 3 VALUE = "outputs:values" VALUE_IDX = 4 # ============================================================================================================== BundleInspectorResults_t = Tuple[int, Dict[str, Tuple[str, str, int, int, Any]]] """Results extracted from a bundle inspector's output attributes by NAME:VALUE. The first value is the count output. The dictionary is a mapping of name to (type, role, arrayDepth, tupleCount, value). It's stored this way to make it easier to guarantee ordering of the lists so that they can be easily compared. """ # ====================================================================== # Special value used by the bundle inspector node when the output for the bundled attribute is not yet supported _BUNDLE_INSPECTOR_UNSUPPORTED_DATA = "__unsupported__" # ====================================================================== def enable_debugging(bundle_inspector_node_name: Union[og.Node, str]): """Sets the debugging input value to true on the given omnigraph.nodes.bundleInspector Raises: AttributeError if the node is not a bundle inspector type """ graph = og.get_all_graphs()[0] if isinstance(bundle_inspector_node_name, og.Node): bundle_node = bundle_inspector_node_name else: bundle_node = graph.get_node(bundle_inspector_node_name) print_attribute = bundle_node.get_attribute("inputs:print") og.Controller.set(print_attribute, True) # ====================================================================== def prim_with_everything_definition( type_names_to_filter: Optional[List[str]] = None, filter_for_inclusion: bool = True ) -> PrimAttrs_t: """Generates an og.Controller prim creation specification for a prim containing one of every attribute. The name of the attribute is derived from the type. int -> IntAttr int[] -> IntArrayAttr int[3] -> Int3Attr int[3][] -> Int3ArrayAttr Args: type_names_to_filter: List of type names to check for inclusion. If empty no filtering happens. The type names should be in OGN format (e.g. "int[3][]") filter_for_inclusion: If True then the type_names_to_filter is treated as the full list of type names to include, otherwise it is treated as a list of types to exclude from the list of all types. Return: A dictionary containing a prim definition that matches what is required by og.Controller.create_prim with all of the specified attributes defined on the prim. """ def __type_passes_filter(type_name: str) -> bool: """Returns True iff the filters allow the type_name to be included""" # The deprecated transform type always fails the filter if type_name.startswith("transform"): return False if filter_for_inclusion: return type_names_to_filter is None or type_name in type_names_to_filter return type_names_to_filter is None or type_name not in type_names_to_filter definition = {} for attribute_type_name in ogn.supported_attribute_type_names(): # Skip the types that are filtered if not __type_passes_filter(attribute_type_name): continue manager = ogn.get_attribute_manager_type(attribute_type_name) sdf_type_name = manager.sdf_type_name() # Skip the types that don't correspond to USD types if sdf_type_name is not None: attribute_name = f"{sdf_type_name}Attr" values = manager.sample_values() definition[attribute_name] = (attribute_type_name, values[0]) return definition # ====================================================================== def get_bundle_with_all_results( prim_source_path: Optional[str] = None, type_names_to_filter: Optional[List[str]] = None, filter_for_inclusion: bool = True, prim_source_type: Optional[str] = None, ) -> BundleInspectorResults_t: """Generates a dictionary of expected bundle inspector contents from a bundle constructed with a filtered list of all attribute types. The name of the attribute is derived from the type. int -> IntAttr int[] -> IntArrayAttr int[3] -> Int3Attr int[3][] -> Int3ArrayAttr Args: prim_source_path: Source of the prim from which the bundle was extracted (to correctly populate the extra attribute the ReadPrim nodes add). If None then no prim addition is required. type_names_to_filter: List of type names to check for inclusion. If empty no filtering happens. The type names should be in OGN format (e.g. "int[3][]") filter_for_inclusion: If True then the type_names_to_filter is treated as the full list of type names to include, otherwise it is treated as a list of types to exclude from the list of all types. prim_source_type: Type of the source prim. Return: A dictionary containing a BundleInspector attribute name mapped onto the value of that attribute. Only the output attributes are considered. """ def __type_passes_filter(type_name: str) -> bool: """Returns True iff the filters allow the type_name to be included""" # The deprecated transform type always fails the filter if type_name.startswith("transform"): return False if filter_for_inclusion: return type_names_to_filter is None or type_name in type_names_to_filter return type_names_to_filter is None or type_name not in type_names_to_filter # This token is hardcoded into the ReadPrimBundle node and will always be present regardless of the prim contents. # This requires either the prim path be "TestPrim", or the value be adjusted to reflect the actual prim per_name_results = {} for attribute_type_name in ogn.supported_attribute_type_names(): # Skip the types that are filtered if not __type_passes_filter(attribute_type_name): continue manager = ogn.get_attribute_manager_type(attribute_type_name) sdf_type_name = manager.sdf_type_name() # Skip the types that don't correspond to USD types if sdf_type_name is not None: attribute_type = og.AttributeType.type_from_ogn_type_name(attribute_type_name) attribute_name = f"{sdf_type_name}Attr" values = manager.sample_values() per_name_results[attribute_name] = ( attribute_type.get_base_type_name(), attribute_type.tuple_count, attribute_type.array_depth, attribute_type.get_role_name(), values[0], ) if prim_source_path is not None: per_name_results.update({"sourcePrimPath": ("token", 1, 0, "none", prim_source_path)}) if prim_source_type is not None: per_name_results.update({"sourcePrimType": ("token", 1, 0, "none", prim_source_type)}) return (len(per_name_results), per_name_results) # ====================================================================== def bundle_inspector_results(inspector_spec: Node_t) -> BundleInspectorResults_t: """Returns attribute values computed from a bundle inspector in the same form as inspected_bundle_values Args: inspector_spec: BundleInspector node from which to extract the output values Return: Output values of the bundle inspector, formatted for easier comparison. Raises: og.OmniGraphError if anything in the inspector outputs could not be interpreted """ inspector_node = og.Controller.node(inspector_spec) output = {} for inspector_attribute in inspector_node.get_attributes(): attribute_name = inspector_attribute.get_name() if inspector_attribute.get_port_type() != og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT: continue if inspector_attribute.get_type_name() == "bundle": continue values = og.Controller.get(inspector_attribute) if inspector_attribute.get_name().endswith("values"): # Bundled values are formatted as strings but are actually a mixture of types values = [ ast.literal_eval(value) if value != _BUNDLE_INSPECTOR_UNSUPPORTED_DATA else _BUNDLE_INSPECTOR_UNSUPPORTED_DATA for value in values ] output[attribute_name] = values # Catch the case of an empty bundle separately if not output: return (0, {}) try: count = output[BundleResultKeys.COUNT] per_name_values = { name: (v1, v2, v3, v4, v5) for name, v1, v2, v3, v4, v5 in zip( output[BundleResultKeys.NAME], output[BundleResultKeys.TYPE], output[BundleResultKeys.TUPLE_COUNT], output[BundleResultKeys.ARRAY_DEPTH], output[BundleResultKeys.ROLE], output[BundleResultKeys.VALUE], ) } except Exception as error: raise og.OmniGraphError(error) return (count, per_name_values) # ============================================================================================================== def verify_bundles_are_equal( actual_values: BundleInspectorResults_t, expected_values: BundleInspectorResults_t, check_values: bool = True ): """Check that the contents of the actual values received from a bundle inspector match the expected values. Args: actual_values: Bundle contents read from the graph expected_values: Test bundle contents expected check_values: If True then check that attribute values as well as the type information, otherwise just types Raises: ValueError: if the contents differ. The message in the exception explains how they differ """ (actual_count, actual_results) = actual_values (expected_count, expected_results) = expected_values def __compare_attributes(attribute_name: str): """Compare a single attribute's result from the bundle inspected, raising ValueError if not equal""" actual_value = actual_results[attribute_name] expected_value = expected_results[attribute_name] try: if actual_value[0] != expected_value[0]: raise ValueError("Type mismatch") if actual_value[1] != expected_value[1]: raise ValueError("Tuple count mismatch") if actual_value[2] != expected_value[2]: raise ValueError("Array depth mismatch") if actual_value[3] != expected_value[3]: raise ValueError("Role mismatch") if check_values: ogts.verify_values(actual_value[4], expected_value[4], "Value mismatch") except ValueError as error: raise ValueError( f"Actual value for '{attribute_name}' of '{actual_value}' did not match expected value" f" of '{expected_value}'" ) from error actual_names = set(actual_results.keys()) expected_names = set(expected_results.keys()) name_difference = actual_names.symmetric_difference(expected_names) if name_difference: problems = [] extra_actual_results = actual_names.difference(expected_names) if extra_actual_results: problems.append(f"Actual members {extra_actual_results} not expected.") extra_expected_results = expected_names.difference(actual_names) if extra_expected_results: problems.append(f"Expected members {extra_expected_results} not found.") problem = "\n".join(problems) raise ValueError(f"Actual output attribute names differ from expected list: {problem}") if actual_count != expected_count: raise ValueError(f"Expected {expected_count} results, actual value was {actual_count}") for output_attribute_name in actual_results.keys(): __compare_attributes(output_attribute_name) # ============================================================================================================== def filter_bundle_inspector_results( raw_results: BundleInspectorResults_t, names_to_filter: Optional[List[str]] = None, filter_for_inclusion: bool = True, ) -> BundleInspectorResults_t: """Filter out the results retrieved from a bundle inspector by name Args: names_to_filter: List of attribute names to check for inclusion. filter_for_inclusion: If True then the names_to_filter is treated as the full list of names to include, otherwise it is treated as a list of names to exclude from the list of all names. Return: The raw_results with the above filtering performed """ def __type_passes_filter(name: str) -> bool: """Returns True iff the filters allow the name to be included""" if filter_for_inclusion: return names_to_filter is None or name in names_to_filter return names_to_filter is None or name not in names_to_filter (_, results) = raw_results filtered_results = {} for attribute_name, attribute_values in results.items(): if __type_passes_filter(attribute_name): filtered_results[attribute_name] = attribute_values return (len(filtered_results), filtered_results)
14,643
Python
43.108434
120
0.623096
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_bundles.py
import omni.graph.core as ogc import omni.kit.test class TestNodeInputAndOutputBundles(ogc.tests.OmniGraphTestCase): """Test to validate access to input/output bundles""" TEST_GRAPH_PATH = "/TestGraph" async def setUp(self): """Set up test environment, to be torn down when done""" await super().setUp() self.graph = ogc.Controller.create_graph(self.TEST_GRAPH_PATH) self.context = self.graph.get_default_graph_context() self.prim_cube = ogc.Controller.create_prim("/cube", {}, "Cube") (self.graph, [self.read_prim, self.extract_prim, self.extract_bundle], _, _,) = ogc.Controller.edit( self.TEST_GRAPH_PATH, { ogc.Controller.Keys.CREATE_NODES: [ ("read_prims", "omni.graph.nodes.ReadPrims"), ("extract_prim", "omni.graph.nodes.ExtractPrim"), ("extract_bundle", "omni.graph.nodes.ExtractBundle"), ], ogc.Controller.Keys.CONNECT: [ ("read_prims.outputs_primsBundle", "extract_prim.inputs:prims"), ("extract_prim.outputs_primBundle", "extract_bundle.inputs:bundle"), ], ogc.Controller.Keys.SET_VALUES: [ ("extract_prim.inputs:primPath", str(self.prim_cube.GetPath())), ], }, ) stage = omni.usd.get_context().get_stage() omni.kit.commands.execute( "AddRelationshipTarget", relationship=stage.GetPropertyAtPath(self.TEST_GRAPH_PATH + "/read_prims.inputs:prims"), target=self.prim_cube.GetPath(), ) async def test_pass_through_output(self): """Test if data from pass through output is accessible through bundles""" await ogc.Controller.evaluate(self.graph) factory = ogc.IBundleFactory.create() # Accessing bundle through get_output_bundle constructs IBundle interface output_bundle = self.context.get_output_bundle(self.extract_bundle, "outputs_passThrough") output_bundle2 = factory.get_bundle(self.context, output_bundle) self.assertTrue(output_bundle2.valid) self.assertTrue(output_bundle2.get_attribute_by_name("extent").is_valid())
2,294
Python
39.982142
108
0.607236
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_read_prims_hierarchy.py
import numpy as np import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.test from pxr import Gf, Sdf, Usd, UsdGeom class TestReadPrimsHierarchy(ogts.OmniGraphTestCase): """Unit tests for hierarchical behavior of the ReadPrimsV2 node in this extension""" async def test_read_prims_hierarchy_permutations(self): # We build a hierarchy, 4 levels deep. # Then we track each possible pair of prims in the hierarchy, # mutate every prim in the hierarchy (scaling), # and check if the pair USD and bundle world matrices and bounding boxes match. # TODO: Find out why this runs so slow! # Originally we ran 3 tests, optionally enabling matrix and/or bounds # But since the test runs so slowly, we only have one now. # The incremental tests will test the options anyway. # We keep these variables to selectively disable either one for debugging. compute_world_matrix = True compute_bounding_box = True usd_context = omni.usd.get_context() stage: Usd.Stage = usd_context.get_stage() test_graph_path = "/World/TestGraph" # Define the compute graph controller = og.Controller() keys = og.Controller.Keys (graph, [read_prims_node], _, _) = controller.edit( test_graph_path, { keys.CREATE_NODES: [ ("Read", "omni.graph.nodes.ReadPrimsV2"), ], keys.SET_VALUES: [ ("Read.inputs:enableChangeTracking", True), # TODO: Re-enable when OgnReadPrimsV2 gets computeWorldMatrix # ("Read.inputs:computeWorldMatrix", compute_world_matrix), ("Read.inputs:computeBoundingBox", compute_bounding_box), ], }, ) debug_stamp = 0 debug_stamp_attribute = read_prims_node.get_attribute("inputs:_debugStamp") init_scale = Gf.Vec3f(0.5, 0.5, 0.5) test_scale = Gf.Vec3f(1.5, 1.5, 1.5) default_time = Usd.TimeCode.Default() # Defines 2 trees with 2 branches and 2 leaves (as spheres), # return the prim paths of all the nodes. # Optionally just define nodes that have the given prefix; # this is used to restore the hierarchy after deleting a subtree def define_hierarchies(prefix=None): tree_prims = [] def add_prim(prim, x, y, z): tree_prims.append(prim) api = UsdGeom.XformCommonAPI(prim) api.SetTranslate(Gf.Vec3d(x, y, z)) # We set the scale of each node to 0.5 instead of 1, # so that deleting the scale attribute (which resets the scale to 1) # is detected as a matrix and bounds change api.SetScale(init_scale) for tree_index in range(2): tree_path = f"/Tree{tree_index}" if prefix is None or Sdf.Path(tree_path).HasPrefix(prefix): tree_prim = UsdGeom.Xform.Define(stage, tree_path) add_prim(tree_prim, (tree_index - 0.5) * 20, 0, 0) for branch_index in range(2): branch_path = f"{tree_path}/Branch{branch_index}" if prefix is None or Sdf.Path(branch_path).HasPrefix(prefix): branch_prim = UsdGeom.Xform.Define(stage, branch_path) add_prim(branch_prim, 0, 10, 0) for leaf_index in range(2): leaf_path = f"{branch_path}/Leaf{leaf_index}" if prefix is None or Sdf.Path(leaf_path).HasPrefix(prefix): leaf_prim = UsdGeom.Sphere.Define(stage, leaf_path) # The leaves are positioned in a diamond shape, # so that deleting any leaf influences that ancestor bounds if branch_index == 0: add_prim(leaf_prim, (leaf_index - 0.5) * 5, 10, 0) else: add_prim(leaf_prim, 0, 10, (leaf_index - 0.5) * 5) return [p.GetPath() for p in tree_prims] def get_usd_matrix_bounds_pair(prim_path): xformable = UsdGeom.Xformable(stage.GetPrimAtPath(prim_path)) self.assertTrue(xformable is not None) world_matrix = xformable.ComputeLocalToWorldTransform(default_time) local_bounds = xformable.ComputeLocalBound(default_time, UsdGeom.Tokens.default_, UsdGeom.Tokens.proxy) return (world_matrix, local_bounds) tree_prim_paths = define_hierarchies() # For debugging test failures, tweak the two variable below (should be lists of Sdf.Path) track_prim_paths = tree_prim_paths change_prim_paths = tree_prim_paths # The original matrix and bound pairs, before changes usd_matrix_bounds_originals = {path: get_usd_matrix_bounds_pair(path) for path in tree_prim_paths} async def check_bundles(changed_prim, tracked_paths, debug_stamp): changed_path = changed_prim.GetPath() controller.set(debug_stamp_attribute, debug_stamp) await controller.evaluate() graph_context = graph.get_default_graph_context() container = graph_context.get_output_bundle(read_prims_node, "outputs_primsBundle") self.assertTrue(container.valid) child_bundles = container.get_child_bundles() self.assertEqual(len(child_bundles), len(tracked_paths)) for bundle in child_bundles: stamp_attr = bundle.get_attribute_by_name("_debugStamp") source_prim_path_attr = bundle.get_attribute_by_name("sourcePrimPath") self.assertTrue(source_prim_path_attr.is_valid()) source_prim_path = Sdf.Path(source_prim_path_attr.get()) self.assertTrue( source_prim_path in tracked_paths, f"{source_prim_path} not in {tracked_paths}!", ) source_self_changed = source_prim_path == changed_path source_ancestor_changed = source_prim_path.HasPrefix(changed_path) source_descendant_changed = changed_path.HasPrefix(source_prim_path) ( usd_world_matrix_before_change, usd_local_bounds_before_change, ) = usd_matrix_bounds_originals[source_prim_path] ( usd_world_matrix_after_change, usd_local_bounds_after_change, ) = get_usd_matrix_bounds_pair(source_prim_path) usd_world_matrix_changed = usd_world_matrix_before_change != usd_world_matrix_after_change usd_local_bounds_changed = usd_local_bounds_before_change != usd_local_bounds_after_change # If the source is geometry (not an xform), # then changes to the ancestors will # NOT cause a change to the local bound source_prim = stage.GetPrimAtPath(source_prim_path) self.assertTrue(source_prim.IsValid()) ancestor_changed_local_bound = source_ancestor_changed and source_prim.IsA(UsdGeom.Xform) # The logic below breaks for structural stage changes, # which is disabled by passing 0 for debug_stamp. if debug_stamp > 0: # We add some tests to verify this complicated unit test itself self.assertEqual( usd_world_matrix_changed, source_self_changed or source_ancestor_changed, f"{source_prim_path} => expected world matrix change", ) self.assertEqual( usd_local_bounds_changed, source_self_changed or source_descendant_changed or ancestor_changed_local_bound, f"{source_prim_path} => expected local bounds change", ) expected_stamp = None world_matrix_attr = bundle.get_attribute_by_name("worldMatrix") if compute_world_matrix: # Compare world matrix in USD and bundle self.assertTrue( world_matrix_attr.is_valid(), f"Bundle for {source_prim_path} is missing worldMatrix", ) bundle_world_matrix = np.array(world_matrix_attr.get()) stage_world_matrix = np.array(usd_world_matrix_after_change).flatten() np.testing.assert_array_equal( stage_world_matrix, bundle_world_matrix, f"{source_prim_path} worldMatrix mismatch", ) if debug_stamp > 0: # Check how the world matrix was changed if source_self_changed: expected_stamp = debug_stamp elif source_ancestor_changed: expected_stamp = debug_stamp + 10000000 else: self.assertFalse( world_matrix_attr.is_valid(), f"Bundle for {source_prim_path} should not contain worldMatrix", ) bbox_transform_attr = bundle.get_attribute_by_name("bboxTransform") bbox_min_corner_attr = bundle.get_attribute_by_name("bboxMinCorner") bbox_max_corner_attr = bundle.get_attribute_by_name("bboxMaxCorner") if compute_bounding_box: # Compare local bound in USD and bundle self.assertTrue( bbox_transform_attr.is_valid(), f"Bundle for {source_prim_path} is missing bboxTransform", ) self.assertTrue( bbox_min_corner_attr.is_valid(), f"Bundle for {source_prim_path} is missing bboxMinCorner", ) self.assertTrue( bbox_max_corner_attr.is_valid(), f"Bundle for {source_prim_path} is missing bboxMaxCorner", ) bundle_bbox_transform = np.array(bbox_transform_attr.get()) bundle_bbox_min_corner = np.array(bbox_min_corner_attr.get()) bundle_bbox_max_corner = np.array(bbox_max_corner_attr.get()) stage_bbox = usd_local_bounds_after_change.GetBox() stage_bbox_transform = np.array(usd_local_bounds_after_change.GetMatrix()).flatten() stage_bbox_min_corner = np.array(stage_bbox.GetMin()) stage_bbox_max_corner = np.array(stage_bbox.GetMax()) np.testing.assert_array_equal( stage_bbox_transform, bundle_bbox_transform, f"{source_prim_path} bbox_transform mismatch", ) np.testing.assert_array_equal( stage_bbox_min_corner, bundle_bbox_min_corner, f"{source_prim_path} bbox_min_corner mismatch", ) np.testing.assert_array_equal( stage_bbox_max_corner, bundle_bbox_max_corner, f"{source_prim_path} bbox_max_corner mismatch", ) if debug_stamp > 0: # Check how the local bounds were changed if source_self_changed: expected_stamp = debug_stamp elif source_descendant_changed: expected_stamp = debug_stamp + 1000000 elif ancestor_changed_local_bound: expected_stamp = debug_stamp + 10000000 else: self.assertFalse( bbox_transform_attr.is_valid(), f"Bundle for {source_prim_path} should not contain bboxTransform", ) self.assertFalse( bbox_min_corner_attr.is_valid(), f"Bundle for {source_prim_path} should not contain bboxMinCorner", ) self.assertFalse( bbox_max_corner_attr.is_valid(), f"Bundle for {source_prim_path} should not contain bboxMaxCorner", ) if debug_stamp > 0: # Check the debug stamp actual_stamp = stamp_attr.get() if stamp_attr.is_valid() else 0 if expected_stamp is None: self.assertNotEqual( actual_stamp % 1000000, debug_stamp, f"{source_prim_path} shouldn't be stamped in this update!", ) else: self.assertEqual( actual_stamp, expected_stamp, f"{source_prim_path} had a wrong stamp!", ) async def run_sub_tests(i, j, debug_stamp): # Track these two prims tracked_pair_paths = [track_prim_paths[i], track_prim_paths[j]] omni.kit.commands.execute( "SetRelationshipTargets", relationship=stage.GetPropertyAtPath(f"{test_graph_path}/Read.inputs:prims"), targets=tracked_pair_paths, ) # We expect a full evaluation here, since we changed the input prims # We don't check that in this test that relates to hierarchy only await controller.evaluate() # Visit all prims in the hierarchy, # scale them, checking the bundle against the USD data (attr change test) # Then delete the scale attribute, and check again (attr resync remove test) # Then re-create the scale attribute, and check again (attr resync create test) # Then delete the prim (and subtree), and check again (prim resync remove test) # Then re-create the subtree, and check again (prim resync create test) for prim_path in change_prim_paths: prim = stage.GetPrimAtPath(prim_path) title = f"change_prim_paths={[prim_path]}, track_prim_paths={tracked_pair_paths}, debug_stamp={debug_stamp}..." with self.subTest(f"Change scale attr, {title}"): # Change the scale UsdGeom.XformCommonAPI(prim).SetScale(test_scale) # Check that the change is picked up debug_stamp += 1 await check_bundles(prim, tracked_pair_paths, debug_stamp) with self.subTest(f"Delete scale attr, {title}"): # Delete the scale property. # This should reset it back to one. prim.RemoveProperty("xformOp:scale") # Check that the change is picked up debug_stamp += 1 await check_bundles(prim, tracked_pair_paths, debug_stamp) with self.subTest(f"Create scale attr, {title}"): # Create the scale property back, and change it. prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Float3, False).Set(test_scale) # Check that the change is picked up debug_stamp += 1 await check_bundles(prim, tracked_pair_paths, debug_stamp) with self.subTest(f"Delete prim, {title}"): stage.RemovePrim(prim_path) # The deleted prim might be a tracked one valid_tracked_pair_paths = [ path for path in tracked_pair_paths if stage.GetPrimAtPath(path).IsValid() ] # Check that the change is picked up debug_stamp += 1 # NOTE: If the deleted prim was a tracked prim, # the ReadPrimsV2 node will currently do a full update await check_bundles( prim, valid_tracked_pair_paths, debug_stamp if len(valid_tracked_pair_paths) == 2 else 0, ) with self.subTest(f"Create prim, {title}"): # Restore deleted sub-tree (and reset scale) define_hierarchies(prim_path) # Check that the change is picked up (wo stamp checking for now) # TODO: We should also do stamp checking here, but couldn't get that working yet. await check_bundles(prim, tracked_pair_paths, 0) return debug_stamp # Iterate over all possible pairs of tree prims for i in range(len(track_prim_paths) - 1): for j in range(i + 1, len(track_prim_paths)): debug_stamp = await run_sub_tests(i, j, debug_stamp)
17,673
Python
46.005319
127
0.529056
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_bundle_attribute_nodes.py
"""Basic tests of the bundled attribute nodes""" import numpy import omni.graph.core as og import omni.graph.core.tests as ogts # ====================================================================== class TestBundleAttributeNodes(ogts.OmniGraphTestCase): """Run a simple unit test that exercises graph functionality""" # ---------------------------------------------------------------------- def compare_values(self, expected_value, actual_value, decimal, error_message): """Generic assert comparison which uses introspection to choose the correct method to compare the data values""" # dbg(f"----Comparing {actual_value} with expected {expected_value}") if isinstance(expected_value, (list, tuple)): # If the numpy module is not available array values cannot be tested so silently succeed if numpy is None: return # Values are returned as numpy arrays so convert the expected value and use numpy to do the comparison numpy.testing.assert_almost_equal( actual_value, numpy.array(expected_value), decimal=decimal, err_msg=error_message ) elif isinstance(expected_value, float): self.assertAlmostEqual(actual_value, expected_value, decimal, error_message) else: self.assertEqual(actual_value, expected_value, error_message) # ---------------------------------------------------------------------- async def test_bundle_functions(self): """Test bundle functions""" await ogts.load_test_file("TestBundleAttributeNodes.usda", use_caller_subdirectory=True) # These prims are known to be in the file bundle_prim = "/defaultPrim/inputData" # However since we no longer spawn OgnPrim for bundle-connected prims, we don't expect it to be # in OG. (Verified in a different test) # self.assertEqual([], ogts.verify_node_existence([bundle_prim])) contexts = og.get_compute_graph_contexts() self.assertIsNotNone(contexts) expected_values = { "boolAttr": (1, ("bool", og.BaseDataType.BOOL, 1, 0, og.AttributeRole.NONE)), "intAttr": (1, ("int", og.BaseDataType.INT, 1, 0, og.AttributeRole.NONE)), "int64Attr": (1, ("int64", og.BaseDataType.INT64, 1, 0, og.AttributeRole.NONE)), "uint64Attr": (1, ("uint64", og.BaseDataType.UINT64, 1, 0, og.AttributeRole.NONE)), "halfAttr": (1, ("half", og.BaseDataType.HALF, 1, 0, og.AttributeRole.NONE)), "floatAttr": (1, ("float", og.BaseDataType.FLOAT, 1, 0, og.AttributeRole.NONE)), "doubleAttr": (1, ("double", og.BaseDataType.DOUBLE, 1, 0, og.AttributeRole.NONE)), "tokenAttr": (1, ("token", og.BaseDataType.TOKEN, 1, 0, og.AttributeRole.NONE)), "stringAttr": (10, ("string", og.BaseDataType.UCHAR, 1, 1, og.AttributeRole.TEXT)), # We don't read relationship attributes in OgnReadPrimBundle # "relSingleAttr": (1, ("rel", og.BaseDataType.RELATIONSHIP, 1, 0, og.AttributeRole.NONE)), "int2Attr": (1, ("int[2]", og.BaseDataType.INT, 2, 0, og.AttributeRole.NONE)), "half2Attr": (1, ("half[2]", og.BaseDataType.HALF, 2, 0, og.AttributeRole.NONE)), "float2Attr": (1, ("float[2]", og.BaseDataType.FLOAT, 2, 0, og.AttributeRole.NONE)), "double2Attr": (1, ("double[2]", og.BaseDataType.DOUBLE, 2, 0, og.AttributeRole.NONE)), "int3Attr": (1, ("int[3]", og.BaseDataType.INT, 3, 0, og.AttributeRole.NONE)), "half3Attr": (1, ("half[3]", og.BaseDataType.HALF, 3, 0, og.AttributeRole.NONE)), "float3Attr": (1, ("float[3]", og.BaseDataType.FLOAT, 3, 0, og.AttributeRole.NONE)), "double3Attr": (1, ("double[3]", og.BaseDataType.DOUBLE, 3, 0, og.AttributeRole.NONE)), "int4Attr": (1, ("int[4]", og.BaseDataType.INT, 4, 0, og.AttributeRole.NONE)), "half4Attr": (1, ("half[4]", og.BaseDataType.HALF, 4, 0, og.AttributeRole.NONE)), "float4Attr": (1, ("float[4]", og.BaseDataType.FLOAT, 4, 0, og.AttributeRole.NONE)), "double4Attr": (1, ("double[4]", og.BaseDataType.DOUBLE, 4, 0, og.AttributeRole.NONE)), "boolArrayAttr": (65, ("bool[]", og.BaseDataType.BOOL, 1, 1, og.AttributeRole.NONE)), "intArrayAttr": (5, ("int[]", og.BaseDataType.INT, 1, 1, og.AttributeRole.NONE)), "floatArrayAttr": (5, ("float[]", og.BaseDataType.FLOAT, 1, 1, og.AttributeRole.NONE)), "doubleArrayAttr": (5, ("double[]", og.BaseDataType.DOUBLE, 1, 1, og.AttributeRole.NONE)), "tokenArrayAttr": (3, ("token[]", og.BaseDataType.TOKEN, 1, 1, og.AttributeRole.NONE)), "int2ArrayAttr": (5, ("int[2][]", og.BaseDataType.INT, 2, 1, og.AttributeRole.NONE)), "float2ArrayAttr": (5, ("float[2][]", og.BaseDataType.FLOAT, 2, 1, og.AttributeRole.NONE)), "double2ArrayAttr": (5, ("double[2][]", og.BaseDataType.DOUBLE, 2, 1, og.AttributeRole.NONE)), "point3fArrayAttr": (3, ("pointf[3][]", og.BaseDataType.FLOAT, 3, 1, og.AttributeRole.POSITION)), "qhAttr": (1, ("quath[4]", og.BaseDataType.HALF, 4, 0, og.AttributeRole.QUATERNION)), "qfAttr": (1, ("quatf[4]", og.BaseDataType.FLOAT, 4, 0, og.AttributeRole.QUATERNION)), "qdAttr": (1, ("quatd[4]", og.BaseDataType.DOUBLE, 4, 0, og.AttributeRole.QUATERNION)), "m2dAttr": (1, ("matrixd[2]", og.BaseDataType.DOUBLE, 4, 0, og.AttributeRole.MATRIX)), "m3dAttr": (1, ("matrixd[3]", og.BaseDataType.DOUBLE, 9, 0, og.AttributeRole.MATRIX)), "m4dAttr": (1, ("matrixd[4]", og.BaseDataType.DOUBLE, 16, 0, og.AttributeRole.MATRIX)), } for context in contexts: bundle = context.get_bundle(bundle_prim) attr_names, attr_types = bundle.get_attribute_names_and_types() attr_count = bundle.get_attribute_data_count() self.assertEqual(attr_count, len(expected_values)) attr_names, attr_types = bundle.get_attribute_names_and_types() self.assertCountEqual(attr_names, list(expected_values.keys())) # The name map has to be created because the output bundle contents are not in a defined order but the # different array elements do correspond to each other. By creating a mapping from the name to the index # at which it was found the other elements can be mapped exactly. expected_types = [expected_values[name][1] for name in attr_names] expected_counts = [expected_values[name][0] for name in attr_names] type_name_and_properties = [] new_constructed_types = [] for attr_type in attr_types: base_type = attr_type.base_type tuple_count = attr_type.tuple_count array_depth = attr_type.array_depth role = attr_type.role type_name_and_properties.append( (attr_type.get_ogn_type_name(), base_type, tuple_count, array_depth, role) ) new_constructed_types.append(og.Type(base_type, tuple_count, array_depth, role)) self.assertCountEqual(type_name_and_properties, expected_types) self.assertEqual(new_constructed_types, attr_types) attrs = bundle.get_attribute_data() attr_elem_counts = [] for attr in attrs: try: elem_count = og.Controller.get_array_size(attr) except AttributeError: elem_count = 1 attr_elem_counts.append(elem_count) self.assertEqual(attr_elem_counts, expected_counts)
7,784
Python
62.292682
120
0.594938
omniverse-code/kit/exts/omni.graph.nodes/omni/graph/nodes/tests/test_settings_removal.py
"""Suite of tests to exercise the implications of the removal of various settings.""" from typing import Any, Dict, List import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.test import omni.usd from pxr import Gf, OmniGraphSchema KEYS = og.Controller.Keys """Shorten keyword names""" FILE_FORMAT_VERSION_INTRODUCING_SCHEMAS = Gf.Vec2i(1, 4) """File format version where the schema prims became the default""" CURRENT_FORMAT_VERSION = Gf.Vec2i(1, 7) """The current version of settings""" # ============================================================================================================== def _verify_stage_contents(expected_contents: Dict[str, str], expected_inactive_prims: List[str] = None) -> List[str]: """Confirm that a stage contains the hierarchical prim type structure passed in. Args: expected_contents: Dictionary of primPath:primType of stage contents that were expected. e.g. a two level prim hierarchy with an Xform and a Mesh would be passd in as {"/MyXform": "Xform", "/MyXform/MyMesh": "Mesh"} expected_inactive_prims: A list of keys to the above whose prims are also expected to be inactive Returns: A list of a description of the differences found (may not be complete), or [] if all was as expected """ stage = omni.usd.get_context().get_stage() if stage is None: return [] if not expected_contents else [f"Stage is empty but expected to find {expected_contents}"] # Copy of the dictionary to removed found prims from that should be empty when done inactive_list = expected_inactive_prims or [] not_found = expected_contents.copy() errors_found = [] iterator = iter(stage.TraverseAll()) for prim in iterator: prim_path = str(prim.GetPrimPath()) prim_type = prim.GetTypeName() # Ignore these boilerplate prims if prim_path.startswith("/Omniverse") or prim_path.startswith("/Render"): continue if prim_path not in expected_contents: errors_found.append( f"Prim '{prim_path}' of type '{prim_type}' was not in the expected list {expected_contents}" ) continue if expected_contents[prim_path] != prim_type: errors_found.append( f"Prim '{prim_path}' expected to be of type '{expected_contents[prim_path]}' but was '{prim_type}'" ) continue if prim_path in inactive_list and prim.IsActive(): errors_found.append(f"Prim '{prim_path}' of type '{prim_type}' expected to be inactive but was not") if prim.GetTypeName() == "OmniGraphNode": # Confirm that the expected schema attributes exist on the node as non-custom types node_prim = OmniGraphSchema.OmniGraphNode(prim) if not node_prim: errors_found.append(f"Prim '{prim_path}' could not be interpreted as OmniGraphNode") else: type_attr = node_prim.GetNodeTypeAttr() if not type_attr.IsValid() or type_attr.IsCustom(): errors_found.append(f"Node '{prim_path}' did not have schema attribute node:type") version_attr = node_prim.GetNodeTypeVersionAttr() if not version_attr.IsValid() or version_attr.IsCustom(): errors_found.append(f"Node '{prim_path}' did not have schema attribute node:typeVersion") elif prim.GetTypeName() == "OmniGraph": # Confirm that the expected schema attributes exist on the graph as non-custom types graph_prim = OmniGraphSchema.OmniGraph(prim) if not graph_prim: errors_found.append(f"Prim '{prim_path}' could not be interpreted as OmniGraph") else: evaluator_attr = graph_prim.GetEvaluatorTypeAttr() if not evaluator_attr.IsValid() or evaluator_attr.IsCustom(): errors_found.append(f"Graph '{prim_path}' did not have schema attribute evaluatorType") version_attr = graph_prim.GetFileFormatVersionAttr() if not version_attr.IsValid() or version_attr.IsCustom(): errors_found.append(f"Graph '{prim_path}' did not have schema attribute fileFormatVersion") backing_attr = graph_prim.GetFabricCacheBackingAttr() if not backing_attr.IsValid() or backing_attr.IsCustom(): errors_found.append(f"Graph '{prim_path}' did not have schema attribute fabricCacheBacking") pipeline_attr = graph_prim.GetPipelineStageAttr() if not pipeline_attr.IsValid() or pipeline_attr.IsCustom(): errors_found.append(f"Graph '{prim_path}' did not have schema attribute pipelineStage") evaluation_mode_attr = graph_prim.GetEvaluationModeAttr() if not evaluation_mode_attr.IsValid() or evaluation_mode_attr.IsCustom(): errors_found.append(f"Graph '{prim_path}' did not have schema attribute evaluationMode") del not_found[prim_path] for prim_path, prim_type in not_found.items(): errors_found.append(f"Prim '{prim_path}' of type '{prim_type}' was expected but not found") return errors_found # ============================================================================================================== def _verify_graph_settings(graph_prim_path: str, expected_settings: Dict[str, Any]): """Verify that the graph prim has the expected settings (after conversion or loading of a new file) Args: graph_prim_path: Path to the graph's prim expected_settings: Dictionary of attributeName:expectedValue for all of the settings Returns: List of descriptions of the differences found or [] if all was as expected """ errors_found = [] stage = omni.usd.get_context().get_stage() graph_prim = stage.GetPrimAtPath(graph_prim_path) if stage is not None else None if graph_prim is None: return [f"Could not find prim `{graph_prim_path}` that is supposed to hold the settings"] for attribute_name, expected_value in expected_settings.items(): attribute = graph_prim.GetAttribute(attribute_name) if not attribute.IsValid(): errors_found.append(f"Could not find setting attribute '{attribute_name}' on prim '{graph_prim_path}'") else: actual_value = attribute.Get() if actual_value != expected_value: errors_found.append( f"Expected value of setting '{attribute_name}' was '{expected_value}', got '{actual_value}'" ) return errors_found # ============================================================================================================== class TestSettingsRemoval(ogts.OmniGraphTestCase): """Wrapper for tests to verify backward compatibility for the removal of the settings prim""" # Settings values when nothing is specified. DEFAULT_SETTINGS = { "evaluator:type": "push", "fileFormatVersion": CURRENT_FORMAT_VERSION, "fabricCacheBacking": "Shared", "pipelineStage": "pipelineStageSimulation", "evaluationMode": "Automatic", } # ---------------------------------------------------------------------- async def test_create_graph(self): """Test creation of a simple graph""" og.Controller.edit("/SimpleGraph", {KEYS.CREATE_NODES: ("NoOp", "omni.graph.nodes.Noop")}) await og.Controller.evaluate() results = _verify_stage_contents({"/SimpleGraph": "OmniGraph", "/SimpleGraph/NoOp": "OmniGraphNode"}) self.assertEqual([], results) results = _verify_graph_settings("/SimpleGraph", self.DEFAULT_SETTINGS) self.assertEqual([], results) # ---------------------------------------------------------------------- async def test_no_settings_1_1(self): """Test that a v1.1 file with a graph and no settings is converted correctly""" (result, error) = await ogts.load_test_file("SettingsMissingFromGraph_v1_1.usda", use_caller_subdirectory=True) self.assertTrue(result, error) results = _verify_stage_contents( { "/defaultGraph": "OmniGraph", } ) self.assertEqual([], results) results = _verify_graph_settings("/defaultGraph", self.DEFAULT_SETTINGS) self.assertEqual([], results) # ---------------------------------------------------------------------- async def test_no_settings_post_schema(self): """Test that an updated file without explicit settings has the default values""" (result, error) = await ogts.load_test_file( "SettingsMissingFromGraph_postSchema.usda", use_caller_subdirectory=True ) self.assertTrue(result, error) results = _verify_stage_contents( { "/defaultGraph": "OmniGraph", } ) self.assertEqual([], results) results = _verify_graph_settings("/defaultGraph", self.DEFAULT_SETTINGS) self.assertEqual([], results) # ---------------------------------------------------------------------- async def test_no_graph_1_0(self): """Test that a v1.0 file that has settings data without FC and pipeline settings is converted correctly""" (result, error) = await ogts.load_test_file("SettingsWithoutGraph_v1_0.usda", use_caller_subdirectory=True) self.assertTrue(result, error) results = _verify_stage_contents( { "/__graphUsingSchemas": "OmniGraph", "/__graphUsingSchemas/NoOp": "OmniGraphNode", "/__graphUsingSchemas/computegraphSettings": "ComputeGraphSettings", }, ["/__graphUsingSchemas/computegraphSettings"], ) self.assertEqual([], results) results = _verify_graph_settings( "/__graphUsingSchemas", { "evaluator:type": "push", "fileFormatVersion": CURRENT_FORMAT_VERSION, "fabricCacheBacking": "Shared", "pipelineStage": "pipelineStageSimulation", "evaluationMode": "Automatic", }, ) self.assertEqual([], results) # ---------------------------------------------------------------------- async def test_no_graph_1_1(self): """Test that a v1.1 file with an implicit graph is converted correctly""" (result, error) = await ogts.load_test_file("SettingsWithoutGraph_v1_1.usda", use_caller_subdirectory=True) self.assertTrue(result, error) results = _verify_stage_contents( { "/__graphUsingSchemas": "OmniGraph", "/__graphUsingSchemas/NoOp": "OmniGraphNode", "/__graphUsingSchemas/computegraphSettings": "ComputeGraphSettings", }, ["/__graphUsingSchemas/computegraphSettings"], ) self.assertEqual([], results) results = _verify_graph_settings( "/__graphUsingSchemas", { "evaluator:type": "push", "fileFormatVersion": CURRENT_FORMAT_VERSION, "fabricCacheBacking": "StageWithHistory", "pipelineStage": "pipelineStagePreRender", "evaluationMode": "Automatic", }, ) self.assertEqual([], results) # ---------------------------------------------------------------------- async def test_no_graph_over_1_1(self): """Test that a v1.1 file with a layer in it is converted correctly. The file has two layers of graph nodes because the layered graph nodes will not be composed unless there is a node at the top level.""" (result, error) = await ogts.load_test_file( "SettingsWithoutGraphWithOver_v1_1.usda", use_caller_subdirectory=True ) self.assertTrue(result, error) results = _verify_stage_contents( { "/World": "World", "/World/layeredGraph": "", "/World/layeredGraph/innerGraph": "OmniGraph", "/World/layeredGraph/innerGraph/NoOpOver": "OmniGraphNode", "/World/layeredGraph/innerGraph/computegraphSettings": "ComputeGraphSettings", "/World/__graphUsingSchemas": "OmniGraph", "/World/__graphUsingSchemas/NoOp": "OmniGraphNode", }, [ "/World/layeredGraph/innerGraph/computegraphSettings", ], ) self.assertEqual([], results) results = _verify_graph_settings( "/World/__graphUsingSchemas", { "evaluator:type": "push", "fileFormatVersion": CURRENT_FORMAT_VERSION, "fabricCacheBacking": "Shared", "pipelineStage": "pipelineStageSimulation", "evaluationMode": "Automatic", }, ) self.assertEqual([], results) results = _verify_graph_settings( "/World/layeredGraph/innerGraph", { "evaluator:type": "push", "fileFormatVersion": FILE_FORMAT_VERSION_INTRODUCING_SCHEMAS, "fabricCacheBacking": "StageWithHistory", "pipelineStage": "pipelineStagePreRender", "evaluationMode": "Automatic", }, ) self.assertEqual([], results) # ---------------------------------------------------------------------- async def test_no_graph_child_1_1(self): """Test that a v1.1 file with a graph underneath a World prim is converted correctly""" (result, error) = await ogts.load_test_file("SettingsWithChildGraph_v1_1.usda", use_caller_subdirectory=True) self.assertTrue(result, error) results = _verify_stage_contents( { "/World": "World", "/World/__graphUsingSchemas": "OmniGraph", "/World/__graphUsingSchemas/NoOp": "OmniGraphNode", "/World/__graphUsingSchemas/computegraphSettings": "ComputeGraphSettings", }, ["/World/__graphUsingSchemas/computegraphSettings"], ) self.assertEqual([], results) results = _verify_graph_settings( "/World/__graphUsingSchemas", { "evaluator:type": "push", "fileFormatVersion": CURRENT_FORMAT_VERSION, "fabricCacheBacking": "StageWithHistory", "pipelineStage": "pipelineStagePreRender", "evaluationMode": "Automatic", }, ) self.assertEqual([], results) # ---------------------------------------------------------------------- async def test_with_graph_1_1(self): """Test that a v1.1 file with an explicit graph and settings is converted correctly""" (result, error) = await ogts.load_test_file("SettingsWithGraph_v1_1.usda", use_caller_subdirectory=True) self.assertTrue(result, error) results = _verify_stage_contents( { "/pushGraph": "OmniGraph", "/pushGraph/NoOp": "OmniGraphNode", "/pushGraph/computegraphSettings": "ComputeGraphSettings", }, ["/pushGraph/computegraphSettings"], ) self.assertEqual([], results) results = _verify_graph_settings( "/pushGraph", { "evaluator:type": "push", "fileFormatVersion": CURRENT_FORMAT_VERSION, "fabricCacheBacking": "StageWithHistory", "pipelineStage": "pipelineStagePreRender", "evaluationMode": "Automatic", }, ) self.assertEqual([], results) # ---------------------------------------------------------------------- async def test_with_bad_backing_name(self): """Test that a file using the backing name with a typo gets the correct name""" (result, error) = await ogts.load_test_file("SettingsWithBadBackingName.usda", use_caller_subdirectory=True) self.assertTrue(result, error) results = _verify_stage_contents( { "/pushGraph": "OmniGraph", "/pushGraph/NoOp": "OmniGraphNode", "/pushGraph/computegraphSettings": "ComputeGraphSettings", }, ["/pushGraph/computegraphSettings"], ) self.assertEqual([], results) results = _verify_graph_settings( "/pushGraph", { "evaluator:type": "push", "fileFormatVersion": CURRENT_FORMAT_VERSION, "fabricCacheBacking": "StageWithHistory", "pipelineStage": "pipelineStagePreRender", "evaluationMode": "Automatic", }, ) self.assertEqual([], results) # ---------------------------------------------------------------------- async def test_with_graph_post_schema(self): """Test that an updated file with a graph and a node is read safely""" (result, error) = await ogts.load_test_file("SettingsWithGraph_postSchema.usda", use_caller_subdirectory=True) self.assertTrue(result, error) results = _verify_stage_contents({"/pushGraph": "OmniGraph", "/pushGraph/NoOp": "OmniGraphNode"}) self.assertEqual([], results) results = _verify_graph_settings( "/pushGraph", { "evaluator:type": "push", "fileFormatVersion": CURRENT_FORMAT_VERSION, "fabricCacheBacking": "StageWithHistory", "pipelineStage": "pipelineStagePreRender", "evaluationMode": "Automatic", }, ) self.assertEqual([], results) # ============================================================================================================== class TestSettingsPreservation(ogts.OmniGraphTestCase): """Wrapper for tests to confirm old files can still be safely loaded""" # ---------------------------------------------------------------------- async def test_no_settings_1_1(self): """Test that a v1.1 file with a graph and no settings is read safely""" (result, error) = await ogts.load_test_file("SettingsMissingFromGraph_v1_1.usda", use_caller_subdirectory=True) self.assertTrue(result, error) results = _verify_stage_contents( { "/defaultGraph": "OmniGraph", } ) self.assertEqual([], results) # ---------------------------------------------------------------------- async def test_no_graph_1_1(self): """Test that a v1.1 file with a scene with a global implicit graph is read safely""" (result, error) = await ogts.load_test_file("SettingsWithoutGraph_v1_1.usda", use_caller_subdirectory=True) self.assertTrue(result, error) results = _verify_stage_contents( { "/__graphUsingSchemas/computegraphSettings": "ComputeGraphSettings", "/__graphUsingSchemas/NoOp": "OmniGraphNode", "/__graphUsingSchemas": "OmniGraph", } ) self.assertEqual([], results) # ---------------------------------------------------------------------- async def test_with_graph_1_1(self): """Test that a v1.1 file with a graph and settings is read safely""" (result, error) = await ogts.load_test_file("SettingsWithGraph_v1_1.usda", use_caller_subdirectory=True) self.assertTrue(result, error) results = _verify_stage_contents( { "/pushGraph": "OmniGraph", "/pushGraph/computegraphSettings": "ComputeGraphSettings", "/pushGraph/NoOp": "OmniGraphNode", } ) self.assertEqual([], results) # ---------------------------------------------------------------------- async def test_with_bad_connections(self): """Test that a file with old prims fails migration""" (result, error) = await ogts.load_test_file("SettingsWithBadConnections.usda", use_caller_subdirectory=True) self.assertTrue(result, error) stage = omni.usd.get_context().get_stage() graph_prim = stage.GetPrimAtPath("/pushGraph") self.assertTrue(graph_prim.IsValid()) self.assertEqual("OmniGraph", graph_prim.GetTypeName()) settings_prim = stage.GetPrimAtPath("/pushGraph/computegraphSettings") self.assertTrue(settings_prim.IsValid()) self.assertEqual("ComputeGraphSettings", settings_prim.GetTypeName()) node_prim = stage.GetPrimAtPath("/pushGraph/BundleInspector") self.assertTrue(node_prim.IsValid()) self.assertEqual("OmniGraphNode", node_prim.GetTypeName())
21,073
Python
46.040178
119
0.560385
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/scripts/style.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 functools import lru_cache from omni.ui import color as cl from omni.ui import constant as fl # If declared as global instead of a function, build doc for omni.kit.window.property will fail, what?? @lru_cache() def get_radio_mark_url() -> str: import omni.kit.app return f"{omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)}/data/icons/radiomark.svg" MENU_TITLE = cl.shade(cl("#25282A")) MENU_BACKGROUND = cl.shade(cl("#25282ACC")) MENU_MEDIUM = cl.shade(cl("#6E6E6E")) MENU_LIGHT = cl.shade(cl("#D6D6D6")) MENU_SELECTION = cl.shade(cl("#34C7FF3B")) MENU_SELECTION_BORDER = cl.shade(cl("#34C7FF")) MENU_ITEM_CHECKMARK_COLOR = cl.shade(cl("#34C7FF")) MENU_ITEM_MARGIN = fl.shade(5) MENU_ITEM_MARGIN_HEIGHT = fl.shade(3) MENU_STYLE = { "Menu.Title": {"color": MENU_TITLE, "background_color": 0x0}, "Menu.Title:hovered": { "background_color": MENU_SELECTION, "border_width": 1, "border_color": MENU_SELECTION_BORDER, }, "Menu.Title:pressed": {"background_color": MENU_SELECTION}, "Menu.Item": { "color": MENU_LIGHT, "margin_width": MENU_ITEM_MARGIN, "margin_HEIGHT": MENU_ITEM_MARGIN_HEIGHT, }, "Menu.Item.CheckMark": {"color": MENU_ITEM_CHECKMARK_COLOR}, "Menu.Separator": { "color": MENU_MEDIUM, "margin_HEIGHT": MENU_ITEM_MARGIN_HEIGHT, "border_width": 1.5, }, "Menu.Window": { "background_color": MENU_BACKGROUND, "border_width": 0, "border_radius": 0, "background_selected_color": MENU_SELECTION, "secondary_padding": 1, "secondary_selected_color": MENU_SELECTION_BORDER, "margin": 2, }, "MenuItem": { "background_selected_color": MENU_SELECTION, "secondary_padding": 1, "secondary_selected_color": MENU_SELECTION_BORDER, }, }
2,318
Python
33.102941
126
0.664366
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/scripts/__init__.py
from .context_menu import * from .viewport_menu import *
57
Python
18.333327
28
0.754386
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/scripts/context_menu.py
# Copyright (c) 2020-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. # """The context menus""" import os, sys import weakref import copy import asyncio import carb import carb.events import omni.kit.ui import omni.kit.usd.layers as layers from omni import ui from functools import partial from typing import Callable, List, Union, Tuple from pathlib import Path from pxr import Usd, Sdf, Gf, Tf, UsdShade, UsdGeom, Trace, UsdUtils, Kind from .singleton import Singleton _extension_instance = None TEST_DATA_PATH = "" SETTING_HIDE_CREATE_MENU = "/exts/omni.kit.context_menu/hideCreateMenu" class ContextMenuEventType: ADDED = 0 # New menu entry is added REMOVED = 0 # Menu entry is removed @Singleton class _CustomMenuDict: """ The singleton object that holds custom context menu which is private """ def __init__(self) -> None: self.__custom_menu_dict = {} self.__counter = 0 self.__event_stream = carb.events.get_events_interface().create_event_stream() def add_menu(self, menu: Union[str, list], index: str, extension_id: str) -> int: menu_id = self.__counter if not index in self.__custom_menu_dict: self.__custom_menu_dict[index] = {} if not extension_id in self.__custom_menu_dict[index]: self.__custom_menu_dict[index][extension_id] = {} self.__custom_menu_dict[index][extension_id][menu_id] = menu self.__counter += 1 self.__event_stream.dispatch(ContextMenuEventType.ADDED, payload={"index": index, "extension_id": extension_id}) return menu_id def remove_menu(self, menu_id: int, index: str, extension_id: str) -> None: # NOTE: removing a menu dictionary that does not exist is not valid if ( index in self.__custom_menu_dict and extension_id in self.__custom_menu_dict[index] and menu_id in self.__custom_menu_dict[index][extension_id] ): del self.__custom_menu_dict[index][extension_id][menu_id] self.__event_stream.dispatch(ContextMenuEventType.REMOVED, payload={"index": index, "extension_id": extension_id}) return carb.log_error(f"remove_menu index:{index} extension_id:{extension_id} doesn't exist.") def get_menu_dict(self, index: str, extension_id: str) -> List[dict]: # NOTE: getting a menu dictionary that does not exist is valid and will return empty list if index in self.__custom_menu_dict and extension_id in self.__custom_menu_dict[index]: return self._merge_submenus(list(self.__custom_menu_dict[index][extension_id].values())) return [] ## merge submenus ## def _get_duplicate_item(self, compare_item: dict, item_list: list) -> bool: for item in item_list: if isinstance(compare_item["name"], str) and isinstance(item["name"], str): if item["name"] != "" and compare_item["name"] == item["name"]: return item elif isinstance(compare_item["name"], dict) and isinstance(item["name"], dict): if compare_item["name"].keys() == item["name"].keys(): return item return None def __merge_submenu(self, keys: list, main_item: dict, merge_item: dict) -> dict: for key in keys: if isinstance(main_item[key], str) and isinstance(merge_item[key], str): main_item[key] = copy.copy(main_item[key]) + merge_item[key] elif isinstance(main_item[key], list) and isinstance(merge_item[key], list): main_item[key] = main_item[key].copy() for item in merge_item[key]: duplicate_item = self._get_duplicate_item(item, main_item[key]) if duplicate_item: dup_item_name = duplicate_item["name"] if (not dup_item_name) or not (hasattr(dup_item_name, "keys")): if dup_item_name != "": carb.log_warn(f"_merge_submenu: failed to merge duplicate item {dup_item_name}") else: duplicate_item["name"] = self.__merge_submenu( dup_item_name.keys(), copy.copy(dup_item_name), item["name"] ) else: main_item[key].append(item) return main_item def _merge_submenus(self, main_list: list) -> list: """ merge submenus into new dict without changing the original """ new_list = [] for item in main_list: duplicate_item = self._get_duplicate_item(item, new_list) if duplicate_item: dup_item_name = duplicate_item["name"] if (not dup_item_name) or not (hasattr(dup_item_name, "keys")): if dup_item_name != "": carb.log_warn(f"_merge_submenus: failed to merge duplicate item {dup_item_name}") else: duplicate_item["name"] = self.__merge_submenu( dup_item_name.keys(), copy.copy(dup_item_name), item["name"] ) else: new_list.append(copy.copy(item)) return new_list def get_event_stream(self): return self.__event_stream class ContextMenuExtension(omni.ext.IExt): """Context menu core functionality. See omni.kit.viewport_legacy.context_menu for datailed usage. Example using viewport mouse event to trigger: .. code-block:: python class ContextMenu: def on_startup(self): # get window event stream import omni.kit.viewport_legacy viewport_win = get_viewport_interface().get_viewport_window() # on_mouse_event called when event dispatched self._stage_event_sub = viewport_win.get_mouse_event_stream().create_subscription_to_pop(self.on_mouse_event) def on_shutdown(self): # remove event self._stage_event_sub = None def on_mouse_event(self, event): # check its expected event if event.type != int(omni.kit.ui.MenuEventType.ACTIVATE): return # 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 # get parameters passed by event objects = {} objects["test_path"] = event.payload["test_path"] # setup objects, this is passed to all functions objects["test"] = "this is a test" # setup menu menu_list = [ # name is name shown on menu. (if name is "" then a menu spacer is added. Can be combined with show_fn) # glyph is icon shown on menu # name_fn funcion to get menu item name # show_fn funcion or list of functions used to decide if menu item is shown. All functions must return True to show # enabled_fn funcion or list of functions used to decide if menu item is enabled. All functions must return True to be enabled # onclick_fn function called when user clicks menu item # onclick_action action called when user clicks menu item # populate_fn a fucntion to be called to populate the menu. Can be combined with show_fn # appear_after a identifier of menu name. Used by custom menus and will allow cusom menu to change order {"name": "Test Menu", "glyph": "question.svg", "show_fn": [ContextMenu.has_reason_to_show, ContextMenu.has_another_reason_to_show], "onclick_fn": ContextMenu.clear_default_prim }, {"name": "", "show_fn": ContextMenu.has_another_reason_to_show}, {"populate_fn": context_menu.show_create_menu}, {"name": ""}, {"name": "Copy URL Link", "glyph": "menu_link.svg", "onclick_fn": ContextMenu.copy_prim_url}, ] # add custom menus menu_list += omni.kit.context_menu.get_menu_dict("MENU", "") menu_list += omni.kit.context_menu.get_menu_dict("MENU", "stagewindow") omni.kit.context_menu.reorder_menu_dict(menu_dict) # show menu context_menu.show_context_menu("stagewindow", objects, menu_list) # show_fn functions def has_reason_to_show(objects: dict): if not "test_path" in objects: return False return True def has_another_reason_to_show(objects: dict): if not "test_path" in objects: return False return True def copy_prim_url(objects: dict): try: import omni.kit.clipboard omni.kit.clipboard.copy("My hovercraft is full of eels") except ImportError: carb.log_warn("Could not import omni.kit.clipboard.") """ # ---------------------------------------------- menu global populate functions ---------------------------------------------- class uiMenu(ui.Menu): def __init__(self, *args, **kwargs): self.glyph = None self.submenu = False if "glyph" in kwargs: self.glyph = kwargs["glyph"] del kwargs["glyph"] if "submenu" in kwargs: self.submenu = kwargs["submenu"] del kwargs["submenu"] tearable = False if "tearable" in kwargs: tearable = kwargs["tearable"] del kwargs["tearable"] super().__init__(*args, **kwargs, menu_compatibility=False, tearable=tearable) class uiMenuItem(ui.MenuItem): def __init__(self, *args, **kwargs): self.glyph = None self.submenu = False if "glyph" in kwargs: self.glyph = kwargs["glyph"] del kwargs["glyph"] super().__init__(*args, **kwargs, menu_compatibility=False) class DefaultMenuDelegate(ui.MenuDelegate): EXTENSION_FOLDER_PATH = Path() ICON_PATH = EXTENSION_FOLDER_PATH.joinpath("data/icons") ICON_SIZE = 14 TEXT_SIZE = 18 ICON_SPACING = [7, 7] MARGIN_SIZE = [4, 4] SUBMENU_SPACING = 4 SUBMENU_ICON_SIZE = 11.7 COLOR_LABEL_ENABLED = 0xFFCCCCCC COLOR_LABEL_DISABLED = 0xFF6F6F6F COLOR_TICK_ENABLED = 0xFFCCCCCC COLOR_TICK_DISABLED = 0xFF4F4F4F COLOR_SEPARATOR = 0xFF6F6F6F # doc compiler breaks if `omni.kit.app.get_app()` or `carb.settings.get_settings()` is called try: EXTENSION_FOLDER_PATH = Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)) ICON_PATH = EXTENSION_FOLDER_PATH.joinpath("data/icons") ICON_SIZE = carb.settings.get_settings().get("exts/omni.kit.context_menu/icon_size") ICON_SPACING = carb.settings.get_settings().get("exts/omni.kit.context_menu/icon_spacing") TEXT_SIZE = carb.settings.get_settings().get("exts/omni.kit.context_menu/text_size") MARGIN_SIZE = carb.settings.get_settings().get("exts/omni.kit.context_menu/margin_size") SUBMENU_SPACING = carb.settings.get_settings().get("exts/omni.kit.context_menu/submenu_spacing") SUBMENU_ICON_SIZE = carb.settings.get_settings().get("exts/omni.kit.context_menu/submenu_icon_size") COLOR_LABEL_ENABLED = carb.settings.get_settings().get("exts/omni.kit.context_menu/color_label_enabled") COLOR_LABEL_DISABLED = carb.settings.get_settings().get("exts/omni.kit.context_menu/color_label_disabled") COLOR_TICK_ENABLED = carb.settings.get_settings().get("exts/omni.kit.context_menu/color_tick_enabled") COLOR_TICK_DISABLED = carb.settings.get_settings().get("exts/omni.kit.context_menu/color_tick_disabled") COLOR_SEPARATOR = carb.settings.get_settings().get("exts/omni.kit.context_menu/color_separator") except Exception as exc: carb.log_warn(f"DefaultMenuDelegate: failed to get EXTENSION_FOLDER_PATH and deafults {exc}") def get_style(self): return {"Label::Enabled": {"margin_width": self.MARGIN_SIZE[0], "margin_height": self.MARGIN_SIZE[1], "color": self.COLOR_LABEL_ENABLED}, "Label::Disabled": {"margin_width": self.MARGIN_SIZE[0], "margin_height": self.MARGIN_SIZE[1], "color": self.COLOR_LABEL_DISABLED}, "Image::Icon": {"margin_width": 0, "margin_height": 0, "color": self.COLOR_LABEL_ENABLED}, "Image::SubMenu": {"image_url": f"{self.ICON_PATH}/subdir.svg", "margin_width": 0, "margin_height": 0, "color": self.COLOR_LABEL_ENABLED}, "Image::TickEnabled": {"image_url": f"{self.ICON_PATH}/checked.svg", "margin_width": 0, "margin_height": 0, "color": self.COLOR_TICK_ENABLED}, "Image::TickDisabled": {"image_url": f"{self.ICON_PATH}/checked.svg", "margin_width": 0, "margin_height": 0, "color": self.COLOR_TICK_DISABLED}, "Menu.Separator": {"color": self.COLOR_SEPARATOR} } def build_item(self, item: ui.Menu): if isinstance(item, ui.Separator): return super().build_item(item) elif not isinstance(item, ContextMenuExtension.uiMenu) and not isinstance(item, ContextMenuExtension.uiMenuItem): carb.log_warn(f"build_item: bad context menu item {item.text} - Should be uiMenu/uiMenuItem") return super().build_item(item) style = ContextMenuExtension.default_delegate.get_style() if item.delegate and hasattr(item.delegate, "get_style"): style |= item.delegate.get_style() with ui.HStack(height=0, style=style): ui.Spacer(width=4) # build tick if item.checkable: ui.Image("", width=self.ICON_SIZE, name="TickEnabled" if item.checked else "TickDisabled") # build glyph if item.glyph: glyph_path = item.glyph if "/" in item.glyph.replace("\\", "/") else carb.tokens.get_tokens_interface().resolve("${glyphs}/"+ item.glyph) ui.Spacer(width=self.ICON_SPACING[0]) ui.Image(glyph_path, width=self.ICON_SIZE, name="Icon") ui.Spacer(width=self.ICON_SPACING[1]) # build label ui.Label(f"{item.text} ", height=self.TEXT_SIZE, name="Enabled" if item.enabled else "Disabled") # build subdir marker if item.submenu: ui.Image("", width=self.SUBMENU_ICON_SIZE, name="SubMenu") ui.Spacer(width=self.SUBMENU_SPACING) default_delegate = DefaultMenuDelegate() def _set_prim_translation(stage, prim_path: Sdf.Path, translate: Gf.Vec3d): prim = stage.GetPrimAtPath(prim_path) if not prim or not prim.IsA(UsdGeom.Xformable): return xformable = UsdGeom.Xformable(prim) for op in xformable.GetOrderedXformOps(): if op.GetOpType() == UsdGeom.XformOp.TypeTranslate and "pivot" not in op.SplitName(): precision = op.GetPrecision() desired_translate = ( translate if precision == UsdGeom.XformOp.Precision else Gf.Vec3f(translate[0], translate[1], translate[2]) ) omni.kit.commands.execute("ChangeProperty", prop_path=op.GetAttr().GetPath().pathString, value=desired_translate, prev=None) break elif op.GetOpType() == UsdGeom.XformOp.TypeTransform: matrix = op.Get() matrix.SetTranslate(translate) omni.kit.commands.execute("ChangeProperty", prop_path=op.GetAttr().GetPath().pathString, value=matrix, prev=None) break def create_prim(objects: dict, prim_type: str, attributes: dict, create_group_xform: bool = False) -> None: """ create prims Args: objects: context_menu data prim_type: created prim's type attributes: created prim's cutsom attributes create_group_xform: passed to CreatePrimWithDefaultXformCommand Returns: None """ usd_context = omni.usd.get_context() stage = usd_context.get_stage() with omni.kit.undo.group(): with layers.active_authoring_layer_context(usd_context): if "mouse_pos" in objects and not create_group_xform: mouse_pos = objects["mouse_pos"] omni.kit.commands.execute( "CreatePrimWithDefaultXform", prim_type=prim_type, attributes=attributes, select_new_prim=True ) paths = usd_context.get_selection().get_selected_prim_paths() if stage: for path in paths: ContextMenuExtension._set_prim_translation( stage, path, Gf.Vec3d(mouse_pos[0], mouse_pos[1], mouse_pos[2]) ) elif create_group_xform: paths = usd_context.get_selection().get_selected_prim_paths() if stage.HasDefaultPrim() and stage.GetDefaultPrim().GetPath().pathString in paths: post_notification("Cannot Group default prim") return omni.kit.commands.execute("GroupPrims", prim_paths=paths) else: prim_path = None if "use_hovered" in objects and objects["use_hovered"]: prim = get_hovered_prim(objects) if prim: new_path = omni.usd.get_stage_next_free_path(stage, prim.GetPrimPath().pathString + "/" + prim_type, False) future_prim = Usd.SchemaRegistry.GetTypeFromName(prim_type) if omni.usd.can_prim_have_children(stage, Sdf.Path(new_path), future_prim): prim_path = new_path else: post_notification(f"Cannot create prim below {prim.GetPrimPath().pathString} as nested prims are not supported for this type.") omni.kit.commands.execute( "CreatePrimWithDefaultXform", prim_type=prim_type, prim_path=prim_path, attributes=attributes, select_new_prim=True ) def create_mesh_prim(objects: dict, prim_type: str) -> None: """ create mesh prims Args: objects: context_menu data prim_type: created prim's type Returns: None """ usd_context = omni.usd.get_context() stage = usd_context.get_stage() prim_path = None if "use_hovered" in objects and objects["use_hovered"]: prim = get_hovered_prim(objects) if prim: # mesh prims are always UsdGeom.Gprim so just check for ancestor prim_type new_path = omni.usd.get_stage_next_free_path(stage, prim.GetPrimPath().pathString + "/" + prim_type, False) if omni.usd.is_ancestor_prim_type(stage, Sdf.Path(new_path), UsdGeom.Gprim): post_notification(f"Cannot create prim below {prim.GetPrimPath().pathString} as nested prims are not supported for this type.") else: prim_path = new_path with omni.kit.undo.group(): with layers.active_authoring_layer_context(usd_context): omni.kit.commands.execute( "CreateMeshPrimWithDefaultXform", prim_type=prim_type, prim_path=prim_path, select_new_prim=True, prepend_default_prim=False if prim_path else True ) if "mouse_pos" in objects: mouse_pos = objects["mouse_pos"] paths = usd_context.get_selection().get_selected_prim_paths() if stage: for path in paths: ContextMenuExtension._set_prim_translation( stage, path, Gf.Vec3d(mouse_pos[0], mouse_pos[1], mouse_pos[2]) ) def show_selected_prims_names(self, objects: dict, delegate=None) -> None: """ populate function that builds menu items with selected prim info Args: objects: context_menu data Returns: None """ context_menu = omni.kit.context_menu.get_instance() if context_menu is None: carb.log_error("context_menu is disabled!") return paths = omni.usd.get_context().get_selection().get_selected_prim_paths() hovered = None if "use_hovered" in objects and objects["use_hovered"]: hovered = omni.kit.context_menu.get_hovered_prim(objects) if not "prim_list" in objects and len(paths) == 0: menu_name = f"(nothing selected)" else: if "prim_list" in objects: paths = objects["prim_list"] if len(paths) > 1: menu_name = f"({len(paths)} models selected)" elif "prim_list" in objects: if paths[0].GetPath() == hovered.GetPrimPath() if hovered else None: menu_name = f"({paths[0].GetPath().name} selected & hovered)" hovered = None else: menu_name = f"({paths[0].GetPath().name} selected)" else: menu_name = f"({os.path.basename(paths[0])} selected)" if hovered: menu_name += f"\n({hovered.GetPath().name} hovered)" context_menu._menu_title = ContextMenuExtension.uiMenuItem( f'{menu_name}', triggered_fn=None, enabled=False if delegate else True, delegate=delegate if delegate else ContextMenuExtension.default_delegate, tearable=True if delegate else False, glyph="menu_prim.svg" ) if not carb.settings.get_settings().get(SETTING_HIDE_CREATE_MENU): ui.Separator() def show_create_menu(self, objects: dict): """ populate function that builds create menu Args: objects: context_menu data Returns: None """ prim = None prim_list = [objects["prim"]] if "prim" in objects else objects["prim_list"] self.build_create_menu(objects, prim_list) def build_create_menu(self, objects: dict, prim_list: list, custom_menu: dict = [], delegate=None): def is_create_type_enabled(type: str): settings = carb.settings.get_settings() if type == "Shape": if settings.get("/app/primCreation/hideShapes") == True or \ settings.get("/app/primCreation/enableMenuShape") == False: return False return True enabled = settings.get(f"/app/primCreation/enableMenu{type}") if enabled == True or enabled == False: return enabled return True if carb.settings.get_settings().get(SETTING_HIDE_CREATE_MENU): return custom_menu += omni.kit.context_menu.get_menu_dict("CREATE", "") usd_context = omni.usd.get_context() paths = usd_context.get_selection().get_selected_prim_paths() item_delegate = delegate if delegate else ContextMenuExtension.default_delegate style = delegate.get_style() if delegate and hasattr(delegate, "get_style") else ContextMenuExtension.default_delegate.get_style() item = ContextMenuExtension.uiMenu( f'Create', style=style, delegate=item_delegate, glyph="menu_create.svg", submenu=True ) self._context_menu_items.append(item) with item: try: geometry_mesh_prim_list = omni.kit.primitive.mesh.get_geometry_mesh_prim_list() item = ContextMenuExtension.uiMenu(f'Mesh', delegate=item_delegate, glyph="menu_prim.svg", submenu=True) self._context_menu_items.append(item) with item: for mesh in geometry_mesh_prim_list: self.menu_item(mesh, triggered_fn=partial(ContextMenuExtension.create_mesh_prim, objects, mesh), delegate=item_delegate) except Exception: pass if is_create_type_enabled("Shape"): def on_create_shape(objects, prim_type): shapes = omni.kit.menu.create.get_geometry_standard_prim_list() shape_attrs = shapes.get(prim_type, {}) ContextMenuExtension.create_prim(objects, prim_type, shape_attrs) item = ContextMenuExtension.uiMenu(f'Shape', delegate=item_delegate, glyph="menu_prim.svg", submenu=True) self._context_menu_items.append(item) with item: for geom in omni.kit.menu.create.get_geometry_standard_prim_list().keys(): self.menu_item( geom, triggered_fn=partial(on_create_shape, objects, geom), delegate=item_delegate ) if is_create_type_enabled("Light"): item = ContextMenuExtension.uiMenu(f'Light', delegate=item_delegate, glyph="menu_light.svg", submenu=True) self._context_menu_items.append(item) with item: for light in omni.kit.menu.create.get_light_prim_list(): self.menu_item( light[0], triggered_fn=partial(ContextMenuExtension.create_prim, objects, light[1], light[2]), delegate=item_delegate ) if is_create_type_enabled("Audio"): item = ContextMenuExtension.uiMenu(f'Audio', delegate=item_delegate, glyph="menu_audio.svg", submenu=True) self._context_menu_items.append(item) with item: for sound in omni.kit.menu.create.get_audio_prim_list(): self.menu_item( sound[0], triggered_fn=partial(ContextMenuExtension.create_prim, objects, sound[1], sound[2]), delegate=item_delegate ) if is_create_type_enabled("Camera"): self.menu_item( f'Camera', triggered_fn=partial(ContextMenuExtension.create_prim, objects, "Camera", {}), glyph="menu_camera.svg", delegate=item_delegate ), if is_create_type_enabled("Scope"): self.menu_item( f'Scope', triggered_fn=partial(ContextMenuExtension.create_prim, objects, "Scope", {}), glyph="menu_scope.svg", delegate=item_delegate ), if is_create_type_enabled("Xform"): self.menu_item( f'Xform', triggered_fn=partial(ContextMenuExtension.create_prim, objects, "Xform", {}), glyph="menu_xform.svg", delegate=item_delegate ), if custom_menu: for menu_entry in custom_menu: if isinstance(menu_entry, list): for item in menu_entry: if self._build_menu(item, objects, delegate=item_delegate): self.menu_item_count += 1 elif self._build_menu(menu_entry, objects, delegate=item_delegate): self.menu_item_count += 1 def build_add_menu(self, objects: dict, prim_list: list, custom_menu: list = None, delegate = None): if carb.settings.get_settings().get(SETTING_HIDE_CREATE_MENU): return menu = omni.kit.context_menu.get_menu_dict("ADD", "") menu = menu + custom_menu if menu: root_menu = ContextMenuExtension.uiMenu( f'Add', delegate=delegate if delegate else ContextMenuExtension.default_delegate, glyph="menu_add.svg", submenu=True) self._context_menu_items.append(root_menu) with root_menu: menu_item_count = self.menu_item_count for menu_entry in menu: if isinstance(menu_entry, list): for item in menu_entry: if self._build_menu(item, objects, None): self.menu_item_count += 1 elif self._build_menu(menu_entry, objects, None): self.menu_item_count += 1 if self.menu_item_count == menu_item_count: root_menu.visible = False def select_prims_using_material(self, objects: dict): """ select stage prims using material Args: objects: context_menu data Returns: None """ if not any(item in objects for item in ["prim", "prim_list"]): return prim_list = [objects["prim"]] if "prim" in objects else objects["prim_list"] omni.usd.get_context().get_selection().clear_selected_prim_paths() paths = [] for mat_prim in prim_list: for prim in objects["stage"].Traverse(): if omni.usd.is_prim_material_supported(prim): mat, rel = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() if mat and mat.GetPrim().GetPath() == mat_prim.GetPath(): paths.append(prim.GetPath().pathString) omni.usd.get_context().get_selection().set_selected_prim_paths(paths, True) def find_in_browser(self, objects: dict) -> None: """ select prim in content_browser Args: objects: context_menu data Returns: None """ prim = objects["prim_list"][0] url_path = omni.usd.get_url_from_prim(prim) try: from omni.kit.window.content_browser import get_content_window content_browser = get_content_window() if content_browser: content_browser.navigate_to(url_path) except Exception as exc: carb.log_warn(f"find_in_browser error {exc}") def duplicate_prim(self, objects: dict): """ duplicate prims Args: objects: context_menu data Returns: None """ paths = [] usd_context = omni.usd.get_context() usd_context.get_selection().clear_selected_prim_paths() edit_mode = layers.get_layers(usd_context).get_edit_mode() is_auto_authoring = edit_mode == layers.LayerEditMode.AUTO_AUTHORING omni.kit.undo.begin_group() for prim in objects["prim_list"]: old_prim_path = prim.GetPath().pathString new_prim_path = omni.usd.get_stage_next_free_path(objects["stage"], old_prim_path, False) omni.kit.commands.execute( "CopyPrim", path_from=old_prim_path, path_to=new_prim_path, exclusive_select=False, copy_to_introducing_layer=is_auto_authoring ) paths.append(new_prim_path) omni.kit.undo.end_group() omni.usd.get_context().get_selection().set_selected_prim_paths(paths, True) def delete_prim(self, objects: dict, destructive=False): """ delete prims Args: objects: context_menu data destructive: If it's true, it will remove all corresponding prims in all layers. Otherwise, it will deactivate the prim in current edit target if its def is not in the current edit target. By default, it will be non-destructive. Returns: None """ prims = objects.get("prim_list", []) if prims: prim_paths = [prim.GetPath() for prim in prims] omni.kit.commands.execute("DeletePrims", paths=prim_paths, destructive=destructive) def copy_prim_url(self, objects: dict): """ Copies url of Prim in USDA references format. @planet.usda@</Planet> """ paths = "" for prim in objects["prim_list"]: if paths: paths += " " paths += omni.usd.get_url_from_prim(prim) omni.kit.clipboard.copy(paths) def copy_prim_path(self, objects: dict) -> None: """ copy prims path to clipboard Args: objects: context_menu data Returns: None """ paths = "" for prim in objects["prim_list"]: if paths: paths += " " paths += f"{prim.GetPath()}" omni.kit.clipboard.copy(paths) def group_selected_prims(self, objects: dict): """ group prims Args: prims: list of prims Returns: None """ # because widget.layer and widget.stage can get confused if prims are just renamed. clear selection and wait a frame, then do the rename to allow for this omni.usd.get_context().get_selection().clear_selected_prim_paths() asyncio.ensure_future(self._group_list(objects)) def ungroup_selected_prims(self, objects: dict): """ ungroup prims Args: prims: list of prims Returns: None """ # because widget.layer and widget.stage can get confused if prims are just renamed. clear selection and wait a frame, then do the rename to allow for this omni.usd.get_context().get_selection().clear_selected_prim_paths() asyncio.ensure_future(self._ungroup_list(objects)) async def _group_list(self, objects: dict): await omni.kit.app.get_app().next_update_async() prim_list = [objects["prim"]] if "prim" in objects else objects["prim_list"] paths = [] for prim in prim_list: paths.append(prim.GetPath().pathString) omni.usd.get_context().get_selection().set_selected_prim_paths(paths, True) omni.usd.get_context().get_selection().set_selected_prim_paths(paths, True) ContextMenuExtension.create_prim(objects, prim_type="Xform", attributes={}, create_group_xform=True) async def _ungroup_list(self, objects: dict): await omni.kit.app.get_app().next_update_async() prim_list = [objects["prim"]] if "prim" in objects else objects["prim_list"] paths = [] for prim in prim_list: paths.append(prim.GetPath().pathString) omni.usd.get_context().get_selection().set_selected_prim_paths(paths, True) omni.usd.get_context().get_selection().set_selected_prim_paths(paths, True) usd_context = omni.usd.get_context() stage = usd_context.get_stage() with omni.kit.undo.group(): with layers.active_authoring_layer_context(usd_context): omni.kit.commands.execute("UngroupPrims", prim_paths=paths) def refresh_payload_or_reference(self, objects: dict): async def reload(layer_handles): context = omni.usd.get_context() for layer in layer_handles: (all_layers, _, _) = UsdUtils.ComputeAllDependencies(layer.identifier) if all_layers: layers_state = layers.get_layers_state(context) all_dirty_layers = [] for dep_layer in all_layers: if layers_state.is_layer_outdated(dep_layer.identifier): all_dirty_layers.append(dep_layer) if all_dirty_layers: Sdf.Layer.ReloadLayers(all_dirty_layers) prim_list = [objects["prim"]] if "prim" in objects else objects["prim_list"] layer_handles = set() for prim in prim_list: for (ref, intro_layer) in omni.usd.get_composed_references_from_prim(prim): layer = Sdf.Find(intro_layer.ComputeAbsolutePath(ref.assetPath)) if ref.assetPath else None if layer: layer_handles.add(layer) for (ref, intro_layer) in omni.usd.get_composed_payloads_from_prim(prim): layer = Sdf.Find(intro_layer.ComputeAbsolutePath(ref.assetPath)) if ref.assetPath else None if layer: layer_handles.add(layer) asyncio.ensure_future(reload(layer_handles)) def convert_payload_to_reference(self, objects: dict): prim_list = [objects["prim"]] if "prim" in objects else objects["prim_list"] async def convert(prim_list): await omni.kit.app.get_app().next_update_async() with omni.kit.undo.group(): with Sdf.ChangeBlock(): for prim in prim_list: stage = prim.GetStage() ref_and_layers = omni.usd.get_composed_payloads_from_prim(prim) for payload, _ in ref_and_layers: reference = Sdf.Reference(assetPath=payload.assetPath.replace("\\", "/"), primPath=payload.primPath, layerOffset=payload.layerOffset) omni.kit.commands.execute("RemovePayload", stage=stage, prim_path=prim.GetPath(), payload=payload) omni.kit.commands.execute("AddReference", stage=stage, prim_path=prim.GetPath(), reference=reference) try: property_window = omni.kit.window.property.get_window() if property_window: property_window._window.frame.rebuild() except Exception: pass asyncio.ensure_future(convert(prim_list)) def convert_reference_to_payload(self, objects: dict): prim_list = [objects["prim"]] if "prim" in objects else objects["prim_list"] async def convert(prim_list): await omni.kit.app.get_app().next_update_async() with omni.kit.undo.group(): with Sdf.ChangeBlock(): for prim in prim_list: stage = prim.GetStage() ref_and_layers = omni.usd.get_composed_references_from_prim(prim) for reference, _ in ref_and_layers: payload = Sdf.Payload(assetPath=reference.assetPath.replace("\\", "/"), primPath=reference.primPath, layerOffset=reference.layerOffset) omni.kit.commands.execute("RemoveReference", stage=stage, prim_path=prim.GetPath(), reference=reference) omni.kit.commands.execute("AddPayload", stage=stage, prim_path=prim.GetPath(), payload=payload) try: property_window = omni.kit.window.property.get_window() if property_window: property_window._window.frame.rebuild() except Exception: pass asyncio.ensure_future(convert(prim_list)) def refresh_reference_payload_name(self, objects: dict): """ checks if prims have references/payload and returns name """ if not any(item in objects for item in ["prim", "prim_list"]): return None prim_list = [objects["prim"]] if "prim" in objects else objects["prim_list"] if not prim_list: return None has_payload = self._prims_have_payloads(prim_list) has_reference = self._prims_have_references(prim_list) if has_payload and has_reference: return "Refresh Payload & Reference" elif has_payload: return "Refresh Payload" return "Refresh Reference" def get_prim_group(self, prim): """ if the prim is or has a parent prim that is a group Kind, returns that prim otherwise None """ model_api = Usd.ModelAPI(prim) if model_api and Kind.Registry.IsA(model_api.GetKind(), "group"): return prim else: if prim.GetParent().IsValid(): return self.get_prim_group(prim.GetParent()) else: return None # ---------------------------------------------- menu show test functions ---------------------------------------------- def is_one_prim_selected(self, objects: dict): """ checks if one prim is selected """ if not "prim_list" in objects: return False return len(objects["prim_list"]) == 1 def is_material(self, objects: dict): """ checks if prims are UsdShade.Material """ if not any(item in objects for item in ["prim", "prim_list"]): return prim_list = [objects["prim"]] if "prim" in objects else objects["prim_list"] for prim in prim_list: if not prim.IsA(UsdShade.Material): return False return True def has_payload_or_reference(self, objects: dict): """ checks if prims have payloads or references """ if not any(item in objects for item in ["prim", "prim_list"]): return False prim_list = [objects["prim"]] if "prim" in objects else objects["prim_list"] if not prim_list: return False return self._prims_have_references(prim_list) or self._prims_have_payloads(prim_list) def can_convert_references_or_payloads(self, objects): """ Checkes if references can be converted into payloads or vice versa. """ if not any(item in objects for item in ["prim", "prim_list"]): return False prim_list = [objects["prim"]] if "prim" in objects else objects["prim_list"] if not prim_list: return False for prim in prim_list: ref_and_layers = omni.usd.get_composed_references_from_prim(prim) if ref_and_layers: return True payload_and_layers = omni.usd.get_composed_payloads_from_prim(prim) if payload_and_layers: return True return False def _prims_have_payloads(self, prim_list): for prim in prim_list: for prim_spec in prim.GetPrimStack(): if prim_spec.HasInfo(Sdf.PrimSpec.PayloadKey) and prim_spec.GetInfo(Sdf.PrimSpec.PayloadKey).ApplyOperations([]): return True return False def _prims_have_references(self, prim_list): for prim in prim_list: for prim_spec in prim.GetPrimStack(): if prim_spec.HasInfo(Sdf.PrimSpec.ReferencesKey) and prim_spec.GetInfo(Sdf.PrimSpec.ReferencesKey).ApplyOperations([]): return True return False def has_payload(self, objects: dict): """ checks if prims have payloads """ if not any(item in objects for item in ["prim", "prim_list"]): return False prim_list = [objects["prim"]] if "prim" in objects else objects["prim_list"] if not prim_list: return False return self._prims_have_payloads(prim_list) def has_reference(self, objects: dict): """ checks if prims have references """ if not any(item in objects for item in ["prim", "prim_list"]): return False prim_list = [objects["prim"]] if "prim" in objects else objects["prim_list"] if not prim_list: return False return self._prims_have_references(prim_list) def can_be_copied(self, objects: dict): """ checks if prims can be copied """ if not "prim_list" in objects: return False for prim in objects["prim_list"]: if not omni.usd.can_be_copied(prim): return False return True def can_use_find_in_browser(self, objects: dict): """ checks if prims are authored """ prim = objects["prim_list"][0] layer = omni.usd.get_sdf_layer(prim) authored_prim = omni.usd.get_authored_prim(prim) return authored_prim and authored_prim != prim def can_show_find_in_browser(self, objects: dict): """ checks if one prim is selected and have URL (authored) """ if not any(item in objects for item in ["prim", "prim_list"]): return False prim_list = [objects["prim"]] if "prim" in objects else objects["prim_list"] if len(prim_list) != 1: return False prim = prim_list[0] url_path = omni.usd.get_url_from_prim(prim) if url_path is not None and url_path[0:5] == "anon:": url_path = None return url_path != None def can_delete(self, objects: dict): """ checks if prims can be deleted """ if not any(item in objects for item in ["prim", "prim_list"]): return False prim_list = [objects["prim"]] if "prim" in objects else objects["prim_list"] for prim in prim_list: if not prim.IsValid(): return False no_delete = prim.GetMetadata("no_delete") if no_delete is not None and no_delete is True: return False return True async def can_assign_material_async(self, objects: dict, menu_item: ui.Widget): """ async show function. The `menu_item` is created but not visible, if this item is shown then `menu_item.visible = True` This scans all the prims in the stage looknig for a material, if one is found then it can "assign material" and `menu_item.visible = True` """ if carb.settings.get_settings().get_as_bool("/exts/omni.kit.context_menu/show_assign_material") == False: return if not self.is_prim_selected(objects) or not self.is_material_bindable(objects): return menu_item.visible = True return 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_prim_in_group(self, objects: dict): """ checks if any prims are in group(s) """ if not "stage" in objects or not "prim_list" in objects or not objects["stage"]: return False stage = objects["stage"] if not stage: return False prim_list = objects["prim_list"] for path in prim_list: if isinstance(path, Usd.Prim): prim = path else: prim = stage.GetPrimAtPath(path) if prim: if not self.get_prim_group(prim): return False return True def is_material_bindable(self, objects: dict): """ checks if prims support matrial binding """ if not any(item in objects for item in ["prim", "prim_list"]): return False prim_list = [objects["prim"]] if "prim" in objects else objects["prim_list"] for prim in prim_list: if not omni.usd.is_prim_material_supported(prim): return False return True def prim_is_type(self, objects: dict, type: Tf.Type) -> bool: """ checks if prims are given class/schema """ if not "stage" in objects or not "prim_list" in objects or not objects["stage"]: return False stage = objects["stage"] if not stage: return False prim_list = objects["prim_list"] for path in prim_list: if isinstance(path, Usd.Prim): prim = path else: prim = stage.GetPrimAtPath(path) if prim: if not prim.IsA(type): return False return len(prim_list) > 0 # ---------------------------------------------- core functions ---------------------------------------------- def __init__(self): super().__init__() self._clipboard = {} def on_startup(self, ext_id): global _extension_instance _extension_instance = self self._context_menu = None self._context_menu_items = [] self._content_window = None self._listeners = [] 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): global _extension_instance _extension_instance = None self._listeners = None if self._context_menu: self._context_menu.destroy() self._context_menu = None self._context_menu_items = [] @property def name(self) -> str: if self._context_menu: return self._context_menu.text return None def close_menu(self): if self._context_menu: self._context_menu.destroy() self._context_menu = None self._context_menu_items = [] self._content_window = None self._menu_title = None self._clipboard = [] def separator(self, name: str="") -> bool: if self.menu_item_count > 1: if isinstance(self.menu_item_prev, ui.Separator) and self.menu_item_prev.text == name: return False self.menu_item_prev = ui.Separator(name) return True return False def menu_item(self, name: str, triggered_fn: Callable = None, enabled: bool = True, checkable: bool = False, checked: bool = False, is_async_func=False, delegate=None, additional_kwargs=None, glyph=""): menuitem_kwargs = {"triggered_fn": triggered_fn, "enabled": enabled, "checkable": checkable, "checked": checked} if additional_kwargs: menuitem_kwargs.update(additional_kwargs) if delegate and hasattr(delegate, "get_parameters"): delegate.get_parameters(name, menuitem_kwargs) # async functions are created but are not visible, so exclude from prev logic if is_async_func: item = ContextMenuExtension.uiMenuItem(name, **menuitem_kwargs, delegate=delegate if delegate else ContextMenuExtension.default_delegate, glyph=glyph) self._context_menu_items.append(item) return item item = ContextMenuExtension.uiMenuItem(name, **menuitem_kwargs, delegate=delegate if delegate else ContextMenuExtension.default_delegate, glyph=glyph) self._context_menu_items.append(item) self.menu_item_prev = item self.menu_item_count += 1 return self.menu_item_prev def _get_fn_result(self, menu_entry: dict, name: str, objects: list): try: if not name in menu_entry: return True if menu_entry[name] is None: return True if isinstance(menu_entry[name], list): for show_fn in menu_entry[name]: if not show_fn(objects): return False else: if not menu_entry[name](objects): return False return True except Exception as exc: carb.log_warn(f"_get_fn_result error for {name}: {exc}") return False def _has_click_fn(self, menu_entry): if "onclick_fn" in menu_entry and menu_entry["onclick_fn"] is not None: return True if "onclick_action" in menu_entry and menu_entry["onclick_action"] is not None: return True return False def _execute_action(self, action: Tuple, objects): if not action: return try: import omni.kit.actions.core import omni.kit.app async def execute_action(action): await omni.kit.app.get_app().next_update_async() # only forward the accepted parameters for this action action_obj = omni.kit.actions.core.acquire_action_registry().get_action(action[0], action[1]) params = {key: objects[key] for key in action_obj.parameters if key in objects} omni.kit.actions.core.execute_action(*action, **params) # omni.ui can sometimes crash is menu callback does ui calls. # To avoid this, use async function with frame delay asyncio.ensure_future(execute_action(action)) except ModuleNotFoundError: carb.log_warn(f"execute_action: error omni.kit.actions.core not loaded") except Exception as exc: carb.log_warn(f"execute_action: error {exc}") def _set_hotkey_for_action(self, menu_entry: dict, menu_item: ui.MenuItem): try: from omni.kit.hotkeys.core import get_hotkey_registry onclick_action = menu_entry["onclick_action"] hotkey_registry = get_hotkey_registry() if not hotkey_registry: raise ImportError for hk in hotkey_registry.get_all_hotkeys_for_extension(onclick_action[0]): menu_item.hotkey_text = hk.key_text if hk.action_id == onclick_action[1] else None except ImportError: pass def _build_menu(self, menu_entry: dict, objects: dict, delegate) -> bool: if "name" in menu_entry and isinstance(menu_entry["name"], dict): menu_entry_name = menu_entry["name"] if "name_fn" in menu_entry: menu_entry_name = menu_entry["name_fn"](objects) for item in menu_entry_name: menu_item_count = self.menu_item_count glyph = None if "glyph" in menu_entry and menu_entry["glyph"]: glyph = menu_entry["glyph"] menu = ContextMenuExtension.uiMenu(f"{item}", tearable=menu_entry.get("tearable", True if delegate else False), delegate=delegate if delegate else ContextMenuExtension.default_delegate, glyph=glyph, submenu=True) self._context_menu_items.append(menu) with menu: for menu_entry in menu_entry_name[item]: if isinstance(menu_entry, list): for item in menu_entry: self._build_menu(item, objects, delegate) else: self._build_menu(menu_entry, objects, delegate) # no submenu items created, remove if menu_item_count == self.menu_item_count: menu.visible = False return False return True if not self._get_fn_result(menu_entry, "show_fn", objects): return False if "populate_fn" in menu_entry: self.menu_item_prev = None menu_entry["populate_fn"](objects) return True menu_entry_name = menu_entry["name"] if "name" in menu_entry else "" if "name_fn" in menu_entry and menu_entry["name_fn"] is not None: menu_entry_name = menu_entry["name_fn"](objects) if menu_entry_name == "" or menu_entry_name.endswith("/"): header = menu_entry["header"] if "header" in menu_entry else "" if "show_fn_async" in menu_entry: menu_item = ui.Separator(header, visible=False) asyncio.ensure_future(menu_entry["show_fn_async"](objects, menu_item)) return self.separator(header) checked = False checkable = False if "checked_fn" in menu_entry and self._has_click_fn(menu_entry): checkable = True checked = self._get_fn_result(menu_entry, "checked_fn", objects) menu_item = None is_async_func = bool("show_fn_async" in menu_entry) additional_kwargs = menu_entry.get("additional_kwargs", None) glyph = None if "glyph" in menu_entry and menu_entry["glyph"]: glyph = menu_entry["glyph"] if self._has_click_fn(menu_entry): enabled = self._get_fn_result(menu_entry, "enabled_fn", objects) if "onclick_action" in menu_entry and menu_entry["onclick_action"]: triggered_fn=partial(self._execute_action, menu_entry["onclick_action"], objects) else: triggered_fn=partial(menu_entry["onclick_fn"], objects) menu_item = self.menu_item( menu_entry_name, triggered_fn=triggered_fn, enabled=enabled, checkable=checkable, checked=checked, is_async_func=is_async_func, delegate=delegate, glyph=glyph, additional_kwargs=additional_kwargs, ) else: menu_item = self.menu_item(menu_entry_name, enabled=False, checkable=checkable, checked=checked, is_async_func=is_async_func, delegate=delegate, glyph=glyph, additional_kwargs=additional_kwargs) if "onclick_action" in menu_entry: self._set_hotkey_for_action(menu_entry, menu_item) if menu_item and is_async_func: menu_item.visible = False asyncio.ensure_future(menu_entry["show_fn_async"](objects, menu_item)) return True def _is_menu_visible(self, menu_entry: dict, objects: dict): if not self._get_fn_result(menu_entry, "show_fn", objects): return False if "populate_fn" in menu_entry: return True return True def show_context_menu(self, menu_name: str, objects: dict, menu_list: List[dict], min_menu_entries: int = 1, delegate = None) -> None: """ build context menu from menu_list Args: menu_name: menu name objects: context_menu data menu_list: list of dictonaries containing context menu values min_menu_entries: minimal number of menu needed for menu to be visible Returns: None """ try: if self._context_menu: self._context_menu.destroy() self._context_menu_items = [] style = delegate.get_style() if delegate and hasattr(delegate, "get_style") else ContextMenuExtension.default_delegate.get_style() menuitem_kwargs = { "tearable": True if delegate else False } if delegate and hasattr(delegate, "get_parameters"): delegate.get_parameters("tearable", menuitem_kwargs) self._context_menu = ContextMenuExtension.uiMenu(f"Context menu {menu_name}", delegate=delegate if delegate else ContextMenuExtension.default_delegate, style=style, **menuitem_kwargs) # setup globals objects["clipboard"] = self._clipboard if "stage" not in objects: # TODO: We can't use `context.get_stage()` because this context # menu can be called for Stage Viewer and it has own stage. objects["stage"] = omni.usd.get_context().get_stage() self.menu_item_count = 0 top_level_menu_count = 0 self.menu_item_prev = None with self._context_menu: for menu_entry in menu_list: if isinstance(menu_entry, list): for item in menu_entry: if self._build_menu(item, objects, delegate): self.menu_item_count += 1 top_level_menu_count += 1 elif self._build_menu(menu_entry, objects, delegate): self.menu_item_count += 1 top_level_menu_count += 1 # Show it if top_level_menu_count >= min_menu_entries: # if the last menu item was a Separator, hide it if isinstance(self.menu_item_prev, ui.Separator): self.menu_item_prev.visible = False if all(k in objects for k in ("menu_xpos", "menu_ypos")): self._context_menu.show_at(objects["menu_xpos"], objects["menu_ypos"]) else: self._context_menu.show() except Exception as exc: import traceback carb.log_error(f"show_context_menu: error {traceback.format_exc()}") def bind_material_to_prims_dialog(self, stage: Usd.Stage, prims: list): carb.log_warn("omni.kit.context_menu.get_instance().bind_material_to_prims_dialog() is deprecated. Use omni.kit.material.library.bind_material_to_prims_dialog() instead") import omni.kit.material.library omni.kit.material.library.bind_material_to_prims_dialog(stage, prims) ################## public static functions ################## def get_instance(): """ get instance of context menu class """ return _extension_instance def close_menu(): if _extension_instance: _extension_instance.close_menu() def add_menu(menu_dict, index: str = "MENU", extension_id: str = ""): """add custom menu to any context_menu Examples menu = {"name": "Open in Material Editor", "onclick_fn": open_material} # add to all context menus self._my_custom_menu = omni.kit.context_menu.add_menu(menu, "MENU", "") # add to omni.kit.widget.stage context menu self._my_custom_menu = omni.kit.context_menu.add_menu(menu, "MENU", "omni.kit.widget.stage") Args: menu_dict: a dictonary containing menu settings. See ContextMenuExtension docs for infomation on values index: name of the menu EG. "MENU" extension_id: name of the target EG. "" or "omni.kit.widget.stage" NOTE: index and extension_id are extension arbitary values. add_menu(menu, "MENU", "omni.kit.widget.stage") works as omni.kit.widget.stage retreives custom context_menus with get_menu_dict("MENU", "omni.kit.widget.stage") Adding a menu to an extension that doesn't support context_menus would have no effect. Returns: MenuSubscription. Keep a copy of this as the custom menu will be removed when `release()` is explictly called or this is garbage collected """ class MenuSubscription: def __init__(self, menu_id): self.__id = menu_id def release(self): if self.__id is not None: _CustomMenuDict().remove_menu(self.__id, index, extension_id) self.__id = None def __del__(self): self.release() menu_id = _CustomMenuDict().add_menu(menu_dict, index, extension_id) return MenuSubscription(menu_id) def get_menu_dict(index: str = "MENU", extension_id: str = "") -> List[dict]: """get custom menus see add_menu for dictonary info Args: index: name of the menu extension_id: name of the target Returns: a list of dictonaries containing custom menu settings. See ContextMenuExtension docs for infomation on values """ return _CustomMenuDict().get_menu_dict(index, extension_id) def reorder_menu_dict(menu_dict: List[dict]): """reorder menus using "appear_after" value in menu Args: menu_dict: list of dictonaries Returns: None """ def find_entry(menu_dict, name): for index, menu_entry in enumerate(menu_dict): if "name" in menu_entry: if menu_entry["name"] == name: return index return -1 for index, menu_entry in enumerate(menu_dict.copy()): if "appear_after" in menu_entry: new_index = find_entry(menu_dict, menu_entry["appear_after"]) if new_index != -1: menu_dict.remove(menu_entry) menu_dict.insert(new_index + 1, menu_entry) def get_menu_event_stream(): """ Gets menu event stream """ return _CustomMenuDict().get_event_stream() def post_notification(message: str, info: bool = False, duration: int = 3): try: import omni.kit.notification_manager as nm if info: type = nm.NotificationStatus.INFO else: type = nm.NotificationStatus.WARNING nm.post_notification(message, status=type, duration=duration) except ModuleNotFoundError: carb.log_warn(message) def get_hovered_prim(objects): if "hovered_prim" in objects: return objects["hovered_prim"] if "prim_list" in objects and len(objects['prim_list'])==1: return objects['prim_list'][0] return None
67,155
Python
41.051346
228
0.558707
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/scripts/viewport_menu.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. ## __all__ = ['ViewportMenu'] import omni.kit import omni.usd import carb import omni.kit.usd.layers as layers from .context_menu import get_instance from .style import MENU_STYLE from .context_menu import ContextMenuExtension from pxr import Usd, UsdShade, Sdf, Gf from typing import Sequence from omni import ui class ViewportMenu: class MenuDelegate(ContextMenuExtension.DefaultMenuDelegate): TEXT_SIZE = 14 ICON_SIZE = 14 MARGIN_SIZE = [3, 3] def get_style(self): vp_style = MENU_STYLE.copy() vp_style["Label::Enabled"] = {"margin_width": self.MARGIN_SIZE[0],"margin_height": self.MARGIN_SIZE[1],"color": self.COLOR_LABEL_ENABLED} vp_style["Label::Disabled"] = {"margin_width": self.MARGIN_SIZE[0], "margin_height": self.MARGIN_SIZE[1], "color": self.COLOR_LABEL_DISABLED} return vp_style menu_delegate = MenuDelegate() @staticmethod def is_on_clipboard(objects, name): clipboard = objects["clipboard"] if not name in clipboard: return False return clipboard[name] != None @staticmethod def is_prim_on_clipboard(objects): return ViewportMenu.is_on_clipboard(objects, "prim_paths") @staticmethod async def can_show_clear_clipboard(objects, menu_item): return False @staticmethod def is_material_bindable(objects): # pragma: no cover if not "prim_list" in objects: return False for prim in objects["prim_list"]: if not omni.usd.is_prim_material_supported(prim): return False return True # ---------------------------------------------- menu onClick functions ---------------------------------------------- @staticmethod def bind_material_to_prim_dialog(objects): import omni.kit.material.library if not "prim_list" in objects: return omni.kit.material.library.bind_material_to_prims_dialog(objects["stage"], objects["prim_list"]) @staticmethod def set_prim_to_pos(path, new_pos): usd_context = omni.usd.get_context() stage = usd_context.get_stage() if stage: prim = stage.GetPrimAtPath(path) attr_position, attr_rotation, attr_scale, attr_order = omni.usd.TransformHelper().get_transform_attr( prim.GetAttributes() ) if attr_position: if attr_position.GetName() == "xformOp:translate": attr_position.Set(Gf.Vec3d(new_pos[0], new_pos[1], new_pos[2])) elif attr_position.GetName() == "xformOp:transform": value = attr_position.Get() if isinstance(value, Gf.Matrix4d): matrix = value else: matrix = Gf.Matrix4d(*value) eps_unused, scale_orient_mat_unused, abs_scale, rot_mat, abs_position, persp_mat_unused = ( matrix.Factor() ) rot_mat.Orthonormalize(False) abs_rotation = Gf.Rotation.DecomposeRotation3( rot_mat, Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis(), 1.0 ) abs_rotation = [ Gf.RadiansToDegrees(abs_rotation[0]), Gf.RadiansToDegrees(abs_rotation[1]), Gf.RadiansToDegrees(abs_rotation[2]), ] # split matrix into rotation and translation/scale matrix_pos = Gf.Matrix4d().SetIdentity() matrix_rot = Gf.Matrix4d().SetIdentity() matrix_pos.SetScale(abs_scale) matrix_pos.SetTranslateOnly(Gf.Vec3d(new_pos[0], new_pos[1], new_pos[2])) matrix_rot.SetRotate( Gf.Rotation(Gf.Vec3d.XAxis(), abs_rotation[0]) * Gf.Rotation(Gf.Vec3d.YAxis(), abs_rotation[1]) * Gf.Rotation(Gf.Vec3d.ZAxis(), abs_rotation[2]) ) # build final matrix attr_position.Set(matrix_rot * matrix_pos) else: carb.log_error(f"unknown existing position type. {attr_position}") else: attr_position = prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Float3, False) attr_position.Set(Gf.Vec3d(new_pos[0], new_pos[1], new_pos[2])) if attr_order: attr_order = omni.usd.TransformHelper().add_to_attr_order(attr_order, attr_position.GetName()) else: attr_order = prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False) attr_order.Set(["xformOp:translate"]) @staticmethod def copy_prim_to_clipboard(objects): objects["clipboard"]["prim_paths"] = [] for prim in objects["prim_list"]: objects["clipboard"]["prim_paths"].append(prim.GetPath().pathString) def clear_clipboard(objects): if "clipboard" in objects: del objects["clipboard"] @staticmethod def paste_prim_from_clipboard(objects): clipboard = objects["clipboard"] set_pos = "mouse_pos" in objects and len(objects["clipboard"]["prim_paths"]) == 1 usd_context = omni.usd.get_context() edit_mode = layers.get_layers(usd_context).get_edit_mode() is_auto_authoring = edit_mode == layers.LayerEditMode.AUTO_AUTHORING omni.kit.undo.begin_group() for prim_path in objects["clipboard"]["prim_paths"]: new_prim_path = omni.usd.get_stage_next_free_path(objects["stage"], prim_path, False) omni.kit.commands.execute( "CopyPrim", path_from=prim_path, path_to=new_prim_path, exclusive_select=True, copy_to_introducing_layer=is_auto_authoring ) if set_pos: ViewportMenu.set_prim_to_pos(new_prim_path, objects["mouse_pos"]) omni.kit.undo.end_group() @staticmethod def show_create_menu(objects): prim_list = None if "prim_list" in objects: prim_list = objects["prim_list"] get_instance().build_create_menu( objects, prim_list, omni.kit.context_menu.get_menu_dict("CREATE", "omni.kit.window.viewport"), delegate=ViewportMenu.menu_delegate ) get_instance().build_add_menu( objects, prim_list, omni.kit.context_menu.get_menu_dict("ADD", "omni.kit.window.viewport") ) @staticmethod def show_menu(usd_context_name: str, prim_path: str = None, world_pos: Sequence[float] = None, stage=None): # get context menu core functionality & check its enabled if hasattr(omni.kit, "context_menu"): context_menu = get_instance() else: context_menu = None if context_menu is None: carb.log_info("context_menu is disabled!") return usd_context = omni.usd.get_context(usd_context_name) # get stage if stage is None: stage = usd_context.get_stage() if stage is None: carb.log_error("stage not avaliable") return None # setup objects, this is passed to all functions objects = {} objects["stage"] = stage objects["usd_context_name"] = usd_context_name prim_list = [] paths = usd_context.get_selection().get_selected_prim_paths() if len(paths) > 0: for path in paths: prim = stage.GetPrimAtPath(path) if prim: prim_list.append(prim) elif prim_path: prim = stage.GetPrimAtPath(prim_path) if prim: prim_list.append(prim) if prim_list: objects["prim_list"] = prim_list if world_pos is not None: # Legacy name 'mouse_pos' objects["mouse_pos"] = world_pos # But it's actually the world-space position objects["world_position"] = world_pos # setup menu menu_dict = [ {"populate_fn": lambda o, d=ViewportMenu.menu_delegate: context_menu.show_selected_prims_names(o, d)}, {"populate_fn": ViewportMenu.show_create_menu}, { "name": "Find in Content Browser", "glyph": "menu_search.svg", "show_fn": [ context_menu.is_one_prim_selected, context_menu.can_show_find_in_browser, ], "onclick_fn": context_menu.find_in_browser, }, {"name": ""}, { "name": "Group Selected", "glyph": "group_selected.svg", "show_fn": context_menu.is_prim_selected, "onclick_fn": context_menu.group_selected_prims, }, { "name": "Ungroup Selected", "glyph": "group_selected.svg", "show_fn": [ context_menu.is_prim_selected, context_menu.is_prim_in_group, ], "onclick_fn": context_menu.ungroup_selected_prims, }, { "name": "Duplicate", "glyph": "menu_duplicate.svg", "show_fn": context_menu.can_be_copied, "onclick_fn": context_menu.duplicate_prim, }, { "name": "Delete", "glyph": "menu_delete.svg", "show_fn": context_menu.can_delete, "onclick_fn": context_menu.delete_prim, }, {"name": ""}, { "name": "Copy", "glyph": "menu_duplicate.svg", "show_fn": context_menu.can_be_copied, "onclick_fn": ViewportMenu.copy_prim_to_clipboard, }, { "name": "Paste Here", "glyph": "menu_paste.svg", "show_fn": ViewportMenu.is_prim_on_clipboard, "onclick_fn": ViewportMenu.paste_prim_from_clipboard, }, # this will not be shown, used by tests to cleanup clipboard { "name": "Clear Clipboard", "glyph": "menu_duplicate.svg", "show_fn_async": ViewportMenu.can_show_clear_clipboard, "onclick_fn": ViewportMenu.clear_clipboard, }, {"name": ""}, { "name": "Refresh Reference", "glyph": "sync.svg", "name_fn": context_menu.refresh_reference_payload_name, "show_fn": [context_menu.is_prim_selected, context_menu.has_payload_or_reference], "onclick_fn": context_menu.refresh_payload_or_reference, }, {"name": ""}, { "name": "Select Bound Objects", "glyph": "menu_search.svg", "show_fn": context_menu.is_material, "onclick_fn": context_menu.select_prims_using_material, }, { "name": "Assign Material", "glyph": "menu_material.svg", "show_fn_async": context_menu.can_assign_material_async, "onclick_fn": ViewportMenu.bind_material_to_prim_dialog, }, {"name": "", "show_fn_async": context_menu.can_assign_material_async}, { "name": "Copy URL Link", "glyph": "menu_link.svg", "show_fn": [ context_menu.is_prim_selected, context_menu.is_one_prim_selected, context_menu.can_show_find_in_browser, ], "onclick_fn": context_menu.copy_prim_url, }, { "name": "Copy Prim Path", "glyph": "menu_link.svg", "show_fn": [ context_menu.is_prim_selected, context_menu.is_one_prim_selected, context_menu.can_show_find_in_browser, ], "onclick_fn": context_menu.copy_prim_path, }, ] menu_dict += omni.kit.context_menu.get_menu_dict("MENU", "") menu_dict += omni.kit.context_menu.get_menu_dict("MENU", "omni.kit.window.viewport") omni.kit.context_menu.reorder_menu_dict(menu_dict) # show menu context_menu.show_context_menu("viewport", objects, menu_dict, delegate=ViewportMenu.menu_delegate)
13,265
Python
38.718563
153
0.5317
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/tests/test_assign_material.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.kit.test import os import carb import omni.kit.app import omni.usd from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from pxr import Tf, UsdShade from omni.kit.test_suite.helpers import get_test_data_path, select_prims, wait_stage_loading, arrange_windows from omni.kit.material.library.test_helper import MaterialLibraryTestHelper class TestContextMenuAssignMaterial(AsyncTestCase): # Before running each test async def setUp(self): import omni.kit.material.library await arrange_windows() # wait for material to be preloaded so create menu is complete & menus don't rebuild during tests await omni.kit.material.library.get_mdl_list_async() await ui_test.human_delay(50) # After running each test async def tearDown(self): await wait_stage_loading() async def test_assign_material(self): # new stage usd_context = omni.usd.get_context() await usd_context.new_stage_async() stage = usd_context.get_stage() # setup await ui_test.find("Stage").focus() # create root prim rootname = "/World" stage.SetDefaultPrim(stage.DefinePrim(rootname)) # create Looks folder omni.kit.commands.execute("CreatePrim", prim_path="{}/Looks".format(rootname), prim_type="Scope", select_new_prim=True) # create material kit_folder = carb.tokens.get_tokens_interface().resolve("${kit}") omni_pbr_mtl = os.path.normpath(kit_folder + "/mdl/core/Base/OmniPBR.mdl") mtl_path = omni.usd.get_stage_next_free_path(stage, "{}/Looks/{}".format(rootname, Tf.MakeValidIdentifier("OmniPBR")), False) omni.kit.commands.execute("CreateMdlMaterialPrim", mtl_url=omni_pbr_mtl, mtl_name="OmniPBR", mtl_path=mtl_path) # create sphere omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere", select_new_prim=True) # select prim await select_prims(["/World/Sphere"]) # expand stage window... stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True").widget.set_expanded(None, True, True) # get prim prim = stage.GetPrimAtPath("/World/Sphere") # click on context menu item & assign ma viewport = ui_test.find("Viewport") await viewport.focus() await viewport.right_click() await ui_test.human_delay(10) await ui_test.select_context_menu("Assign Material") # assign material await ui_test.human_delay() async with MaterialLibraryTestHelper() as material_test_helper: await material_test_helper.handle_assign_material_dialog(1, 0) bound_material, relationship = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() strength = UsdShade.MaterialBindingAPI.GetMaterialBindingStrength(relationship) self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, mtl_path) self.assertEqual(strength, UsdShade.Tokens.weakerThanDescendants) # click on context menu item viewport = ui_test.find("Viewport") await viewport.focus() await viewport.right_click() await ui_test.human_delay(10) await ui_test.select_context_menu("Assign Material") # assign material with different strength await ui_test.human_delay() async with MaterialLibraryTestHelper() as material_test_helper: await material_test_helper.handle_assign_material_dialog(1, 1) bound_material, relationship = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() strength = UsdShade.MaterialBindingAPI.GetMaterialBindingStrength(relationship) self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, mtl_path) self.assertEqual(strength, UsdShade.Tokens.strongerThanDescendants)
4,351
Python
41.252427
133
0.69892
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/tests/test_populate_fn.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. ## import omni.kit.app import omni.kit.commands import omni.kit.test import pathlib import omni.ui as ui from omni.ui.tests.test_base import OmniUiTest from omni.kit import ui_test from pxr import Kind, Sdf, Gf from omni.kit.test_suite.helpers import get_test_data_path, select_prims, get_prims, wait_stage_loading, arrange_windows from omni.kit.context_menu import ContextMenuExtension class TestContextMenuPopulateFn(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() await arrange_windows() # After running each test async def tearDown(self): await super().tearDown() # Test(s) async def test_populate_context_menu(self): menu = {"name": "Entry 0"} entry0 = omni.kit.context_menu.add_menu(menu, "TEST", "NO_SEP_TEST") # add separator menu = {"name": ""} sep = omni.kit.context_menu.add_menu(menu, "TEST", "NO_SEP_TEST") menu = { "name": "Entry 1", "populate_fn": lambda *_: ContextMenuExtension.uiMenuItem("Entry 1") } entry1 = omni.kit.context_menu.add_menu(menu, "TEST", "NO_SEP_TEST") menu_list = omni.kit.context_menu.get_menu_dict("TEST", "NO_SEP_TEST") omni.kit.context_menu.get_instance().show_context_menu("TEST", {}, menu_list) await ui_test.human_delay() menu_dict = await ui_test.get_context_menu(get_all=True) self.assertEqual(menu_dict["_"], ['Entry 0', '', 'Entry 1'])
1,933
Python
36.192307
121
0.679772
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/tests/test_prim_copy_paste.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.kit.test import os import omni.kit.app import omni.usd from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from pxr import Sdf, UsdShade from omni.kit.viewport.utility import get_ui_position_for_prim from omni.kit.test_suite.helpers import ( open_stage, get_test_data_path, select_prims, get_prims, wait_stage_loading, arrange_windows ) class PrimMeshCopyPatse(AsyncTestCase): # Before running each test async def setUp(self): self._viewport_window = await arrange_windows("Stage", 768) await omni.usd.get_context().new_stage_async() stage = omni.usd.get_context().get_stage() stage.SetDefaultPrim(stage.DefinePrim("/World")) await wait_stage_loading() # expand treeview stage_window = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True") stage_window.widget.set_expanded(None, True, True) await ui_test.human_delay(50) # After running each test async def tearDown(self): await wait_stage_loading() await omni.usd.get_context().new_stage_async() async def test_prim_copy_paste(self): def find_menu_item(menu_path: str): from omni import ui from omni.kit.ui_test.menu import _find_menu_item, _find_context_menu_item return _find_context_menu_item(menu_path, ui.Menu.get_current(), _find_menu_item) await wait_stage_loading() # setup stage = omni.usd.get_context().get_stage() stage_window = ui_test.find("Stage") safe_target = stage_window.position + ui_test.Vec2(stage_window.size.x / 2, stage_window.size.y - 32) tree_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True") await stage_window.focus() # get context menu & create scope await stage_window.right_click(pos=safe_target) menu_dict = await ui_test.get_context_menu() await ui_test.human_delay() await ui_test.select_context_menu("Create/Scope", offset=ui_test.Vec2(10, 10)) base_prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] # create mesh, no children await select_prims([]) await stage_window.right_click(pos=safe_target) await ui_test.human_delay() await ui_test.select_context_menu("Create/Mesh/Sphere", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay(10) # wait for VP to be ready await wait_stage_loading() await ui_test.human_delay(100) prim_pos, valid = get_ui_position_for_prim(self._viewport_window, "/World/Sphere") self.assertTrue(valid) viewport = ui_test.find("Viewport") await viewport.focus() # open VP context menu & copy prim await viewport.right_click(pos=ui_test.Vec2(prim_pos[0], prim_pos[1] + 30)) await ui_test.human_delay(50) await ui_test.select_context_menu("Copy", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay(50) # copy VP context menu & paste here await viewport.right_click(pos=ui_test.Vec2(prim_pos[0] + 50, prim_pos[1] + 50)) await ui_test.human_delay(50) await ui_test.select_context_menu("Paste Here", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay(50) # verify await ui_test.human_delay(50) stage = omni.usd.get_context().get_stage() prim = stage.GetPrimAtPath("/World/Sphere_01") self.assertTrue(prim.IsValid()) # clear VP context menu clipboard await viewport.right_click(pos=ui_test.Vec2(prim_pos[0] + 50, prim_pos[1] + 50)) await ui_test.human_delay(50) find_menu_item("Clear Clipboard").call_triggered_fn() await ui_test.human_delay(10) omni.kit.context_menu.close_menu()
4,358
Python
37.919643
117
0.658559
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/tests/test_prim_shape_children.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.kit.test import os import omni.kit.app import omni.usd from omni.kit.test.async_unittest import AsyncTestCase 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, get_prims, wait_stage_loading, arrange_windows ) class CreatePrimShapeChildren(AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows("Stage", 768) await omni.usd.get_context().new_stage_async() stage = omni.usd.get_context().get_stage() stage.SetDefaultPrim(stage.DefinePrim("/World")) stage.DefinePrim("/World/Red_Herring", "Scope") await wait_stage_loading() # expand treeview stage_window = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True") stage_window.widget.set_expanded(None, True, True) await ui_test.human_delay(50) # After running each test async def tearDown(self): await wait_stage_loading() async def test_create_prim_children_shape(self): await wait_stage_loading() # setup stage = omni.usd.get_context().get_stage() stage_window = ui_test.find("Stage") safe_target = stage_window.position + ui_test.Vec2(stage_window.size.x / 2, stage_window.size.y - 32) tree_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True") await stage_window.focus() # get context menu & create scope await stage_window.right_click(pos=safe_target) menu_dict = await ui_test.get_context_menu() await ui_test.human_delay() await ui_test.select_context_menu(f"Create/Scope", offset=ui_test.Vec2(10, 10)) base_prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] # create shape, no children await select_prims([]) for shape in menu_dict['Create']['Shape']['_']: await stage_window.right_click(pos=safe_target) await ui_test.human_delay() await ui_test.select_context_menu(f"Create/Shape/{shape}", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay(10) prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] created_prims = [x for x in prims if x not in base_prims] # create shape with as child (should fail) await tree_widget.find(f"**/StringField[*].model.path=='/World/Red_Herring'").click() for prim_path in created_prims: widget = tree_widget.find(f"**/StringField[*].model.path=='{prim_path}'") widget.widget.scroll_here_y(0.5) await ui_test.human_delay(10) widget = tree_widget.find(f"**/StringField[*].model.path=='{prim_path}'") menu_pos = widget.position + ui_test.Vec2(10, 10) for shape in menu_dict['Create']['Shape']['_']: await stage_window.right_click(menu_pos) await ui_test.select_context_menu(f"Create/Shape/{shape}", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay(10) # verify prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] final_prims = [x for x in prims if x not in base_prims] self.assertEqual(final_prims, ['/World/Capsule', '/World/Cone', '/World/Cube', '/World/Cylinder', '/World/Sphere', '/World/Capsule_01', '/World/Cone_01', '/World/Cube_01', '/World/Cylinder_01', '/World/Sphere_01', '/World/Capsule_02', '/World/Cone_02', '/World/Cube_02', '/World/Cylinder_02', '/World/Sphere_02', '/World/Capsule_03', '/World/Cone_03', '/World/Cube_03', '/World/Cylinder_03', '/World/Sphere_03', '/World/Capsule_04', '/World/Cone_04', '/World/Cube_04', '/World/Cylinder_04', '/World/Sphere_04', '/World/Capsule_05', '/World/Cone_05', '/World/Cube_05', '/World/Cylinder_05', '/World/Sphere_05']) async def test_create_prim_children_shape_scope_empty(self): await wait_stage_loading() # setup stage = omni.usd.get_context().get_stage() stage_window = ui_test.find("Stage") safe_target = stage_window.position + ui_test.Vec2(stage_window.size.x / 2, stage_window.size.y - 32) tree_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True") await stage_window.focus() # get context menu & create scope await stage_window.right_click(pos=safe_target) menu_dict = await ui_test.get_context_menu() await ui_test.human_delay() await ui_test.select_context_menu(f"Create/Scope", offset=ui_test.Vec2(10, 10)) base_prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] # create shape, no children for shape in menu_dict['Create']['Shape']['_']: await select_prims(["/World/Scope"]) await stage_window.right_click(pos=safe_target) await ui_test.human_delay() await ui_test.select_context_menu(f"Create/Shape/{shape}", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay(10) prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] created_prims = [x for x in prims if x not in base_prims] # verify prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] self.assertEqual(prims, ['/World', '/World/Red_Herring', '/World/Scope', '/World/Capsule', '/World/Cone', '/World/Cube', '/World/Cylinder', '/World/Sphere']) async def test_create_prim_children_shape_xform_empty(self): await wait_stage_loading() # setup stage = omni.usd.get_context().get_stage() stage_window = ui_test.find("Stage") safe_target = stage_window.position + ui_test.Vec2(stage_window.size.x / 2, stage_window.size.y - 32) tree_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True") await stage_window.focus() # get context menu & create scope await stage_window.right_click(pos=safe_target) menu_dict = await ui_test.get_context_menu() await ui_test.human_delay() await ui_test.select_context_menu(f"Create/Xform", offset=ui_test.Vec2(10, 10)) base_prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] # create shape, no children for shape in menu_dict['Create']['Shape']['_']: await select_prims(["/World/Xform"]) await stage_window.right_click(pos=safe_target) await ui_test.human_delay() await ui_test.select_context_menu(f"Create/Shape/{shape}", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay(10) prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] created_prims = [x for x in prims if x not in base_prims] # verify prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] self.assertEqual(prims, ['/World', '/World/Red_Herring', '/World/Xform', '/World/Capsule', '/World/Cone', '/World/Cube', '/World/Cylinder', '/World/Sphere']) async def test_create_prim_children_shape_scope_hover(self): await wait_stage_loading() # setup stage = omni.usd.get_context().get_stage() stage_window = ui_test.find("Stage") safe_target = stage_window.position + ui_test.Vec2(stage_window.size.x / 2, stage_window.size.y - 32) tree_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True") await stage_window.focus() # get context menu & create scope await stage_window.right_click(pos=safe_target) menu_dict = await ui_test.get_context_menu() await ui_test.human_delay() await ui_test.select_context_menu(f"Create/Scope", offset=ui_test.Vec2(10, 10)) base_prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] # create shape, no children for shape in menu_dict['Create']['Shape']['_']: await select_prims(["/World/Scope"]) #await stage_window.right_click(pos=safe_target) stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True") await stage_widget.find(f"**/StringField[*].model.path=='/World/Scope'").right_click() await ui_test.human_delay() await ui_test.select_context_menu(f"Create/Shape/{shape}", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay(10) prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] created_prims = [x for x in prims if x not in base_prims] # verify prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] self.assertEqual(prims, ['/World', '/World/Red_Herring', '/World/Scope', '/World/Scope/Capsule', '/World/Scope/Cone', '/World/Scope/Cube', '/World/Scope/Cylinder', '/World/Scope/Sphere']) async def test_create_prim_children_shape_xform_hover(self): await wait_stage_loading() # setup stage = omni.usd.get_context().get_stage() stage_window = ui_test.find("Stage") safe_target = stage_window.position + ui_test.Vec2(stage_window.size.x / 2, stage_window.size.y - 32) tree_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True") await stage_window.focus() # get context menu & create scope await stage_window.right_click(pos=safe_target) menu_dict = await ui_test.get_context_menu() await ui_test.human_delay() await ui_test.select_context_menu(f"Create/Xform", offset=ui_test.Vec2(10, 10)) base_prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] # create shape, no children for shape in menu_dict['Create']['Shape']['_']: await select_prims(["/World/Xform"]) #await stage_window.right_click(pos=safe_target) stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True") await stage_widget.find(f"**/StringField[*].model.path=='/World/Xform'").right_click() await ui_test.human_delay() await ui_test.select_context_menu(f"Create/Shape/{shape}", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay(10) prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] created_prims = [x for x in prims if x not in base_prims] # verify prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] self.assertEqual(prims, ['/World', '/World/Red_Herring', '/World/Xform', '/World/Xform/Capsule', '/World/Xform/Cone', '/World/Xform/Cube', '/World/Xform/Cylinder', '/World/Xform/Sphere'])
11,776
Python
50.204348
618
0.64071
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/tests/test_add_mdl_file.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.test import os import omni.kit.app import omni.usd from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from pxr import Sdf, UsdShade from omni.kit.test_suite.helpers import get_test_data_path, wait_stage_loading, arrange_windows from omni.kit.material.library.test_helper import MaterialLibraryTestHelper class TestCreateMenuContextMenu(AsyncTestCase): # Before running each test async def setUp(self): # manually arrange windows as linux fails to auto-arrange await arrange_windows() # After running each test async def tearDown(self): await wait_stage_loading() async def test_viewport_menu_add_mdl_file(self): # new stage usd_context = omni.usd.get_context() await usd_context.new_stage_async() stage = usd_context.get_stage() # setup await ui_test.find("Stage").focus() viewport = ui_test.find("Viewport") await viewport.focus() # click on context menu item await viewport.right_click() await ui_test.human_delay(50) await ui_test.select_context_menu("Create/Material/Add MDL File") await ui_test.human_delay() # use add material dialog async with MaterialLibraryTestHelper() as material_test_helper: await material_test_helper.handle_add_material_dialog(get_test_data_path(__name__, "TESTEXPORT.mdl")) # wait for material to load & UI to refresh await wait_stage_loading() # 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")
2,261
Python
37.338982
113
0.704998
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/tests/__init__.py
from .test_context_menu import * from .test_icon_menu import * from .test_add_mdl_file import * from .test_assign_material import * from .test_prim_mesh_children_stage import CreatePrimMeshChildrenStage from .test_prim_mesh_children_viewport import CreatePrimMeshChildrenViewport from .test_prim_shape_children import CreatePrimShapeChildren from .test_no_style_leaking import TestContextMenuNoStyleLeakage from .test_menu_delegate import TestContextMenuDelegate from .test_delegate_style import TestContextMenuDelegateStyle from .test_group_prims import TestContextMenuGroupPrims from .test_populate_fn import TestContextMenuPopulateFn from .test_enable_menu import TestEnableCreateMenu from .test_prim_copy_paste import PrimMeshCopyPatse
741
Python
48.466663
76
0.850202
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/tests/test_group_prims.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.kit.test import os import carb import omni.kit.app import omni.usd import omni.kit.undo from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from pxr import Tf, UsdShade from omni.kit.test_suite.helpers import get_test_data_path, select_prims, get_prims, wait_stage_loading, arrange_windows from omni.kit.material.library.test_helper import MaterialLibraryTestHelper class TestContextMenuGroupPrims(AsyncTestCase): # Before running each test async def setUp(self): import omni.kit.material.library await arrange_windows() # wait for material to be preloaded so create menu is complete & menus don't rebuild during tests await omni.kit.material.library.get_mdl_list_async() await ui_test.human_delay(50) # After running each test async def tearDown(self): await wait_stage_loading() async def test_group_prims(self): # new stage usd_context = omni.usd.get_context() await usd_context.new_stage_async() stage = usd_context.get_stage() # setup stage = omni.usd.get_context().get_stage() stage_window = ui_test.find("Stage") safe_target = stage_window.position + ui_test.Vec2(stage_window.size.x / 2, stage_window.size.y - 32) tree_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True") await stage_window.focus() # create root prim rootname = "/World" stage.SetDefaultPrim(stage.DefinePrim(rootname)) ## create prim omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere") await ui_test.human_delay() # verify prims were created prim_list = [prim.GetPath().pathString for prim in get_prims(stage) if not omni.usd.is_hidden_type(prim)] self.assertTrue(prim_list == ['/World', '/World/Sphere']) # group sphere & world await select_prims(['/World', '/World/Sphere']) # get context menu & create scope await stage_window.right_click(pos=safe_target) menu_dict = await ui_test.get_context_menu() await ui_test.human_delay() await ui_test.select_context_menu(f"Group Selected", offset=ui_test.Vec2(10, 10)) # verify prims were not grouped prim_list = [prim.GetPath().pathString for prim in get_prims(stage) if not omni.usd.is_hidden_type(prim)] self.assertTrue(prim_list == ['/World', '/World/Sphere']) # select sphere await select_prims(["/World/Sphere"]) # get context menu & create scope await stage_window.right_click(pos=safe_target) menu_dict = await ui_test.get_context_menu() await ui_test.human_delay() await ui_test.select_context_menu(f"Group Selected", offset=ui_test.Vec2(10, 10)) # verify prims were grouped prim_list = [prim.GetPath().pathString for prim in get_prims(stage) if not omni.usd.is_hidden_type(prim)] self.assertTrue(prim_list == ['/World', '/World/Group', '/World/Group/Sphere']) # ungroup the prims await select_prims(['/World/Group']) # get context menu & create scope await stage_window.right_click(pos=safe_target) menu_dict = await ui_test.get_context_menu() await ui_test.human_delay() await ui_test.select_context_menu(f"Ungroup Selected", offset=ui_test.Vec2(10, 10)) # verify prims were ungrouped prim_list = [prim.GetPath().pathString for prim in get_prims(stage) if not omni.usd.is_hidden_type(prim)] self.assertTrue(prim_list == ['/World', '/World/Sphere'])
4,094
Python
39.95
121
0.672692
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/tests/test_menu_delegate.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 import omni.kit.commands import omni.kit.test from omni.ui.tests.test_base import OmniUiTest import omni.ui as ui from omni.kit import ui_test from pxr import Kind, Sdf, Gf import pathlib class TestContextMenuDelegate(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() # After running each test async def tearDown(self): await super().tearDown() # Test(s) async def test_delegate_context_menu(self): from omni.kit.context_menu import ContextMenuExtension def stub_fn(): pass def show_stub_false(objects): return False # setup menu menu_list = [ { "name": "Set Authoring Layer", "glyph": "menu_rename.svg", "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Create Sublayer", "glyph": "menu_create_sublayer.svg", "onclick_fn": stub_fn, }, { "name": "Insert Sublayer", "glyph": "menu_insert_sublayer.svg", "onclick_fn": stub_fn, }, { "name": "Merge Down One", "glyph": "menu_merge_down.svg", "onclick_fn": stub_fn, }, { "name": "Flatten Sublayers", "glyph": "menu_flatten_layers.svg", "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Save", "glyph": "menu_save.svg", "onclick_fn": stub_fn, }, { "name": "Save As", "glyph": "menu_save_as.svg", "onclick_fn": stub_fn, }, { "name": "Save As And Replace", "glyph": "menu_save_as.svg", "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Reload Layer", "glyph": "menu_refresh.svg", "onclick_fn": stub_fn, }, { "name": "Remove Layer", "glyph": "menu_remove_layer.svg", "onclick_fn": stub_fn, }, { "name": "Delete Prim", "glyph": "menu_delete.svg", "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Select Bound Objects", "glyph": "menu_search.svg", "onclick_fn": stub_fn, }, {"name": ""}, {"glyph": "menu_link.svg", "name": { 'SubMenu': [ {'name': 'Set up axis +Y', 'onclick_fn': stub_fn}, {'name': 'Set up axis +Z', 'onclick_fn': stub_fn} ] }, }, {"glyph": "none.svg", "name": { 'SubMenu Hidden': [ {'name': 'Set up axis +Y', "show_fn": show_stub_false, 'onclick_fn': stub_fn}, {'name': 'Set up axis +Z', "show_fn": show_stub_false, 'onclick_fn': stub_fn} ] } }, ] delegate_calls = {"init": 0, "build_item": 0, "build_status": 0, "build_title": 0, "get_style": 0, "get_parameters": 0} class MenuDelegate(ContextMenuExtension.DefaultMenuDelegate): def __init__(self, **kwargs): nonlocal delegate_calls super().__init__(**kwargs) delegate_calls["init"] += 1 def build_item(self, item: ui.MenuHelper): nonlocal delegate_calls super().build_item(item) delegate_calls["build_item"] += 1 def build_status(self, item: ui.MenuHelper): nonlocal delegate_calls super().build_status(item) delegate_calls["build_status"] += 1 def build_title(self, item: ui.MenuHelper): nonlocal delegate_calls super().build_title(item) delegate_calls["build_title"] += 1 def get_style(self): nonlocal delegate_calls delegate_calls["get_style"] += 1 return {} def get_parameters(self, name, kwargs): nonlocal delegate_calls delegate_calls["get_parameters"] += 1 await ui_test.human_delay(50) menu_delegate = MenuDelegate() window = await self.create_test_window(width=200, height=330) context_menu = omni.kit.context_menu.get_instance() context_menu.show_context_menu("delegate", {"menu_xpos": 4, "menu_ypos": 4}, menu_list, delegate=menu_delegate) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() await self.finalize_test_no_image() await ui_test.human_delay(50) self.assertEqual(delegate_calls, {'init': 1, 'build_item': 21, 'build_status': 2, 'build_title': 2, 'get_style': 17, 'get_parameters': 15})
5,744
Python
32.994083
147
0.475453
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/tests/test_no_style_leaking.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 import omni.kit.commands import omni.kit.test from omni.ui.tests.test_base import OmniUiTest import omni.ui as ui from omni.kit import ui_test from omni.kit.test_suite.helpers import wait_stage_loading, arrange_windows from pxr import Kind, Sdf, Gf import pathlib class TestContextMenuNoStyleLeakage(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() await arrange_windows() await omni.usd.get_context().new_stage_async() stage = omni.usd.get_context().get_stage() stage.SetDefaultPrim(stage.DefinePrim("/World")) from omni.kit.context_menu.scripts.context_menu import TEST_DATA_PATH self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() self._usd_path = TEST_DATA_PATH.absolute().joinpath("usd").absolute() # After running each test async def tearDown(self): await super().tearDown() # Test(s) async def test_no_style_leaking(self): def stub_fn(): pass def show_stub_false(objects): return False # setup menu menu_list = [ { "name": "Set Authoring Layer", "glyph": "menu_rename.svg", "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Create Sublayer", "glyph": "menu_create_sublayer.svg", "onclick_fn": stub_fn, }, { "name": "Insert Sublayer", "glyph": "menu_insert_sublayer.svg", "onclick_fn": stub_fn, }, { "name": "Merge Down One", "glyph": "menu_merge_down.svg", "onclick_fn": stub_fn, }, { "name": "Flatten Sublayers", "glyph": "menu_flatten_layers.svg", "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Save", "glyph": "menu_save.svg", "onclick_fn": stub_fn, }, { "name": "Save As", "glyph": "menu_save_as.svg", "onclick_fn": stub_fn, }, { "name": "Save As And Replace", "glyph": "menu_save_as.svg", "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Reload Layer", "glyph": "menu_refresh.svg", "onclick_fn": stub_fn, }, { "name": "Remove Layer", "glyph": "menu_remove_layer.svg", "onclick_fn": stub_fn, }, { "name": "Delete Prim", "glyph": "menu_delete.svg", "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Select Bound Objects", "glyph": "menu_search.svg", "onclick_fn": stub_fn, }, {"name": ""}, {"glyph": "menu_link.svg", "name": { 'SubMenu': [ {'name': 'Set up axis +Y', 'onclick_fn': stub_fn}, {'name': 'Set up axis +Z', 'onclick_fn': stub_fn} ] }, }, {"glyph": "none.svg", "name": { 'SubMenu Hidden': [ {'name': 'Set up axis +Y', "show_fn": show_stub_false, 'onclick_fn': stub_fn}, {'name': 'Set up axis +Z', "show_fn": show_stub_false, 'onclick_fn': stub_fn} ] } }, ] await wait_stage_loading() await ui_test.find("Stage").focus() viewport = ui_test.find("Viewport") await viewport.focus() # show viewport context menu await viewport.right_click() await ui_test.human_delay(10) # without closing context menu open new one & check for style leaking window = await self.create_test_window(width=200, height=330) context_menu = omni.kit.context_menu.get_instance() context_menu.show_context_menu("toolbar", {"menu_xpos": 4, "menu_ypos": 4}, menu_list) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_context_menu_style_leak_ui.png")
5,102
Python
33.47973
124
0.489808
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/tests/test_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 pathlib import omni.kit.app import omni.kit.commands import omni.kit.test import omni.ui as ui import omni.usd from omni.ui.tests.test_base import OmniUiTest from omni.kit import ui_test from pxr import Kind, Sdf, Gf, Usd class TestContextMenu(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() from omni.kit.context_menu.scripts.context_menu import TEST_DATA_PATH self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() self._usd_path = TEST_DATA_PATH.absolute().joinpath("usd").absolute() self._usd_context = omni.usd.get_context() await self._usd_context.new_stage_async() # After running each test async def tearDown(self): await super().tearDown() # Test(s) async def test_basic_context_menu(self): def stub_fn(): pass def show_stub_false(objects): return False # setup menu menu_list = [ { "name": "Set Authoring Layer", "glyph": "menu_rename.svg", "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Create Sublayer", "glyph": "menu_create_sublayer.svg", "onclick_fn": stub_fn, }, { "name": "Insert Sublayer", "glyph": "menu_insert_sublayer.svg", "onclick_fn": stub_fn, }, { "name": "Merge Down One", "glyph": "menu_merge_down.svg", "onclick_fn": stub_fn, }, { "name": "Flatten Sublayers", "glyph": "menu_flatten_layers.svg", "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Save", "glyph": "menu_save.svg", "onclick_fn": stub_fn, }, { "name": "Save As", "glyph": "menu_save_as.svg", "onclick_fn": stub_fn, }, { "name": "Save As And Replace", "glyph": "menu_save_as.svg", "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Reload Layer", "glyph": "menu_refresh.svg", "onclick_fn": stub_fn, }, { "name": "Remove Layer", "glyph": "menu_remove_layer.svg", "onclick_fn": stub_fn, }, { "name": "Delete Prim", "glyph": "menu_delete.svg", "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Select Bound Objects", "glyph": "menu_search.svg", "onclick_fn": stub_fn, }, {"name": ""}, {"glyph": "menu_link.svg", "name": { 'SubMenu': [ {'name': 'Set up axis +Y', 'onclick_fn': stub_fn}, {'name': 'Set up axis +Z', 'onclick_fn': stub_fn} ] }, }, {"glyph": "none.svg", "name": { 'SubMenu Hidden': [ {'name': 'Set up axis +Y', "show_fn": show_stub_false, 'onclick_fn': stub_fn}, {'name': 'Set up axis +Z', "show_fn": show_stub_false, 'onclick_fn': stub_fn} ] } }, ] window = await self.create_test_window(width=200, height=330) context_menu = omni.kit.context_menu.get_instance() context_menu.show_context_menu("toolbar", {"menu_xpos": 4, "menu_ypos": 4}, menu_list) await ui_test.human_delay(10) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_context_menu_ui.png") async def test_conversion_between_payloads_and_references(self): from omni.kit import ui_test stage = self._usd_context.get_stage() prim = stage.DefinePrim("/root/prim", "Xform") reference_layer = Sdf.Layer.CreateAnonymous() reference_layer2 = Sdf.Layer.CreateAnonymous() reference_stage = Usd.Stage.Open(reference_layer) reference_prim = reference_stage.DefinePrim("/root/reference", "Xform") payload_prim = reference_stage.DefinePrim("/root/payload", "Xform") default_prim = reference_stage.GetPrimAtPath("/root") reference_stage.SetDefaultPrim(default_prim) reference_prim.GetReferences().AddReference(reference_layer2.identifier) payload_prim.GetPayloads().AddPayload(reference_layer2.identifier) prim.GetReferences().AddReference(reference_layer.identifier) await ui_test.wait_n_updates(2) self._usd_context.get_selection().set_selected_prim_paths(["/root/prim/reference"], True) await ui_test.wait_n_updates(2) self._usd_context.get_selection().set_selected_prim_paths([], True) ref_and_layers = omni.usd.get_composed_references_from_prim(prim) self.assertTrue(len(ref_and_layers) == 1) reference_prim = stage.GetPrimAtPath("/root/prim/reference") ref_and_layers = omni.usd.get_composed_references_from_prim(reference_prim) self.assertTrue(len(ref_and_layers) == 1) payload_prim = stage.GetPrimAtPath("/root/prim/payload") payload_and_layers = omni.usd.get_composed_payloads_from_prim(payload_prim) self.assertTrue(len(payload_and_layers) == 1) await ui_test.find("Stage").focus() stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True") prim_widget = stage_widget.find("**/Label[*].text=='prim'") self.assertTrue(prim_widget) await prim_widget.right_click() await ui_test.select_context_menu("Convert References to Payloads") await ui_test.wait_n_updates(5) reference_prim = stage.GetPrimAtPath("/root/prim") ref_and_layers = omni.usd.get_composed_references_from_prim(prim) self.assertTrue(len(ref_and_layers) == 0) payload_and_layers = omni.usd.get_composed_payloads_from_prim(prim) self.assertTrue(len(payload_and_layers) == 1) prim_widget = stage_widget.find("**/Label[*].text=='prim'") await prim_widget.right_click() await ui_test.select_context_menu("Convert Payloads to References") await ui_test.wait_n_updates(5) payload_and_layers = omni.usd.get_composed_payloads_from_prim(prim) self.assertTrue(len(payload_and_layers) == 0) reference_prim = stage.GetPrimAtPath("/root/prim") ref_and_layers = omni.usd.get_composed_references_from_prim(prim) self.assertTrue(len(ref_and_layers) == 1) reference_prim_widget = stage_widget.find("**/Label[*].text=='reference'") self.assertTrue(reference_prim_widget) await reference_prim_widget.right_click() with self.assertRaises(Exception): await ui_test.select_context_menu("Convert Payloads to References") await ui_test.select_context_menu("Convert References to Payloads") prim = stage.GetPrimAtPath("/root/prim/reference") ref_and_layers = omni.usd.get_composed_references_from_prim(prim) self.assertTrue(len(ref_and_layers) == 0) prim = stage.GetPrimAtPath("/root/prim/reference") payload_and_layers = omni.usd.get_composed_payloads_from_prim(prim) self.assertTrue(len(payload_and_layers) == 1) payload_prim_widget = stage_widget.find("**/Label[*].text=='payload'") self.assertTrue(payload_prim_widget) await payload_prim_widget.right_click() with self.assertRaises(Exception): await ui_test.select_context_menu("Convert References to Payloads") await ui_test.select_context_menu("Convert Payloads to References") prim = stage.GetPrimAtPath("/root/prim/payload") payload_and_layers = omni.usd.get_composed_payloads_from_prim(prim) self.assertTrue(len(payload_and_layers) == 0) reference_prim = stage.GetPrimAtPath("/root/prim/payload") ref_and_layers = omni.usd.get_composed_references_from_prim(prim) self.assertTrue(len(ref_and_layers) == 1)
8,933
Python
38.706666
113
0.567335
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/tests/test_icon_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.app import omni.kit.commands import omni.kit.test import omni.ui as ui import omni.usd from omni.ui.tests.test_base import OmniUiTest from omni.kit import ui_test from pxr import Kind, Sdf, Gf, Usd from pathlib import Path class TestIconMenu(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() from omni.kit.context_menu.scripts.context_menu import TEST_DATA_PATH self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() self._usd_path = TEST_DATA_PATH.absolute().joinpath("usd").absolute() self._usd_context = omni.usd.get_context() await self._usd_context.new_stage_async() # After running each test async def tearDown(self): await super().tearDown() # Test(s) async def test_icon_menu(self): def stub_fn(): pass def show_stub_false(objects): return False # setup menu icon_path = str(Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)).joinpath("data/tests/icons/button.svg")) menu_list = [ { "name": "Set Authoring Layer", "glyph": icon_path, "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Create Sublayer", "glyph": icon_path, "onclick_fn": stub_fn, }, { "name": "Insert Sublayer", "glyph": icon_path, "onclick_fn": stub_fn, }, { "name": "Merge Down One", "glyph": icon_path, "onclick_fn": stub_fn, }, { "name": "Flatten Sublayers", "glyph": icon_path, "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Save", "glyph": icon_path, "onclick_fn": stub_fn, }, { "name": "Save As", "glyph": icon_path, "onclick_fn": stub_fn, }, { "name": "Save As And Replace", "glyph": icon_path, "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Reload Layer", "glyph": icon_path, "onclick_fn": stub_fn, }, { "name": "Remove Layer", "glyph": icon_path, "onclick_fn": stub_fn, }, { "name": "Delete Prim", "glyph": icon_path, "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Select Bound Objects", "glyph": icon_path, "onclick_fn": stub_fn, }, {"name": ""}, {"glyph": "menu_link.svg", "name": { 'SubMenu': [ {'name': 'Set up axis +Y', 'onclick_fn': stub_fn}, {'name': 'Set up axis +Z', 'onclick_fn': stub_fn} ] }, }, {"glyph": "none.svg", "name": { 'SubMenu Hidden': [ {'name': 'Set up axis +Y', "show_fn": show_stub_false, 'onclick_fn': stub_fn}, {'name': 'Set up axis +Z', "show_fn": show_stub_false, 'onclick_fn': stub_fn} ] } }, ] window = await self.create_test_window(width=200, height=330) context_menu = omni.kit.context_menu.get_instance() context_menu.show_context_menu("toolbar", {"menu_xpos": 4, "menu_ypos": 4}, menu_list) await ui_test.human_delay(10) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_icon_menu_ui.png")
4,526
Python
32.533333
156
0.468626
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/tests/test_enable_menu.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. ## import carb import omni.kit.app import omni.kit.test import omni.usd from omni.ui.tests.test_base import OmniUiTest from omni.kit import ui_test from omni.kit.test_suite.helpers import wait_stage_loading, arrange_windows class TestEnableCreateMenu(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() await arrange_windows() await omni.usd.get_context().new_stage_async() await wait_stage_loading() # After running each test async def tearDown(self): await super().tearDown() # Test(s) async def test_enable_create_menu(self): settings = carb.settings.get_settings() def reset_prim_creation(): settings.set("/app/primCreation/hideShapes", False) settings.set("/app/primCreation/enableMenuShape", True) settings.set("/app/primCreation/enableMenuLight", True) settings.set("/app/primCreation/enableMenuAudio", True) settings.set("/app/primCreation/enableMenuCamera", True) settings.set("/app/primCreation/enableMenuScope", True) settings.set("/app/primCreation/enableMenuXform", True) def verify_menu(menu_dict: dict, mesh:bool, shape:bool, light:bool, audio:bool, camera:bool, scope:bool, xform:bool): self.assertEqual("Mesh" in menu_dict, mesh) self.assertEqual("Shape" in menu_dict, shape) self.assertEqual("Light" in menu_dict, light) self.assertEqual("Audio" in menu_dict, audio) self.assertEqual("Camera" in menu_dict["_"], camera) self.assertEqual("Scope" in menu_dict["_"], scope) self.assertEqual("Xform" in menu_dict["_"], xform) async def test_menu(mesh:bool, shape:bool, light:bool, audio:bool, camera:bool, scope:bool, xform:bool): # right click on viewport await ui_test.find("Viewport").right_click() await ui_test.human_delay(10) #get context menu as dict menu_dict = await ui_test.get_context_menu() omni.kit.context_menu.close_menu() # verify verify_menu(menu_dict['Create'], mesh, shape, light, audio, camera, scope, xform) await ui_test.human_delay(10) try: # verify default reset_prim_creation() await test_menu(mesh=True, shape=True, light=True, audio=True, camera=True, scope=True, xform=True) # verify hide shapes reset_prim_creation() settings.set("/app/primCreation/hideShapes", True) await test_menu(mesh=True, shape=False, light=True, audio=True, camera=True, scope=True, xform=True) reset_prim_creation() settings.set("/app/primCreation/enableMenuShape", False) await test_menu(mesh=True, shape=False, light=True, audio=True, camera=True, scope=True, xform=True) # verify hide light reset_prim_creation() settings.set("/app/primCreation/enableMenuLight", False) await test_menu(mesh=True, shape=True, light=False, audio=True, camera=True, scope=True, xform=True) # verify hide audio reset_prim_creation() settings.set("/app/primCreation/enableMenuAudio", False) await test_menu(mesh=True, shape=True, light=True, audio=False, camera=True, scope=True, xform=True) # verify hide camera reset_prim_creation() settings.set("/app/primCreation/enableMenuCamera", False) await test_menu(mesh=True, shape=True, light=True, audio=True, camera=False, scope=True, xform=True) # verify hide scope reset_prim_creation() settings.set("/app/primCreation/enableMenuScope", False) await test_menu(mesh=True, shape=True, light=True, audio=True, camera=True, scope=False, xform=True) # verify hide xform reset_prim_creation() settings.set("/app/primCreation/enableMenuXform", False) await test_menu(mesh=True, shape=True, light=True, audio=True, camera=True, scope=True, xform=False) finally: reset_prim_creation()
4,667
Python
43.884615
125
0.643668
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/tests/test_delegate_style.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 import omni.kit.commands import omni.kit.test import pathlib import omni.ui as ui from omni.ui.tests.test_base import OmniUiTest from omni.kit import ui_test from omni.kit.test_suite.helpers import wait_stage_loading, arrange_windows from pxr import Kind, Sdf, Gf class TestContextMenuDelegateStyle(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() await arrange_windows() await omni.usd.get_context().new_stage_async() stage = omni.usd.get_context().get_stage() stage.SetDefaultPrim(stage.DefinePrim("/World")) from omni.kit.context_menu.scripts.context_menu import TEST_DATA_PATH self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() self._usd_path = TEST_DATA_PATH.absolute().joinpath("usd").absolute() # After running each test async def tearDown(self): await super().tearDown() # Test(s) async def test_context_menu_style_leaks(self): from omni.kit.context_menu import ContextMenuExtension def stub_fn(): pass def show_stub_false(objects): return False # setup menu menu_list = [ { "name": "Set Authoring Layer", "glyph": "menu_rename.svg", "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Create Sublayer", "glyph": "menu_create_sublayer.svg", "onclick_fn": stub_fn, }, { "name": "Insert Sublayer", "glyph": "menu_insert_sublayer.svg", "onclick_fn": stub_fn, }, { "name": "Merge Down One", "glyph": "menu_merge_down.svg", "onclick_fn": stub_fn, }, { "name": "Flatten Sublayers", "glyph": "menu_flatten_layers.svg", "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Save", "glyph": "menu_save.svg", "onclick_fn": stub_fn, }, { "name": "Save As", "glyph": "menu_save_as.svg", "onclick_fn": stub_fn, }, { "name": "Save As And Replace", "glyph": "menu_save_as.svg", "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Reload Layer", "glyph": "menu_refresh.svg", "onclick_fn": stub_fn, }, { "name": "Remove Layer", "glyph": "menu_remove_layer.svg", "onclick_fn": stub_fn, }, { "name": "Delete Prim", "glyph": "menu_delete.svg", "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Select Bound Objects", "glyph": "menu_search.svg", "onclick_fn": stub_fn, }, {"name": ""}, {"glyph": "menu_link.svg", "name": { 'SubMenu': [ {'name': 'Set up axis +Y', 'onclick_fn': stub_fn}, {'name': 'Set up axis +Z', 'onclick_fn': stub_fn} ] }, }, {"glyph": "none.svg", "name": { 'SubMenu Hidden': [ {'name': 'Set up axis +Y', "show_fn": show_stub_false, 'onclick_fn': stub_fn}, {'name': 'Set up axis +Z', "show_fn": show_stub_false, 'onclick_fn': stub_fn} ] } }, ] class MenuDelegate(ContextMenuExtension.DefaultMenuDelegate): TEXT_SIZE = 14 ICON_SIZE = 14 MARGIN_SIZE = [3, 3] def get_style(self): from omni.kit.context_menu import style vp_style = style.MENU_STYLE.copy() vp_style["Label::Enabled"] = {"margin_width": self.MARGIN_SIZE[0],"margin_height": self.MARGIN_SIZE[1],"color": self.COLOR_LABEL_ENABLED} vp_style["Label::Disabled"] = {"margin_width": self.MARGIN_SIZE[0], "margin_height": self.MARGIN_SIZE[1], "color": self.COLOR_LABEL_DISABLED} return vp_style def get_parameters(self, name, kwargs): kwargs["tearable"] = False window = await self.create_test_window(width=200, height=280) context_menu = omni.kit.context_menu.get_instance() context_menu.show_context_menu("viewport", {"menu_xpos": 4, "menu_ypos": 4}, menu_list, delegate=MenuDelegate()) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_context_menu_style_ui.png")
5,589
Python
34.605095
157
0.496869
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/tests/test_prim_mesh_children_viewport.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.kit.test import os import omni.kit.app import omni.usd from omni.kit.test.async_unittest import AsyncTestCase 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, get_prims, wait_stage_loading, arrange_windows ) class CreatePrimMeshChildrenViewport(AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows("Stage") await omni.usd.get_context().new_stage_async() stage = omni.usd.get_context().get_stage() stage.SetDefaultPrim(stage.DefinePrim("/World")) await wait_stage_loading() # After running each test async def tearDown(self): await wait_stage_loading() async def test_create_prim_nochildren_mesh(self): await wait_stage_loading() # setup stage = omni.usd.get_context().get_stage() viewport_window = ui_test.find("Viewport") await viewport_window.focus() base_prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] # create light to be parent await viewport_window.right_click() menu_dict = await ui_test.get_context_menu() await ui_test.human_delay(10) await ui_test.select_context_menu("Create/Light/Distant Light", offset=ui_test.Vec2(10, 10)) # select light await ui_test.human_delay(10) await viewport_window.click() await ui_test.human_delay(10) # create meshes for mesh in menu_dict['Create']['Mesh']['_']: await viewport_window.right_click() await ui_test.human_delay() await ui_test.select_context_menu(f"Create/Mesh/{mesh}", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay(10) # verify prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] final_prims = [x for x in prims if x not in base_prims] self.assertEqual(final_prims, ['/World/DistantLight', '/World/Cone', '/World/Cube', '/World/Cylinder', '/World/Disk', '/World/Plane', '/World/Sphere', '/World/Torus'])
2,683
Python
36.802816
175
0.671264
omniverse-code/kit/exts/omni.kit.window.property/omni/kit/window/property/property_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. # __all__ = ["PropertyWidget"] from abc import abstractmethod from typing import Optional import omni.ui as ui from .property_filter import PropertyFilter # Base class of a property widget class PropertyWidget: """ Base class to create a group of widgets in Property Window """ def __init__(self, title: str): self._title = title # Ensure we always have a valid filter because PropertyWidgets may be created outside PropertyWindow self._filter = PropertyFilter() @abstractmethod def clean(self): """ Clean up function to be called before destorying the object. """ pass @abstractmethod def reset(self): """ Clean up function to be called when previously built widget is no longer visible given new scheme/payload """ pass @abstractmethod def build_impl(self): """ Main function to creates the UI elements. """ pass @abstractmethod def on_new_payload(self, payload) -> bool: """ Called when a new payload is delivered. PropertyWidget can take this opportunity to update its ui models, or schedule full UI rebuild. Args: payload: The new payload to refresh UI or update model. Return: True if the UI needs to be rebuilt. build_impl will be called as a result. False if the UI does not need to be rebuilt. build_impl will not be called. """ pass def build(self, filter: Optional[PropertyFilter] = None): # TODO some other decoration/styling here if filter: self._filter = filter self.build_impl()
2,131
Python
29.89855
113
0.66213
omniverse-code/kit/exts/omni.kit.window.property/omni/kit/window/property/property_filter.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. # import omni.ui as ui class PropertyFilter: """User defined filters for properties. For now, just a substring filter on property names""" def __init__(self): self._name = ui.SimpleStringModel() def matches(self, name: str) -> bool: """Returns True if name matches filter, so property should be visible""" return not self.name or self.name.lower() in name.lower() @property def name_model(self): return self._name @property def name(self): return self._name.as_string @name.setter def name(self, n): self._name.as_string = n
1,043
Python
29.705881
97
0.701822
omniverse-code/kit/exts/omni.kit.window.property/omni/kit/window/property/managed_frame.py
import omni.ui as ui collapsed_settings = {} def prep(frame: ui.CollapsableFrame, type: str): global collapsed_settings index_name = f"{type}/{frame.title}" state = collapsed_settings.get(index_name, None) if not state is None: frame.collapsed = state frame.set_collapsed_changed_fn(lambda c, i=index_name: set_collapsed_state(i, c)) def set_collapsed_state(index_name: str, state: bool): global collapsed_settings if state == None: del collapsed_settings[index_name] else: collapsed_settings[index_name] = state def get_collapsed_state(index_name: str=None): global collapsed_settings if index_name: state = collapsed_settings.get(index_name, None) return state return collapsed_settings def reset_collapsed_state(): global collapsed_settings collapsed_settings = {}
874
Python
21.435897
85
0.680778
omniverse-code/kit/exts/omni.kit.window.property/omni/kit/window/property/extension.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. # __all__ = ["get_window", "PropertyExtension"] import omni.ext import omni.kit.ui import weakref import omni.ui as ui from functools import partial from pathlib import Path from .window import PropertyWindow from .templates.header_context_menu import GroupHeaderContextMenu _property_window_instance = None TEST_DATA_PATH = "" def get_window(): return _property_window_instance if not _property_window_instance else _property_window_instance() class PropertyExtension(omni.ext.IExt): WINDOW_NAME = "Property" MENU_PATH = f"Window/{WINDOW_NAME}" def __init__(self): super().__init__() self._window = None self._header_context_menu = GroupHeaderContextMenu() def on_startup(self, ext_id): ui.Workspace.set_show_window_fn(PropertyExtension.WINDOW_NAME, partial(self.show_window, None)) editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: self._menu = editor_menu.add_item(PropertyExtension.MENU_PATH, self.show_window, toggle=True, value=True) ui.Workspace.show_window(PropertyExtension.WINDOW_NAME) 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._menu = None if self._window: self._window.destroy() self._window = None if self._header_context_menu: self._header_context_menu.destroy() self._header_context_menu = None ui.Workspace.set_show_window_fn(PropertyExtension.WINDOW_NAME, None) def _visiblity_changed_fn(self, visible): omni.kit.ui.get_editor_menu().set_value(PropertyExtension.MENU_PATH, visible) def show_window(self, menu, value): global _property_window_instance if value: if self._window is None: self._window = PropertyWindow() self._window.set_visibility_changed_listener(self._visiblity_changed_fn) _property_window_instance = weakref.ref(self._window) self._window.set_visible(value) elif self._window: self._window.set_visible(value)
2,722
Python
33.910256
117
0.680382
omniverse-code/kit/exts/omni.kit.window.property/omni/kit/window/property/property_scheme_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. # __all__ = ["PropertySchemeDelegate"] from abc import abstractmethod from typing import List class PropertySchemeDelegate: """ PropertySchemeDelegate is a class to test given payload and determine what widgets to be drawn in what order. """ @abstractmethod def get_widgets(self, payload) -> List[str]: """ Tests the payload and gathers widgets in interest to be drawn in specific order. """ return [] def get_unwanted_widgets(self, payload) -> List[str]: """ Tests the payload and returns a list of widget names which this delegate does not want to include. Note that if there is another PropertySchemeDelegate returning widget in its get_widgets that conflicts with names in get_unwanted_widgets, get_widgets always wins (i.e. the Widget will be drawn). This function is optional. """ return []
1,342
Python
36.305555
117
0.71535
omniverse-code/kit/exts/omni.kit.window.property/omni/kit/window/property/window.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. # __all__ = ["PropertyWindow"] import copy from typing import Any, List, Optional import carb import carb.settings import omni.ui as ui from omni.kit.widget.searchfield import SearchField from .property_filter import PropertyFilter from .property_scheme_delegate import PropertySchemeDelegate from .property_widget import PropertyWidget from .templates.simple_property_widget import LABEL_HEIGHT # Property Window framework class PropertyWindow: def __init__(self, window_kwargs=None, properties_frame_kwargs=None): """ Create a PropertyWindow Args: window_kwargs: Additional kwargs to pass to ui.Window properties_frame_kwargs: Additional kwargs to pass to ui.ScrollingFrame """ window_flags = ui.WINDOW_FLAGS_NO_SCROLLBAR self._settings = carb.settings.get_settings() self._visibility_changed_listener = None self._window_kwargs = { "title": "Property", "width": 600, "height": 800, "flags": window_flags, "dockPreference": ui.DockPreference.RIGHT_BOTTOM, } if window_kwargs: self._window_kwargs.update(window_kwargs) self._properties_frame_kwargs = { "name": "canvas", "horizontal_scrollbar_policy": ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, "vertical_scrollbar_policy": ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, } if properties_frame_kwargs: self._properties_frame_kwargs.update(properties_frame_kwargs) self._window = ui.Window(**self._window_kwargs) self._window.set_visibility_changed_fn(self._visibility_changed_fn) self._window.frame.set_build_fn(self._rebuild_window) # Dock it to the same space where Layers is docked, make it the first tab and the active tab. self._window.deferred_dock_in("Details", ui.DockPolicy.CURRENT_WINDOW_IS_ACTIVE) self._window.dock_order = 0 self._scheme = "" self._payload = None self._scheme_delegates = {} self._scheme_delegates_layout = {} self._widgets_top = {} self._widgets_bottom = {} self._built_widgets = set() self._notification_paused = False self._notifications_while_paused = [] self._filter = PropertyFilter() self._window_frame = None # for compatiblity with clients that look for this to modify ScrollingFrame def destroy(self): self._visibility_changed_listener = None self._window = None def set_visible(self, visible: bool): if self._window: self._window.visible = visible def _on_search(self, search_words: Optional[List[str]]) -> None: self._filter.name = "" if search_words is None else " ".join(search_words) def _rebuild_window(self): # We should only rebuild the properties ScrollingFrame on payload change, but that doesn't work # reliably so as a workaround we rebuild the entire window including static searchfield. use_default_style = ( carb.settings.get_settings().get_as_string("/persistent/app/window/useDefaultStyle") or False ) if use_default_style: style = {} else: from .style import get_style style = get_style() with ui.VStack(style=style): if carb.settings.get_settings().get_as_bool("/ext/omni.kit.window.property/enableSearch"): with ui.HStack(height=0): ui.Spacer(width=8) self._searchfield = SearchField( on_search_fn=self._on_search, subscribe_edit_changed=True, show_tokens=False, height=LABEL_HEIGHT, style=style, ) # Workaround for needing to rebuild SearchField: fill with existing filter text if self._filter.name: self._searchfield._search_field.model.as_string = self._filter.name self._searchfield._set_in_searching(True) ui.Spacer(width=5 + 12) # scrollbar width is 12 ui.Spacer(height=5) self._window_frame = ui.ScrollingFrame(**self._properties_frame_kwargs) with self._window_frame: with ui.VStack(height=0, name="main_v_stack", spacing=6): if self._scheme != "": widgets_to_build = [] unwanted_widgets = [] scheme_delegates_layout = self._scheme_delegates_layout.get(self._scheme) scheme_delegates = self._scheme_delegates.setdefault(self._scheme, {}) scheme_delegates_filtered = [] if scheme_delegates_layout: for delegate_name in scheme_delegates_layout: delegate = scheme_delegates.get(delegate_name) if delegate: scheme_delegates_filtered.append(delegate) else: scheme_delegates_filtered = scheme_delegates.values() for delegate in scheme_delegates_filtered: widgets_to_build.extend(delegate.get_widgets(self._payload)) unwanted_widgets.extend(delegate.get_unwanted_widgets(self._payload)) # ordered top stack + reverse ordered bottom stack all_registered_widgets = { **self._widgets_top.setdefault(self._scheme, {}), **dict(reversed(list(self._widgets_bottom.setdefault(self._scheme, {}).items()))), } # keep order widget_name_already_built = set() built_widgets = set() for widget_name in widgets_to_build: # skip dup if widget_name in widget_name_already_built: continue widget = all_registered_widgets.get(widget_name) if widget and widget.on_new_payload(self._payload): widget.build(self._filter) built_widgets.add(widget) widget_name_already_built.add(widget_name) # Build the rest of the widgets that are not unwanted unwanted_widgets_set = set(unwanted_widgets) all_widgets = all_registered_widgets.keys() for widget_name in all_widgets: if widget_name not in widget_name_already_built and widget_name not in unwanted_widgets_set: widget = all_registered_widgets.get(widget_name) if widget and widget.on_new_payload(self._payload): widget.build(self._filter) built_widgets.add(widget) # Reset those widgets that are built before but no longer needed for widget in self._built_widgets: if widget not in built_widgets: widget.reset() self._built_widgets = built_widgets def _visibility_changed_fn(self, visible): if not visible: # When the property window is no longer visible, reset all the built widget so they don't take CPU time in background for widget in self._built_widgets: widget.reset() self._built_widgets.clear() # schedule a rebuild of window frame. _rebuild_window won't be actually called until the window is visible again. self._window.frame.rebuild() if self._visibility_changed_listener: self._visibility_changed_listener(visible) def set_visibility_changed_listener(self, listener): self._visibility_changed_listener = listener def register_widget(self, scheme: str, name: str, property_widget: PropertyWidget, top_stack: bool = True): """ Registers a PropertyWidget to PropertyWindow. Args: scheme (str): Scheme of the PropertyWidget will work with. name (str): A unique name to identify the PropertyWidget under. Widget with existing name will be overridden. property_widget (property_widget.PropertyWidget): A PropertyWidget instance to be added. top_stack (bool): Widgets are managed in double stack: True to register the widget to "Top" stack which layouts widgets from top to bottom. False to register the widget to "Button" stack which layouts widgets from bottom to top and always below the "Top" stack. """ if top_stack: self._widgets_top.setdefault(scheme, {})[name] = property_widget self._widgets_bottom.setdefault(scheme, {}).pop(name, None) else: self._widgets_bottom.setdefault(scheme, {})[name] = property_widget self._widgets_top.setdefault(scheme, {}).pop(name, None) if scheme == self._scheme: self._window.frame.rebuild() def unregister_widget(self, scheme: str, name: str, top_stack: bool = True): """ Unregister a PropertyWidget from PropertyWindow. Args: scheme (str): Scheme of the PropertyWidget to be removed from. name (str): The name to find the PropertyWidget and remove. top_stack (bool): see @register_widget """ if top_stack: widget = self._widgets_top.setdefault(scheme, {}).pop(name, None) else: widget = self._widgets_bottom.setdefault(scheme, {}).pop(name, None) if widget: widget.clean() if scheme == self._scheme: self._window.frame.rebuild() def register_scheme_delegate(self, scheme: str, name: str, delegate: PropertySchemeDelegate): """ Register a PropertySchemeDelegate for a given scheme. A PropertySchemeDelegate tests the payload and determines what widgets to be drawn in what order. A scheme can have multiple PropertySchemeDelegate and their result will be merged to display all relevant widgets. PropertySchemeDelegate does not hide widgets that are not returned from its get_widgets function. If you want to hide certain widget, return them in PropertySchemeDelegate.get_unwanted_widgets. See PropertySchemeDelegate's documentation for details. Args: scheme (str): Scheme of the PropertySchemeDelegate to be added to. name (str): A unique name to identify the PropertySchemeDelegate under. Delegate with existing name will be overridden. delegate (PropertySchemeDelegate): A PropertySchemeDelegate instance to be added. """ self._scheme_delegates.setdefault(scheme, {})[name] = delegate if scheme == self._scheme: self._window.frame.rebuild() def unregister_scheme_delegate(self, scheme: str, name: str): """ Unregister a PropertySchemeDelegate from PropertyWindow by name. Args: scheme (str): Scheme of the PropertySchemeDelegate to be removed from. name (str): The name to find the PropertySchemeDelegate and remove. """ self._scheme_delegates.setdefault(scheme, {}).pop(name, None) if scheme == self._scheme: self._window.frame.rebuild() def set_scheme_delegate_layout(self, scheme: str, layout: List[str]): """ Register a list of PropertySchemeDelegate's names to finalize the order and visibility of all registered PropertySchemeDelegate. Useful if you need a fixed layout of Property Widgets for your Kit experience. Remark: If you're a Property Widget writer, DO NOT call this function. It should only be called by Kit Experience to tune the final look and layout of the Property Window. Args: scheme (str): Scheme of the PropertySchemeDelegate order to be added to. layout (List(str)): a list of PropertySchemeDelegate's name, in the order of being processed when building UI. Scheme delegate not in this will be skipped. """ self._scheme_delegates_layout[scheme] = layout if scheme == self._scheme: self._window.frame.rebuild() def reset_scheme_delegate_layout(self, scheme: str): """ Reset the order so PropertySchemeDelegate will be processed in the order of registration when building UI. Args: scheme (str): Scheme of the PropertySchemeDelegate order to be removed from. """ self._scheme_delegates_layout.pop(scheme) if scheme == self._scheme: self._window.frame.rebuild() def notify(self, scheme: str, payload: Any): """ Notify Property Window of a scheme and/or payload change. This is the function to trigger refresh of PropertyWindow. Args: scheme (str): Scheme of this notification. payload: Payload to refresh the widgets. """ if self._notification_paused: self._notifications_while_paused.append((scheme, copy.copy(payload))) else: if self._scheme != scheme: if payload: self._scheme = scheme self._payload = payload self._window.frame.rebuild() elif self._payload != payload: self._payload = payload self._window.frame.rebuild() def get_scheme(self): """ Gets the current scheme being displayed in Property Window. """ return self._scheme def request_rebuild(self): """ Requests the entire property window to be rebuilt. """ if self._window: self._window.frame.rebuild() @property def paused(self): """ Gets if property window refresh is paused. """ return self._notification_paused @paused.setter def paused(self, to_pause: bool): """ Sets if property window refresh is paused. When property window is paused, calling `notify` will not refresh Property Window content. When property window is resumed, the window will refresh using the queued schemes and payloads `notified` to Property Window while paused. Args: to_pause: True to pause property window refresh. False to resume property window refresh. """ if to_pause: self._notification_paused = True else: if self._notification_paused: self._notification_paused = False for notification in self._notifications_while_paused: self.notify(notification[0], notification[1]) self._notifications_while_paused.clear() @property def properties_frame(self): """Gets the ui.ScrollingFrame container of PropertyWidgets""" return self._window_frame # misnamed for backwards compatibility
16,027
Python
44.276836
151
0.592937
omniverse-code/kit/exts/omni.kit.window.property/omni/kit/window/property/templates/simple_property_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. # __all__ = [ "LABEL_WIDTH", "LABEL_WIDTH_LIGHT", "LABEL_HEIGHT", "HORIZONTAL_SPACING", "build_frame_header", "SimplePropertyWidget", "GroupHeaderContextMenu", "GroupHeaderContextMenuEvent", "PropertyWidget", # omni.kit.property.environment tries to import this from here ] import asyncio import functools import traceback import carb import omni.ui as ui import omni.kit.window.property.managed_frame import omni.kit.app from omni.kit.async_engine import run_coroutine from omni.kit.widget.highlight_label import HighlightLabel from omni.kit.window.property.property_widget import PropertyWidget from omni.kit.window.property.style import get_style from .header_context_menu import GroupHeaderContextMenu, GroupHeaderContextMenuEvent LABEL_WIDTH = 160 LABEL_WIDTH_LIGHT = 235 LABEL_HEIGHT = 18 HORIZONTAL_SPACING = 4 def handle_exception(func): """ Decorator to print exception in async functions """ @functools.wraps(func) async def wrapper(*args, **kwargs): try: return await func(*args, **kwargs) except asyncio.CancelledError: # We always cancel the task. It's not a problem. pass except Exception as e: carb.log_error(f"Exception when async '{func}'") carb.log_error(f"{e}") carb.log_error(f"{traceback.format_exc()}") return wrapper def build_frame_header(collapsed, text: str, id: str = None): """Custom header for CollapsibleFrame""" if id is None: id = text if collapsed: alignment = ui.Alignment.RIGHT_CENTER width = 5 height = 7 else: alignment = ui.Alignment.CENTER_BOTTOM width = 7 height = 5 header_stack = ui.HStack(spacing=8) with header_stack: with ui.VStack(width=0): ui.Spacer() ui.Triangle( style_type_name_override="CollapsableFrame.Header", width=width, height=height, alignment=alignment ) ui.Spacer() ui.Label(text, style_type_name_override="CollapsableFrame.Header") def show_attribute_context_menu(b): if b != 1: return event = GroupHeaderContextMenuEvent(group_id=id, payload=[]) GroupHeaderContextMenu.on_mouse_event(event) header_stack.set_mouse_pressed_fn(lambda x, y, b, _: show_attribute_context_menu(b)) class SimplePropertyWidget(PropertyWidget): """ SimplePropertyWidget provides a simple vertical list of "Label" -> "Value widget" pair layout. """ def __init__(self, title: str, collapsed: bool = False, collapsable: bool = True): super().__init__(title) self._collapsed_default = collapsed self._collapsed = collapsed self._collapsable = collapsable self._collapsable_frame = None self._payload = None self._pending_rebuild_task = None self._filter_changed_sub = None self.__style = get_style() def clean(self): """ See PropertyWidget.clean """ self.reset() if self._pending_rebuild_task is not None: self._pending_rebuild_task.cancel() self._pending_rebuild_task = None if self._collapsable_frame is not None: self._collapsable_frame.set_build_fn(None) if self._collapsable: self._collapsable_frame.set_collapsed_changed_fn(None) self._collapsable_frame = None def reset(self): """ See PropertyWidget.reset """ # Do not cancel rebuild task here as we are called from that task through derived build_items() pass def request_rebuild(self): """ Request the widget to rebuild. It will be rebuilt on next frame. """ if self._pending_rebuild_task: return self._pending_rebuild_task = run_coroutine(self._delayed_rebuild()) def add_label(self, label: str): """ Add a Label with a highlight text based on current filter """ filter_text = self._filter.name HighlightLabel(label, highlight=filter_text, name="label", width=LABEL_WIDTH, height=LABEL_HEIGHT, style=self.__style) def add_item(self, label: str, value): """ This function is supposed to be called inside of build_items function. Adds a "Label" -> "Value widget" pair item to the widget. "value" will be an uneditable string in a StringField. Args: label (str): The label text of the entry. value: The value to be stringified and displayed in a StringField. """ if not self._filter.matches(label): return with ui.HStack(spacing=HORIZONTAL_SPACING): self.add_label(label) ui.StringField(name="models").model.set_value(str(value)) self._any_item_visible = True def add_item_with_model(self, label: str, model, editable: bool = False, identifier: str=None): """ This function is supposed to be called inside of build_items function. Adds a "Label" -> "Value widget with model" pair item to the widget. "value" will be an editable string in a StringField backed by supplied model. Args: label (str): The label text of the entry. model: The model to be used by the string field. editable: If the StringField generated from model should be editable. Default is False. """ if not self._filter.matches(label): return with ui.HStack(spacing=HORIZONTAL_SPACING): self.add_label(label) sf = ui.StringField(name="models", model=model, enabled=editable) if identifier and sf: sf.identifier = identifier self._any_item_visible = True def on_new_payload(self, payload, ignore_large_selection=False) -> bool: """ See PropertyWidget.on_new_payload """ self._payload = payload if ( not ignore_large_selection and payload and hasattr(payload, "is_large_selection") and payload.is_large_selection() ): return False return True def build_items(self): """ When deriving from SimplePropertyWidget, override this function to build your items. """ self.add_item("Hello", "World") def build_impl(self): """ See PropertyWidget.build_impl """ if self._filter_changed_sub is None: self._filter_changed_sub = self._filter.name_model.add_value_changed_fn(self._on_filter_changed) if self._collapsable: self._collapsable_frame = ui.CollapsableFrame( self._title, build_header_fn=self._build_frame_header, collapsed=self._collapsed_default ) def on_collapsed_changed(collapsed): self._collapsed = collapsed self._collapsable_frame.set_collapsed_changed_fn(on_collapsed_changed) omni.kit.window.property.managed_frame.prep(self._collapsable_frame, type="Property") else: self._collapsable_frame = ui.Frame(height=0, style={"Frame": {"padding": 0}}) # We cannot use build_fn because rebuild() won't trigger on invisible frames and toggling visible # first causes flicker during property search. So we build explicitly here. # request_rebuild() is still deferred to support batching of changes. self.request_rebuild() def _build_frame_header(self, collapsed, text: str, id: str = None): build_frame_header(collapsed, text, id) def _build_frame(self): import time start = time.time() with ui.VStack(height=0, spacing=5, name="frame_v_stack"): # ui.Spacer(height=0) self._any_item_visible = False self.build_items() if self._filter.name: self._collapsable_frame.visible = self._any_item_visible else: # for compatibility with widgets which don't support filtering self._collapsable_frame.visible = True ui.Spacer(height=0) took = time.time() - start if took > 0.2: import carb carb.log_warn(f"{self.__class__.__name__}.build_items took {took} seconds") @handle_exception async def _delayed_rebuild(self): if self._pending_rebuild_task is not None: try: if self._collapsable_frame: with self._collapsable_frame: self._build_frame() self._collapsable_frame.rebuild() # force rebuild of frame header too finally: self._pending_rebuild_task = None def _on_filter_changed(self, m: ui.AbstractValueModel): """ Called when filter changes. Default calls request_rebuild(). Derived classes can override to optimize by selectively changing property visibility. """ self.request_rebuild()
9,549
Python
34.110294
126
0.620903
omniverse-code/kit/exts/omni.kit.window.property/omni/kit/window/property/templates/header_context_menu.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 typing import Any import omni.kit.commands import omni.kit.undo import omni.usd class GroupHeaderContextMenuEvent: def __init__(self, group_id: str, payload: Any): self.group_id = group_id self.payload = payload self.type = 0 class GroupHeaderContextMenu: _instance = None def __init__(self): GroupHeaderContextMenu._instance = self def __del__(self): self.destroy() def destroy(self): GroupHeaderContextMenu._instance = None @classmethod def on_mouse_event(cls, event: GroupHeaderContextMenuEvent): if cls._instance: cls._instance._on_mouse_event(event) def _on_mouse_event(self, event: GroupHeaderContextMenuEvent): import omni.kit.context_menu # check its expected event if event.type != int(omni.kit.ui.MenuEventType.ACTIVATE): return # setup objects, this is passed to all functions objects = { "payload": event.payload, } menu_list = omni.kit.context_menu.get_menu_dict( "group_context_menu." + event.group_id, "omni.kit.window.property" ) omni.kit.context_menu.get_instance().show_context_menu( "group_context_menu." + event.group_id, objects, menu_list )
1,737
Python
28.965517
78
0.668969
omniverse-code/kit/exts/omni.kit.window.property/omni/kit/window/property/tests/property_test.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 import omni.kit.commands import omni.kit.test import omni.ui as ui from omni.ui.tests.test_base import OmniUiTest async def wait_for_update(usd_context=omni.usd.get_context(), wait_frames=10): max_loops = 0 while max_loops < wait_frames: _, files_loaded, total_files = usd_context.get_stage_loading_status() await omni.kit.app.get_app().next_update_async() if files_loaded or total_files: continue max_loops = max_loops + 1 class TestPropertyWindow(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() from omni.kit.window.property.extension import TEST_DATA_PATH self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() self._usd_path = TEST_DATA_PATH.absolute() import omni.kit.window.property as p self._w = p.get_window() # After running each test async def tearDown(self): await super().tearDown() # test scheme async def test_property_window_scheme(self): from omni.kit.window.property.property_scheme_delegate import PropertySchemeDelegate from omni.kit.window.property.templates import LABEL_HEIGHT, SimplePropertyWidget class SchemeTestWidget(SimplePropertyWidget): def __init__(self, name: str): super().__init__(title="SchemeTestWidget", collapsable=False) self._name = name nonlocal init_called init_called = True def on_new_payload(self, payload): nonlocal new_payload_called new_payload_called = True return True def build_items(self): nonlocal build_items_called build_items_called = True ui.Separator() with ui.HStack(height=0): ui.Spacer(width=8) ui.Button(self._name, width=52, height=LABEL_HEIGHT, name="add") ui.Spacer(width=88 - 52) widget = ui.StringField(name="scheme_name", height=LABEL_HEIGHT, enabled=False) widget.model.set_value(f"{self._name}-" * 100) ui.Separator() class TestPropertySchemeDelegate(PropertySchemeDelegate): def get_widgets(self, payload): widgets_to_build = [] if len(payload): # should still only appear once widgets_to_build.append("test_property_window_scheme_test") widgets_to_build.append("test_property_window_scheme_test") return widgets_to_build # enable custom widget/scheme w = self._w init_called = False w.register_widget("test_scheme_1", "test_property_window_scheme_test", SchemeTestWidget("TEST1")) self.assertTrue(init_called) init_called = False w.register_widget("test_scheme_2", "test_property_window_scheme_test", SchemeTestWidget("TEST2")) self.assertTrue(init_called) init_called = False w.register_widget("test_scheme_3", "test_property_window_scheme_test", SchemeTestWidget("TEST3")) self.assertTrue(init_called) init_called = False w.register_widget("test_scheme_4", "test_property_window_scheme_test", SchemeTestWidget("TEST4")) self.assertTrue(init_called) w.register_scheme_delegate( "test_scheme_delegate", "test_property_window_scheme_test_scheme", TestPropertySchemeDelegate() ) w.set_scheme_delegate_layout("test_scheme_delegate", ["test_property_window_scheme_test_scheme"]) self.assertEqual(w.get_scheme(), "") # draw (should draw SchemeTestWidget item "TEST1") for scheme in ["test_scheme_1", "test_scheme_2", "test_scheme_3", "test_scheme_4"]: new_payload_called = False build_items_called = False await self.docked_test_window( window=self._w._window, width=450, height=200, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) w.notify(scheme, {"payload": ["Items..."]}) await wait_for_update() self.assertTrue(w.get_scheme() == scheme) self.assertTrue(new_payload_called) self.assertTrue(build_items_called) await self.finalize_test( golden_img_dir=self._golden_img_dir, golden_img_name=f"property_window_{scheme}.png" ) # disable custom widget/scheme await self.docked_test_window( window=self._w._window, width=450, height=200, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) w.reset_scheme_delegate_layout("test_scheme_delegate") w.unregister_widget("test_scheme_4", "test_property_window_scheme_test") w.unregister_widget("test_scheme_3", "test_property_window_scheme_test") w.unregister_widget("test_scheme_2", "test_property_window_scheme_test") w.unregister_widget("test_scheme_1", "test_property_window_scheme_test") w.unregister_scheme_delegate("test_scheme_delegate", "test_property_window_scheme_test_scheme") # draw (should draw nothing) for scheme in ["test_scheme_1", "test_scheme_2", "test_scheme_3", "test_scheme_4"]: new_payload_called = False build_items_called = False await self.docked_test_window( window=self._w._window, width=450, height=200, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) w.notify(scheme, {"payload": ["Items..."]}) await wait_for_update() self.assertTrue(w.get_scheme() == scheme) self.assertFalse(new_payload_called) self.assertFalse(build_items_called) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name=f"property_window_empty.png") await wait_for_update() async def test_pause_resume_property_window(self): from omni.kit.window.property.templates import LABEL_HEIGHT, SimplePropertyWidget class SchemeTestWidget(SimplePropertyWidget): def __init__(self, name: str): super().__init__(title="SchemeTestWidget", collapsable=False) self._name = name def on_new_payload(self, payload): if not super().on_new_payload(payload): return False return self._payload == self._name def build_items(self): ui.Separator() with ui.HStack(height=0): ui.Spacer(width=8) ui.Button(self._name, width=52, height=LABEL_HEIGHT, name="add") ui.Spacer(width=88 - 52) widget = ui.StringField(name="scheme_name", height=LABEL_HEIGHT, enabled=False) widget.model.set_value(f"{self._name}-" * 100) ui.Separator() # enable custom widget/scheme w = self._w w.register_widget("test_scheme_1", "test_property_window_scheme_test", SchemeTestWidget("TEST1")) w.register_widget("test_scheme_1", "test_property_window_scheme_test2", SchemeTestWidget("TEST2")) w.register_widget("test_scheme_2", "test_property_window_scheme_test3", SchemeTestWidget("TEST3")) # Not paused, refresh normally, show TEST1 await self.docked_test_window( window=self._w._window, width=450, height=200, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) w.notify("test_scheme_1", "TEST1") await wait_for_update() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="property_window_paused.png") # Pause property window w.paused = True # Paused, property window stops updating, show TEST1 await self.docked_test_window( window=self._w._window, width=450, height=200, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) w.notify("test_scheme_1", "TEST2") await wait_for_update() w.notify("test_scheme_2", "TEST3") await wait_for_update() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="property_window_paused.png") # Resume property window, refresh to last scheme/payload, show TEST3 w.paused = False await self.docked_test_window( window=self._w._window, width=450, height=200, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) await wait_for_update() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="property_window_resumed.png") # Not paused, refresh normally, show TEST2 await self.docked_test_window( window=self._w._window, width=450, height=200, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) w.notify("test_scheme_1", "TEST2") await wait_for_update() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="property_window_resumed2.png") w.unregister_widget("test_scheme_2", "test_property_window_scheme_test3") w.unregister_widget("test_scheme_1", "test_property_window_scheme_test2") w.unregister_widget("test_scheme_1", "test_property_window_scheme_test") # clear the schema - notify("", "") is ignored w.notify("", "payload") await wait_for_update()
10,878
Python
40.522901
119
0.607189
omniverse-code/kit/exts/omni.videoencoding/video_encoding/__init__.py
from .impl import *
20
Python
9.499995
19
0.7
omniverse-code/kit/exts/omni.videoencoding/video_encoding/tests/test_encoding.py
import omni.kit.test import carb.settings import os import tempfile import numpy as np from video_encoding import get_video_encoding_interface VIDEO_FULL_RANGE_PATH = "/exts/omni.videoencoding/vui/videoFullRangeFlag" class Test(omni.kit.test.AsyncTestCase): def get_next_frame(self, shape=(480,640,4)): values = self._rng.random(shape) result = (values * 255.).astype(np.uint8) return result async def setUp(self): print('setUp called') self._rng = np.random.default_rng(seed=1234) self._settings = carb.settings.acquire_settings_interface() self._encoding_interface = get_video_encoding_interface() async def tearDown(self): self._rng = None def _encode_test_sequence(self, n_frames=10): n_frames = 10 with tempfile.TemporaryDirectory() as tmpdirname: video_filename = os.path.join(tmpdirname,'output.mp4') self.assertTrue(self._encoding_interface.start_encoding(video_filename, 24, n_frames, True), msg="Failed to initialize encoding interface.") for i_frame in range(n_frames): frame_data = self.get_next_frame() self._encoding_interface.encode_next_frame_from_buffer(frame_data) self._encoding_interface.finalize_encoding() encoded_size = os.path.getsize(video_filename) return encoded_size async def test_encoding_interface(self): self._settings.set(VIDEO_FULL_RANGE_PATH, False) encoded_size = self._encode_test_sequence(n_frames=10) expected_encoded_size = 721879 self.assertAlmostEqual(encoded_size / expected_encoded_size, 1., places=1, msg=f"Expected encoded video size {expected_encoded_size}; got: {encoded_size}") async def test_encoding_interface_with_full_range(self): self._settings.set(VIDEO_FULL_RANGE_PATH, True) encoded_size = self._encode_test_sequence(n_frames=10) expected_encoded_size = 1081165 self.assertAlmostEqual(encoded_size / expected_encoded_size, 1., places=1, msg=f"Expected encoded video size {expected_encoded_size}; got: {encoded_size}")
2,201
Python
34.516128
104
0.663789
omniverse-code/kit/exts/omni.videoencoding/video_encoding/tests/__init__.py
from .test_encoding import *
28
Python
27.999972
28
0.785714
omniverse-code/kit/exts/omni.videoencoding/video_encoding/impl/__init__.py
from .video_encoding import *
30
Python
14.499993
29
0.766667