Beispiel #1
0
    def setUp(self):
        self.stage = Usd.Stage.CreateInMemory()

        instancer = UsdGeom.PointInstancer.Define(self.stage, '/MyPointInstancer')
        prototypesPrim = self.stage.DefinePrim(instancer.GetPath().AppendChild('prototypes'))
        prototypesPrimPath = prototypesPrim.GetPath()

        # A cube at the origin that is of length 1 in each dimension.
        originCube = self._AddCubeModel(self.stage, prototypesPrimPath.AppendChild('OriginCube'))

        # A cube at the origin with a scale xformOp that makes it of length 5
        # in each dimension.
        originScaledCube = self._AddCubeModel(self.stage, prototypesPrimPath.AppendChild('OriginScaledCube'))
        xformable = UsdGeom.Xformable(originScaledCube)
        xformable.AddScaleOp().Set(Gf.Vec3f(5.0))

        # A cube with a translate xformOp that is of length 1 in each dimension.
        translatedCube = self._AddCubeModel(self.stage, prototypesPrimPath.AppendChild('TranslatedCube'))
        xformable = UsdGeom.Xformable(translatedCube)
        xformable.AddTranslateOp().Set(Gf.Vec3d(3.0, 6.0, 9.0))

        # A cube with a rotateZ xformOp that is of length 1 in each dimension.
        rotatedCube = self._AddCubeModel(self.stage, prototypesPrimPath.AppendChild('RotatedCube'))
        xformable = UsdGeom.Xformable(rotatedCube)
        xformable.AddRotateZOp().Set(45.0)

        instancer.CreatePrototypesRel().SetTargets([
            originCube.GetPath(),
            originScaledCube.GetPath(),
            translatedCube.GetPath(),
            rotatedCube.GetPath()
        ])

        self.instancer = instancer
Beispiel #2
0
def createSimpleXformScene():
    '''Create a simple scene with a trivial hierarchy:

    A    translation (1, 2, 3)
    |_B  translation (7, 8, 9)

    '''

    psPathStr = mayaUsd_createStageWithNewLayer.createStageWithNewLayer()
    psPath = ufe.PathString.path(psPathStr)
    ps = ufe.Hierarchy.createItem(psPath)
    stage = mayaUsd.lib.GetPrim(psPathStr).GetStage()
    aPrim = stage.DefinePrim('/A', 'Xform')
    aXformable = UsdGeom.Xformable(aPrim)
    aXlateOp = aXformable.AddTranslateOp()
    aXlation = Gf.Vec3d(1, 2, 3)
    aXlateOp.Set(aXlation)
    aUsdUfePathStr = psPathStr + ',/A'
    aUsdUfePath = ufe.PathString.path(aUsdUfePathStr)
    aUsdItem = ufe.Hierarchy.createItem(aUsdUfePath)

    bPrim = stage.DefinePrim('/A/B', 'Xform')
    bXformable = UsdGeom.Xformable(bPrim)
    bXlateOp = bXformable.AddTranslateOp()
    bXlation = Gf.Vec3d(7, 8, 9)
    bXlateOp.Set(bXlation)
    bUsdUfePathStr = aUsdUfePathStr + '/B'
    bUsdUfePath = ufe.PathString.path(bUsdUfePathStr)
    bUsdItem = ufe.Hierarchy.createItem(bUsdUfePath)

    return (ps, aXlateOp, aXlation, aUsdUfePathStr, aUsdUfePath, aUsdItem,
            bXlateOp, bXlation, bUsdUfePathStr, bUsdUfePath, bUsdItem)
