Esempio n. 1
0
def TestExtentCalculation():
    stage = Usd.Stage.Open("pointsAndCurves.usda")
    bboxCache = UsdGeom.BBoxCache(Usd.TimeCode(0.0),
                                  includedPurposes=[UsdGeom.Tokens.default_])

    print("-" * 80)
    print("Testing extent calculations on prims")
    print("-" * 80)
    print()

    validPrims = stage.GetPrimAtPath("/ValidPrims")
    warningPrims = stage.GetPrimAtPath("/WarningPrims")
    errorPrims = stage.GetPrimAtPath("/ErrorPrims")

    print("Visit Extent: " + str(validPrims))
    for prim in validPrims.GetChildren():
        print(str(prim) + ": " + \
            str(bboxCache.ComputeWorldBound(prim).GetRange()))
    print()

    print("Visit Extent: " + str(warningPrims))
    for prim in warningPrims.GetChildren():
        print(str(prim) + ": " + \
            str(bboxCache.ComputeWorldBound(prim).GetRange()))
    print()

    print("Visit Extent: " + str(errorPrims))
    for prim in errorPrims.GetChildren():
        bboxRange = bboxCache.ComputeWorldBound(prim).GetRange()
        print(str(prim) + ": " + \
            str(bboxCache.ComputeWorldBound(prim).GetRange()))
Esempio n. 2
0
def set_radius(usd_light, xsi_param, anim_opt):
    attr = usd_light.CreateRadiusAttr()
    if anim_opt is None:
        attr.Set(xsi_param.Value)
    else:
        for frame in range(anim_opt[0], anim_opt[1] + 1):
            attr.Set(xsi_param.GetValue(frame), Usd.TimeCode(frame))
 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)
         print primpath, e
         self.assertEqual(extents[primpath], e)
Esempio n. 4
0
 def testNumericTimeRepr(self):
     """
     Validates the string representation of a numeric time code.
     """
     timeCode = Usd.TimeCode(123.0)
     timeRepr = repr(timeCode)
     self.assertEqual(timeRepr, 'Usd.TimeCode(123.0)')
Esempio n. 5
0
    def _create_usd_animation2(self, usd_node, gltf_node, animation_channels):
        """Converts a glTF animation to a USD animation

        Arguments:
            usd_node {[type]} -- usd node
            gltf_node {[type]} -- glTF node
            animation_channel {AnimationMap} -- map of animation target path and animation sampler indices

        Returns:
            [type] -- [description]
        """

        max_time = -999
        min_time = 999
        for channel in animation_channels:
            max_time = max(max_time, int(round(channel.sampler.get_input_max()[0])))
            min_time = min(min_time, int(round(channel.sampler.get_input_min()[0])))


        transform = usd_node.AddTransformOp(opSuffix='transform')

        for i, keyframe in enumerate(numpy.arange(min_time, max_time, 1./self.fps)):
            transform_node = self._create_keyframe_transform_node(gltf_node, animation_channels, keyframe)
            transform.Set(transform_node, Usd.TimeCode(i))

        MinMaxTime = collections.namedtuple('MinMaxTime', ('max', 'min'))
        return MinMaxTime(max=max_time, min=min_time)
Esempio n. 6
0
    def sync_update(self, context, depsgraph):
        """ sync just the updated things """

        if not self.is_synced:
            return

        settings = self.get_settings(depsgraph.scene)
        self.render_params.frame = Usd.TimeCode(depsgraph.scene.frame_current)

        if self.renderer.IsPauseRendererSupported():
            self.renderer.PauseRenderer()

        if self._check_restart_renderer(depsgraph.scene):
            self.renderer = None  # explicit renderer deletion
            self.renderer = UsdImagingGL.Engine()

        gl_delegate_changed = self.is_gl_delegate != settings.is_gl_delegate

        self._sync_update(context, depsgraph)

        if gl_delegate_changed:
            usd_utils.set_delegate_variant_stage(self.cached_stage(),
                                                 settings.delegate_name)

        if self.renderer.IsPauseRendererSupported():
            self.renderer.ResumeRenderer()

        self.render_engine.tag_redraw()
