Example #1
0
    def test_Cat(self):
        v = Vt.FloatArray((1,2,3,4,5,6))

        vcat = Vt.Cat(v,v)
        self.assertEqual(len(vcat), 12)
        self.assertEqual(vcat[11], 6)
        vcat = Vt.Cat(Vt.Cat(v),Vt.Cat(v,v,v,v),Vt.Cat(v,v,v,v,v))
        self.assertEqual(len(vcat), 60)
        self.assertEqual(vcat[58], 5)
        vcat = Vt.Cat(v,self.empty)
        self.assertEqual(vcat, Vt.Cat(v))
        e = Vt.Cat(self.empty,self.empty)
        self.assertEqual((len(e)), 0)
Example #2
0
    def testExportPerspectiveCameraAnimatedShape(self):
        usdCamera = self._GetUsdCamera('PerspCamAnimShape')

        # Since the focalLength on the Maya camera shape is animated, all of
        # the attributes from the camera shape will have time samples.
        # However, the values on the USD camera at the default time should
        # not have been written and should still be the schema default values.
        expectedPropertyTuples = [
            ('clippingRange', Gf.Vec2f(1, 1000000.0), True),
            ('focalLength', 50.0, True),
            ('horizontalAperture', 20.955, True),
            ('horizontalApertureOffset', 0.0, True),
            ('projection', UsdGeom.Tokens.perspective, True),
            ('verticalAperture', 15.2908, True),
            ('verticalApertureOffset', 0.0, True),

            ('xformOpOrder', Vt.TokenArray(['xformOp:translate', 'xformOp:rotateXYZ']), False),
        ]

        # There should be no animation on the transform.
        self._ValidateUsdCamera(usdCamera, expectedPropertyTuples, False)

        # Now validate again at a non-default time and we should see the values
        # authored in Maya.
        expectedPropertyTuples = [
            ('clippingRange', Gf.Vec2f(0.1, 10000.0), True),
            ('focalLength', 35.0, True),
            ('focusDistance', 5.0, True),
            ('fStop', 5.6, True),
            ('horizontalAperture', 36.0, True),
            ('horizontalApertureOffset', 0.0, True),
            ('projection', UsdGeom.Tokens.perspective, True),
            ('verticalAperture', 24.0, True),
            ('verticalApertureOffset', 0.0, True),

            ('xformOpOrder', Vt.TokenArray(['xformOp:translate', 'xformOp:rotateXYZ']), False),
        ]

        # There should be no animation on the transform.
        self._ValidateUsdCamera(usdCamera, expectedPropertyTuples, False, self.START_TIMECODE)

        # The focal length should be animated on this camera, so validate the
        # value at a few timecodes.
        attr = usdCamera.GetFocalLengthAttr()
        self.assertTrue(Gf.IsClose(attr.Get(self.START_TIMECODE), 35.0, 1e-6))
        self.assertTrue(Gf.IsClose(attr.Get(self.END_TIMECODE), 100.0, 1e-6))
Example #3
0
def get_parameter_type(typed, value):
    current_type = None
    current_value = None
    # FloatAttr2 == Float2
    # FloatAttr3 == Color3f
    # FloatAttr6 == Double3Array
    # DoubleAttr3 == 3DDouble3Arry
    # DoubleAttr6 == Double3Arry
    if typed == 'StringAttr1':
        current_type = Sdf.ValueTypeNames.String
        if os.path.isabs(value):
            current_type = Sdf.ValueTypeNames.Asset
        current_value = value
    if typed == 'IntAttr1':
        current_type = Sdf.ValueTypeNames.Int
        current_value = int(value)
    if typed == 'FloatAttr1':
        current_type = Sdf.ValueTypeNames.Float
        current_value = value
    if typed == 'FloatAttr2':  # Float2
        current_type = Sdf.ValueTypeNames.Float2
        current_value = Gf.Vec2f(value)
    if typed == 'FloatAttr3':  # Color3f
        current_type = Sdf.ValueTypeNames.Color3f
        current_value = Gf.Vec3f(value)
    if typed == 'FloatAttr6':  # Double3Array
        current_type = Sdf.ValueTypeNames.Double3Array
        current_value = Vt.Vec3fArray(2,
                                      (Gf.Vec3f(value[0], value[1], value[2]),
                                       Gf.Vec3f(value[3], value[4], value[5])))
    if typed == 'FloatArray2':
        current_type = Sdf.ValueTypeNames.Float23Array
        array_size = len(value)
        current_value = Vt.Vec2fArray(array_size, value)
    if typed == 'IntArrayAttr':
        current_type = Sdf.ValueTypeNames.IntArray
        current_value = Vt.IntArray(value)
    if typed == 'DoubleAttr3':  # 3DDouble3Arry
        current_type = Sdf.ValueTypeNames.Double3Array
        current_value = Gf.Vec3f(value)
    if typed == 'DoubleAttr6' and len(current_value) == 3:  # Double3Arry
        current_type = Sdf.ValueTypeNames.Double3Array
        current_value = Vt.Vec3dArray(2,
                                      (Gf.Vec3d(value[0], value[1], value[2]),
                                       Gf.Vec3d(value[3], value[4], value[5])))
    return current_type, current_value
 def _VerifyFallbacksInStageMetdata(typeName, expectedFallbacksList):
     fallbacks = stage.GetMetadataByDictKey("fallbackPrimTypes",
                                            typeName)
     if expectedFallbacksList is None:
         self.assertIsNone(fallbacks)
     else:
         self.assertEqual(fallbacks,
                          Vt.TokenArray(expectedFallbacksList))