Beispiel #3
0
    def createTransformAttributesSection(self, sectionName, attrsToAdd):
        # Get the xformOp order and add those attributes (in order)
        # followed by the xformOp order attribute.
        allAttrs = self.attrS.attributeNames
        geomX = UsdGeom.Xformable(self.prim)
        xformOps = geomX.GetOrderedXformOps()
        xformOpOrderNames = [op.GetOpName() for op in xformOps]
        xformOpOrderNames.append(UsdGeom.Tokens.xformOpOrder)

        # Don't use createSection because we want a sub-sections.
        with ufeAeTemplate.Layout(self, sectionName):
            with ufeAeTemplate.Layout(self, 'Transform Attributes'):
                attrsToAdd.remove(UsdGeom.Tokens.xformOpOrder)
                self.addControls(xformOpOrderNames)

                # Get the remainder of the xformOps and add them in an Unused section.
                xformOpUnusedNames = fnmatch.filter(allAttrs, 'xformOp:*')
                xformOpUnusedNames = [
                    ele for ele in xformOpUnusedNames
                    if ele not in xformOpOrderNames
                ]
                self.createSection('Unused Transform Attributes',
                                   xformOpUnusedNames,
                                   collapse=True)

            # Then add any reamining Xformable attributes
            self.addControls(attrsToAdd)

            # Add a custom control for UFE attribute changed.
            t3dObs = UfeAttributesObserver(self.item)
            self.defineCustom(t3dObs)
    def test_mass_rigid_body_cube_compound(self):
        self.setup_scene()

        # top level xform - rigid body
        self.xform = UsdGeom.Xform.Define(self.stage, "/xform")
        rigidBodyAPI = UsdPhysics.RigidBodyAPI.Apply(self.xform.GetPrim())

        # Create test collider cube0
        self.cube = UsdGeom.Cube.Define(self.stage, "/xform/cube0")
        self.cube.GetSizeAttr().Set(1.0)
        UsdPhysics.CollisionAPI.Apply(self.cube.GetPrim())
        self.cube.AddTranslateOp().Set(Gf.Vec3f(0, 0, -2.0))

        # Create test colli
        self.cube2 = UsdGeom.Cube.Define(self.stage, "/xform/cube1")
        self.cube2.GetSizeAttr().Set(1.0)
        UsdPhysics.CollisionAPI.Apply(self.cube2.GetPrim())
        self.cube2.AddTranslateOp().Set(Gf.Vec3f(0, 0, 2.0))

        self.rigidBodyWorldTransform = UsdGeom.Xformable(
            self.xform.GetPrim()).ComputeLocalToWorldTransform(
                Usd.TimeCode.Default())
        self.rigidBodyPrim = self.xform.GetPrim()

        self.compare_mass_information(rigidBodyAPI,
                                      1000.0 * 2.0,
                                      expectedCoM=Gf.Vec3f(0.0))
    def test_mass_rigid_body_cube_rigid_body_principal_axes(self):
        self.setup_scene()

        # top level xform - rigid body
        self.xform = UsdGeom.Xform.Define(self.stage, "/xform")
        rigidBodyAPI = UsdPhysics.RigidBodyAPI.Apply(self.xform.GetPrim())
        massAPI = UsdPhysics.MassAPI.Apply(self.xform.GetPrim())

        # custom principal axes
        massAPI.GetPrincipalAxesAttr().Set(Gf.Quatf(0.707, 0.0, 0.707, 0.0))

        # Create test collider cube
        self.cube = UsdGeom.Cube.Define(self.stage, "/xform/cube")
        self.cube.GetSizeAttr().Set(1.0)
        UsdPhysics.CollisionAPI.Apply(self.cube.GetPrim())

        self.rigidBodyWorldTransform = UsdGeom.Xformable(
            self.xform.GetPrim()).ComputeLocalToWorldTransform(
                Usd.TimeCode.Default())
        self.rigidBodyPrim = self.xform.GetPrim()

        self.compare_mass_information(rigidBodyAPI,
                                      1000.0,
                                      expectedPrincipalAxes=Gf.Quatf(
                                          0.707, 0.0, 0.707, 0.0))
    def test_mass_rigid_body_cube_inertia_precedence(self):
        self.setup_scene()

        # top level xform - rigid body
        self.xform = UsdGeom.Xform.Define(self.stage, "/xform")
        rigidBodyAPI = UsdPhysics.RigidBodyAPI.Apply(self.xform.GetPrim())
        massAPI = UsdPhysics.MassAPI.Apply(self.xform.GetPrim())

        # custom inertia (has precedence)
        massAPI.GetDiagonalInertiaAttr().Set(Gf.Vec3f(2.0))

        # Create test collider cube
        self.cube = UsdGeom.Cube.Define(self.stage, "/xform/cube")
        self.cube.GetSizeAttr().Set(1.0)
        UsdPhysics.CollisionAPI.Apply(self.cube.GetPrim())
        massAPI = UsdPhysics.MassAPI.Apply(self.cube.GetPrim())

        # custom inertia
        massAPI.GetDiagonalInertiaAttr().Set(Gf.Vec3f(1.0))

        self.rigidBodyWorldTransform = UsdGeom.Xformable(
            self.xform.GetPrim()).ComputeLocalToWorldTransform(
                Usd.TimeCode.Default())
        self.rigidBodyPrim = self.xform.GetPrim()

        self.compare_mass_information(rigidBodyAPI,
                                      1000.0,
                                      expectedInertia=Gf.Vec3f(2.0))
    def test_mass_rigid_body_cube_mass_precedence(self):
        self.setup_scene()

        # top level xform - rigid body
        self.xform = UsdGeom.Xform.Define(self.stage, "/xform")
        rigidBodyAPI = UsdPhysics.RigidBodyAPI.Apply(self.xform.GetPrim())
        massAPI = UsdPhysics.MassAPI.Apply(self.xform.GetPrim())

        # increase the mass twice (has a precedence)
        massAPI.GetMassAttr().Set(2000.0)

        # Create test collider cube
        self.cube = UsdGeom.Cube.Define(self.stage, "/xform/cube")
        self.cube.GetSizeAttr().Set(1.0)
        UsdPhysics.CollisionAPI.Apply(self.cube.GetPrim())
        massAPI = UsdPhysics.MassAPI.Apply(self.cube.GetPrim())

        # increase the mass twice
        massAPI.GetMassAttr().Set(500.0)

        self.rigidBodyWorldTransform = UsdGeom.Xformable(
            self.xform.GetPrim()).ComputeLocalToWorldTransform(
                Usd.TimeCode.Default())
        self.rigidBodyPrim = self.xform.GetPrim()

        self.compare_mass_information(rigidBodyAPI,
                                      2000.0,
                                      expectedCoM=Gf.Vec3f(0.0),
                                      expectedInertia=Gf.Vec3f(166.667 * 2.0))
    def test_mass_rigid_body_cube_material_density(self):
        self.setup_scene()

        # top level xform - rigid body
        self.xform = UsdGeom.Xform.Define(self.stage, "/xform")
        rigidBodyAPI = UsdPhysics.RigidBodyAPI.Apply(self.xform.GetPrim())

        # Create test collider cube
        self.cube = UsdGeom.Cube.Define(self.stage, "/xform/cube")
        self.cube.GetSizeAttr().Set(1.0)
        UsdPhysics.CollisionAPI.Apply(self.cube.GetPrim())

        # Create base physics material
        self.basePhysicsMaterial = UsdShade.Material.Define(
            self.stage, "/basePhysicsMaterial")
        materialAPI = UsdPhysics.MaterialAPI.Apply(
            self.basePhysicsMaterial.GetPrim())
        # set half the default gravity
        materialAPI.GetDensityAttr().Set(500.0)
        bindingAPI = UsdShade.MaterialBindingAPI.Apply(self.cube.GetPrim())
        bindingAPI.Bind(self.basePhysicsMaterial,
                        UsdShade.Tokens.weakerThanDescendants, "physics")

        self.rigidBodyWorldTransform = UsdGeom.Xformable(
            self.xform.GetPrim()).ComputeLocalToWorldTransform(
                Usd.TimeCode.Default())
        self.rigidBodyPrim = self.xform.GetPrim()

        self.compare_mass_information(rigidBodyAPI,
                                      500.0,
                                      expectedCoM=Gf.Vec3f(0.0),
                                      expectedInertia=Gf.Vec3f(166.667 * 0.5))
 def testXformOpsNonIdentity(self):
     assembly = self._stage.GetPrimAtPath('/XformOpAssembly_NonIdentity')
     xformable = UsdGeom.Xformable(assembly)
     self.assertEqual(xformable.GetXformOpOrderAttr().Get(),
                      Vt.TokenArray(["xformOp:translate"]))
     self.assertEqual(xformable.GetLocalTransformation(),
                      Gf.Matrix4d().SetTranslate(Gf.Vec3d(7.0, 8.0, 9.0)))