Esempio n. 7
0
 def _CheckValues(self,
                  camera,
                  schema,
                  time,
                  skipTransformAndClippingPlanes=False):
     if not skipTransformAndClippingPlanes:
         self.assertEqual(camera.transform,
                          schema.GetLocalTransformation(Usd.TimeCode(time)))
     self.assertEqual(camera.projection,
                      self._GetSchemaProjection(schema, time))
     self.assertEqual(camera.horizontalAperture,
                      schema.GetHorizontalApertureAttr().Get(time))
     self.assertEqual(camera.verticalAperture,
                      schema.GetVerticalApertureAttr().Get(time))
     self.assertEqual(camera.horizontalApertureOffset,
                      schema.GetHorizontalApertureOffsetAttr().Get(time))
     self.assertEqual(camera.verticalApertureOffset,
                      schema.GetVerticalApertureOffsetAttr().Get(time))
     self.assertEqual(camera.focalLength,
                      schema.GetFocalLengthAttr().Get(time))
     self.assertEqual(camera.clippingRange,
                      self._GetSchemaClippingRange(schema, time))
     if not skipTransformAndClippingPlanes:
         self.assertEqual(camera.clippingPlanes,
                          self._GetSchemaClippingPlanes(schema, time))
     self.assertTrue(
         Gf.IsClose(camera.fStop,
                    schema.GetFStopAttr().Get(time), 1e-6))
     self.assertEqual(camera.focusDistance,
                      schema.GetFocusDistanceAttr().Get(time))
Esempio n. 8
0
File: common.py Progetto: warioh/USD
def GetAttributeStatus(attribute,
                       frame,
                       hasValue=None,
                       hasAuthoredValue=None,
                       valueIsDefault=None):
    if not isinstance(frame, Usd.TimeCode):
        frame = Usd.TimeCode(frame)

    # Save time if someone has already made the queries
    if hasValue == False:
        return AttributeStatus.NOVALUE
    elif hasValue is not None and hasAuthoredValue == False:
        return AttributeStatus.FALLBACK

    if not attribute.HasValue():
        return AttributeStatus.NOVALUE

    # no authored value? it's using fallback
    if not attribute.HasAuthoredValueOpinion():
        return AttributeStatus.FALLBACK

    if frame.IsDefault() or valueIsDefault:
        return AttributeStatus.DEFAULT

    bracketingTS = attribute.GetBracketingTimeSamples(frame.GetValue())
    if len(bracketingTS) == 0:
        return AttributeStatus.DEFAULT

    return (AttributeStatus.KEYFRAME if bracketingTS[0] == frame.GetValue()
            else AttributeStatus.CLAMPED)