Example #5
0
    def testExportPolyCubeOneAssignedFace(self):
        """
        Tests exporting a cube that has no object-level shader assigned and
        only one face that has an assigned shader.
        """
        cubeMesh = self._GetCubeMesh('OneFaceCube')

        expectedColors = Vt.Vec3fArray([(0.5, 0.5, 0.5), (0.0, 1.0, 0.0)])
        expectedOpacities = Vt.FloatArray([0.0, 0.7])

        expectedIndices = Vt.IntArray([1, 0, 0, 0, 0, 0])
        expectedUnauthoredValuesIndex = 0
        self._AssertMeshDisplayColorAndOpacity(cubeMesh, expectedColors,
                                               expectedOpacities,
                                               UsdGeom.Tokens.uniform,
                                               expectedIndices,
                                               expectedUnauthoredValuesIndex)
Example #6
0
 def writeEdits(self, pc, mayaObj):
     pWidth = om.MPlug(mayaObj, type(self)._width)
     pHeight = om.MPlug(mayaObj, type(self)._height)
     pDepth = om.MPlug(mayaObj, type(self)._depth)
     halfExtents = Gf.Vec3f(0.5 * pWidth.asFloat(), 0.5 * pHeight.asFloat(),
                            0.5 * pDepth.asFloat())
     minMax = Vt.Vec3fArray(2, [-halfExtents, halfExtents])
     pc.GetExtentAttr().Set(minMax)
Example #7
0
    def testExportPolyCubeSharedFaces(self):
        """
        Tests exporting a cube where each of three pairs of faces have the
        same shader assigned.
        """
        cubeMesh = self._GetCubeMesh('SharedFacesCube')

        expectedColors = Vt.Vec3fArray([
            (1.0, 0.0, 1.0),
            (1.0, 0.0, 0.0),
            (0.0, 0.0, 1.0)])
        expectedOpacities = Vt.FloatArray([
            0.25,
            0.85,
            0.55])
        expectedIndices = Vt.IntArray([0, 2, 0, 1, 2, 1])
        self._AssertMeshDisplayColorAndOpacity(cubeMesh, expectedColors,
            expectedOpacities, UsdGeom.Tokens.uniform, expectedIndices)
Example #8
0
    def testToken(self):
        """Validates GetAllowedTokens() for token attributes"""
        prim = self.stage.GetPrimAtPath('/World/TokenPrim')

        attrProxy = _AttributeProxy(
            [prim.GetAttribute('a'), prim.GetAttribute('b'),
             prim.GetAttribute('c')])
        self.assertEqual(attrProxy.GetAllowedTokens(),
                         Vt.TokenArray(['one', 'two']))
Example #9
0
 def test_TranslateOp(self):
     s = Usd.Stage.CreateInMemory()
     x = UsdGeom.Xform.Define(s, '/World')
     translation = Gf.Vec3d(10., 20., 30.)
     x.AddTranslateOp().Set(translation)
     xform = x.GetLocalTransformation(Usd.TimeCode.Default())
     self._AssertCloseXf(xform, Gf.Matrix4d(1.0).SetTranslate(translation))
     self.assertEqual(x.GetXformOpOrderAttr().Get(), 
                 Vt.TokenArray(('xformOp:translate', )))
Example #10
0
 def test_ScaleOp(self):
     s = Usd.Stage.CreateInMemory()
     x = UsdGeom.Xform.Define(s, '/World')
     scaleVec = Gf.Vec3f(1., 2., 3.)
     x.AddScaleOp().Set(scaleVec)
     xform = x.GetLocalTransformation(Usd.TimeCode.Default())
     self._AssertCloseXf(xform, Gf.Matrix4d(1.0).SetScale(Gf.Vec3d(scaleVec)))
     self.assertEqual(x.GetXformOpOrderAttr().Get(), 
                 Vt.TokenArray(('xformOp:scale', )))
Example #11
0
    def testExport(self):
        '''
        Export the Maya file and validate a handful of properties.
        '''
        usdFile = os.path.abspath('UsdExportNurbsCurveTest.usda')
        cmds.usdExport(mergeTransformAndShape=True,
                       file=usdFile,
                       shadingMode='none')

        stage = Usd.Stage.Open(usdFile)

        nc = UsdGeom.NurbsCurves.Get(stage, '/curve1')
        self.assertEqual(nc.GetWidthsAttr().Get(), Vt.FloatArray([1.0]))
        self.assertEqual(nc.GetWidthsInterpolation(), UsdGeom.Tokens.constant)
        self.assertEqual(nc.GetRangesAttr().Get(),
                         Vt.Vec2dArray([Gf.Vec2d(0, 5)]))
        self.assertEqual(nc.GetOrderAttr().Get(), Vt.IntArray([4]))
        self.assertEqual(nc.GetCurveVertexCountsAttr().Get(), Vt.IntArray([8]))
