file_path
stringlengths
21
224
content
stringlengths
0
80.8M
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/paths/get-parent-path/header.md
If you want have a Prim path and you want to get the Prim path of its parent, you can use [Sdf.Path.GetParentPath()](https://openusd.org/release/api/class_sdf_path.html#a0da79e196526d8f2e9bfd075e36e505f).
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/paths/concatenate-prim-path/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Sdf def concat_prim_path(prim_path: Sdf.Path, path_to_add: str) -> Sdf.Path: concat_path = prim_path.AppendPath(path_to_add) return concat_path ############# # Full Usage ############# from pxr import Usd, UsdGeom # Create an in-memory Stage with /World Xform prim as the default prim stage: Usd.Stage = Usd.Stage.CreateInMemory() default_prim: Usd.Prim = UsdGeom.Xform.Define(stage, Sdf.Path("/World")).GetPrim() stage.SetDefaultPrim(default_prim) # Concatenate the Paths concatenated_prim_path: Sdf.Path = concat_prim_path(default_prim.GetPrimPath(), "Kitchen_set/Props_grp/North_grp/NorthWall_grp/MeasuringSpoon_1") usda = stage.GetRootLayer().ExportToString() print(usda) assert concatenated_prim_path.pathString == "/World/Kitchen_set/Props_grp/North_grp/NorthWall_grp/MeasuringSpoon_1"
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/paths/concatenate-prim-path/py_usd.md
``` {literalinclude} py_usd.py :language: py ```
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/paths/concatenate-prim-path/config.toml
[core] title = "Concatenate a Prim Path" [metadata] description = "Universal Scene Description (OpenUSD) code samples for concatenating prim paths." keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "concatenate", "prim", "path", "AppendPath"]
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/paths/concatenate-prim-path/header.md
If you want to concatenate two strings to extend a prim path, you can use `Sdf.Path` to store and manipulate prim and property paths. This is useful for extending a prim path with the name of a new child prim that you plan to create. In this snippet we use `Sdf.Path.AppendPath()`, but you can [learn more about other append methods](https://openusd.org/release/api/class_sdf_path.html).
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/get-relationship-targets/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Usd, UsdGeom # For example, getting the proxy prim on an Imageable proxy_prim_rel: Usd.Relationship = UsdGeom.Imageable(myprim).GetProxyPrimRel() proxyPrimTargets = proxy_prim_rel.GetForwardedTargets()
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/get-relationship-targets/py_usd.md
``` {literalinclude} py_usd.py :language: py ```
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/get-relationship-targets/config.toml
[core] # The title for this code sample. Used to name the page. title = "Get the Targets of a Relationship" [metadata] #A concise description of the code sample for SEO. description = "Universal Scene Description (OpenUSD) code samples for getting the targets of a Relationship taking into account relationship forwarding." # Put in SEO keywords relevant to this code sample. keywords = ["OpenUSD", "USD", "code sample", "snippet", "Python", "C++", "relationship", "targets", "relationship forwarding"]
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/get-relationship-targets/header.md
If you need to get the targets of a Relationship, you can use [Usd.Relationship.GetForwardedTargets()](https://openusd.org/release/api/class_usd_relationship.html#a66140abeac945df3998b3297e52ca99b). This method will give you the final composed targets for the Relationship and also take into account the relationship forwarding. That is, if the Relationship itself targets another Relationship, we want to get the final targets in a potential chain of Relationships. Learn more about [relationship forwarding](https://openusd.org/release/api/class_usd_relationship.html#usd_relationship_forwarding).
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/check-property-exists/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Usd pts_attr: Usd.Attribute = mesh_prim.GetAttribute("points") if pts_attr.IsValid(): print("Attribute exists!")
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/check-property-exists/py_usd.md
``` {literalinclude} py_usd.py :language: py ``` Alternatively, `Usd.Object` overrides the boolean operator so you can check with a simple boolean expression. ``` {literalinclude} py_usd_var1.py :language: py ```
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/check-property-exists/config.toml
[core] # The title for this code sample. Used to name the page. title = "Check if a Property Exists" [metadata] #A concise description of the code sample for SEO. description = "Universal Scene Description (OpenUSD) code samples for checking if a Property exists." # Put in SEO keywords relevant to this code sample. keywords = ["OpenUSD", "USD", "code sample", "snippet", "Python", "C++", "property", "relationship", "attribute", "IsValid", "exists", "valid"]
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/check-property-exists/py_usd_var1.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Usd pts_attr: Usd.Attribute = mesh_prim.GetAttribute("points") if pts_attr: print("Attribute exists!")
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/check-property-exists/header.md
Certain functions may return a `Usd.Property` object, but the Property may not exist due to an incorrect path or because of changes on the Stage. You can use [Usd.Object.IsValid()](https://openusd.org/release/api/class_usd_object.html#ac532c4b500b1a85ea22217f2c65a70ed) to check if the Property is valid or exists. ```{note} Remember, that Properties consist of `Usd.Attribute` and `Usd.Relationship`. You can perform this check on both types of objects. ```
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/create-relationship/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Usd prim: Usd.Prim = stage.GetPrimAtPath("/World/MyPrim") custom_relationship: Usd.Relationship = prim.CreateRelationship("myCustomRelationship") # You can also use Usd.Relationship.AddTarget() to add targets to an existing Relationship. custom_relationship.SetTargets(["/World/TargetA", "/World/TargetB"])
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/create-relationship/py_usd.md
``` {literalinclude} py_usd.py :language: py ```
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/create-relationship/config.toml
[core] # The title for this code sample. Used to name the page. title = "Create a Relationship" [metadata] #A concise description of the code sample for SEO. description = "Universal Scene Description (OpenUSD) code samples for creating a Relationship." # Put in SEO keywords relevant to this code sample. keywords = ["OpenUSD", "USD", "code sample", "snippet", "Python", "C++", "property", "relationship", "create", "create relationship"]
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/create-relationship/header.md
A [Relationship](https://openusd.org/release/api/class_usd_relationship.html) is a type of `Usd.Property` that points to other Prims, Attributes or Relationships. The Relationship targets are represented by a list of Paths. This code sample shows how to create a Relationship and set some initial targets.
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/create-attribute/py_kit_cmds.md
The `CreateUsdAttributeCommand` command in Kit can create an Attribute on a prim. The Attribute name and type are required. ``` {literalinclude} py_kit_cmds.py :language: py ```
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/create-attribute/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Gf, Sdf, Usd, UsdGeom """ Find all relevant data types at: https://openusd.org/release/api/_usd__page__datatypes.html """ def create_float_attribute(prim: Usd.Prim, attribute_name: str) -> Usd.Attribute: """Creates attribute for a prim that holds a float. See: https://openusd.org/release/api/class_usd_prim.html Args: prim (Usd.Prim): A Prim for holding the attribute. attribute_name (str): The name of the attribute to create. Returns: Usd.Attribute: An attribute created at specific prim. """ attr: Usd.Attribute = prim.CreateAttribute(attribute_name, Sdf.ValueTypeNames.Float) return attr def create_vector_attribute(prim: Usd.Prim, attribute_name: str) -> Usd.Attribute: """Creates attribute for a prim that holds a vector. See: https://openusd.org/release/api/class_usd_prim.html Args: prim (Usd.Prim): A Prim for holding the attribute. attribute_name (str): The name of the attribute to create. Returns: Usd.Attribute: An attribute created at specific prim. """ attr: Usd.Attribute = prim.CreateAttribute( attribute_name, Sdf.ValueTypeNames.Float3 ) return attr ############# # Full Usage ############# # Create an in-memory Stage stage: Usd.Stage = Usd.Stage.CreateInMemory() # Create a prim named /World (type Xform) and make it the default prim. prim_path = "/World" xform: UsdGeom.Xform = UsdGeom.Xform.Define(stage, prim_path) prim: Usd.Prim = xform.GetPrim() stage.SetDefaultPrim(prim) # Create a float attribute on /World float_attr: Usd.Attribute = create_float_attribute(prim, "my_float_attr") # Create a vector attribute on /World vector_attr: Usd.Attribute = create_vector_attribute(prim, "my_vector_attr") # Set and query values print(float_attr.Get()) float_attr.Set(0.1) print(float_attr.Get()) vector_value: Gf.Vec3f = Gf.Vec3f(0.1, 0.2, 0.3) print(vector_attr.Get()) vector_attr.Set(vector_value) print(vector_attr.Get()) # Optionally preview the usd # print(stage.GetRootLayer().ExportToString())
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/create-attribute/usda.usda
#usda 1.0 ( defaultPrim = "World" ) def Xform "World" { custom float my_float_attr = 0.1 custom float3 my_vector_attr = (0.1, 0.2, 0.3) }
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/create-attribute/py_usd.md
With the USD API, you can use `Usd.Prim.CreateAttribute()` to create `attributes` on `Usd.Prim` objects. You can set the value using `Usd.Attribute.Set()` and query the value using `Usd.Attribute.Get()` ``` {literalinclude} py_usd.py :language: py ```
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/create-attribute/py_kit_cmds.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 import omni.kit.commands import omni.usd from pxr import Gf, Sdf, Usd, UsdGeom def create_float_attribute(prim: Usd.Prim, attribute_name: str) -> Usd.Attribute: """Creates attribute for a prim that holds a float. See: https://openusd.org/release/api/class_usd_prim.html See: https://docs.omniverse.nvidia.com/kit/docs/omni.usd/latest/omni.usd.commands/omni.usd.commands.CreateUsdAttributeCommand.html Args: prim (Usd.Prim): A Prim for holding the attribute. attribute_name (str): The name of the attribute to create. Returns: Usd.Attribute: An attribute created at specific prim. """ omni.kit.commands.execute( "CreateUsdAttributeCommand", prim=prim, attr_name=attribute_name, attr_type=Sdf.ValueTypeNames.Float, ) attr: Usd.Attribute = prim.GetAttribute(attribute_name) return attr def create_vector_attribute(prim: Usd.Prim, attribute_name: str) -> Usd.Attribute: """Creates attribute for a prim that holds a vector. See: https://openusd.org/release/api/class_usd_prim.html See: https://docs.omniverse.nvidia.com/kit/docs/omni.usd/latest/omni.usd.commands/omni.usd.commands.CreateUsdAttributeCommand.html Args: prim (Usd.Prim): A Prim for holding the attribute. attribute_name (str): The name of the attribute to create. Returns: Usd.Attribute: An attribute created at specific prim. """ omni.kit.commands.execute( "CreateUsdAttributeCommand", prim=prim, attr_name=attribute_name, attr_type=Sdf.ValueTypeNames.Float3, ) attr: Usd.Attribute = prim.GetAttribute(attribute_name) return attr ############# # Full Usage ############# # Get the current stage stage: Usd.Stage = omni.usd.get_context().get_stage() # Get the default prim prim: Usd.Prim = stage.GetDefaultPrim() # Create a float attribute on /World float_attr: Usd.Attribute = create_float_attribute(prim, "my_float_attr") # Create a vector attribute on /World vector_attr: Usd.Attribute = create_vector_attribute(prim, "my_vector_attr") # Set and query values print(float_attr.Get()) float_attr.Set(0.1) print(float_attr.Get()) vector_value: Gf.Vec3f = Gf.Vec3f(0.1, 0.2, 0.3) print(vector_attr.Get()) vector_attr.Set(vector_value) print(vector_attr.Get()) # Optionally preview the usd # print(stage.GetRootLayer().ExportToString())
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/create-attribute/usda.md
This is an example USDA result from creating an Xform and Cube prim. Where the Cube prim is a child of the Xform and the Xform has it's own Translation Ops. ``` {literalinclude} usda.usda :language: usd ```
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/create-attribute/config.toml
[core] # The title for this code sample. Used to name the page. title = "Create an Attribute" [metadata] description = "Universal Scene Description (OpenUSD) code samples to create an attribute." keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "attribute", "property", "create"]
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/create-attribute/header.md
Creating an Attribute on a layer ensures that it is concretely defined on the Stage. It will always return a value `Usd.Attribute` object.
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/set-attribute/py_kit_cmds.md
The `ChangeProperty` command allows users to undo the operation, but you must provide the value to use during the undo operation as the `prev` parameter. ``` {literalinclude} py_kit_cmds.py :language: py ``` You can also set a timesample value at a particular time: ``` {literalinclude} py_kit_cmds_var1.py :language: py ```
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/set-attribute/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Usd, Sdf, Gf def set_float_attribute(attr: Usd.Attribute, value: float) -> None: """ See: https://openusd.org/release/api/class_usd_attribute.html Args: attr: The attribute to set. value: A floating point value, i.e. `3.141516`. """ attr.Set(value) def set_vector_attribute(attr: Usd.Attribute, value: Gf.Vec3f) -> None: """ Args: attr: The attribute to set. value: A floating point vector, i.e. `(1., 2., 3.)`. """ attr.Set(value)
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/set-attribute/py_usd.md
``` {literalinclude} py_usd.py :language: py ``` You can also set a timesample value at a particular time: ``` {literalinclude} py_usd_var1.py :language: py ```
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/set-attribute/py_kit_cmds_var1.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 import omni.kit.commands from pxr import Gf, Sdf, Usd prim_path = Sdf.Path("/World/defaultLight") prim: Usd.Prim = stage.GetPrimAtPath(prim_path) prop_name = "xformOp:rotateXYZ" rotation = prim.GetAttribute(prop_name) omni.kit.commands.execute("ChangeProperty", prop_path=Sdf.Path(prim_path.AppendProperty(prop_name)), value=Gf.Vec3d(180.0, 0.0, 0.0), prev=rotation.Get(10.0), timecode=Usd.TimeCode(10.0) )
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/set-attribute/py_kit_cmds.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 import omni.kit.commands from pxr import Gf, Sdf, Usd prim_path = Sdf.Path("/World/defaultLight") prim: Usd.Prim = stage.GetPrimAtPath(prim_path) prop_name = "xformOp:rotateXYZ" rotation = prim.GetAttribute(prop_name) omni.kit.commands.execute("ChangeProperty", prop_path=Sdf.Path(prim_path.AppendProperty(prop_name)), value=Gf.Vec3d(180.0, 0.0, 0.0), prev=rotation.Get() )
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/set-attribute/config.toml
[core] # The title for this code sample. Used to name the page. title = "Set the Value of an Attribute" [metadata] #A concise description of the code sample for SEO. description = "Universal Scene Description (OpenUSD) code samples for setting the value of an Attribute." # Put in SEO keywords relevant to this code sample. keywords = ["OpenUSD", "USD", "code sample", "snippet", "Python", "C++", "attribute", "set", "value", "ChangeProperty", "Omniverse Kit", "Kit Commands"]
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/set-attribute/py_usd_var1.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Usd, Sdf, Gf def set_float_attribute_at_time(attr: Usd.Attribute, value: float, time_value: float) -> None: """ See: https://openusd.org/release/api/class_usd_attribute.html Args: attr: The attribute to set. value: A floating point value, i.e. `3.141516`. time_value: Set a timesample at a particular time. """ attr.Set(value, time_value) def set_vector_attribute_at_time(attr: Usd.Attribute, value: Gf.Vec3f, time_value: float) -> None: """ Args: attr: The attribute to set. value: A floating point vector, i.e. `(1., 2., 3.)`. time_value: Set a timesample at a particular time. """ attr.Set(value, time_value)
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/set-attribute/header.md
In Omniverse, you can use the `ChangeProperty` command to set the default value or timesample value of an Attribute. With the USD API, you can call `Usd.Attribute.Set()` to set a default value or timesample value.
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/get-attribute-value/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Usd, Sdf def get_attribute_value(prim: Usd.Prim, attribute_name: str): """ See: https://openusd.org/release/api/class_usd_attribute.html Args: prim: The prim owner of the attribute. attribute_name: The name of the attribute to retrieve. Return: The value of the attribute, see https://openusd.org/release/api/_usd__page__datatypes.html for the return types. For example, for `float3`, the return type will be `Gf.Vec3f`. """ attr = prim.GetAttribute(attribute_name) return attr.Get()
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/get-attribute-value/py_usd.md
``` {literalinclude} py_usd.py :language: py ``` You can also get the value at a particular time: ``` {literalinclude} py_usd_var1.py :language: py ```
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/get-attribute-value/config.toml
[core] # The title for this code sample. Used to name the page. title = "Get the Value of an Attribute" [metadata] #A concise description of the code sample for SEO. description = "Universal Scene Description (OpenUSD) code samples for getting the value of an Attribute." # Put in SEO keywords relevant to this code sample. keywords = ["OpenUSD", "USD", "code sample", "snippet", "Python", "C++", "attribute", "get", "value", "value resolution", "GetAttribute"]
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/get-attribute-value/py_usd_var1.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Usd, Sdf def get_attribute_value_at_time(prim: Usd.Prim, attribute_name: str, time_value: float): """ See: https://openusd.org/release/api/class_usd_attribute.html Args: prim: The prim owner of the attribute. attribute_name: The name of the attribute to retrieve. time_value: Get the value authored or interpolated at a particular time. Return: The value of the attribute, see https://openusd.org/release/api/_usd__page__datatypes.html for the return types. For example, for `float3`, the return type will be `Gf.Vec3f`. """ attr = prim.GetAttribute(attribute_name) return attr.Get(time_value)
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/get-attribute-value/header.md
`Usd.Prim.GetAttribute()` returns a `Usd.Attribute`, but this is not the value for the Attribute. You must call `Usd.Attribute.Get()` to perform the [attribute value resolution](https://openusd.org/release/glossary.html#usdglossary-valueresolution) resulting in a default value, timesample value or interpolated value for the Attribute.
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/add-relationship-target/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Usd, UsdGeom # For example, adding a proxy prim target on an Imageable proxy_prim_rel: Usd.Relationship = UsdGeom.Imageable(myprim).GetProxyPrimRel() proxy_prim_rel.AddTarget("/World/MyProxy")
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/add-relationship-target/py_usd.md
``` {literalinclude} py_usd.py :language: py ```
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/add-relationship-target/config.toml
[core] # The title for this code sample. Used to name the page. title = "Add a Relationship Target" [metadata] #A concise description of the code sample for SEO. description = "Universal Scene Description (OpenUSD) code samples for adding a target to a Relationship." # Put in SEO keywords relevant to this code sample. keywords = ["OpenUSD", "USD", "code sample", "snippet", "Python", "C++", "relationship", "targets", "property"]
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/add-relationship-target/header.md
If you just want to add a target to an existing Relationship, you can use [Usd.Relationship.AddTarget()](https://openusd.org/release/api/class_usd_relationship.html#a0db3d68820f130f08152592b0fe10b00) to add a Path to the Relationship's targets list.
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/materials/create-usdpreviewsurface-material/py_kit_cmds.md
This version creates just the material prim and UsdPreviewSurface Shader. ``` {literalinclude} py_kit_cmds.py :language: py ``` This version also creates UsdUVTexture Shader prims for the diffuse, roughness, metallic, and normal properties and connects them to the UsdPreviewSurface. ``` {literalinclude} py_kit_cmds_var1.py :language: py ```
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/materials/create-usdpreviewsurface-material/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Sdf, UsdShade mtl_path = Sdf.Path("/World/Looks/PreviewSurface") mtl = UsdShade.Material.Define(stage, mtl_path) shader = UsdShade.Shader.Define(stage, mtl_path.AppendPath("Shader")) shader.CreateIdAttr("UsdPreviewSurface") shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set([1.0, 0.0, 0.0]) shader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(0.5) shader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(0.0) mtl.CreateSurfaceOutput().ConnectToSource(shader.ConnectableAPI(), "surface")
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/materials/create-usdpreviewsurface-material/py_usd.md
This version creates just the Material prim and UsdPreviewSurface Shader. ``` {literalinclude} py_usd.py :language: py ``` This version also creates UsdUVTexture Shader prim and connects it to the diffuse property of the UsdPreviewSurface. ``` {literalinclude} py_usd_var1.py :language: py ```
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/materials/create-usdpreviewsurface-material/py_kit_cmds_var1.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 import omni.kit.commands omni.kit.commands.execute("CreatePreviewSurfaceTextureMaterialPrim", mtl_path="/World/Looks/PreviewSurfaceWithTextures", select_new_prim=True)
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/materials/create-usdpreviewsurface-material/py_kit_cmds.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 import omni.kit.commands omni.kit.commands.execute("CreatePreviewSurfaceMaterialPrim", mtl_path="/World/Looks/PreviewSurface", select_new_prim=True)
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/materials/create-usdpreviewsurface-material/config.toml
[core] title = "Create a UsdPreviewSurface Material" [metadata] description = "Universal Scene Description (OpenUSD) code samples for creating a UsdPreviewSurface material including UsdUVTexture Shader for loading data from textures." keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "Omniverse Kit", "Kit Commands", "UsdPreviewSurface", "material", "CreatePreviewSurfaceMaterialPrim", "UsdUVTexture"]
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/materials/create-usdpreviewsurface-material/py_usd_var1.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Sdf, UsdShade mtl_path = Sdf.Path("/World/Looks/PreviewSurface") mtl = UsdShade.Material.Define(stage, mtl_path) shader = UsdShade.Shader.Define(stage, mtl_path.AppendPath("Shader")) shader.CreateIdAttr("UsdPreviewSurface") shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set((1.0, 0.0, 0.0)) shader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(0.5) shader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(0.0) diffuse_tx = UsdShade.Shader.Define(stage,mtl_path.AppendPath("DiffuseColorTx")) diffuse_tx.CreateIdAttr('UsdUVTexture') diffuse_tx.CreateInput('file', Sdf.ValueTypeNames.Asset).Set("C:/path/to/texture.png") diffuse_tx.CreateOutput('rgb', Sdf.ValueTypeNames.Float3) shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).ConnectToSource(diffuse_tx.ConnectableAPI(), 'rgb') mtl.CreateSurfaceOutput().ConnectToSource(shader.ConnectableAPI(), "surface")
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/materials/create-usdpreviewsurface-material/header.md
These snippets show how to create a Material prim and a `UsdPreviewSurface` Shader prim. Optionally, you can also create a `UsdUVTexture` to read from a texture file and connect it to the `UsdPreviewSurface`.
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/materials/create-mdl-material/py_kit_cmds.md
``` {literalinclude} py_kit_cmds.py :language: py ```
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/materials/create-mdl-material/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Sdf, UsdShade mtl_path = Sdf.Path("/World/Looks/OmniPBR") mtl = UsdShade.Material.Define(stage, mtl_path) shader = UsdShade.Shader.Define(stage, mtl_path.AppendPath("Shader")) shader.CreateImplementationSourceAttr(UsdShade.Tokens.sourceAsset) # MDL shaders should use "mdl" sourceType shader.SetSourceAsset("OmniPBR.mdl", "mdl") shader.SetSourceAssetSubIdentifier("OmniPBR", "mdl") # MDL materials should use "mdl" renderContext mtl.CreateSurfaceOutput("mdl").ConnectToSource(shader.ConnectableAPI(), "out") mtl.CreateDisplacementOutput("mdl").ConnectToSource(shader.ConnectableAPI(), "out") mtl.CreateVolumeOutput("mdl").ConnectToSource(shader.ConnectableAPI(), "out")
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/materials/create-mdl-material/py_usd.md
``` {literalinclude} py_usd.py :language: py ```
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/materials/create-mdl-material/py_kit_cmds.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 import omni.kit.commands success, result = omni.kit.commands.execute('CreateMdlMaterialPrimCommand', mtl_url='OmniPBR.mdl', # This can be path to local or remote MDL mtl_name='OmniPBR', # sourceAsset:subIdentifier (i.e. the name of the material within the MDL) mtl_path="/World/Looks/OmniPBR" # Prim path for the Material to create. )
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/materials/create-mdl-material/config.toml
[core] title = "Create an MDL Material" [metadata] description = "Universal Scene Description (OpenUSD) code samples for creating an MDL material with a Shader prim with an MDL source asset." keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "Omniverse Kit", "Kit Commands", "shader", "material", "CreateMdlMaterialPrimCommand"]
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/materials/create-mdl-material/header.md
If you want to create an MDL material, you can use the `CreateMdlMaterialPrimCommand` or the USD API to do the same. These snippets show how to create a Material prim and a Shader prim that reads from an MDL file. They also utilizes the `sourceAsset:subIdentifier` attribute to choose a specific material description from within the MDL file.
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/stage/set-default-prim/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Usd def set_default_prim(stage: Usd.Stage, prim: Usd.Prim): stage.SetDefaultPrim(prim) ############# # Full Usage ############# from pxr import UsdGeom, Sdf # Create new USD stage for this sample stage: Usd.Stage = Usd.Stage.CreateInMemory() # Create an xform which should be set as the default prim default_prim: Usd.Prim = UsdGeom.Xform.Define(stage, Sdf.Path("/World")).GetPrim() # Make the xform the default prim set_default_prim(stage, default_prim) usda = stage.GetRootLayer().ExportToString() print(usda) # Check that the expected default prim was set assert stage.GetDefaultPrim() == default_prim
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/stage/set-default-prim/usda.usda
#usda 1.0 ( defaultPrim = "World" ) def Xform "World" { }
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/stage/set-default-prim/py_usd.md
``` {literalinclude} py_usd.py :language: py ```
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/stage/set-default-prim/usda.md
This is an example USDA result from setting the `defaultPrim` metadata in an empty layer. ``` {literalinclude} usda.usda :language: usd ```
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/stage/set-default-prim/config.toml
[core] title = "Set the Default Prim on a Stage" [metadata] description = "Universal Scene Description (OpenUSD) code samples for setting the default prim on a Stage." keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "stage", "metadata", "default prim"]
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/stage/set-default-prim/header.md
It's best practice to set the `defaultPrim` metadata on a Stage if the Stage's root layer may be used as a Reference or Payload. Otherwise, consumers of your Stage are forced to provide a target prim when they create a Reference or Payload arc. Even though the `Usd.Stage.SetDefaultPrim()` accepts any `Usd.Prim`, the default prim must be a top-level prim on the Stage.
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/stage/set-stage-linear-units/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Usd, UsdGeom def set_meters_per_unit(stage: Usd.Stage, unit: UsdGeom.LinearUnits = UsdGeom.LinearUnits.centimeters): UsdGeom.SetStageMetersPerUnit(stage, unit) # Any double-precision float can be used for metersPerUnit. ############# # Full Usage ############# unit: UsdGeom.LinearUnits = UsdGeom.LinearUnits.centimeters stage: Usd.Stage = Usd.Stage.CreateInMemory() set_meters_per_unit(stage, unit) usda = stage.GetRootLayer().ExportToString() print(usda) # Check that the expected meterPerUnit were set assert UsdGeom.GetStageMetersPerUnit(stage) == unit
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/stage/set-stage-linear-units/usda.usda
#usda 1.0 ( metersPerUnit = 0.01 )
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/stage/set-stage-linear-units/py_usd.md
You can set the `metersPerUnit` metadata on the stage using `UsdGeom.SetStageMetersPerUnit` to define the linear units of the stage. Convenience shortcuts for units are scoped in `UsdGeom.LinearUnits` (e.g. `UsdGeom.LinearUnits.meters` is `1.0 metersPerUnit`) ``` {literalinclude} py_usd.py :language: py ```
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/stage/set-stage-linear-units/usda.md
This is an example USDA result from setting the `metersPerUnit` metadata in an empty layer. ``` {literalinclude} usda.usda :language: usd ```
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/stage/set-stage-linear-units/config.toml
[core] title = "Set the Stage Linear Units" [metadata] description = "Universal Scene Description (OpenUSD) code samples for defining the linear units of a Stage (i.e. metersPerUnit metadata)." keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "stage", "metadata", "metersPerUnit", "units", "linear units"]
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/stage/set-stage-linear-units/header.md
You can set the `metersPerUnit` metadata on the stage using `UsdGeom.SetStageMetersPerUnit`. Convenience shortcuts for units are scoped in `UsdGeom.LinearUnits` (e.g. `UsdGeom.LinearUnits.meters` is `1.0 metersPerUnit`) ```{note} Fallback stage linear units are centimeters (0.01). ``` ```{warning} Existing objects will not be automatically scaled to adapt to the stage linear units. Learn more about [stage linear units](https://openusd.org/release/api/group___usd_geom_linear_units__group.html). ```
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/stage/set-stage-up-axis/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Usd, UsdGeom def set_up_axis(stage: Usd.Stage, axis: UsdGeom.Tokens): UsdGeom.SetStageUpAxis(stage, axis) ############# # Full Usage ############# axis: UsdGeom.Tokens = UsdGeom.Tokens.z stage: Usd.Stage = Usd.Stage.CreateInMemory() set_up_axis(stage, axis) usda = stage.GetRootLayer().ExportToString() print(usda) # Check that the expected upAxis was set assert UsdGeom.GetStageUpAxis(stage) == axis
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/stage/set-stage-up-axis/usda.usda
#usda 1.0 ( upAxis = "Z" )
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/stage/set-stage-up-axis/py_usd.md
You can set the `upAxis` metadata on the stage using `UsdGeom.SetStageUpAxis` to define which world axis points up. The tokens for the different axes are scoped in `UsdGeom.Tokens`. ``` {literalinclude} py_usd.py :language: py ```
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/stage/set-stage-up-axis/usda.md
This is an example USDA result from setting the `upAxis` metadata in an empty layer. ``` {literalinclude} usda.usda :language: usd ```
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/stage/set-stage-up-axis/config.toml
[core] title = "Set the Stage Up Axis" [metadata] description = "Universal Scene Description (OpenUSD) code samples for defining the up axis of a Stage." keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "stage", "metadata", "upAxis", "axis", "coordinate system"]
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/stage/set-stage-up-axis/header.md
You can set the `upAxis` metadata on the stage using `UsdGeom.SetStageUpAxis` to define which world axis points up. The tokens for the different axes are scoped in `UsdGeom.Tokens`. ```{note} Fallback stage upAxis is Y. ``` ```{warning} Existing objects will not be automatically rotated to adapt to the stage `upAxis`. Learn more about [stage up axis](https://openusd.org/release/api/group___usd_geom_up_axis__group.html). ```
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/stage/get-current-stage/py_usdview.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Usd stage: Usd.Stage = usdviewApi.stage
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/stage/get-current-stage/py_omni_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Usd import omni.usd def get_current_stage() -> Usd.Stage: return omni.usd.get_context().get_stage() ############# # Full Usage ############# # Create a new USD stage through the UsdContext success: bool = omni.usd.get_context().new_stage() # Get the the current stage from the UsdContext current_stage: Usd.Stage = get_current_stage() # Check if the a new stage was created and a valid stage was returned assert success assert current_stage
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/stage/get-current-stage/py_usdview.md
*usdview* Python interpreter has a built-in object called `usdviewApi` that gives you access to the currently loaded Stage. ``` {literalinclude} py_usdview.py :language: py ```
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/stage/get-current-stage/config.toml
[core] title = "Get the Current Stage" [metadata] description = "Universal Scene Description (OpenUSD) code samples for getting the current Stage in Omniverse Kit and usdview." keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "stage", "Omniverse Kit", "usdview", "USD View"]
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/stage/get-current-stage/py_omni_usd.md
``` {literalinclude} py_omni_usd.py :language: py ```
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/stage/get-current-stage/header.md
USD itself does not currently have a notion of a user session associated with a current stage. This is handled by higher-level facilities in USD applications such as `usdviewApi` in USDView and `omni.usd` in Omniverse Kit.
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/transforms/get-local-transforms/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 import typing from pxr import Gf, Usd, UsdGeom def get_local_transform_xform(prim: Usd.Prim) -> typing.Tuple[Gf.Vec3d, Gf.Rotation, Gf.Vec3d]: """ Get the local transformation of a prim using Xformable. See https://openusd.org/release/api/class_usd_geom_xformable.html Args: prim: The prim to calculate the local transformation. Returns: A tuple of: - Translation vector. - Rotation quaternion, i.e. 3d vector plus angle. - Scale vector. """ xform = UsdGeom.Xformable(prim) local_transformation: Gf.Matrix4d = xform.GetLocalTransformation() translation: Gf.Vec3d = local_transformation.ExtractTranslation() rotation: Gf.Rotation = local_transformation.ExtractRotation() scale: Gf.Vec3d = Gf.Vec3d(*(v.GetLength() for v in local_transformation.ExtractRotationMatrix())) return translation, rotation, scale ############# # Full Usage ############# from pxr import Sdf # Create an in-memory Stage with /World Xform prim as the default prim stage: Usd.Stage = Usd.Stage.CreateInMemory() default_prim: Usd.Prim = UsdGeom.Xform.Define(stage, Sdf.Path("/World")).GetPrim() stage.SetDefaultPrim(default_prim) xform: Usd.Prim = UsdGeom.Xform.Define(stage, default_prim.GetPath().AppendPath("Xform")) xform.AddTranslateOp().Set(value=(100,10,0)) xform.AddRotateXYZOp().Set(value=(0,50,0)) xform.AddScaleOp().Set(value=(5,5,5)) cube = UsdGeom.Cube.Define(stage, xform.GetPath().AppendPath("Cube")) cube.AddTranslateOp().Set(value=(4,0,0)) cube.AddRotateXYZOp().Set(value=(100,0,0)) cube.AddScaleOp().Set(value=(2,2,2)) transform = get_local_transform_xform(cube) usda = stage.GetRootLayer().ExportToString() print(usda) cube_prim = cube.GetPrim() assert transform[0] == cube_prim.GetAttribute('xformOp:translate').Get() assert (100,0,0) == cube_prim.GetAttribute('xformOp:rotateXYZ').Get() assert transform[2] == cube_prim.GetAttribute('xformOp:scale').Get()
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/transforms/get-local-transforms/usda.usda
#usda 1.0 ( defaultPrim = "World" ) def Xform "World" { def Xform "Xform" { float3 xformOp:rotateXYZ = (0, 50, 0) float3 xformOp:scale = (5, 5, 5) double3 xformOp:translate = (100, 10, 0) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] def Cube "Cube" { float3 xformOp:rotateXYZ = (100, 0, 0) float3 xformOp:scale = (2, 2, 2) double3 xformOp:translate = (4, 0, 0) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } } }
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/transforms/get-local-transforms/py_omni_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 import typing import omni.usd from pxr import Usd, Gf def get_local_transform_omni(prim: Usd.Prim) -> typing.Tuple[Gf.Vec3d, Gf.Rotation, Gf.Vec3d]: """ Get the local transformation of a prim using omni.usd.get_local_transform_SRT. See https://docs.omniverse.nvidia.com/kit/docs/omni.usd/latest/omni.usd/omni.usd.get_local_transform_SRT.html Args: prim: The prim to calculate the local transformation. Returns: A tuple of: - Translation vector. - Rotation quaternion, i.e. 3d vector plus angle. - Scale vector. """ local_transform = omni.usd.get_local_transform_SRT(prim) scale: Gf.Vec3d = local_transform[0] rotation: Gf.Vec3d = local_transform[1] rotation_order: float = local_transform[2] translation: Gf.Vec3d = local_transform[3] return translation, Gf.Rotation(rotation, rotation_order), scale ############# # Full Usage ############# import omni.kit.commands # Create an Xform with a Cube Prim as it's Child omni.kit.commands.execute('CreatePrimWithDefaultXform', prim_type='Xform', attributes={}, select_new_prim=True) omni.kit.commands.execute('TransformMultiPrimsSRTCpp', count=1, paths=['/World/Xform'], new_translations=[100, 0, 0], new_rotation_eulers=[0, 50 ,0], new_rotation_orders=[0, 1, 2], new_scales=[5, 5, 5], old_translations=[0.0, 0.0, 0.0], old_rotation_eulers=[0.0, 0.0, 0.0], old_rotation_orders=[0, 1, 2], old_scales=[1.0, 1.0, 1.0], usd_context_name='', time_code=0.0) omni.kit.commands.execute('CreateMeshPrimWithDefaultXform', prim_type='Cube', prim_path='/World/Xform/Cube', select_new_prim=True, prepend_default_prim=False) omni.kit.commands.execute('TransformMultiPrimsSRTCpp', count=1, paths=['/World/Xform/Cube'], new_translations=[4, 0, 0], new_rotation_eulers=[100, 0 ,0], new_rotation_orders=[0, 1, 2], new_scales=[2, 2, 2], old_translations=[0.0, 0.0, 0.0], old_rotation_eulers=[0.0, 0.0, 0.0], old_rotation_orders=[0, 1, 2], old_scales=[1.0, 1.0, 1.0], usd_context_name='', time_code=0.0) stage = omni.usd.get_context().get_stage() cube_prim = stage.GetPrimAtPath("/World/Xform/Cube") transform = get_local_transform_omni(cube_prim) assert transform[0] == cube_prim.GetAttribute('xformOp:translate').Get() assert (100,0,0) == cube_prim.GetAttribute('xformOp:rotateXYZ').Get() assert transform[2] == cube_prim.GetAttribute('xformOp:scale').Get()
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/transforms/get-local-transforms/py_usd.md
``` {literalinclude} py_usd.py :language: py ```
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/transforms/get-local-transforms/usda.md
This is an example USDA result from creating (and setting) `float` and `float3` Attributes on the default Prim. ``` {literalinclude} usda.usda :language: usd ```
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/transforms/get-local-transforms/config.toml
[core] title = "Get the Local Space Transforms for a Prim" [metadata] description = "Universal Scene Description (OpenUSD) code samples showing how to get the local transform for a prim." keywords = ["OpenUSD", "USD", "Python", "omni.usd", "code sample", "local space", "local", "transforms", "get_local_transform_SRT", "GetLocalTransformation"]
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/transforms/get-local-transforms/py_omni_usd.md
``` {literalinclude} py_omni_usd.py :language: py ```
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/transforms/get-local-transforms/header.md
If you need to get the local transformation of a prim (i.e. not taking into account the transformations of any ancestor prims), you can use a convenience function in Kit, [omni.usd.get_local_transform_SRT()](https://docs.omniverse.nvidia.com/kit/docs/omni.usd/latest/omni.usd/omni.usd.get_local_transform_SRT.html). Alternatively, you can use [UsdGeom.Xformable.GetLocalTransformation()](https://openusd.org/release/api/class_usd_geom_xformable.html#a9a04ccb1ba8aa16e8cc1e878c2c92969) to get the local transformation matrix and decompose it into individual components.
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/transforms/get-world-transforms/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.transform # SPDX-License-Identifier: Apache-2.0 import typing from pxr import Usd, UsdGeom, Gf def get_world_transform_xform(prim: Usd.Prim) -> typing.Tuple[Gf.Vec3d, Gf.Rotation, Gf.Vec3d]: """ Get the local transformation of a prim using Xformable. See https://openusd.org/release/api/class_usd_geom_xformable.html Args: prim: The prim to calculate the world transformation. Returns: A tuple of: - Translation vector. - Rotation quaternion, i.e. 3d vector plus angle. - Scale vector. """ xform = UsdGeom.Xformable(prim) time = Usd.TimeCode.Default() # The time at which we compute the bounding box world_transform: Gf.Matrix4d = xform.ComputeLocalToWorldTransform(time) translation: Gf.Vec3d = world_transform.ExtractTranslation() rotation: Gf.Rotation = world_transform.ExtractRotation() scale: Gf.Vec3d = Gf.Vec3d(*(v.GetLength() for v in world_transform.ExtractRotationMatrix())) return translation, rotation, scale ############# # Full Usage ############# from pxr import Sdf # Create an in-memory Stage with /World Xform prim as the default prim stage: Usd.Stage = Usd.Stage.CreateInMemory() default_prim: Usd.Prim = UsdGeom.Xform.Define(stage, Sdf.Path("/World")).GetPrim() stage.SetDefaultPrim(default_prim) xform: Usd.Prim = UsdGeom.Xform.Define(stage, default_prim.GetPath().AppendPath("Xform")) xform.AddTranslateOp().Set(value=(100,10,0)) xform.AddRotateXYZOp().Set(value=(0,50,0)) xform.AddScaleOp().Set(value=(5,5,5)) cube = UsdGeom.Cube.Define(stage, xform.GetPath().AppendPath("Cube")) cube.AddTranslateOp().Set(value=(4,0,0)) cube.AddRotateXYZOp().Set(value=(100,0,0)) cube.AddScaleOp().Set(value=(2,2,2)) transform = get_world_transform_xform(cube) usda = stage.GetRootLayer().ExportToString() print(usda)
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/transforms/get-world-transforms/usda.usda
[py stdout]: #usda 1.0 ( defaultPrim = "World" ) def Xform "World" { def Xform "Xform" { float3 xformOp:rotateXYZ = (0, 50, 0) float3 xformOp:scale = (5, 5, 5) double3 xformOp:translate = (100, 10, 0) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] def Cube "Cube" { float3 xformOp:rotateXYZ = (100, 0, 0) float3 xformOp:scale = (2, 2, 2) double3 xformOp:translate = (4, 0, 0) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } } }
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/transforms/get-world-transforms/py_omni_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 import omni.usd from pxr import Usd, Gf import typing def get_world_transform_xform(prim: Usd.Prim) -> typing.Tuple[Gf.Vec3d, Gf.Rotation, Gf.Vec3d]: """ Get the local transformation of a prim using omni.usd.get_world_transform_matrix(). See https://docs.omniverse.nvidia.com/kit/docs/omni.usd/latest/omni.usd/omni.usd.get_world_transform_matrix.html Args: prim: The prim to calculate the world transformation. Returns: A tuple of: - Translation vector. - Rotation quaternion, i.e. 3d vector plus angle. - Scale vector. """ world_transform: Gf.Matrix4d = omni.usd.get_world_transform_matrix(prim) translation: Gf.Vec3d = world_transform.ExtractTranslation() rotation: Gf.Rotation = world_transform.ExtractRotation() scale: Gf.Vec3d = Gf.Vec3d(*(v.GetLength() for v in world_transform.ExtractRotationMatrix())) return translation, rotation, scale ############# # Full Usage ############# import omni.kit.commands # Create an Xform with a Cube Prim as it's Child omni.kit.commands.execute('CreatePrimWithDefaultXform', prim_type='Xform', attributes={}, select_new_prim=True) omni.kit.commands.execute('TransformMultiPrimsSRTCpp', count=1, paths=['/World/Xform'], new_translations=[100, 0, 0], new_rotation_eulers=[0, 50 ,0], new_rotation_orders=[0, 1, 2], new_scales=[5, 5, 5], old_translations=[0.0, 0.0, 0.0], old_rotation_eulers=[0.0, 0.0, 0.0], old_rotation_orders=[0, 1, 2], old_scales=[1.0, 1.0, 1.0], usd_context_name='', time_code=0.0) omni.kit.commands.execute('CreateMeshPrimWithDefaultXform', prim_type='Cube', prim_path='/World/Xform/Cube', select_new_prim=True, prepend_default_prim=False) omni.kit.commands.execute('TransformMultiPrimsSRTCpp', count=1, paths=['/World/Xform/Cube'], new_translations=[4, 0, 0], new_rotation_eulers=[100, 0 ,0], new_rotation_orders=[0, 1, 2], new_scales=[2, 2, 2], old_translations=[0.0, 0.0, 0.0], old_rotation_eulers=[0.0, 0.0, 0.0], old_rotation_orders=[0, 1, 2], old_scales=[1.0, 1.0, 1.0], usd_context_name='', time_code=0.0) stage = omni.usd.get_context().get_stage() cube_prim = stage.GetPrimAtPath("/World/Xform/Cube") transform = get_world_transform_xform(cube_prim)
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/transforms/get-world-transforms/py_usd.md
``` {literalinclude} py_usd.py :language: py ``` Alternatively, if you need to compute the world transform for multiple prims on a stage, [UsdGeom.XformCache](https://openusd.org/release/api/class_usd_geom_xform_cache.html) is more efficient. ``` {literalinclude} py_usd_var1.py :language: py ```
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/transforms/get-world-transforms/usda.md
This is an example USDA result from creating a Xform with a Cube as a child. ``` {literalinclude} usda.usda :language: usd ```
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/transforms/get-world-transforms/config.toml
[core] title = "Get the World Space Transforms for a Prim" [metadata] description = "Universal Scene Description (OpenUSD) code samples showing how to get the world space transforms for a prim." keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "omni.usd", "world space", "world", "transforms", "omni.usd","get_world_transform_matrix", "ComputeLocalToWorldTransform"]
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/transforms/get-world-transforms/py_omni_usd.md
``` {literalinclude} py_omni_usd.py :language: py ```
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/transforms/get-world-transforms/py_usd_var1.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 import typing from pxr import Usd, UsdGeom, Gf def get_world_transform_cache(cache: UsdGeom.XformCache, prim: Usd.Prim) -> typing.Tuple[Gf.Vec3d, Gf.Rotation, Gf.Vec3d]: """ Get the local transformation of a prim using UsdGeom.XformCache. See: https://openusd.org/release/api/class_usd_geom_xform_cache.html Args: cache: A cache, created for example as `UsdGeom.XformCache()` prim: The prim to calculate the world transformation. Returns: A tuple of: - Translation vector. - Rotation quaternion, i.e. 3d vector plus angle. - Scale vector. """ world_transform: Gf.Matrix4d = cache.GetLocalToWorldTransform(prim) translation: Gf.Vec3d = world_transform.ExtractTranslation() rotation: Gf.Rotation = world_transform.ExtractRotation() scale: Gf.Vec3d = Gf.Vec3d(*(v.GetLength() for v in world_transform.ExtractRotationMatrix())) return translation, rotation, scale ############# # Full Usage ############# from pxr import Sdf # Create an in-memory Stage with /World Xform prim as the default prim stage: Usd.Stage = Usd.Stage.CreateInMemory() default_prim: Usd.Prim = UsdGeom.Xform.Define(stage, Sdf.Path("/World")).GetPrim() stage.SetDefaultPrim(default_prim) xform: Usd.Prim = UsdGeom.Xform.Define(stage, default_prim.GetPath().AppendPath("Xform")) xform.AddTranslateOp().Set(value=(100,10,0)) xform.AddRotateXYZOp().Set(value=(0,50,0)) xform.AddScaleOp().Set(value=(5,5,5)) cube = UsdGeom.Cube.Define(stage, xform.GetPath().AppendPath("Cube")) cube.AddTranslateOp().Set(value=(4,0,0)) cube.AddRotateXYZOp().Set(value=(100,0,0)) cube.AddScaleOp().Set(value=(2,2,2)) time = Usd.TimeCode.Default() # The time at which we compute the bounding box cache = UsdGeom.XformCache(time) transform = get_world_transform_cache(cache, cube.GetPrim()) usda = stage.GetRootLayer().ExportToString() print(usda)
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/transforms/get-world-transforms/header.md
If you need to get the transformation of a prim in world space (i.e. taking into account the transformations of any ancestor prims), you can use a convenience function in Kit, [omni.usd.get_world_transform_matrix()](https://docs.omniverse.nvidia.com/kit/docs/omni.usd/latest/omni.usd/omni.usd.get_world_transform_matrix.html). Alternatively, you can use [UsdGeom.Xformable.ComputeLocalToWorldTransform()](https://openusd.org/release/api/class_usd_geom_imageable.html#a8e3fb09253ba63d63921f665d63cd270) or [UsdGeom.XformCache.GetLocalToWorldTransform()](https://openusd.org/release/api/class_usd_geom_xform_cache.html#aaba1e27b19713a49c1b5b77805184113) to get the world transformation matrix. Once you have the matrix, decompose it into individual xform components.
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/transforms/compute-prim-bounding-box/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Usd, UsdGeom, Gf def compute_bbox(prim: Usd.Prim) -> Gf.Range3d: """ Compute Bounding Box using ComputeWorldBound at UsdGeom.Imageable See https://openusd.org/release/api/class_usd_geom_imageable.html Args: prim: A prim to compute the bounding box. Returns: A range (i.e. bounding box), see more at: https://openusd.org/release/api/class_gf_range3d.html """ imageable = UsdGeom.Imageable(prim) time = Usd.TimeCode.Default() # The time at which we compute the bounding box bound = imageable.ComputeWorldBound(time, UsdGeom.Tokens.default_) bound_range = bound.ComputeAlignedBox() return bound_range
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/transforms/compute-prim-bounding-box/py_omni_usd.py
import typing import carb import omni.usd def compute_path_bbox(prim_path: str) -> typing.Tuple[carb.Double3, carb.Double3]: """ Compute Bounding Box using omni.usd.UsdContext.compute_path_world_bounding_box See https://docs.omniverse.nvidia.com/kit/docs/omni.usd/latest/omni.usd/omni.usd.UsdContext.html#omni.usd.UsdContext.compute_path_world_bounding_box Args: prim_path: A prim path to compute the bounding box. Returns: A range (i.e. bounding box) as a minimum point and maximum point. """ return omni.usd.get_context().compute_path_world_bounding_box(prim_path)