Esempio n. 9
0
    def test_Layers(self):
        layeredFile = 'testUsdAbcSDFArguments.usda'
        topologyFile = 'testUsdAbcSDFArgumentsMesh.abc'
        flatFile = 'testUsdAbcSDFArgumentsFlat.abc'
        time = Usd.TimeCode()
        xformCache = UsdGeom.XformCache(time)

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

        pCubeShape1 = UsdGeom.Mesh.Get(stage, '/AlembicRoot/pCubeShape1')
        pCubeShape2 = UsdGeom.Mesh.Get(stage, '/AlembicRoot/pCubeShape2')
        self.assertTrue(pCubeShape1)
        self.assertTrue(pCubeShape2)


        topoABC = Usd.Stage.Open(topologyFile)
        self.assertTrue(topoABC)
        pCubeShape1ABCPure = UsdGeom.Mesh.Get(topoABC, '/pCubeShape1')
        pCubeShape2ABCPure = UsdGeom.Mesh.Get(topoABC, '/pCubeShape2')
        self.assertTrue(pCubeShape1ABCPure)
        self.assertTrue(pCubeShape2ABCPure)

        # Test the Xforms got layered in properly
        #
        self.assertEqual(xformCache.GetLocalToWorldTransform(pCubeShape1.GetPrim()),
                         xformCache.GetLocalToWorldTransform(pCubeShape1ABCPure.GetPrim()))

        self.assertEqual(xformCache.GetLocalToWorldTransform(pCubeShape2.GetPrim()),
                         xformCache.GetLocalToWorldTransform(pCubeShape2ABCPure.GetPrim()))

        # Test various attributes & primavars came through
        #
        self.assertEqual(len(pCubeShape1.GetPointsAttr().Get(time)),
                         len(pCubeShape2.GetPointsAttr().Get(time)))

        self.assertEqual(len(pCubeShape1.GetNormalsAttr().Get(time)), 8)
        self.assertEqual(len(pCubeShape2.GetNormalsAttr().Get(time)), 24)

        pCubeShape1UV = pCubeShape1.GetPrimvar('uv')
        pCubeShape2UV = pCubeShape2.GetPrimvar('uv')

        self.assertEqual(pCubeShape1UV.GetTypeName(), 'float2[]')
        self.assertEqual(pCubeShape2UV.GetTypeName(), 'float2[]')

        self.assertEqual(pCubeShape1UV.GetInterpolation() , 'varying')
        self.assertEqual(len(pCubeShape1UV.Get(time)),  8)

        self.assertEqual(pCubeShape2UV.GetInterpolation(), 'faceVarying')
        self.assertEqual(len(pCubeShape2UV.Get(time)), 14)
        self.assertEqual(len(pCubeShape2UV.GetIndices(time)), 24)

        # Test against the known flattened version
        #
        flatABC = Usd.Stage.Open(flatFile)
        self.assertTrue(flatABC)

        self.assertEqual(UsdGeom.Mesh.Get(flatABC, '/pCubeShape1').GetPrimvar('uv').Get(time), pCubeShape1UV.Get(time))
        self.assertEqual(UsdGeom.Mesh.Get(flatABC, '/pCubeShape2').GetPrimvar('uv').Get(time), pCubeShape2UV.Get(time))
Esempio n. 10
0
 def testDefaultConstructedTimeRepr(self):
     """
     Validates the string representation of a time code created using
     the default constructor.
     """
     timeCode = Usd.TimeCode()
     timeRepr = repr(timeCode)
     self.assertEqual(timeRepr, 'Usd.TimeCode()')
Esempio n. 11
0
def TestIgnoreVisibility():
    stage = Usd.Stage.Open("animVis.usda")
    bboxCache = UsdGeom.BBoxCache(Usd.TimeCode(0.0),
                                  includedPurposes=[UsdGeom.Tokens.default_],
                                  useExtentsHint=True,
                                  ignoreVisibility=True)
    pseudoRoot = stage.GetPrimAtPath("/")
    assert not bboxCache.ComputeWorldBound(pseudoRoot).GetRange().IsEmpty()
Esempio n. 12
0
def set_diffuse(usd_light, parameter, anim_opt, value=None):  # value used for background light
    if value is not None:
        usd_light.CreateDiffuseAttr().Set(value)
    else:
        attr = usd_light.CreateDiffuseAttr()
        if anim_opt is None or utils.is_param_animated(parameter, anim_opt):
            for frame in range(anim_opt[0], anim_opt[1] + 1):
                attr.Set(1.0 if parameter.GetValue(frame) else 0.0, Usd.TimeCode(frame))
        else:
            attr.Set(1.0 if parameter.Value else 0.0)
Esempio n. 13
0
def set_specular(usd_light, parameter, anim_opt, value=None):
    if value is not None:
        usd_light.CreateSpecularAttr().Set(value)
    else:
        attr = usd_light.CreateSpecularAttr()
        if anim_opt is None or utils.is_param_animated(parameter, anim_opt):
            for frame in range(anim_opt[0], anim_opt[1] + 1):
                attr.Set(1.0 if parameter.GetValue(frame) else 0.0, Usd.TimeCode(frame))
        else:
            attr.Set(1.0 if parameter.Value else 0.0)