Example #12
0
    def _create_usd_skeleton_animation(self, gltf_skin, usd_skeleton, joint_names):
        #get the animation data per joint
        skelAnim = None
        gltf_animations = self.gltf_loader.get_animations()

        if len(gltf_animations):
            skelAnim = UsdSkel.Animation.Define(self.stage, '{0}/{1}'.format(usd_skeleton.GetPath(), 'anim'))

            usd_skel_root_path = usd_skeleton.GetPath().GetParentPath()
            usd_skel_root = self.stage.GetPrimAtPath(usd_skel_root_path)

            skelAnim.CreateJointsAttr().Set(joint_names)
            gltf_animation = self.gltf_loader.get_animations()[0]
            min_sample = 999
            max_sample = -999
            for sampler in gltf_animation.get_samplers():
                input_data = sampler.get_input_data()
                min_sample = min(min_sample, input_data[0])
                max_sample = max(max_sample, input_data[-1])

            rotate_attr = skelAnim.CreateRotationsAttr()
            for input_key in numpy.arange(min_sample, max_sample, 1./self.fps):
                entries = []
                for joint in gltf_skin.get_joints():
                    anim = self._get_anim_data_for_joint_and_path(gltf_animation, joint, 'rotation', input_key)
                    entries.append(anim)

                if len(gltf_skin.get_joints()) != len(entries):
                    raise Exception('up oh!')

                rotate_attr.Set(Vt.QuatfArray(entries), Usd.TimeCode(input_key * self.fps))

            translate_attr = skelAnim.CreateTranslationsAttr()
            for input_key in numpy.arange(min_sample, max_sample, 1./self.fps):
                entries = []
                for joint in gltf_skin.get_joints():
                    anim = self._get_anim_data_for_joint_and_path(gltf_animation, joint, 'translation', input_key)
                    entries.append(anim)

                if len(gltf_skin.get_joints()) != len(entries):
                    raise Exception('up oh!')

                translate_attr.Set(entries, Usd.TimeCode(input_key * self.fps))

            scale_attr = skelAnim.CreateScalesAttr()
            for input_key in numpy.arange(min_sample, max_sample, 1./self.fps):
                entries = []
                for joint in gltf_skin.get_joints():
                    anim = self._get_anim_data_for_joint_and_path(gltf_animation, joint, 'scale', input_key)
                    entries.append(anim)

                if len(gltf_skin.get_joints()) != len(entries):
                    raise Exception('up oh!')

                scale_attr.Set(entries, Usd.TimeCode(input_key * self.fps))

        return skelAnim
Example #13
0
    def test_ResetXformStack(self):
        s = Usd.Stage.CreateInMemory()
        x = UsdGeom.Xform.Define(s, '/World')
        x.AddTranslateOp().Set(Gf.Vec3d(20, 30, 40))

        x.SetResetXformStack(True)
        self.assertEqual(x.GetXformOpOrderAttr().Get(),
                    Vt.TokenArray(('!resetXformStack!', 'xformOp:translate')))
        # Calling it twice should have no effect the second time.
        x.SetResetXformStack(True)
        self.assertEqual(x.GetXformOpOrderAttr().Get(),
                    Vt.TokenArray(('!resetXformStack!', 'xformOp:translate')))

        x.SetResetXformStack(False)
        self.assertEqual(x.GetXformOpOrderAttr().Get(),
                    Vt.TokenArray(('xformOp:translate', )))

        # Again, calling this twice shouldn't make a difference.
        x.SetResetXformStack(False)
        self.assertEqual(x.GetXformOpOrderAttr().Get(),
                    Vt.TokenArray(('xformOp:translate', )))

        x.AddTransformOp().Set(Gf.Matrix4d(1.0))
        x.SetResetXformStack(True)
        self.assertEqual(x.GetXformOpOrderAttr().Get(),
                    Vt.TokenArray(('!resetXformStack!', 'xformOp:translate', 
                                   'xformOp:transform')))

        x.SetResetXformStack(False)
        self.assertEqual(x.GetXformOpOrderAttr().Get(),
                    Vt.TokenArray(('xformOp:translate', 
                                        'xformOp:transform')))

        cx = UsdGeom.Xform.Define(s, '/World/Model')
        cx.AddTranslateOp().Set(Gf.Vec3d(10, 10, 10))
        cache = UsdGeom.XformCache()
        cxCtm = cache.GetLocalToWorldTransform(cx.GetPrim())
        self._AssertCloseXf(cxCtm, Gf.Matrix4d(1.0).SetTranslate(Gf.Vec3d(30.0, 40.0, 50.0)))

        cx.SetResetXformStack(True)
        self.assertEqual(cx.GetXformOpOrderAttr().Get(),
            Vt.TokenArray(('!resetXformStack!', 'xformOp:translate')))

        # Clear the xform cache and recompute local-to-world xform.
        cache.Clear()

        newCxCtm = cache.GetLocalToWorldTransform(cx.GetPrim())
        localCxXform = cx.GetLocalTransformation(Usd.TimeCode.Default())
        self._AssertCloseXf(newCxCtm, Gf.Matrix4d(1.0).SetTranslate(Gf.Vec3d(10.0, 10.0, 10.0)))
        self._AssertCloseXf(newCxCtm, localCxXform)

        # Test resetXformStack when it's not at the beginning of xformOpOrder.
        cx.SetResetXformStack(False)
        newXformOpOrder = list(cx.GetXformOpOrderAttr().Get())
        newXformOpOrder.append(UsdGeom.XformOpTypes.resetXformStack)
        cx.GetXformOpOrderAttr().Set(newXformOpOrder)

        cx.AddTransformOp().Set(Gf.Matrix4d(2.0))
        self.assertTrue(cx.GetResetXformStack())