Beispiel #10
0
        def verifyMergeToUsd():
            # Edit will re-allocate anything that was under pulled prim due to deactivation
            # Grab new references for /A/B prim
            bUsdPrim = mayaUsd.ufe.ufePathToPrim(bUsdUfePathStr)
            bXlateOp = UsdGeom.Xformable(bUsdPrim).GetOrderedXformOps()[0]

            # Check that edits have been preserved in USD.
            for (usdUfePathStr, mayaMatrix, xlateOp) in \
                zip([aUsdUfePathStr, bUsdUfePathStr], [aMayaMatrix, bMayaMatrix],
                    [aXlateOp, bXlateOp]):
                usdMatrix = xlateOp.GetOpTransform(
                    mayaUsd.ufe.getTime(usdUfePathStr))
                mayaValues = [v for v in mayaMatrix]
                usdValues = [v for row in usdMatrix for v in row]

                assertVectorAlmostEqual(self, mayaValues, usdValues)

            # There no longer are any Maya to USD path mappings.
            for mayaPath in [aMayaPath, bMayaPath]:
                self.assertEqual(len(mayaToUsd.fromHost(mayaPath)), 0)

            # Hierarchy is restored: USD item is child of proxy shape, Maya item is
            # not.  Be careful to use the Maya path rather than the Maya item, which
            # should no longer exist.
            self.assertIn(aUsdItem, psHier.children())
            self.assertNotIn(aMayaPath,
                             [child.path() for child in psHier.children()])

            # Maya nodes are removed.
            for mayaPathStr in [aMayaPathStr, bMayaPathStr]:
                with self.assertRaises(RuntimeError):
                    om.MSelectionList().add(mayaPathStr)