Esempio n. 14
0
def set_camera_at_frame(xsi_camera, usd_camera, frame=None):
    xsi_interest = xsi_camera.Interest
    # get global position of the camera and the interest
    xsi_camera_position = xsi_camera.Kinematics.Global.Transform.Translation if frame is None else xsi_camera.Kinematics.Local.GetTransform2(
        frame).Translation
    xsi_interest_position = xsi_interest.Kinematics.Global.Transform.Translation if frame is None else xsi_interest.Kinematics.Local.GetTransform2(
        frame).Translation
    xsi_focal_length = (
        xsi_camera.Parameters("projplanedist").Value if frame is None else
        xsi_camera.Parameters("projplanedist").GetValue2(frame))
    if frame is None:
        usd_camera.CreateFocalLengthAttr().Set(xsi_focal_length)
        usd_camera.CreateFocusDistanceAttr().Set(
            get_distance(xsi_camera_position, xsi_interest_position))
    else:
        usd_camera.CreateFocalLengthAttr().Set(xsi_focal_length,
                                               Usd.TimeCode(frame))
        usd_camera.CreateFocusDistanceAttr().Set(
            get_distance(xsi_camera_position, xsi_interest_position),
            Usd.TimeCode(frame))
    def test_TimeSampledAssets(self):
        src_stage = Usd.Stage.Open('time_sampled_assets.usda')
        layer = UsdUtils.FlattenLayerStack(src_stage)
        result_stage = Usd.Stage.Open(layer)

        prim = result_stage.GetPrimAtPath(
            '/materials/usdpreviewsurface1/usduvtexture1')
        attr = prim.GetAttribute('inputs:file')
        time_samples = attr.GetTimeSamples()
        for time_sample in time_samples:
            time_sample_array_value = attr.Get(Usd.TimeCode(time_sample))
            for time_sample_value in time_sample_array_value:
                self.assertTrue(os.path.isabs(time_sample_value.path))

        prim = result_stage.GetPrimAtPath('/volume/density')
        attr = prim.GetAttribute('filePath')
        time_samples = attr.GetTimeSamples()
        for time_sample in time_samples:
            time_sample_value = attr.Get(Usd.TimeCode(time_sample))
            self.assertTrue(os.path.isabs(time_sample_value.path))
Esempio n. 16
0
def TestUnloadedExtentsHints():
    stage = Usd.Stage.Open(
        "unloadedCubeModel.usda",
        load = Usd.Stage.LoadNone)
    bboxCacheNo = UsdGeom.BBoxCache(Usd.TimeCode(0.0), 
        includedPurposes=[UsdGeom.Tokens.default_], useExtentsHint=False)
    bboxCacheYes = UsdGeom.BBoxCache(Usd.TimeCode(0.0), 
        includedPurposes=[UsdGeom.Tokens.default_], useExtentsHint=True)

    print "-"*80
    print "Testing aggregate bounds with unloaded child prims"
    print "-"*80
    print 

    prim = stage.GetPseudoRoot()
    bboxNo  = bboxCacheNo.ComputeWorldBound(prim)
    bboxYes = bboxCacheYes.ComputeWorldBound(prim)
    
    assert bboxNo.GetRange().IsEmpty()
    assert not bboxYes.GetRange().IsEmpty()
Esempio n. 17
0
    def test_AppendFaceGroupAnimated(self):
        animatedFaceSet = UsdGeom.FaceSetAPI(sphere, "animated")

        # Test appending at default time.
        animatedFaceSet.AppendFaceGroup(faceIndices=[0],
                                        time=Usd.TimeCode.Default())
        animatedFaceSet.AppendFaceGroup(faceIndices=[1],
                                        time=Usd.TimeCode.Default())
        faceCounts = animatedFaceSet.GetFaceCounts(Usd.TimeCode.Default())
        self.assertEqual(len(faceCounts), 2)

        # Test appending at the same time ordinate.
        animatedFaceSet.AppendFaceGroup(faceIndices=[2], time=Usd.TimeCode(1))
        animatedFaceSet.AppendFaceGroup(faceIndices=[3], time=Usd.TimeCode(1))
        faceCounts = animatedFaceSet.GetFaceCounts(Usd.TimeCode(1))
        self.assertEqual(len(faceCounts), 2)

        # Test appending at a new time ordinate.
        animatedFaceSet.AppendFaceGroup(faceIndices=[4], time=Usd.TimeCode(2))

        faceCounts = animatedFaceSet.GetFaceCounts(Usd.TimeCode.Default())
        self.assertEqual(len(faceCounts), 2)
        faceCounts = animatedFaceSet.GetFaceCounts(Usd.TimeCode(1))
        self.assertEqual(len(faceCounts), 2)
        faceCounts = animatedFaceSet.GetFaceCounts(Usd.TimeCode(2))
        self.assertEqual(len(faceCounts), 1)