Example #14
0
    def testExport(self):
        #Check the imported Usd.
        selectionList = OpenMaya.MSelectionList()
        selectionList.add('Curve')
        dagPath = OpenMaya.MDagPath()
        selectionList.getDagPath( 0, dagPath )
        MFnNurbsCurve = OpenMaya.MFnNurbsCurve(dagPath)
        self.assertEqual(MFnNurbsCurve.numCVs(), 7)

        #Export the Maya file and validate a handful of properties.
        usdFile = os.path.abspath('UsdExportBasisCurveTest.usda')
        cmds.usdExport(mergeTransformAndShape=True, file=usdFile,
            shadingMode='none')

        stage = Usd.Stage.Open(usdFile)
        nc = UsdGeom.BasisCurves.Get(stage, '/Curve')
        self.assertEqual(nc.GetWidthsAttr().Get(), Vt.FloatArray([1.0]))
        self.assertEqual(nc.GetWidthsInterpolation(), UsdGeom.Tokens.constant)
        self.assertEqual(nc.GetCurveVertexCountsAttr().Get(), Vt.IntArray([7]))
Example #15
0
    def _AssertPrimvar(self,
                       primvar,
                       expectedTypeName=None,
                       expectedValues=None,
                       expectedInterpolation=None,
                       expectedIndices=None,
                       expectedUnauthoredValuesIndex=None):
        self.assertTrue(primvar)

        if expectedInterpolation is None:
            expectedInterpolation = UsdGeom.Tokens.constant
        if expectedIndices is None:
            expectedIndices = Vt.IntArray()
        elif isinstance(expectedIndices, list):
            expectedIndices = Vt.IntArray(expectedIndices)
        if expectedUnauthoredValuesIndex is None:
            expectedUnauthoredValuesIndex = -1

        # This should work for undefined primvars.
        self.assertEqual(primvar.GetIndices(), expectedIndices)
        self.assertEqual(primvar.GetUnauthoredValuesIndex(),
                         expectedUnauthoredValuesIndex)

        if expectedTypeName is None:
            self.assertFalse(primvar.IsDefined())
            # No further testing for primvars that we expect not to exist.
            return

        self.assertTrue(primvar.IsDefined())
        self.assertEqual(primvar.GetTypeName(), expectedTypeName)
        self.assertEqual(primvar.GetInterpolation(), expectedInterpolation)

        if expectedValues is None:
            self.assertFalse(primvar.GetAttr().HasAuthoredValueOpinion())
            self.assertEqual(primvar.Get(), None)
        else:
            for idx in range(len(primvar.Get())):
                val1 = primvar.Get()[idx]
                val2 = expectedValues[idx]
                if isinstance(val1, Gf.Vec3f):
                    self.assertEqual(val1, val2)  # both are 3-vectors
                    continue
                self.assertAlmostEqual(val1, val2, places=5)  # default==7