Beispiel #11
0
def add_xform(app, params, path_for_objects, create_ref, stage, obj, root_path, is_instance=False):
    if DEBUG_MODE:
        imp.reload(utils)
    # we should create a new stage and reference the old one to this new
    opt_animation = params.get("animation", None)
    if create_ref:
        new_stage_name = obj.FullName + "." + utils.get_extension_from_params(params)
        stage_asset_path = path_for_objects + new_stage_name
        new_stage = Usd.Stage.CreateNew(stage_asset_path)
        utils.add_stage_metadata(new_stage, params)

        # add dfault root xform node for this new stage
        usd_xform = UsdGeom.Xform.Define(new_stage, "/" + obj.Name)
        # reference main stage to this new stage
        ref = stage.DefinePrim(root_path + "/" + obj.Name)
        ref.GetReferences().AddReference("./" + utils.get_last_folder(path_for_objects) + "/" + new_stage_name, "/" + obj.Name)
        if is_instance:
            ref.SetInstanceable(True)
        refXform = UsdGeom.Xformable(ref)
        add_visibility_to_xfo(refXform, obj)
    else:
        usd_xform = UsdGeom.Xform.Define(stage, root_path + "/" + obj.Name)
        add_visibility_to_xfo(usd_xform, obj)

    if create_ref:
        add_transform_to_xfo(refXform, obj, opt_animation)
    else:
        add_transform_to_xfo(usd_xform, obj, opt_animation)

    if create_ref:
        return usd_xform, new_stage, stage_asset_path
    else:
        return usd_xform, None, None
Beispiel #12
0
        def checkParentDone():
            # The xform now has the capsule as its child.
            xformChildren = xformHier.children()
            self.assertEqual(len(xformChildren), 1)
            self.assertIn('Capsule1', childrenNames(xformChildren))

            # Confirm that the capsule has not moved in world space.  Must
            # re-create the prim and its scene item, as its path has changed.
            capsulePath = ufe.Path([
                proxyShapePathSegment,
                usdUtils.createUfePathSegment('/Xform1/Capsule1')
            ])
            capsulePrim = mayaUsd.ufe.ufePathToPrim(
                ufe.PathString.string(capsulePath))
            capsuleXformable = UsdGeom.Xformable(capsulePrim)
            capsuleItem = ufe.Hierarchy.createItem(capsulePath)
            capsuleT3d = ufe.Transform3d.transform3d(capsuleItem)
            capsuleWorld = capsuleT3d.inclusiveMatrix()
            assertVectorAlmostEqual(self,
                                    capsuleWorldPre,
                                    matrixToList(capsuleWorld),
                                    places=6)
            # Using setMatrixCmd() on a common transform API prim will set
            # translate, rotate, and scale.
            self.assertEqual(
                capsuleXformable.GetXformOpOrderAttr().Get(),
                Vt.TokenArray(("xformOp:translate", "xformOp:translate:pivot",
                               "xformOp:rotateXYZ", "xformOp:scale",
                               "!invert!xformOp:translate:pivot")))