Esempio n. 18
0
    def test_AppendTarget(self):
        appendTestCollection = UsdGeom.CollectionAPI.Create(root, "AppendTest")

        # Appending an empty target should result in a coding error.
        with self.assertRaises(RuntimeError):
            appendTestCollection.AppendTarget(Sdf.Path())

        appendTestCollection.AppendTarget(sphere.GetPath(), [],
                                          Usd.TimeCode(1))
        appendTestCollection.AppendTarget(cube.GetPath(), [0, 1, 2, 3, 4],
                                          Usd.TimeCode(1))
        appendTestCollection.AppendTarget(cone.GetPath(), [], Usd.TimeCode(1))
        appendTestCollection.AppendTarget(cylinder.GetPath(), [5, 6, 7, 8],
                                          Usd.TimeCode(1))

        self.assertEqual(appendTestCollection.GetTargets(), [
            sphere.GetPath(),
            cube.GetPath(),
            cone.GetPath(),
            cylinder.GetPath()
        ])
        self.assertEqual(
            list(appendTestCollection.GetTargetFaceCounts(Usd.TimeCode(1))),
            [0, 5, 0, 4])
        self.assertEqual(
            list(appendTestCollection.GetTargetFaceIndices(Usd.TimeCode(1))),
            [0, 1, 2, 3, 4, 5, 6, 7, 8])
Esempio n. 19
0
    def test_GetTimeSamples(self):
        s = Usd.Stage.CreateInMemory()
        x = UsdGeom.Xform.Define(s, '/World')

        xlateOp = x.AddTranslateOp()
        scaleOp = x.AddScaleOp()

        self.assertEqual([], xlateOp.GetTimeSamples())
        self.assertEqual([], scaleOp.GetTimeSamples())

        xlate1 = Gf.Vec3d(10., 20., 30.)
        scale2 = Gf.Vec3f(1., 2., 3.)

        xlate3 = Gf.Vec3d(10., 20., 30.)
        scale4 = Gf.Vec3f(1., 2., 3.)

        self.assertEqual(x.GetTimeSamples(), [])

        xlateOp.Set(xlate1, Usd.TimeCode(1))
        self.assertEqual(x.GetTimeSamples(), [1.0])

        xlateOp.Set(xlate3, Usd.TimeCode(3))
        self.assertEqual(x.GetTimeSamples(), [1.0, 3.0])

        scaleOp.Set(scale2, Usd.TimeCode(2))
        self.assertEqual(x.GetTimeSamples(), [1.0, 2.0, 3.0])

        scaleOp.Set(scale4, Usd.TimeCode(4))
        self.assertEqual(x.GetTimeSamples(), [1.0, 2.0, 3.0, 4.0])

        self.assertEqual([1.0, 3.0], xlateOp.GetTimeSamples())
        self.assertEqual([2.0, 4.0], scaleOp.GetTimeSamples())

        self.assertEqual([3.0], 
                         xlateOp.GetTimeSamplesInInterval(Gf.Interval(2, 4)))
        self.assertEqual([2.0], 
                         scaleOp.GetTimeSamplesInInterval(Gf.Interval(0, 3)))

        self.assertEqual(x.GetTimeSamplesInInterval(Gf.Interval(1.5, 3.2)), 
                        [2.0, 3.0])