Example #16
0
 def test_PrimvarIndicesBlock(self):
     # We'll put all our Primvar on a single mesh gprim
     stage = Usd.Stage.CreateInMemory('indexPrimvars.usda')
     gp = UsdGeom.Mesh.Define(stage, '/myMesh')
     foo = gp.CreatePrimvar('foo', Sdf.ValueTypeNames.FloatArray)
     indices = Vt.IntArray([0, 1, 2, 2, 1, 0])
     self.assertTrue(foo.SetIndices(indices))
     self.assertTrue(foo.IsIndexed())
     foo.BlockIndices()
     self.assertFalse(foo.IsIndexed())
    def testSkelRestXformsWithNoDagPose(self):
        """
        Tests export of rest xforms when there is no dagPose node at all.
        """
        mayaFile = os.path.join(self.inputPath, "UsdExportSkeletonTest",
            "UsdExportSkeletonNoDagPose.ma")
        cmds.file(mayaFile, force=True, open=True)

        usdFile = os.path.abspath('UsdExportSkeletonRestXformsWithNoDagPose.usda')
        cmds.select('skel_root')
        cmds.mayaUSDExport(mergeTransformAndShape=True, file=usdFile,
                           shadingMode='none', exportSkels='auto', selection=True)

        stage = Usd.Stage.Open(usdFile)

        skeleton = UsdSkel.Skeleton.Get(stage, '/skel_root/joint1')

        self.assertEqual(skeleton.GetJointsAttr().Get(),
            Vt.TokenArray(['joint1',
                           'joint1/joint2',
                           'joint1/joint2/joint3',
                           'joint1/joint2/joint3/joint4']))

        self.assertEqual(
            skeleton.GetBindTransformsAttr().Get(),
            Vt.Matrix4dArray([
                Gf.Matrix4d( (-1, 0, 0, 0), (0, 1, 0, 0), (0, 0, -1, 0), (0, 0, 0, 1) ),
                Gf.Matrix4d( (0, -1, 0, 0), (-1, 0, 0, 0), (0, 0, -1, 0), (3, 0, 0, 1) ),
                Gf.Matrix4d( (0, -1, 0, 0), (0, 0, -1, 0), (1, 0, 0, 0), (3, 0, -2, 1) ),
                Gf.Matrix4d( (0, -1, 0, 0), (1, 0, 0, 0), (0, 0, 1, 0), (3, 0, -4, 1) ),
            ])
        )

        self.assertEqual(
            skeleton.GetRestTransformsAttr().Get(),
            Vt.Matrix4dArray([
                Gf.Matrix4d( (-1, 0, 0, 0), (0, 1, 0, 0), (0, 0, -1, 0), (0, 0, 0, 1) ),
                Gf.Matrix4d( (0, -1, 0, 0), (1, 0, 0, 0), (0, 0, 1, 0), (-3, 0, 0, 1) ),
                Gf.Matrix4d( (1, 0, 0, 0), (0, 0, 1, 0), (0, -1, 0, 0), (0, 0, 2, 1) ),
                Gf.Matrix4d( (1, 0, 0, 0), (0, 0, 1, 0), (0, -1, 0, 0), (0, 2, 0, 1) ),
            ])
        )        
    def test_Basic(self):
        usdFilePath = "Sphere.usda"

        stage = Usd.Stage.Open(usdFilePath)
        self.assertTrue(stage)

        sphere = stage.GetPrimAtPath('/Sphere/Mesh')
        mat1 = stage.GetPrimAtPath('/Sphere/Materials/initialShadingGroup')
        mat2= stage.GetPrimAtPath('/Sphere/Materials/lambert2SG')
        mat3= stage.GetPrimAtPath('/Sphere/Materials/lambert3SG')

        self.assertTrue(sphere and mat1 and mat2 and mat3)

        # Verify that the sphere mesh does not have an existing material face-set.
        geomSphere = UsdGeom.Imageable(sphere)
        materialBindSubsets = UsdShade.Material.GetMaterialBindFaceSubsets(
            geomSphere)
        self.assertEqual(len(materialBindSubsets), 0)

        faceIndices1 = Vt.IntArray((0, 1, 2, 3))
        faceIndices2 = Vt.IntArray((4, 5, 6, 7, 8, 9, 10, 11))
        faceIndices3 = Vt.IntArray((12, 13, 14, 15))

        # Create a new family of subsets with familyName="materialBind" .
        subset1 = UsdShade.Material.CreateMaterialBindFaceSubset(geomSphere, 'subset1', 
            faceIndices1)
        subset2 = UsdShade.Material.CreateMaterialBindFaceSubset(geomSphere, 'subset2', 
            faceIndices2)
        subset3 = UsdShade.Material.CreateMaterialBindFaceSubset(geomSphere, 'subset3', 
            faceIndices3)

        (valid, reason) = UsdGeom.Subset.ValidatePartition(
                            [subset1, subset2, subset3], 16)
        self.assertTrue(valid)

        UsdShade.Material(mat1).Bind(subset1.GetPrim())
        UsdShade.Material(mat2).Bind(subset2.GetPrim())
        UsdShade.Material(mat3).Bind(subset3.GetPrim())

        # Don't save the modified source stage. Export it into a 
        # new layer for baseline diffing.
        stage.Export("SphereWithMaterialBind.usda", addSourceFileComment=False)
Example #19
0
    def test_ValueTypeMismatch(self):
        src_stage = Usd.Stage.Open('valueTypeMismatch_root.usda')
        src_layer_stack = src_stage._GetPcpCache().layerStack
        layer = Usd.FlattenLayerStack(src_layer_stack, tag='valueBlocks')
        print(layer.ExportToString())
        result_stage = Usd.Stage.Open(layer)

        # Verify that the strongest value type prevailed
        prim = result_stage.GetPrimAtPath('/p')
        a = prim.GetAttribute('x')
        self.assertEqual(a.Get(), Vt.IntArray(1, (0, )))
Example #20
0
        def createCommonAPI(testCase, sphereXformable):
            sphereXformable.AddTranslateOp(UsdGeom.XformOp.PrecisionFloat,
                                           "pivot")
            sphereXformable.AddTranslateOp(UsdGeom.XformOp.PrecisionFloat,
                                           "pivot", True)

            self.assertEqual(
                sphereXformable.GetXformOpOrderAttr().Get(),
                Vt.TokenArray(("xformOp:translate:pivot",
                               "!invert!xformOp:translate:pivot")))
            self.assertTrue(UsdGeom.XformCommonAPI(sphereXformable))
Example #21
0
    def test_IdentityRemapping(self):
        """Test remapping on an identity map."""

        mapper = MakeMapper("ABC", "ABC")
        assert mapper.IsIdentity()

        source = Vt.IntArray([1, 2, 3])
        self.assertEqual(source, mapper.Remap(source))

        assert not MakeMapper("ABC", "DABC").IsIdentity()
        assert not MakeMapper("ABC", "AB").IsIdentity()