Beispiel #13
0
        def checkParentDone():
            # The xform now has the capsule as its child.
            xformChildren = xformHier.children()
            self.assertEqual(len(xformChildren), 1)
            self.assertIn('Capsule1', childrenNames(xformChildren))

            # Confirm that the capsule has not moved in world space.  Must
            # re-create the prim and its scene item, as its path has changed.
            capsulePath = ufe.Path([
                proxyShapePathSegment,
                usdUtils.createUfePathSegment('/Xform1/Capsule1')
            ])
            capsulePrim = mayaUsd.ufe.ufePathToPrim(
                ufe.PathString.string(capsulePath))
            capsuleXformable = UsdGeom.Xformable(capsulePrim)
            capsuleItem = ufe.Hierarchy.createItem(capsulePath)
            capsuleT3d = ufe.Transform3d.transform3d(capsuleItem)
            capsuleWorld = capsuleT3d.inclusiveMatrix()
            assertVectorAlmostEqual(self, capsuleWorldPre,
                                    matrixToList(capsuleWorld))

            # The capsule's transform ops now have Maya fallback stack ops.  A
            # scale fallback op is added, even though it's uniform unit.
            self.assertEqual(
                capsuleXformable.GetXformOpOrderAttr().Get(),
                Vt.TokenArray(
                    ("xformOp:translate", "xformOp:rotateXYZ",
                     "xformOp:rotateX", "xformOp:translate:maya_fallback",
                     "xformOp:rotateXYZ:maya_fallback",
                     "xformOp:scale:maya_fallback")))
Beispiel #14
0
 def test_PureOvers(self):
     s = Usd.Stage.CreateInMemory()
     # Create a pure over prim and invoke various API.
     x = s.OverridePrim('/World')
     xf = UsdGeom.Xformable(x)
     xf.SetResetXformStack(True)
     xf.MakeMatrixXform().Set(Gf.Matrix4d(1.0))
     xf.SetXformOpOrder(xf.GetOrderedXformOps(), False)
Beispiel #15
0
def get_transform(usd_item):
    usd_xform = UsdGeom.Xformable(usd_item)
    times_array = usd_xform.GetTimeSamples()  # array of time samples, it empty if no animation
    if len(times_array) == 0:
        usd_transform = usd_xform.GetLocalTransformation()
    else:
        usd_transform = [usd_xform.GetLocalTransformation(t) for t in times_array]
    return (usd_transform, times_array)
Beispiel #16
0
 def local_transform_from_usd_node(self,
                                   prim,
                                   unit_scale=1.0,
                                   up_axis='y',
                                   extra_rotate=None,
                                   frame=Usd.TimeCode.Default()):
     usd_xform = UsdGeom.Xformable(prim)
     usd_transform = usd_xform.GetLocalTransformation(frame)
     return self.transform_from_usd_transform(usd_transform, unit_scale,
                                              up_axis, extra_rotate)
Beispiel #17
0
    def testFallbackCases(self):
        '''Fallback handler test cases.'''

        cmds.file(new=True, force=True)

        import mayaUsd_createStageWithNewLayer
        proxyShape = mayaUsd_createStageWithNewLayer.createStageWithNewLayer()

        proxyShapePath = ufe.PathString.path(proxyShape)
        proxyShapeItem = ufe.Hierarchy.createItem(proxyShapePath)
        proxyShapeContextOps = ufe.ContextOps.contextOps(proxyShapeItem)
        proxyShapeContextOps.doOp(['Add New Prim', 'Sphere'])

        spherePath = ufe.PathString.path('%s,/Sphere1' % proxyShape)
        sphereItem = ufe.Hierarchy.createItem(spherePath)
        sphereT3d = ufe.Transform3d.transform3d(sphereItem)

        spherePrim = mayaUsd.ufe.ufePathToPrim(
            ufe.PathString.string(spherePath))
        sphereXformable = UsdGeom.Xformable(spherePrim)

        # Add transform ops that do not match either the Maya transform stack,
        # the USD common API transform stack, or a matrix stack.
        sphereXformable.AddTranslateOp()
        sphereXformable.AddTranslateOp(UsdGeom.XformOp.PrecisionFloat, "pivot")
        sphereXformable.AddRotateZOp()
        sphereXformable.AddTranslateOp(UsdGeom.XformOp.PrecisionFloat, "pivot",
                                       True)

        self.assertEqual(
            sphereXformable.GetXformOpOrderAttr().Get(),
            Vt.TokenArray(
                ("xformOp:translate", "xformOp:translate:pivot",
                 "xformOp:rotateZ", "!invert!xformOp:translate:pivot")))

        self.assertFalse(UsdGeom.XformCommonAPI(sphereXformable))
        self.assertFalse(mayaUsd.lib.XformStack.MayaStack().MatchingSubstack(
            sphereXformable.GetOrderedXformOps()))

        # Select sphere.
        sn = ufe.GlobalSelection.get()
        sn.clear()
        sn.append(sphereItem)

        # Rotate sphere around X.
        cmds.rotate(30, 0, 0, r=True, os=True, fo=True)

        # Fallback interface will have added a RotXYZ transform op.
        self.assertEqual(
            sphereXformable.GetXformOpOrderAttr().Get(),
            Vt.TokenArray(
                ("xformOp:translate", "xformOp:translate:pivot",
                 "xformOp:rotateZ", "!invert!xformOp:translate:pivot",
                 "xformOp:rotateXYZ:maya_fallback")))