Esempio n. 20
0
    def test_CurrentFrame(self):

        rootDataModel = RootDataModel()

        # Default currentFrame should be TimeCode.Default()
        self.assertEqual(rootDataModel.currentFrame, Usd.TimeCode.Default())

        # Setting a numeric TimeCode works properly.
        rootDataModel.currentFrame = Usd.TimeCode(1)
        self.assertEqual(rootDataModel.currentFrame, Usd.TimeCode(1))

        # Setting back to TimeCode.Default() works properly.
        rootDataModel.currentFrame = Usd.TimeCode.Default()
        self.assertEqual(rootDataModel.currentFrame, Usd.TimeCode.Default())

        # currentFrame cannot be a number.
        with self.assertRaises(ValueError):
            rootDataModel.currentFrame = 1.0

        # currentFrame cannot be None.
        with self.assertRaises(ValueError):
            rootDataModel.currentFrame = None
Esempio n. 21
0
    def test_SingularTransformOp(self):
        s = Usd.Stage.CreateInMemory()
        x = UsdGeom.Xform.Define(s, '/World')
        transformOp = x.AddTransformOp()
        singularMat = Gf.Matrix4d(32, 8, 11, 17, 8, 20, 17, 23, 11, 17, 14, 26,
                                  17, 23, 26, 2)
        transformOp.Set(singularMat, Usd.TimeCode(1.0))

        # Insert a translate op in the middle , as two consecutive inverse
        # ops are simply skipped when computing local transform value.
        x.AddTranslateOp().Set(Gf.Vec3d(1, 1, 1))
        x.AddTransformOp(isInverseOp=True)

        with self.assertRaises(RuntimeError):
            xform = x.GetLocalTransformation(Usd.TimeCode(1.))

        # If the translateOp in the middle is removed from xformOpOrder, then
        # calling GetLocalTransformation() should not result in an error as the pair
        # of consecutive inverse xformOps will get skipped.
        x.GetXformOpOrderAttr().Set(
            Vt.TokenArray(('xformOp:transform', '!invert!xformOp:transform')))
        self.assertEqual(x.GetLocalTransformation(1.0), Gf.Matrix4d(1))
    def _render(self, scene):
        # creating renderer
        renderer = UsdImagingLite.Engine()
        if not self._sync_render_settings(renderer, scene):
            renderer = None
            return

        renderer.SetRenderViewport((0, 0, self.width, self.height))
        renderer.SetRendererAov('color')

        # setting camera
        self._set_scene_camera(renderer, scene)

        params = UsdImagingLite.RenderParams()
        params.frame = Usd.TimeCode(scene.frame_current)

        render_images = {
            'Combined': np.empty((self.width, self.height, 4), dtype=np.float32)
        }

        time_begin = time.perf_counter()
        while True:
            if self.render_engine.test_break():
                break

            try:
                renderer.Render(self.stage.GetPseudoRoot(), params)

            except Exception as e:
                # known RenderMan issue https://github.com/PixarAnimationStudios/USD/issues/1415
                if isinstance(e, Tf.ErrorException) and "Failed to load plugin 'rmanOslParser'" in str(e):
                    pass  # we won't log error "GL error: invalid operation"
                else:
                    log.error(e)

            percent_done = usd_utils.get_renderer_percent_done(renderer)
            self.notify_status(percent_done / 100,
                               f"Render Time: {time_str(time.perf_counter() - time_begin)} | "
                               f"Done: {int(percent_done)}%")

            if renderer.IsConverged():
                break

            renderer.GetRendererAov('color', render_images['Combined'].ctypes.data)
            self.update_render_result(render_images)

        renderer.GetRendererAov('color', render_images['Combined'].ctypes.data)
        self.update_render_result(render_images)

        # explicit renderer deletion
        renderer = None
Esempio n. 23
0
def main():
    """Run the main execution of the current script."""
    stage = Usd.Stage.CreateInMemory()
    sphere = UsdGeom.Sphere.Define(stage, "/SomeSphere")
    sphere.AddTranslateOp().Set(Gf.Vec3d(20, 30, 40))

    # Method #1: Compute at a certain time
    print(
        UsdGeom.Imageable(sphere).ComputeWorldBound(Usd.TimeCode(1),
                                                    purpose1="default"))

    # Method #2: Compute using a cache
    cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), ["default", "render"])
    print(cache.ComputeWorldBound(sphere.GetPrim()))