Example #22
0
    def test_TypeUsage(self):
        # Perform Type-Ness Checking for ComputeExtent
        pointsAsList = [(0, 0, 0), (1, 1, 1), (2, 2, 2)]
        pointsAsVec3fArr = Vt.Vec3fArray(pointsAsList)

        comp = UsdGeom.PointBased.ComputeExtent
        expectedExtent = comp(pointsAsVec3fArr)
        actualExtent = comp(pointsAsList)

        for a, b in zip(expectedExtent, actualExtent):
            self.assertTrue(Gf.IsClose(a, b, 1e-5))
Example #23
0
    def test_Bug109853(self):
        s = Usd.Stage.CreateInMemory()
        x = UsdGeom.Xform.Define(s, '/World')

        # Test to make sure that having a non-existent xformOp in xformOpOrder
        # does not result in a crash when GetLocalTransformation is called.
        x.GetXformOpOrderAttr().Set(Vt.TokenArray(('xformOp:transform', )))

        # This used to crash before bug 109853 was fixed. It now results in a 
        # warning.
        x.GetLocalTransformation(Usd.TimeCode.Default())
Example #24
0
    def _AssertDisplayColorEqual(self, prim, expectedColor):
        # expectedColor should be given as a list, so turn it into the type we'd
        # expect to get out of the displayColor attribute, namely a VtVec3fArray.
        expectedColor = Vt.Vec3fArray(1, expectedColor)

        gprim = UsdGeom.Gprim(prim)
        self.assertTrue(gprim)

        displayColorPrimvar = gprim.GetDisplayColorPrimvar()
        self.assertTrue(displayColorPrimvar)
        self.assertEqual(displayColorPrimvar.ComputeFlattened(), expectedColor)
    def testModifyDisplayColor(self):
        self._StartTest('capsule')

        cmds.move(3, 3, 3, 'persp')
        cmds.rotate(-30, 45, 0, 'persp')
        self.assertSnapshotClose('%s_unselected.png' % self._testName)

        stage = mayaUsdUfe.getStage("|stage|stageShape")
        rprim = stage.GetPrimAtPath('/Capsule1')
        displayColorPrimvar = rprim.GetAttribute('primvars:displayColor')
        displayColorPrimvar.Set(Vt.Vec3fArray([(0.0, 1.0, 0.0)]))
        self.assertSnapshotClose('%s_green.png' % self._testName)
 def test_TimeSampled(self):
     extents = {
         '/capsule' :  Vt.Vec3fArray(2, (Gf.Vec3f(-4.0, -4.0, -6.0),
                                         Gf.Vec3f(4.0, 4.0, 6.0))),
         '/cone' :     Vt.Vec3fArray(2, (Gf.Vec3f(-4.0, -4.0, -3.0),
                                         Gf.Vec3f(4.0, 4.0, 3.0))),
         '/cube' :     Vt.Vec3fArray(2, (Gf.Vec3f(-3.0, -3.0, -3.0),
                                         Gf.Vec3f(3.0, 3.0, 3.0))),
         '/cylinder' : Vt.Vec3fArray(2, (Gf.Vec3f(-4.0, -4.0, -3.0),
                                         Gf.Vec3f(4.0, 4.0, 3.0))),
         '/sphere' :   Vt.Vec3fArray(2, (Gf.Vec3f(-4.0, -4.0, -4.0),
                                         Gf.Vec3f(4.0, 4.0, 4.0)))
     }
     testFile = "test.usda"
     s = Usd.Stage.Open(testFile)
     for primpath in self.primpaths:
         p = s.GetPrimAtPath(primpath)
         b = UsdGeom.Boundable(p)
         tc = Usd.TimeCode(2.0)
         e = UsdGeom.Boundable.ComputeExtentFromPlugins(b, tc)
         self.assertEqual(extents[primpath], e)
Example #27
0
 def __init__(
     self,
     prim,
     points,
     indices,
     vertOffsets,
     vertCounts,
     indexOffsets,
     indexCounts,
     displayOpacity,
 ):  # pylint: disable=too-many-arguments
     self.dirty = True
     self.adj = 2 * random.random()
     self.prim = prim
     self.points = points
     self.indices = Vt.IntArray(len(indices), 0)
     self.originalIndices = Vt.IntArray(indices)
     self.maskIndices = Vt.IntArray(len(indices), 0)
     self.vertOffsets = vertOffsets
     self.vertCounts = vertCounts
     self.indexOffsets = indexOffsets
     self.indexCounts = indexCounts
     self.displayOpacity = Vt.FloatArray(len(displayOpacity))
     self.previousOpacity = Vt.FloatArray(displayOpacity)
     self.originalOpacity = Vt.FloatArray(displayOpacity)
     self.substrokes = self._GetSubstrokes()
     self.adjs = []
     for i in enumerate(displayOpacity):
         displayOpacity[i] = 0
     for i in self.vertOffsets:
         self.adjs.append(random.random() - 1)
     self.adjs.append(random.random() - 1)