Beispiel #18
0
 def test_InvalidXformable(self):
     xf = UsdGeom.Xformable()
     # This used to crash before the SchemaBase __getattribute__ method
     # was overridden to test the validity of the underlying prim.
     with self.assertRaises(RuntimeError):
         xf.ClearXformOpOrder()
     # It should still be safe to get the prim, but the prim will be invalid.
     p = xf.GetPrim()
     with self.assertRaises(RuntimeError):
         p.IsActive()
     # It should still be safe to get the path, but the path will be empty.
     self.assertEqual(xf.GetPath(), Sdf.Path())
Beispiel #19
0
    def _AssertPrototype(self, prim, typeName, numChildren,
            hasInstancerTranslate):
        self.assertEqual(prim.GetTypeName(), typeName)
        self.assertEqual(len(prim.GetChildren()), numChildren)
        self.assertEqual(Usd.ModelAPI(prim).GetKind(), Kind.Tokens.subcomponent)

        xformOps = UsdGeom.Xformable(prim).GetOrderedXformOps()
        foundInstancerTranslate = False
        for op in xformOps:
            if op.GetOpName() == "xformOp:translate:instancerTranslate":
                foundInstancerTranslate = True
                break
        self.assertEqual(foundInstancerTranslate, hasInstancerTranslate)
Beispiel #20
0
def set_rotate(prim, rot_mat):
    properties = prim.GetPropertyNames()
    if "xformOp:rotate" in properties:
        rotate_attr = prim.GetAttribute("xformOp:rotate")
        rotate_attr.Set(rot_mat)
    elif "xformOp:transform" in properties:
        transform_attr = prim.GetAttribute("xformOp:transform")
        matrix = prim.GetAttribute("xformOp:transform").Get()
        matrix.SetRotateOnly(rot_mat.ExtractRotation())
        transform_attr.Set(matrix)
    else:
        xform = UsdGeom.Xformable(prim)
        xform_op = xform.AddXformOp(UsdGeom.XformOp.TypeTransform,
                                    UsdGeom.XformOp.PrecisionDouble, "")
        xform_op.Set(Gf.Matrix4d().SetRotate(rot_mat))
Beispiel #21
0
def _addGround(stage, width, height):
    boxPrim = UsdGeom.Cube.Define(stage, '/World/ground')
    boxPrim.CreateDisplayColorAttr([(0.5, 0.2, 0.0)])
    xformable = UsdGeom.Xformable(boxPrim)
    xformable.AddScaleOp().Set(Gf.Vec3f(width / 2, 0.1, height / 2))

    material = UsdShade.Material.Define(stage, '/World/GroundMaterial')
    pbrShader = UsdShade.Shader.Define(stage,
                                       '/World/GroundMaterial/GroundShader')
    pbrShader.CreateIdAttr("UsdPreviewSurface")
    pbrShader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set(
        (0.5, 0.2, 0.0))

    pbrShader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(0.9)
    pbrShader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(0.0)
Beispiel #22
0
    def test_InvalidXformOps(self):
        s = Usd.Stage.CreateInMemory()
        p = s.DefinePrim('/World', 'Xform')
        x = UsdGeom.Xformable(p)

        # Create an attribute that is not in the xformOp namespace.
        attr1 = p.CreateAttribute("myXformOp:transform", Sdf.ValueTypeNames.Matrix4d)
        self._TestInvalidXformOp(attr1)

        # Create an xform op with an invalid optype.
        attr2 = p.CreateAttribute("xformOp:translateXYZ", Sdf.ValueTypeNames.Double3)
        self._TestInvalidXformOp(attr2)

        # Create an xform op with opType=transform and typeName=Matrix4f.
        with self.assertRaises(RuntimeError):
            xformOp = x.AddTransformOp(precision=UsdGeom.XformOp.PrecisionFloat)