Esempio n. 24
0
def set_pointcloud_at_frame(pointcloud_geometry,
                            usd_pointcloud,
                            usd_points_prim,
                            frame=None):
    xsi_pp = pointcloud_geometry.GetICEAttributeFromName("PointPosition")
    xsi_size = pointcloud_geometry.GetICEAttributeFromName("Size")

    xsi_pp_data = xsi_pp.DataArray
    xsi_size_data = xsi_size.DataArray

    usd_points = usd_pointcloud.CreatePointsAttr()
    usd_width = usd_pointcloud.CreateWidthsAttr()

    data_points = []
    data_width = []

    for index in range(len(xsi_pp_data)):
        data_points.append(utils.vector_to_tuple(xsi_pp_data[index]))
        data_width.append(
            xsi_size_data[index] if index < len(xsi_size_data) else 0.0)

    if frame is None:
        usd_points.Set(data_points)
        usd_width.Set(data_width)
    else:
        usd_points.Set(data_points, Usd.TimeCode(frame))
        usd_width.Set(data_width, Usd.TimeCode(frame))

    # set bounding box
    usd_extent = usd_points_prim.CreateAttribute(
        "extent", Sdf.ValueTypeNames.Float3Array)
    if frame is None:
        usd_extent.Set(utils.get_bounding_box(data_points))
    else:
        usd_extent.Set(utils.get_bounding_box(data_points),
                       Usd.TimeCode(frame))
Esempio n. 25
0
def GetAttributeTextFont(attribute, frame):
    if isinstance(attribute, CustomAttribute):
        return None

    if not isinstance(frame, Usd.TimeCode):
        frame = Usd.TimeCode(frame)

    frameVal = frame.GetValue()
    bracketing = attribute.GetBracketingTimeSamples(frameVal)

    # Note that some attributes return an empty tuple, some None, from
    # GetBracketingTimeSamples(), but all will be fed into this function.
    if bracketing and (len(bracketing) == 2) and (bracketing[0] != frameVal):
        return ItalicFont

    return None
    def _render_gl(self, scene):
        CLEAR_DEPTH = 1.0

        # creating draw_target
        draw_target = Glf.DrawTarget(self.width, self.height)
        draw_target.Bind()
        draw_target.AddAttachment("color", bgl.GL_RGBA, bgl.GL_FLOAT, bgl.GL_RGBA)

        # creating renderer
        renderer = UsdImagingGL.Engine()
        if not self._sync_render_settings(renderer, scene):
            renderer = None
            return

        # setting camera
        self._set_scene_camera(renderer, scene)

        renderer.SetRenderViewport((0, 0, self.width, self.height))
        renderer.SetRendererAov('color')

        root = self.stage.GetPseudoRoot()
        params = UsdImagingGL.RenderParams()
        params.renderResolution = (self.width, self.height)
        params.frame = Usd.TimeCode(scene.frame_current)

        if scene.hdusd.final.data_source:
            world_data = world.WorldData.init_from_stage(self.stage)
        else:
            world_data = world.WorldData.init_from_world(scene.world)

        params.clearColor = world_data.clear_color

        try:
            renderer.Render(root, params)

        except Exception as e:
            log.error(e)

        self.update_render_result({
            'Combined': gl.get_framebuffer_data(self.width, self.height)
        })

        draw_target.Unbind()

        # it's important to clear data explicitly
        draw_target = None
        renderer = None
Esempio n. 27
0
    def _set_blendshape_weights(self, skel_anim, usd_node, gltf_node):
        animations = self.gltf_loader.get_animations()
        if (len(animations) > 0): # only support first animation group
            animation = animations[0]

            animation_channels = animation.get_animation_channels_for_node(gltf_node)
            for animation_channel in animation_channels:
                if animation_channel.target.path == 'weights':
                    output_data = animation_channel.sampler.get_output_data()
                    input_data = animation_channel.sampler.get_input_data()
                    
                    output_data_entries = []
                    for index in range(0, len(output_data)/2):
                        output_data_entries.append([output_data[index * 2], output_data[index * 2 + 1]])
                    usd_blend_shape_weights = skel_anim.CreateBlendShapeWeightsAttr()
                    for entry in zip(output_data_entries, input_data):
                        usd_blend_shape_weights.Set(Vt.FloatArray(entry[0]), Usd.TimeCode(entry[1] * self.fps))