Example #28
0
    def test_Dictionary(self):
        good = {
            'key': 'value',
            'key2': 'value',
            'key3': [1, 2, 3, 'one', 'two', 'three'],
            'key4': ['four', 'five', {
                'six': 7,
                'eight': [{
                    'nine': 9
                }]
            }],
            'key5': {
                'key6': 'value'
            },
            'key5': None,
            'key6': 'value',
        }

        bad1 = {1: 2}
        bad2 = {'key': Ellipsis}

        self.assertEqual(good, Vt._test_Ident(good))

        vtdict = Vt._ReturnDictionary(good)
        self.assertEqual(good, vtdict)
        self.assertEqual(vtdict['key6'], 'value')

        with self.assertRaises(TypeError):
            Vt._ReturnDictionary(bad1)
        with self.assertRaises(TypeError):
            Vt._ReturnDictionary(bad2)
Example #29
0
    def test_InverseOps(self):
        IDENTITY = Gf.Matrix4d(1.)

        s = Usd.Stage.CreateInMemory()
        x = UsdGeom.Xform.Define(s, '/World')
        x.AddTranslateOp().Set(Gf.Vec3d(20, 30, 40))
        x.AddTranslateOp(isInverseOp=True)
        self._AssertCloseXf(x.GetLocalTransformation(Usd.TimeCode.Default()), IDENTITY)

        x.AddScaleOp().Set(Gf.Vec3f(2,3,4))
        x.AddScaleOp(isInverseOp=True)
        self._AssertCloseXf(x.GetLocalTransformation(Usd.TimeCode.Default()), IDENTITY)

        x.AddRotateXOp().Set(30.)
        x.AddRotateXOp(isInverseOp=True)
        self._AssertCloseXf(x.GetLocalTransformation(Usd.TimeCode.Default()), IDENTITY)

        x.AddRotateYOp().Set(45.)
        x.AddRotateYOp(isInverseOp=True)
        self._AssertCloseXf(x.GetLocalTransformation(Usd.TimeCode.Default()), IDENTITY)

        x.AddRotateZOp().Set(60.)
        x.AddRotateZOp(isInverseOp=True)
        self._AssertCloseXf(x.GetLocalTransformation(Usd.TimeCode.Default()), IDENTITY)

        x.AddRotateXYZOp(opSuffix="firstRotate").Set(Gf.Vec3f(10, 20, 30))
        x.AddRotateXYZOp(opSuffix="firstRotate", isInverseOp=True)
        self._AssertCloseXf(x.GetLocalTransformation(Usd.TimeCode.Default()), IDENTITY)

        x.AddRotateZYXOp(opSuffix="lastRotate").Set(Gf.Vec3f(30, 60, 45))
        x.AddRotateZYXOp(opSuffix="lastRotate", isInverseOp=True)
        self._AssertCloseXf(x.GetLocalTransformation(Usd.TimeCode.Default()), IDENTITY)

        quat = Gf.Quatf(1, Gf.Vec3f(2, 3, 4))
        x.AddOrientOp().Set(quat)
        x.AddOrientOp(isInverseOp=True)
        self._AssertCloseXf(x.GetLocalTransformation(Usd.TimeCode.Default()), IDENTITY)

        rotation = Gf.Rotation(Gf.Vec3d(quat.GetImaginary()), quat.GetReal())
        x.AddTransformOp().Set(Gf.Matrix4d(rotation, Gf.Vec3d(10, 20, 30)))
        x.AddTransformOp(isInverseOp=True)
        self._AssertCloseXf(x.GetLocalTransformation(Usd.TimeCode.Default()), IDENTITY)

        # We've got tons of xform ops in x now, let's test GetOrderedXformOps API.
        orderedXformOps = x.GetOrderedXformOps()
        xformOpOrder = Vt.TokenArray(len(orderedXformOps))
        index = 0
        for op in orderedXformOps:
            xformOpOrder[index] = op.GetOpName()
            index += 1

        self.assertEqual(xformOpOrder, x.GetXformOpOrderAttr().Get())
    def test_EmptyXformable(self):
        s = Usd.Stage.CreateInMemory()
        x = UsdGeom.Xform.Define(s, "/X")
        xXformAPI = UsdGeom.XformCommonAPI(x)
        self.assertTrue(xXformAPI)

        self.assertEqual(
            xXformAPI.GetXformVectors(Usd.TimeCode.Default()),
            (Gf.Vec3d(0, 0, 0), Gf.Vec3f(0, 0, 0), Gf.Vec3f(1, 1, 1),
             Gf.Vec3f(0, 0, 0), UsdGeom.XformCommonAPI.RotationOrderXYZ))

        self.assertTrue(
            xXformAPI.SetXformVectors(
                translation=Gf.Vec3d(10., 20., 30.),
                rotation=Gf.Vec3f(30, 45, 60),
                scale=Gf.Vec3f(1., 2., 3.),
                pivot=Gf.Vec3f(0, 10, 0),
                rotationOrder=UsdGeom.XformCommonAPI.RotationOrderYXZ,
                time=Usd.TimeCode.Default()))

        self.assertEqual(
            x.GetXformOpOrderAttr().Get(),
            Vt.TokenArray(('xformOp:translate', 'xformOp:translate:pivot',
                           'xformOp:rotateYXZ', 'xformOp:scale',
                           '!invert!xformOp:translate:pivot')))
        self.assertTrue(xXformAPI)

        self.assertEqual(xXformAPI.GetXformVectors(Usd.TimeCode.Default()),
                         (Gf.Vec3d(10., 20., 30.), Gf.Vec3f(30, 45, 60),
                          Gf.Vec3f(1., 2., 3.), Gf.Vec3f(0, 10, 0),
                          UsdGeom.XformCommonAPI.RotationOrderYXZ))

        # Call SetXformVectors with a different rotation order. This should fail
        # and no values should get authored.
        with self.assertRaises(RuntimeError):
            xXformAPI.SetXformVectors(
                translation=Gf.Vec3d(100., 200., 300.),
                rotation=Gf.Vec3f(3, 4, 6),
                scale=Gf.Vec3f(3., 2., 1.),
                pivot=Gf.Vec3f(10, 0, 10),
                rotationOrder=UsdGeom.XformCommonAPI.RotationOrderZYX,
                time=Usd.TimeCode(10.0))

        # Verify that the second SetXformVectors did not author any values.
        self.assertEqual(xXformAPI.GetXformVectors(Usd.TimeCode(10.0)),
                         (Gf.Vec3d(10., 20., 30.), Gf.Vec3f(30, 45, 60),
                          Gf.Vec3f(1., 2., 3.), Gf.Vec3f(0, 10, 0),
                          UsdGeom.XformCommonAPI.RotationOrderYXZ))

        # Adding an extra op, causes X to become incompatible.
        x.AddTranslateOp(opSuffix="extraTranslate")
        self.assertFalse(UsdGeom.XformCommonAPI(x))