Beispiel #23
0
    def spawn(self, location, rotation):
        stage = self.omni_kit.get_stage()
        prefix = "/World/Robot/STR"
        prim_path = omni.kit.utils.get_stage_next_free_path(
            stage, prefix, False)
        print(prim_path)
        self.robot_prim = stage.DefinePrim(prim_path, "Xform")
        self.robot_prim.GetReferences().AddReference(self.usd_path)
        xform = UsdGeom.Xformable(self.robot_prim)
        xform_op = xform.AddXformOp(UsdGeom.XformOp.TypeTransform,
                                    UsdGeom.XformOp.PrecisionDouble, "")
        mat = Gf.Matrix4d().SetTranslate(location)
        mat.SetRotateOnly(Gf.Rotation(Gf.Vec3d(0, 0, 1), rotation))
        xform_op.Set(mat)

        self.camera_path = prim_path + "/STR/Vehicle/str_camera"
Beispiel #24
0
def _addGround(stage):
    boxPrim = UsdGeom.Cube.Define(stage, '/World/ground')
    boxPrim.CreateDisplayColorAttr([(0.5, 0.2, 0.0)])
    xformable = UsdGeom.Xformable(boxPrim)
    xformable.AddScaleOp().Set(Gf.Vec3f(280.0, 0.1, 280))

    material = UsdShade.Material.Define(stage, '/World/GroundMaterial')
    pbrShader = UsdShade.Shader.Define(stage,
                                       '/World/GroundMaterial/GroundShader')
    pbrShader.CreateIdAttr("UsdPreviewSurface")
    pbrShader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set(
        (0.5, 0.2, 0.0))

    pbrShader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(0.9)
    pbrShader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(0.0)
    material.CreateSurfaceOutput().ConnectToSource(pbrShader, "surface")
    UsdShade.MaterialBindingAPI(boxPrim).Bind(material)
    def test_mass_rigid_body_cube(self):
        self.setup_scene()

        # Create test collider cube
        self.cube = UsdGeom.Cube.Define(self.stage, "/cube")
        self.cube.GetSizeAttr().Set(1.0)
        UsdPhysics.CollisionAPI.Apply(self.cube.GetPrim())
        rigidBodyAPI = UsdPhysics.RigidBodyAPI.Apply(self.cube.GetPrim())

        self.rigidBodyWorldTransform = UsdGeom.Xformable(
            self.cube.GetPrim()).ComputeLocalToWorldTransform(
                Usd.TimeCode.Default())
        self.rigidBodyPrim = self.cube.GetPrim()

        self.compare_mass_information(rigidBodyAPI,
                                      1000.0,
                                      expectedCoM=Gf.Vec3f(0.0),
                                      expectedInertia=Gf.Vec3f(166.667))
Beispiel #26
0
def set_translate(prim, new_loc):
    properties = prim.GetPropertyNames()
    if "xformOp:translate" in properties:
        translate_attr = prim.GetAttribute("xformOp:translate")
        translate_attr.Set(new_loc)
    elif "xformOp:translation" in properties:
        translation_attr = prim.GetAttribute("xformOp:translate")
        translation_attr.Set(new_loc)
    elif "xformOp:transform" in properties:
        transform_attr = prim.GetAttribute("xformOp:transform")
        matrix = prim.GetAttribute("xformOp:transform").Get()
        matrix.SetTranslateOnly(new_loc)
        transform_attr.Set(matrix)
    else:
        xform = UsdGeom.Xformable(prim)
        xform_op = xform.AddXformOp(UsdGeom.XformOp.TypeTransform,
                                    UsdGeom.XformOp.PrecisionDouble, "")
        xform_op.Set(Gf.Matrix4d().SetTranslate(new_loc))
    def mass_information_fn(self, prim):
        massInfo = UsdPhysics.RigidBodyAPI.MassInformation()
        if prim.IsA(UsdGeom.Cube):
            cubeLocalToWorldTransform = UsdGeom.Xformable(
                prim).ComputeLocalToWorldTransform(Usd.TimeCode.Default())
            extents = Gf.Transform(cubeLocalToWorldTransform).GetScale()

            cube = UsdGeom.Cube(prim)
            sizeAttr = cube.GetSizeAttr().Get()
            sizeAttr = abs(sizeAttr)
            extents = extents * sizeAttr

            # cube volume
            massInfo.volume = extents[0] * extents[1] * extents[2]

            # cube inertia
            inertia_diagonal = Gf.Vec3f(
                1.0 / 12.0 *
                (extents[1] * extents[1] + extents[2] * extents[2]), 1.0 /
                12.0 * (extents[0] * extents[0] + extents[2] * extents[2]),
                1.0 / 12.0 *
                (extents[0] * extents[0] + extents[1] * extents[1]))
            massInfo.inertia = Gf.Matrix3f(1.0)
            massInfo.inertia.SetDiagonal(inertia_diagonal)

            # CoM
            massInfo.centerOfMass = Gf.Vec3f(0.0)

            # local pose
            if prim == self.rigidBodyPrim:
                massInfo.localPos = Gf.Vec3f(0.0)
                massInfo.localRot = Gf.Quatf(1.0)
            else:
                # massInfo.localPos, massInfo.localRot
                lp, lr = self.get_collision_shape_local_transfrom(
                    cubeLocalToWorldTransform, self.rigidBodyWorldTransform)
                massInfo.localPos = Gf.Vec3f(lp)
                massInfo.localRot = Gf.Quatf(lr)

        else:
            print("UsdGeom type not supported.")
            massInfo.volume = -1.0

        return massInfo