Esempio n. 28
0
def TestBug113044():
    stage = Usd.Stage.Open("animVis.usda")
    bboxCache = UsdGeom.BBoxCache(Usd.TimeCode(0.0),
                                  includedPurposes=[UsdGeom.Tokens.default_])
    pseudoRoot = stage.GetPrimAtPath("/")
    assert bboxCache.ComputeWorldBound(pseudoRoot).GetRange().IsEmpty()

    # The cube is visible at frame 1. This should invalidate the bounds at '/'
    # and cause the bbox to be non-empty.
    bboxCache.SetTime(1.0)
    assert not bboxCache.ComputeWorldBound(pseudoRoot).GetRange().IsEmpty()

    bboxCache.SetTime(2.0)
    assert bboxCache.ComputeWorldBound(pseudoRoot).GetRange().IsEmpty()

    bboxCache.SetTime(3.0)
    assert not bboxCache.ComputeWorldBound(pseudoRoot).GetRange().IsEmpty()
Esempio n. 29
0
    def test_SetFromCamera(self):
        camera = Gf.Camera()

        usdStage = Usd.Stage.CreateInMemory()
        usdCamera = UsdGeom.Camera.Define(usdStage, '/camera')
        usdCameraProj = usdCamera.GetProjectionAttr()

        # test fall-back values
        self._CheckValues(camera, usdCamera, 1.0)
        self.assertEqual(usdCameraProj.GetResolveInfo().GetSource(),
                         Usd.ResolveInfoSourceFallback)

        camera.transform = (
            Gf.Matrix4d().SetRotate(Gf.Rotation(Gf.Vec3d(1.0, 2.0, 3.0), 10.0))
            * Gf.Matrix4d().SetTranslate(Gf.Vec3d(4.0, 5.0, 6.0)))
        camera.projection = Gf.Camera.Orthographic
        camera.horizontalAperture = 5.1
        camera.verticalAperture = 2.0
        camera.horizontalApertureOffset = 0.13
        camera.verticalApertureOffset = -0.14
        camera.focalLength = 28
        camera.clippingRange = Gf.Range1f(5, 15)
        camera.clippingPlanes = [[1, 2, 3, 4], [8, 7, 6, 5]]
        camera.fStop = 1.2
        camera.focusDistance = 300

        usdCamera.SetFromCamera(camera, 1.0)

        # test assigned values
        self._CheckValues(camera, usdCamera, 1.0)
        self.assertEqual(usdCameraProj.GetResolveInfo().GetSource(),
                         Usd.ResolveInfoSourceTimeSamples)

        usdCamera.SetFromCamera(camera, 1.0)

        actual = usdCamera.GetLocalTransformation(Usd.TimeCode(1.0))
        expected = Gf.Matrix4d(0.9858929135, 0.14139860385, -0.089563373740,
                               0.0, -0.1370579618, 0.98914839500,
                               0.052920390613, 0.0, 0.0960743367,
                               -0.03989846462, 0.994574197504, 0.0, 4.0, 5.0,
                               6.0, 1.0)

        for a, e in zip(actual, expected):
            self.assertTrue(Gf.IsClose(a, e, 1e-2))
Esempio n. 30
0
    def sync(self, context, depsgraph):
        log('Start sync')

        scene = depsgraph.scene
        settings = self.get_settings(scene)

        self.is_gl_delegate = settings.is_gl_delegate

        self.space_data = context.space_data
        self.shading_data = world.ShadingData(context, depsgraph.scene.world)

        self.render_params = UsdImagingGL.RenderParams()
        self.render_params.frame = Usd.TimeCode(scene.frame_current)

        self.renderer = UsdImagingGL.Engine()

        self._sync(context, depsgraph)

        usd_utils.set_delegate_variant_stage(self.stage,
                                             settings.delegate_name)

        self.is_synced = True
        log('Finish sync')