Example #31
0
    def test_Dictionary(self):
        good = {'key' : 'value',
                'key2' : 'value',
                'key3' : [1,2,3,'one','two','three'],
                'key4' : ['four', 'five', { 'six' : 7, 'eight' : [ {'nine':9} ] } ],
                'key5' : { 'key6' : 'value' },
                'key5' : None,
                'key6' : u'value',
                }

        bad1 = {1 : 2}
        bad2 = {'key' : Ellipsis}

        self.assertEqual(good, Vt._test_Ident(good))

        vtdict = Vt._ReturnDictionary(good)
        self.assertEqual(good, vtdict)
        self.assertEqual(vtdict['key6'], 'value')

        with self.assertRaises(TypeError):
            Vt._ReturnDictionary(bad1)
        with self.assertRaises(TypeError):
            Vt._ReturnDictionary(bad2)
Example #32
0
 def test_AutoConversion(self):
     '''Call a func that takes a VtValue without a VtValue (test
        auto-conversion)'''
     self.assertEqual(Vt._test_ValueTypeName(1.234), 'double')
     self.assertEqual(Vt._test_ValueTypeName('hello'), 'string')
     self.assertEqual(Vt._test_ValueTypeName(Ellipsis), 'TfPyObjWrapper')
Example #33
0
 def test_Ident(self):
     self.assertEqual(Vt._test_Ident(1.234), 1.234)
Example #34
0
 def test_Str(self):
     self.assertEqual(Vt._test_Str(Ellipsis), str(Ellipsis))
     self.assertEqual(Vt._test_Str((1,2,3)), str((1,2,3)))
     self.assertEqual(Vt._test_Str(Vt.DoubleArray()), str(Vt.DoubleArray()))
     self.assertEqual(Vt._test_Str(1.234), str(1.234))
     self.assertEqual(Vt._test_Str(u'unicode'), 'unicode')
Example #35
0
    def test_ValueTypeName(self):
        self.assertEqual(Vt._test_ValueTypeName(True), 'bool')
        self.assertEqual(Vt._test_ValueTypeName(False), 'bool')
        self.assertEqual(Vt._test_ValueTypeName(0), 'int')
        self.assertEqual(Vt._test_ValueTypeName(1), 'int')

        self.assertEqual(Vt._test_ValueTypeName(Vt.Bool(True)), 'bool')
        self.assertEqual(Vt._test_ValueTypeName(Vt.UChar(100)), 'unsigned char')
        self.assertEqual(Vt._test_ValueTypeName(Vt.Short(1234)), 'short')
        self.assertEqual(Vt._test_ValueTypeName(Vt.UShort(1234)), 'unsigned short')
        self.assertEqual(Vt._test_ValueTypeName(Vt.Int(12345)), 'int')
        self.assertEqual(Vt._test_ValueTypeName(Vt.UInt(12345)), 'unsigned int')
        self.assertEqual(Vt._test_ValueTypeName(Vt.Long(1234)), 'long')
        self.assertEqual(Vt._test_ValueTypeName(Vt.ULong(100)), 'unsigned long')

        self.assertEqual(Vt._test_ValueTypeName(Vt.Half(1.234)), 'pxr_half::half')
        self.assertEqual(Vt._test_ValueTypeName(Vt.Float(1.234)), 'float')
        self.assertEqual(Vt._test_ValueTypeName(Vt.Double(1.234)), 'double')