Beispiel #28
0
    def _ValidateXformOps(self, prim, expectedTranslation=None):
        xformable = UsdGeom.Xformable(prim)
        self.assertTrue(xformable)

        xformOps = xformable.GetOrderedXformOps()

        if expectedTranslation is None:
            self.assertEqual(len(xformOps), 0)
            return xformable

        self.assertEqual(len(xformOps), 1)

        translateOp = xformOps[0]

        self.assertEqual(translateOp.GetOpName(), 'xformOp:translate')
        self.assertEqual(translateOp.GetOpType(), UsdGeom.XformOp.TypeTranslate)

        self.assertTrue(Gf.IsClose(translateOp.Get(), expectedTranslation, 1e-6))

        return xformable
Beispiel #29
0
def TestUsd4957():
    """ Tests the case in which a prim has an xform directly on it and its
        bounding box relative to one of its ancestors is computed using
        ComputeRelativeBound().
    """
    s = Usd.Stage.Open("testUSD4957.usda")
    b = s.GetPrimAtPath("/A/B")
    c = s.GetPrimAtPath("/A/B/C")
    bc = UsdGeom.BBoxCache(Usd.TimeCode.Default(), ['default', 'render'])
    
    # Call the function being tested
    relativeBbox = bc.ComputeRelativeBound(c, b)
    
    # Compare the result with the bbox of C in its local space
    cExtent = UsdGeom.Boundable(c).GetExtentAttr().Get()
    cRange = Gf.Range3d(Gf.Vec3d(cExtent[0]), Gf.Vec3d(cExtent[1]))
    cLocalXform = UsdGeom.Xformable(c).GetLocalTransformation()
    cBbox = Gf.BBox3d(cRange, cLocalXform)
    
    AssertBBoxesClose(relativeBbox, cBbox,
                      "ComputeRelativeBound produced a wrong bbox.")
Beispiel #30
0
    def createTransformAttributesSection(self):
        # Get the xformOp order and add those attributes (in order)
        # followed by the xformOp order attribute.
        prim = mayaUsd.ufe.getPrimFromRawItem(self.item.getRawAddress())
        geomX = UsdGeom.Xformable(prim)
        xformOps = geomX.GetOrderedXformOps()
        xformOpOrderNames = [op.GetOpName() for op in xformOps]
        xformOpOrderNames.append(UsdGeom.Tokens.xformOpOrder)
        # Don't use createSection because we want a sub-section for Unused.
        with ufeAeTemplate.Layout(self, 'Transform Attributes'):
            self.addControls(xformOpOrderNames)

            # Get the remainder of the xformOps and add them in an Unused section.
            allAttrs = self.attrS.attributeNames
            xformOpUnusedNames = fnmatch.filter(allAttrs, 'xformOp:*')
            xformOpUnusedNames = [
                ele for ele in xformOpUnusedNames
                if ele not in xformOpOrderNames
            ]
            self.createSection('Unused Transform Attributes',
                               xformOpUnusedNames,
                               collapse=True)