file_path
stringlengths 21
202
| content
stringlengths 12
1.02M
| size
int64 12
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 3.33
100
| max_line_length
int64 10
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/prims/get-prim/py_usd.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
from typing import Union
from pxr import Usd, Sdf
def get_prim_by_path(stage: Usd.Stage, prim_path: Union[str, Sdf.Path]) -> Usd.Prim:
return stage.GetPrimAtPath(prim_path)
##############
# Full Usage
##############
from pxr import UsdGeom
# Create an in-memory Stage with /World Xform prim as the default prim
stage: Usd.Stage = Usd.Stage.CreateInMemory()
default_prim = UsdGeom.Xform.Define(stage, Sdf.Path("/World"))
stage.SetDefaultPrim(default_prim.GetPrim())
# Create some prims
UsdGeom.Xform.Define(stage, "/World/Group")
UsdGeom.Cube.Define(stage, "/World/Group/Foo")
# Get a prim using a str object
group_prim_path = "/World/Group"
group_prim = get_prim_by_path(stage, group_prim_path)
# Get a prim using an Sdf.Path object
foo_prim_path = Sdf.Path("/World/Group/Foo")
foo_prim = get_prim_by_path(stage, foo_prim_path)
# Print the prim objects that were retrieved
print(group_prim)
print(foo_prim)
# Check that the prims retrieve match the paths provided
assert group_prim.GetPath() == Sdf.Path(group_prim_path)
assert foo_prim.GetPath() == foo_prim_path | 1,214 | Python | 30.973683 | 98 | 0.729819 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/prims/get-prim/py_usd.md | Get a prim by using the prim’s path:
``` {literalinclude} py_usd.py
:language: py
``` | 86 | Markdown | 16.399997 | 36 | 0.674419 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/prims/get-prim/config.toml | [core]
title = "Get a Prim"
[metadata]
description = "Universal Scene Description (OpenUSD) code samples for accessing or getting a Prim on the Stage."
keywords = ["OpenUSD", "USD", "Python", "code sample", "prim", "get prim", "accessing", "IsValid", "valid"] | 260 | TOML | 42.499993 | 112 | 0.696154 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/prims/get-current-selected-prims/py_usdview.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
from typing import List
from pxr import Usd
prims: List[Usd.Prim] = usdviewApi.selectedPrims | 231 | Python | 32.142853 | 98 | 0.792208 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/prims/get-current-selected-prims/py_omni_usd.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
import omni.usd
prim_path = "/World/My/Prim"
ctx = omni.usd.get_context()
# returns a list of prim path strings
selection = ctx.get_selection().get_selected_prim_paths() | 308 | Python | 33.33333 | 98 | 0.756494 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/prims/get-current-selected-prims/py_usdview.md | *usdview* Python interpreter has a built-in object called `usdviewApi` that gives you access to the currently selected prims.
``` {literalinclude} py_usdview.py
:language: py
``` | 178 | Markdown | 43.749989 | 125 | 0.769663 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/prims/get-current-selected-prims/config.toml | [core]
title = "Get the Currently Selected Prims"
[metadata]
description = "Universal Scene Description (OpenUSD) code samples for getting the currently selected prim(s)."
keywords = ["OpenUSD", "USD", "Python", "code sample", "prim", "selection", "selected", "prims", "usdview"] | 281 | TOML | 45.999992 | 110 | 0.715302 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/inherits/add-inherit/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 add_inherit(stage: Usd.Stage, prim: Usd.Prim, class_prim: Usd.Prim):
inherits: Usd.Inherits = prim.GetInherits()
inherits.AddInherit(class_prim.GetPath())
#############
# Full Usage
#############
from pxr import Sdf, 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)
# The base prim typically uses the "class" Specifier to designate that it
# is meant to be inherited and skipped in standard stage traversals
tree_class: Usd.Prim = stage.CreateClassPrim("/_class_Tree")
tree_prim: Usd.Prim = UsdGeom.Mesh.Define(stage, default_prim.GetPath().AppendPath("TreeA")).GetPrim()
add_inherit(stage, tree_prim, tree_class)
usda = stage.GetRootLayer().ExportToString()
print(usda)
# Check to see if the inherit was added
inherits_list = tree_prim.GetInherits().GetAllDirectInherits()
assert tree_class.GetPath() in inherits_list | 1,190 | Python | 35.090908 | 102 | 0.743697 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/inherits/add-inherit/py_usd.md | This code sample shows how to add an Inherit arc to a prim. A single prim can have multiple Inherits.
``` {literalinclude} py_usd.py
:language: py
```
| 152 | Markdown | 24.499996 | 101 | 0.730263 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/inherits/add-inherit/usda.md | This is an example USDA result adding an Inherit Arc to a prim.
``` {literalinclude} usda.usda
:language: usd
``` | 114 | Markdown | 27.749993 | 63 | 0.72807 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/data-types/convert-vtarray-numpy/py_usd.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
import numpy
from pxr import Vt
def convert_vt_to_np(my_array: Vt.Vec3fArray) -> numpy.ndarray:
return numpy.array(my_vec3_array)
#############
# Full Usage
#############
# Create a Vt.Vec3fArray and convert it to a numpy array
my_vec3_array = Vt.Vec3fArray([(1,2,3),(4,5,6),(7,8,9)])
np_array: numpy.ndarray = convert_vt_to_np(my_vec3_array)
# print the numpy array to check the values
print(np_array)
# check the size and length of the numpy array
assert np_array.size == 9
assert len(np_array) == 3
| 651 | Python | 24.076922 | 98 | 0.695853 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/data-types/convert-vtarray-numpy/py_usd.md | **Convert to Numpy Array**
To convert a VtArray to a Numpy Array, simply pass the VtArray object to `numpy.array` constructor.
``` {literalinclude} py_usd.py
:language: py
```
**Convert from Numpy Array**
To convert a Numpy Array to a VtArray, you can use `FromNumpy()` from the VtArray class you want to convert to.
``` {literalinclude} py_usd_var1.py
:language: py
``` | 377 | Markdown | 24.199998 | 111 | 0.71618 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/data-types/convert-vtarray-numpy/config.toml | [core]
title = "Convert Between VtArray and Numpy Array"
[metadata]
description = "Universal Scene Description (OpenUSD) code samples for converting between VtArray classes and Numpy."
keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "types", "array", "numpy", "VtArray"] | 289 | TOML | 47.333325 | 116 | 0.726644 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/data-types/convert-vtarray-numpy/py_usd_var1.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
import numpy
from pxr import Vt
def convert_np_to_vt(my_array: numpy.ndarray) -> Vt.Vec3fArray:
return Vt.Vec3fArray.FromNumpy(my_array)
#############
# Full Usage
#############
# Create a numpy array and convert it into a Vt.Vec3fArray
np_array = numpy.array([(1,2,3),(4,5,6),(7,8,9)])
from_numpy: Vt.Vec3fArray = convert_np_to_vt(np_array)
# Print the Vt.Vec3fArray to check the values
print(from_numpy)
# Check the length of the numpy array
assert len(np_array) == 3 | 618 | Python | 24.791666 | 98 | 0.700647 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/data-types/convert-vtarray-numpy/header.md | Some Attributes store array type data which are accessed using the VtArray classes. You can find a list of the VtArray classes in our [USD Data Types documentation](https://docs.omniverse.nvidia.com/dev-guide/latest/dev_usd/quick-start/usd-types.html)
If you need to manipulate the arrays using Python, it is advantageous to use Numpy to benefit from it's speed and efficiency. These code samples show how you can convert between the VtArray objects and Numpy Array objects.
```{note}
These examples show how to convert using only the Vt.Vec3fArray class, but the same can be applied to any VtArray class. See what other VtArray classes exist in the [USD Data Types documentation](https://docs.omniverse.nvidia.com/dev-guide/latest/dev_usd/quick-start/usd-types.html).
```
| 778 | Markdown | 76.899992 | 283 | 0.790488 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/paths/concatenate-property-with-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_property_with_prim_path(prim_path: Sdf.Path, prop) -> Sdf.Path:
prop_path = prim_path.AppendProperty(prop)
return prop_path
#############
# Full Usage
#############
# e.g., get path to "points" attribute on a mesh prim
from pxr import UsdGeom, Usd
stage: Usd.Stage = Usd.Stage.CreateInMemory()
default_prim: Usd.Prim = UsdGeom.Xform.Define(stage, Sdf.Path("/World")).GetPrim()
stage.SetDefaultPrim(default_prim)
mesh_prim: Usd.Prim = UsdGeom.Xform.Define(stage, Sdf.Path("/World/Mesh")).GetPrim()
prop_path: Sdf.Path = concat_property_with_prim_path(mesh_prim.GetPrimPath(), UsdGeom.Tokens.points) #nothing happend so did it get added?
usda = stage.GetRootLayer().ExportToString()
print(usda)
assert Sdf.Path.IsValidPathString(prop_path.pathString) | 932 | Python | 33.555554 | 138 | 0.73176 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/paths/concatenate-property-with-prim-path/config.toml | [core]
title = "Concatenate a Property Name with a Prim Path"
[metadata]
description = "Universal Scene Description (OpenUSD) code samples showing how to concatenate a property name with a prim path."
keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "prim", "property", "path", "AppendProperty"] | 313 | TOML | 51.333325 | 127 | 0.728435 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/paths/get-parent-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 get_parent_path(prim_path: Sdf.Path) -> Sdf.Path:
parent_path = prim_path.GetParentPath()
return parent_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)
cone_prim = UsdGeom.Cone.Define(stage, Sdf.Path("/World/Cone")).GetPrim()
# Given Sdf.Path('/World/Cone') for my_prim_path, parent_path will contain Sdf.Path('/World')
parent_path = get_parent_path(cone_prim.GetPrimPath())
usda = stage.GetRootLayer().ExportToString()
print(usda)
assert parent_path == default_prim.GetPrimPath() | 918 | Python | 33.037036 | 98 | 0.724401 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/paths/get-parent-path/usda.md | This is an example USDA result from adding a Cone to the a World Prim.
``` {literalinclude} usda.usda
:language: usd
``` | 121 | Markdown | 29.499993 | 70 | 0.727273 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/paths/get-parent-path/config.toml | [core]
title = "Get the Parent Path for a Prim Path"
[metadata]
description = "Universal Scene Description (OpenUSD) code samples for getting the parent path from a prim path."
keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "prim", "path", "GetParentPath"] | 276 | TOML | 45.166659 | 112 | 0.713768 |
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" | 960 | Python | 34.592591 | 145 | 0.742708 |
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"] | 261 | TOML | 42.66666 | 111 | 0.712644 |
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() | 356 | Python | 43.624995 | 98 | 0.797753 |
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"] | 503 | TOML | 54.999994 | 153 | 0.751491 |
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!") | 271 | Python | 32.999996 | 98 | 0.756458 |
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"] | 461 | TOML | 50.333328 | 143 | 0.720174 |
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.
```
| 464 | Markdown | 76.499987 | 314 | 0.773707 |
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"]) | 461 | Python | 50.333328 | 98 | 0.789588 |
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"] | 440 | TOML | 47.999995 | 133 | 0.731818 |
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
``` | 180 | Markdown | 35.199993 | 125 | 0.755556 |
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())
| 2,205 | Python | 30.514285 | 98 | 0.702041 |
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
```
| 253 | Markdown | 35.285709 | 104 | 0.719368 |
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())
| 2,539 | Python | 31.151898 | 134 | 0.700276 |
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
``` | 207 | Markdown | 50.999987 | 156 | 0.753623 |
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"] | 297 | TOML | 41.571423 | 100 | 0.717172 |
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.
| 139 | Markdown | 68.999966 | 138 | 0.798561 |
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
``` | 327 | Markdown | 28.818179 | 153 | 0.743119 |
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) | 655 | Python | 30.238094 | 98 | 0.638168 |
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
``` | 162 | Markdown | 17.111109 | 57 | 0.691358 |
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)
) | 561 | Python | 34.124998 | 98 | 0.741533 |
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) | 851 | Python | 36.043477 | 98 | 0.653349 |
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() | 706 | Python | 38.277776 | 98 | 0.686969 |
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
``` | 153 | Markdown | 16.111109 | 48 | 0.679739 |
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"] | 462 | TOML | 50.444439 | 137 | 0.722944 |
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")
| 348 | Python | 37.777774 | 98 | 0.784483 |
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"] | 432 | TOML | 47.111106 | 111 | 0.729167 |
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
``` | 345 | Markdown | 30.454543 | 155 | 0.776812 |
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") | 673 | Python | 50.84615 | 98 | 0.783061 |
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
``` | 296 | Markdown | 25.999998 | 116 | 0.77027 |
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)
| 316 | Python | 30.699997 | 98 | 0.791139 |
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)
| 297 | Python | 28.799997 | 98 | 0.777778 |
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"]
| 420 | TOML | 59.142849 | 183 | 0.77619 |
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") | 1,055 | Python | 54.578944 | 114 | 0.788626 |
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") | 824 | Python | 50.562497 | 98 | 0.792476 |
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.
)
| 486 | Python | 43.272723 | 98 | 0.751029 |
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"]
| 346 | TOML | 48.571422 | 152 | 0.736994 |
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
| 773 | Python | 24.799999 | 98 | 0.728331 |
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
``` | 140 | Markdown | 34.249991 | 89 | 0.75 |
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"] | 271 | TOML | 44.333326 | 107 | 0.712177 |
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
| 721 | Python | 30.391303 | 106 | 0.755895 |
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
``` | 308 | Markdown | 76.249981 | 259 | 0.775974 |
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"] | 323 | TOML | 52.999991 | 138 | 0.718266 |
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).
```
| 511 | Markdown | 41.666663 | 219 | 0.755382 |
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
| 564 | Python | 24.681817 | 98 | 0.723404 |
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
``` | 230 | Markdown | 56.749986 | 181 | 0.76087 |
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"] | 280 | TOML | 45.833326 | 125 | 0.7 |
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).
```
| 437 | Markdown | 32.692305 | 186 | 0.734554 |
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 | 194 | Python | 31.499995 | 98 | 0.783505 |
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
| 604 | Python | 25.304347 | 98 | 0.720199 |
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
``` | 176 | Markdown | 43.249989 | 123 | 0.767045 |
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"] | 292 | TOML | 47.833325 | 126 | 0.719178 |
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() | 2,084 | Python | 35.578947 | 102 | 0.714971 |
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() | 2,549 | Python | 31.278481 | 113 | 0.68929 |
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
``` | 162 | Markdown | 39.74999 | 111 | 0.740741 |
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"] | 346 | TOML | 56.833324 | 157 | 0.731214 |
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)
| 1,924 | Python | 36.01923 | 107 | 0.713617 |
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
``` | 298 | Markdown | 32.222219 | 193 | 0.741611 |
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
``` | 127 | Markdown | 30.999992 | 76 | 0.732283 |
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"] | 384 | TOML | 63.166656 | 188 | 0.734375 |
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
| 815 | Python | 37.857141 | 103 | 0.715337 |
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) | 614 | Python | 37.437498 | 152 | 0.723127 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/transforms/compute-prim-bounding-box/py_usd.md | ``` {literalinclude} py_usd.py
:language: py
```
Alternatively, if you need to compute the bounding box for multiple prims on a stage, [UsdGeom.BBoxCache](https://openusd.org/release/api/class_usd_geom_b_box_cache.html) is more efficient.
``` {literalinclude} py_usd_var1.py
:language: py
``` | 294 | Markdown | 31.777774 | 189 | 0.734694 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/transforms/compute-prim-bounding-box/config.toml | [core]
title = "Compute the Bounding Box for a Prim"
[metadata]
description = "Universal Scene Description (OpenUSD) code samples showing how to compute the bounding box for a prim."
keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "bounding box", "prim", "omni.usd", "bbox", "ComputeWorldBound", "ComputeAlignedBox"] | 335 | TOML | 54.999991 | 151 | 0.722388 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/transforms/compute-prim-bounding-box/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, UsdGeom, Gf
def compute_bbox_with_cache(cache: UsdGeom.BBoxCache, prim: Usd.Prim) -> Gf.Range3d:
"""
Compute Bounding Box using ComputeWorldBound at UsdGeom.BBoxCache. More efficient if used multiple times.
See https://openusd.org/release/api/class_usd_geom_b_box_cache.html
Args:
cache: A cached, i.e. `UsdGeom.BBoxCache(Usd.TimeCode.Default(), ['default', 'render'])`
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
"""
bound = cache.ComputeWorldBound(prim)
bound_range = bound.ComputeAlignedBox()
return bound_range
| 846 | Python | 37.499998 | 109 | 0.702128 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/hierarchy-traversal/find-prim-by-name/py_usd.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
from typing import List
from pxr import Usd
def find_prims_by_name(stage: Usd.Stage, prim_name: str) -> List[Usd.Prim]:
found_prims = [x for x in stage.Traverse() if x.GetName() == prim_name]
return found_prims
##############
# Full Usage
##############
from pxr import UsdGeom, Sdf
# Create an in-memory Stage with /World Xform prim as the default prim
stage: Usd.Stage = Usd.Stage.CreateInMemory()
default_prim = UsdGeom.Xform.Define(stage, Sdf.Path("/World"))
stage.SetDefaultPrim(default_prim.GetPrim())
# Create some shape prims
UsdGeom.Xform.Define(stage, "/World/Group")
UsdGeom.Cone.Define(stage, "/World/Foo")
UsdGeom.Cube.Define(stage, "/World/Group/Foo")
UsdGeom.Sphere.Define(stage, "/World/Group/Bar")
# find the prims with the name "Foo"
prims: List[Usd.Prim] = find_prims_by_name(stage, "Foo")
# Print the prims to check the found prims by name.
print(prims)
# Check the number of prims found and whether the found data is correct.
assert len(prims) == 2
assert isinstance(prims[0], Usd.Prim)
assert prims[0].GetName() == "Foo" | 1,198 | Python | 29.743589 | 98 | 0.716194 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/hierarchy-traversal/find-prim-by-name/py_usd.md | ``` {literalinclude} py_usd.py
:language: py
```
```{warning}
This will be slow for stages with many prims, as stage traversal is currently single-threaded. Learn more about [scene complexity](https://openusd.org/release/maxperf.html#what-makes-a-usd-scene-heavy-expensive).
```
| 286 | Markdown | 22.916665 | 212 | 0.730769 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/hierarchy-traversal/find-prim-by-name/config.toml | [core]
title = "Find a Prim by Name"
[metadata]
description = "Universal Scene Description (OpenUSD) code samples for finding a Prim by its name on a Stage."
keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "prim", "name", "Traverse"] | 252 | TOML | 41.16666 | 109 | 0.694444 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/hierarchy-traversal/find-prim-by-name/header.md | If you want to find all of the prims of a certain type, you can [Traverse](https://openusd.org/release/api/class_usd_stage.html#adba675b55f41cc1b305bed414fc4f178) the stage and use [Usd.Prim.GetName()](https://openusd.org/release/api/class_usd_object.html#ae57e12beedf10c423e11c5b889343f6d) to compare the name of every prim on the stage with the name you are looking for.
```{note}
There could be more than one prim with the same name on a stage.
```
| 454 | Markdown | 63.999991 | 372 | 0.777533 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/hierarchy-traversal/get-prim-child/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 get_child_prim(parent_prim, child_name) -> Usd.Prim:
child_prim: Usd.Prim = parent_prim.GetChild(child_name)
return child_prim
#############
# Full Usage
#############
from pxr import Sdf, 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)
# Create a Cube prim
cube: Usd.Prim = UsdGeom.Cube.Define(stage, default_prim.GetPath().AppendPath("Box"))
# Get the child prim of the default prim with the name "Box"
child_prim = get_child_prim(default_prim, "Box")
# Print the full Stage
usda = stage.GetRootLayer().ExportToString()
print(usda)
# Print the path of the child prim you were looking for.
print(child_prim.GetPath())
# Verify the child and parent relationship
assert child_prim.GetParent() == default_prim
assert child_prim.GetPath() == cube.GetPath() | 1,128 | Python | 31.257142 | 98 | 0.728723 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/hierarchy-traversal/get-prim-child/py_usd.md | If you know the name of the child prim, you can use `Usd.Prim.GetChild()`. This returns an invalid prim if the child doesn't exist. You can [check if the returned prim exists](../prims/check-prim-exists).
``` {literalinclude} py_usd.py
:language: py
```
Another option is to iterate through all of the prim's children to operate on all the children or query them to find the child you are looking for.
``` {literalinclude} py_usd_var1.py
:language: py
``` | 457 | Markdown | 44.799996 | 204 | 0.737418 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/hierarchy-traversal/get-prim-child/usda.md | This is an example USDA result to show that the Cube prim is the Child Prim of World.
``` {literalinclude} usda.usda
:language: usd
``` | 136 | Markdown | 33.249992 | 85 | 0.735294 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/hierarchy-traversal/get-prim-child/config.toml | [core]
title = "Get the Child of a Prim"
[metadata]
description = "Universal Scene Description (OpenUSD) code samples for getting the child of a Prim."
keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "prim", "child", "children"] | 247 | TOML | 40.333327 | 99 | 0.696356 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/hierarchy-traversal/get-prim-child/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, UsdGeom
def get_first_child_mesh(parent_prim: Usd.Prim) -> Usd.Prim:
# Iterates only active, loaded, defined, non-abstract children
for child_prim in parent_prim.GetChildren():
if child_prim.IsA(UsdGeom.Mesh):
return child_prim
def print_all_children_names(parent_prim: Usd.Prim):
# Iterates over all children
for child_prim in parent_prim.GetAllChildren():
print(child_prim.GetName()) | 590 | Python | 38.399997 | 98 | 0.716949 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/hierarchy-traversal/find-prims-by-type/py_usd.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
from typing import List, Type
from pxr import Usd, UsdGeom
def find_prims_by_type(stage: Usd.Stage, prim_type: Type[Usd.Typed]) -> List[Usd.Prim]:
found_prims = [x for x in stage.Traverse() if x.IsA(prim_type)]
return found_prims
##############
# Full Usage
##############
from pxr import UsdGeom, Sdf
# Create an in-memory Stage with /World Xform prim as the default prim
stage: Usd.Stage = Usd.Stage.CreateInMemory()
default_prim = UsdGeom.Xform.Define(stage, Sdf.Path("/World"))
stage.SetDefaultPrim(default_prim.GetPrim())
# Create some shape prims
UsdGeom.Xform.Define(stage, "/World/Group")
UsdGeom.Mesh.Define(stage, "/World/Foo")
UsdGeom.Mesh.Define(stage, "/World/Group/Bar")
UsdGeom.Sphere.Define(stage, "/World/Group/Baz")
# find the prims with of type UsdGeom.Mesh
prims: List[Usd.Prim] = find_prims_by_type(stage, UsdGeom.Mesh)
# Print the mesh prims you found
print(prims)
# Check the number of prims found and whether the found data is correct.
assert len(prims) == 2
prim: Usd.Prim
for prim in prims:
assert isinstance(prim, Usd.Prim)
assert prim.GetTypeName() == "Mesh" | 1,250 | Python | 29.512194 | 98 | 0.7208 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/hierarchy-traversal/find-prims-by-type/config.toml | [core]
title = "Find All the Prims of a Given Type"
[metadata]
description = "Universal Scene Description (OpenUSD) code samples for finding all the Prims on a Stage of a certain type."
keywords = ["OpenUSD", "USD", "Python", "code sample", "snippet", "code sample", "prim", "IsA", "Traverse"] | 294 | TOML | 48.166659 | 122 | 0.704082 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/sphinx/usd_header.rst | ========================================================
Universal Scene Description (OpenUSD) Code Samples
========================================================
This is an index of code samples or snippets for Universal Scene Description (OpenUSD). The code samples are indexed by topics and each code sample is titled by the task that it is used for. Where applicable, we include code samples using Kit OpenUSD wrappers for developing within Omniverse apart from the original USD API. New USD developers will find this useful for finding the appropriate API used to accomplish a task and using the `OpenUSD Python API reference <https://docs.omniverse.nvidia.com/kit/docs/pxr-usd-api>`__ or `OpenUSD C++ API reference <https://openusd.org/release/api/index.html>`_ to learn more about the API. Experienced developers can use this index for quick code lookups.
**Want to contribute to the USD Code Samples?**
All the code samples are open-source with a permissive license. You can contribute new code samples for new tasks or improve existing code samples. Visit the `OpenUSD Code Samples GitHub Repository <https://github.com/NVIDIA-Omniverse/OpenUSD-Code-Samples>`__ to learn more and contribute.
.. button-link:: https://github.com/NVIDIA-Omniverse/OpenUSD-Code-Samples
:color: secondary
:align: center
:outline:
Contribute | 1,357 | reStructuredText | 74.44444 | 699 | 0.714075 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/sphinx/index.rst | .. toctree::
:caption: USD Code Samples
:maxdepth: 4
usd | 66 | reStructuredText | 12.399998 | 29 | 0.606061 |
NVIDIA-Omniverse/OpenUSD-Code-Samples/sphinx/conf.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
# -- Project information -----------------------------------------------------
project = 'USD Code Samples'
copyright = '2023, NVIDIA'
author = 'NVIDIA'
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
"myst_parser",
"sphinx_design",
"sphinx_rtd_theme"
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
html_theme_options = {
'collapse_navigation': True,
'navigation_depth': -1
}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static'] | 2,147 | Python | 33.095238 | 98 | 0.658593 |
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.custom_ui/Workshop/Siggraph2022_Scatter_Workshop.md |

# NVIDIA OMNIVERSE
# Build Beautiful, Custom UI for 3D Tools on NVIDIA Omniverse
Become a master in UI with a hands-on deep dive into NVIDIA Omniverse Kit’s powerful omni.ui suite of tools and frameworks. In this session, you’ll build your own custom UI for workflows in Omniverse with Python script.
# Learning Objectives
- Enable Extension
- Build with omni.ui
- Create Columns and Rows
- Create a button
<video width="560" height="315" controls>
<source src="https://d36m44n9vdbmda.cloudfront.net/assets/x-ov-05-v1/BuildUIIntro.mp4" type="video/mp4">
</video>
# Omni.ui_Window Scatter
## Section I
<video width="560" height="315" controls>
<source src="https://d36m44n9vdbmda.cloudfront.net/assets/x-ov-05-v1/BuildUISection1.mp4" type="video/mp4">
</video>
### Step 1: Open the Workshop Stage
#### <b>Step 1.1: Download the Stage from the Link Provided</b>
[Stage Link](https://dli-lms.s3.amazonaws.com/assets/x-ov-05-v1/Stage.zip)
#### <b> Step 1.2: Unzip Stage Using Extract All...
This creates an unzipped file folder called `Stage`.
#### <b> Step 1.3: Open Stage in Omniverse
Navigate inside Omniverse Code's `Content tab` to the stage file's location on your system.
(i.e. C:/Users/yourName/Downloads/Stage)
**Double Click** `Stage.usd` in the center window pane of the `Content tab` at the bottom of the Omniverse Code Console and it will appear in the viewport.
### Step 2: Install the Scatter Tool Extension
#### <b>Step 2.1: Open the Extensions Tab</b>
Click on `Extensions` Manager Tab
#### <b>Step 2.2: Filter by Commnuity / Third Party Extensions</b>
Select `Community / Third Party` tab
<br>

<br>
#### <b>Step 2.3: Search for Scatter Tool</b>
Search for `Scatter Tool` and click on `Omni.UI Window Scatter`

<br>
#### <b>Step 2.4: Install/Enable the Extension</b>
Click on the extension and then click `Install` in the right console. Once installed, enable the extension.
<span>❗</span> You may get a warning that this extension is not verified. It is safe to install this extension.
<br>
`Scatter Window` will appear on the screen when the extension is enabled.

<br>
#### <b>Step 2.5: Does it work? Set the Source</b>
In the `Viewport` select a prim in the `Stage Hierarchy` and then set the Source of the prim in the Scatter Window by clicking the "S" in Source of `Scatter Window` .
A `prim` is short for primitive. The prim is the fundamental unit in Omniverse. Anything imported or created in a `USD`, Universal Scene Description, scene. This includes camera, sounds, lights, meshes, etc.

<br>
#### <b>Step 2.6: Scatter the Prim</b>
Scatter 20 objects on the `X-axis` with a distance of 30.
Leave Y and Z at default and then click `Scatter Prim A` at the bottom of the `Scatter Window`.
Here is an example of what your scene may look like:

><span>❓</span>Did you notice?
>- Prim scatters at World Origin `[0,0,0]`. How do you think this can be fixed?
>- You can set multiple prim's in the Source but you cannot scatter multiple prim's individually, which we will fix in Section II!
<br>
#### <b>Step 3: Enable Physics</b>
Find the `Play` button and enable physics, watch what happens! Don't forget to hit the `Stop` button after the physics have played.
<details>
<summary>Click here to see where the play button is located</summary>

</details>
<br>
### <b>Step 4: Undo Scatter</b>
Find the `Scatter01` folder in `Stage` and left-click on the folder then right-click to delete or hit the `delete` button on your keyboard.
`Stage` is the panel that allows you to see all the assets in your current `USD`, or Universal Scene Description. It lists the prims in heirarchical order.
><span>❗</span> Warning <span>❗</span> If you `ctrl+z` you will undo the last 3 scatters.

<br>
>#### <span>🧠</span><b>Challenge Step 5: Brainstorm Use Cases</b>
><i>All Challenges in this workshop are optional</i>
>
>Think of 3 ways this tool could be used. Brain storm with your peers and think of how it can be used for your industry!
<br>
>### <span>⛔</span> Stop here and wait to move on to Section II
<br>
## Section II
<video width="560" height="315" controls>
<source src="https://d36m44n9vdbmda.cloudfront.net/assets/x-ov-05-v1/BuildUIIntroSection2.mp4" type="video/mp4">
</video>
<video width="560" height="315" controls>
<source src="https://d36m44n9vdbmda.cloudfront.net/assets/x-ov-05-v1/buildUISection2.mp4" type="video/mp4">
</video>
### Step 6: Add another Source to the UI
#### <b>Step 6.1: Open Visual Studio</b>
Go to the `Extensions` tab and click the `Scatter Window` extension to open the extension overview to the right. Click the `VS Code` icon next to the folder icon:

<br>
#### <b>Step 6.2: Locate Window Script</b>
Locate the files you need for this session at:
`exts -> omni\example\ui_scatter_tool`
You are working in
`window.py`
<br>

<br>
#### <b>Step 6.3: Locate Models</b>
Locate the sets of `Models` at the top of the `ScatterWindow` class.
This is where prim A is defined for both the source and the scatter properties.

<br>
#### <b>Step 6.4: Add Prim Model B to Models</b>
Below `self._scatter_prim_model_a` in the sets of `Models`, add the source and scatter for our new prim, `prim model b`, as so:
```python
self._source_prim_model_b = ui.SimpleStringModel()
self._scatter_prim_model_b = ui.SimpleStringModel()
```
><span>❗</span> Check that you have tabbed correctly. Your new `Models` section should look like this:

<br>
#### <b>Step 6.5: Locate Defaults</b>
Locate the sets of `Defaults` below the sets of `Models`.
This is the default name for the scatter that will be nested in `Stage`.

<br>
#### <b>Step 6.6: Add Default for Prim Model B </b>
Below the property for `self._scatter_prim_model_a._as_string`, set the same for `prim model b` but instead, define the path in the stage as `/World/Scatter02`. This will default where the scatter for prim b will be nested in `Stage`.
```python
self._scatter_prim_model_b.as_string = "/World/Scatter02"
```
Now your `Defaults` section should look like this:

<br>
#### <b>Step 6.7: Locate _build_source function</b>
Locate `_build_source` function in the same script.

This function creates the UI for the `Source` of `Scatter Window` where you set the selected prim by clicking the "S".
<br>
#### <b>Step 6.8: Add Source UI for Prim B</b>
Add this new `ui.HStack` to the bottom of this function, underneath the existing `ui.HStack` for Prim A.
```python
with ui.HStack():
ui.Label("Prim B", name="attribute_name", width=self.label_width)
ui.StringField(model=self._source_prim_model_b)
# Button that puts the selection to the string field
ui.Button(
" S ",
width=0,
height=0,
style={"margin": 0},
clicked_fn=lambda:self._on_get_selection(self._source_prim_model_b),
tooltip="Get From Selection",
)
```
So that your updated function looks like this:

<br>
Save your `window.py` script and check that your Scatter Window UI updated.
## <span>🎉</span> CONGRATULATIONS! <span>🎉</span>
You have created your first piece of UI in Omniverse!

<br>
><span>❓</span> If your UI did not update or your `Scatter Window` disappeared, check the console for errors. The `Console` tab can be found here:
>
>
<br>
><span>❗</span> A common error may be that your code is not aligned properly. Check that the indents match the snippets in step 6.8.
<br>
#### <b>Step 6.9: Locate _build_scatter Function</b>
Locate the function `_build_scatter` in `window.py`.
This function creates the UI for the Scatter group below `Source` in `Scatter Window`.

<br>
#### <b>Step 6.10: Add Scatter UI for Prim B</b>
Create this new `ui.HStack`, for `Prim B Path` below the row for `Prim A Path` as follows:
```python
with ui.HStack():
ui.Label("Prim B Path", name="attribute_name", width=self.label_width)
ui.StringField(model=self._scatter_prim_model_b)
```
So now your `_build_scatter` looks like this:

<br>
Save your `window.py` script and check that your UI has updated in Omniverse.
## <span>🌟</span> AMAZING! <span>🌟</span>
You've done it again and successfully created UI!

<br>
#### <b>Step 6.11: Locate _build_fn Function</b>
Locate the function `_build_fn` in `window.py`
This function builds the entire UI in the `Scatter Window` and also calls the function for when the `Scatter Prim` button is clicked.

<br>
#### <b>Step 6.12: Add a scatter button for Prim B</b>
Create this new button underneath the `Go Button` for `Prim A`.
```python
# The Go button
ui.Button("Scatter Prim B", clicked_fn=lambda:self._on_scatter(self._source_prim_model_b, self._scatter_prim_model_b))
```
So your `_build_fn` should look like this:

<br>
Save `window.py` and check that your UI has been updated in Omniverse.
## <span>✨</span> WOW! <span>✨</span>
You've created a new button, great job!

<br>
### Step 7: Set and Scatter Prim A and Prim B
#### <b>Step 7.1: Set the Source of Prim A and Prim B</b>
Set the Source for Prim A and Prim B, just as you did in Step 2.5

<br>
Make sure that you have set Prim B as a different Prim than Prim A.
For example, set Prim A as Twist Marble and set Prim B as Gummy Bear.

<br>
#### <b>Step 7.2: Set Parameters for X, Y, Z Axis</b>
Set X axis object count to 5 with a distance of 25.
Set Y axis object count to 4 with a distance of 25.
Set Z axis object count to 4 with distance of 25.

<br>
#### <b>Step 7.3: Scatter Prim A</b>
Click Scatter Prim A button.
You should see a quad of Prim A appear on the screen and a folder in `Stage` labeled `Scatter01`.
Select the prims in `Scatter 01` by selecting the first prim in the folder and then <b>shift+click</b> the last prim in the folder then move the quad of Prims over the serving bowl in the viewport.

<br>
#### <b>Step 7.4: Scatter Prim B</b>
Click Scatter Prim B button.
You should see a quad of Pim B appear on the screen and a folder in `Stage` labeled `Scatter 02`.
Leave these prims where they originated.

<br>
#### <b>Step 7.5: Press the Play Button</b>
Press `Play` and watch the Prims fall into the bowl and jar!
Press `Stop` when you are done.

<br>
>#### <span>🧠</span><b>Challenge Step 8: Set Scale Parameters in the UI</b>
><i>All Challenges in this workshop are optional</i>
>
>The function to scale the prim on scatter already exists in the code, can you create the UI for it?
>
><b>Hint:</b> It will be built in `_build_scatter`.
>
>[You can search the omni.ui documentation here.](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html#omni.ui.StringField)
>
><details>
><summary> Click here for the answer </summary>
>
>### Challenge Step 8.1: Build UI for Scale
><i>All Challenges in this workshop are optional</i>
>
>Locate `_build_scatter` in `window.py` as we did in step 6.9.
>
>Add this new row for Scale at the bottom of the function:
>
>```python
> with ui.HStack():
> ui.Label("Scale", name="attribute_name", width=self.label_width)
> for field in zip(["X:", "Y:", "Z:"], self._scale_models):
> ui.Label(field[0], width=0, style={"margin": 3.0})
> ui.FloatField(model=field[1], height=0, style={"margin": 3.0})
>```
>
>So now your `_build_scatter` function should look like this:
>
>
>
>Save `window.py` and check that the UI has updated in Omniverse.
>
>This is what your new UI should look like:
>
>
>
>Check that it is working by setting new parameters for scale and object count then click `Scatter Prim A`.
>
></details>
<br>
>### <span>⛔</span> Stop here and wait to move on to Section III
<br>
## Section III
<video width="560" height="315" controls>
<source src="https://d36m44n9vdbmda.cloudfront.net/assets/x-ov-05-v1/buildUISection3.mp4" type="video/mp4">
</video>
### Step 9: Make your scene
#### <b>Step 9.1: Play with the Parameters</b>
Scatter your prims using various object and distance parameters along the X, Y, and Z axis.
#### <b>Step 9.2: Randomize your Parameters</b>
Scatter your prims again changing the `Random` parameters along the different axis.
What does Random do?
The `Random` parameter in `Scatter Tool` is a scalar factor that multiples against a random number and is then added to the uniform distribution for each object.
For example: If the `Distance` parameter is set to 20, each other be would distanced at 0, 20, 40, etc. If you add a `Random` parameter of 15 then it turns into 0 = (15 * random_number_gen), 20 + (15 * random_number_gen), etc.
>:bulb:Press play when you are finished
>
>
>#### <span>🧠</span><b>Challenge Step 10: How many marbles can you get in the jars and bowls?</b>
>
><i>All Challenges in this workshop are optional</i>
>
>How can you use the scatter tool to drop as many marbles into the jars and bowls?
>
><details>
><summary>Click here for a suggestion</summary>
>
>Similar to Step 7.2, scatter a Prim in a smaller distance and higher object count to create a large stack of prims then move over a jar or bowl before pressing play. Then watch them all fall!
>
>
>
></details>
<br>
## Congratulations!
You have completed this workshop! We hope you have enjoyed learning and playing in Omniverse!
[Join us on Discord to extend the conversation!](https://discord.com/invite/nvidiaomniverse)
| 19,036 | Markdown | 35.12334 | 235 | 0.718061 |
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.custom_ui/Workshop/CN_UI_Workshop.md |

# NVIDIA OMNIVERSE
# 通过 NVIDIA Omniverse 为 3D 工具构建漂亮的自定义 UI 界面
亲自试用 NVIDIA Omniverse 套件中的 Omni.ui 工具及框架套件,深入了解其强大功能,从而成为用户界面大师。在本培训中,您将使用 Python 脚本在 Omniverse 中为工作流构建自定义用户界面。
# 学习目标
- 启用扩展程序
- 使用 omni.ui 构建用户界面
- 创建列和行
- 创建按钮
<video width="560" height="315" controls>
<source src="https://dli-lms.s3.amazonaws.com/assets/x-ov-05-v1-zh/BuildUIIntro_CN_v1.mp4" type="video/mp4">
</video>
# Omni.ui_Window Scatter
## 第 I 部分
<video width="560" height="315" controls>
<source src="https://dli-lms.s3.amazonaws.com/assets/x-ov-05-v1-zh/BuildUISection1_CN_v1.mp4" type="video/mp4">
</video>
### <b>第 1 步:打开 Workshop Stage</b>
#### <b>第 1.1 步:从下面提供的链接下载 Stage</b>
[Stage的下载链接](https://dli-lms.s3.amazonaws.com/assets/x-ov-05-v1/Stage.zip)
#### <b>第 1.2 步:使用 “Extract All...”(提取所有文件...)解压 Stage</b>
此操作会创建一个名为 `Stage` 的解压文件夹。
#### <b>第 1.3 步:在 Omniverse 中打开 Stage</b>
在 Omniverse Code 的 `Content`(内容)选项卡中,找到系统中存放 Stage 文件的位置。
(即 C:/Users/yourName/Downloads/Stage)
在 Omniverse Code 控制台底部的 `Content` (内容)选项卡中,**双击**中间窗格中的 `Stage.usd`,即可在视图区中打开该 Stage。
### <b> 第 2 步:安装 Scatter 工具扩展功能</b>
#### <b>第 2.1 步:打开`Extensions`(扩展功能)选项卡</b>
单击 `Extensions`(扩展功能)管理器选项卡
#### <b>第 2.2 步:对来自社区或第三方的扩展功能进行筛选</b>
选择 `Community/Third Party`(社区/第三方)选项卡
<br>

<br>
#### <b>第 2.3 步:搜索 Scatter 工具</b>
搜索 `Scatter Tool`(散布工具),然后单击 `Omni.UI Window Scatter`

<br>
#### <b>第 2.4 步:安装/启用扩展功能</b>
单击选中的扩展功能,然后在右侧控制台中单击 `Install`(安装)。安装后,启用该扩展功能。
<span>❗</span>您可能会收到一个警告,指明此扩展功能未经验证。安装此扩展功能是安全的。
<br>
启用此扩展功能后,屏幕上会显示 `Scatter Window`(散布窗口)。

<br>
#### <b>第 2.5 步:看到窗口了吗? 设置来源</b>
在 `Viewport`(视图区)部分的 `Stage Hierarchy`(Stage 层次结构)中选择一个 prim (基元),然后按此方式在`Scatter Window`(散布窗口)中设置基元的来源:在 `Scatter Window`(散布窗口)中,单击`Source`(资源)下的`S`按钮。
`Prim`(基元)是 primitive 的简写,它是 Omniverse 中的基本单元。在 `USD` 中导入或创建的任何对象都是一个基元(prim),例如照相机、声音、光线、网格等等。

<br>
#### <b>第 2.6 步:对基元执行散布操作</b>
在 X 轴上,以 30 为间距值散布 20 个对象。
在 Y 轴和 Z 轴上保留默认设置,然后单击 `Scatter Window`(散布窗口)底部的 `Scatter Prim A`(散布基元 A)。
此时,您的 Stage 应该与下面的示例相似:

><span>❓</span>您注意到了吗?
>- 基元散布操作将在 Stage 的原点 `[0,0,0]` 执行。您有什么方法可以解决这个问题?
>- 您可以在 `Source`(来源)部分设置多个基元,但是无法对多个基元单独执行散布操作。我们将在第 II 部分解决这个问题。
<br>
### <b>第 3 步:启用物理效果</b>
找到 `Play`(播放)按钮并启用物理效果,看看会发生什么!物理效果播放完毕后,请记得单击 `Stop`(停止)按钮。
<details>
<summary>单击此处,查看 Play(播放)按钮所在的位置。</summary>

</details>
<br>
### <b>第 4 步:撤消散布操作</b>
在 `Stage` 中找到 `Scatter01` 文件夹并用左键单击该文件夹,然后单击鼠标右键选择“Delete”(删除)或按下键盘上的 `delete` 键。
`Stage`是一个面板,在上面您可以看到当前 `USD` (Universal Scene Description) 中的所有素材。它会按层次顺序列出所有的基元。
><span>❗</span> 警告 <span>❗</span> 如果使用 `ctrl+z` 组合键,则会撤消最后 3 项散布操作。

<br>
>### <span>🧠</span><b>第 5 步(自我挑战):尽情想象用例</b>
><i>本培训中的所有自我挑战都是可选的。</i>
>
>思考此工具的 3 种使用方式。与同事进行头脑风暴,并思考如何将此工具应用于您所从事的行业!
<br>
>### <span>⛔</span> 建议在此处暂停,思考一下,再继续学习第 II 部分
<br>
## 第 II 部分
<video width="560" height="315" controls>
<source src="https://dli-lms.s3.amazonaws.com/assets/x-ov-05-v1-zh/BuildUIIntroSection2_CN_v1.mp4" type="video/mp4">
</video>
<video width="560" height="315" controls>
<source src="https://dli-lms.s3.amazonaws.com/assets/x-ov-05-v1-zh/BuildUISection2_CN_v1.mp4" type="video/mp4">
</video>
### <b> 第 6 步:向用户界面添加其他来源</b>
#### <b>第 6.1 步:打开 Visual Studio</b>
转至 `Extensions`(扩展功能)选项卡,然后单击 `Scatter Window`(散布窗口)扩展功能,以在右侧打开扩展功能的概览。单击文件夹图标旁边的 `VS Code` 图标:

<br>
#### <b>第 6.2 步:找到窗口脚本</b>
在以下位置找到本培训需要使用的文件:
`exts -> omni\example\ui_scatter_tool`
我们将使用
`window.py`
<br>

<br>
#### <b>第 6.3 步:找到模型</b>
在 `ScatterWindow` 类的顶部,找到 `Models`(模型)代码集。
此代码集定义了基元 A 的来源和散布属性。

<br>
#### <b>第 6.4 步:在模型代码集中添加基元模型 B</b>
在 `Models`(模型)代码集的 `self._scatter_prim_model_a` 下方,添加新基元 `prim model b` 的来源和散布属性,具体如下:
```python
self._source_prim_model_b = ui.SimpleStringModel()
self._scatter_prim_model_b = ui.SimpleStringModel()
```
><span>❗</span> 确保代码正确对齐。编辑后的 `Models` 部分将与以下示例类似:

<br>
#### <b>第 6.5 步:找到默认设置</b>
在 `Models`(模型)代码集下面,找到 `Defaults`(默认设置)代码集。
这是将要在 `Stage`中执行的散布操作的默认名称。

<br>
#### <b>第 6.6 步:为基元模型 B 添加默认设置</b>
在 `self._scatter_prim_model_a._as_string` 属性下方,为 `prim model b` 设置相同的属性,但是将其在场景中的路径定义为 `/World/Scatter02`。这将决定在 `Stage`中对基元 B 执行散布操作的默认位置。
```python
self._scatter_prim_model_b.as_string = "/World/Scatter02"
```
此时,您的 `Defaults`(默认设置)部分应该与下面的示例相似:

<br>
#### <b>第 6.7 步:找到 _build_source 函数</b>
在同一脚本中,找到 `_build_source` 函数。

此函数用于为 `Scatter Window`(散布窗口)中`Source`(来源)选项(即单击“S”按钮设置所选基元的功能)创建用户界面。
<br>
#### <b>第 6.8 步:为基元 B 添加来源用户界面</b>
在这个函数的底部,将下面的新 `ui.HStack` 添加到原有的基元 A 的 `ui.HStack` 下方。
```python
with ui.HStack():
ui.Label("Prim B", name="attribute_name", width=self.label_width)
ui.StringField(model=self._source_prim_model_b)
# Button that puts the selection to the string field
ui.Button(
" S ",
width=0,
height=0,
style={"margin": 0},
clicked_fn=lambda:self._on_get_selection(self._source_prim_model_b),
tooltip="Get From Selection",
)
```
此时,更新后的函数应该与下面的示例相似:

<br>
保存更改后的 `window.py` 脚本,然后查看`Scatter Window`(散布窗口)的用户界面是否相应更新。
## <span>🎉</span> 恭喜! <span>🎉</span>
您在 Omniverse 中创建了自己的第一个用户界面组件!

<br>
><span>❓</span> 如果用户界面没有更新或者 `Scatter Window`(散布窗口)消失了,请在控制台中检查代码是否有误。`Console`(控制台)选项卡位于此处:
>
>
<br>
><span>❗</span> 造成这些问题的一个常见错误是代码没有正确对齐。请检查代码缩进格式是否与第 6.8 步中的屏幕截图完全相同。
<br>
#### <b>第 6.9 步:找到 _build_scatter 函数</b>
在 `window.py` 中,找到 `_build_scatter` 函数。
此函数用于为 `Scatter Window`(散布窗口)中 `Source`(资源)下的散布组创建用户界面。

<br>
#### <b>第 6.10 步:为基元 B 添加散布工具用户界面</b>
使用如下代码,在 `Prim A Path` 行的下面,为 `Prim B Path` 创建新的 `ui.HStack`:
```python
with ui.HStack():
ui.Label("Prim B Path", name="attribute_name", width=self.label_width)
ui.StringField(model=self._scatter_prim_model_b)
```
此时,您的 `_build_scatter` 应该与下面的示例相似:

<br>
保存更改后的 `window.py` 脚本,然后查看 Omniverse 中的用户界面是否相应更新。
## <span>🌟</span> 太棒了! <span>🌟</span>
您又一次成功创建了用户界面!

<br>
#### <b>第 6.11 步:找到 _build_fn 函数</b>
在 `window.py`中,找到函数 `_build_fn`。
此函数用于构建整个 `Scatter Window`(散布窗口)的用户界面,它还会调用单击 `Scatter Prim`(散布基元)按钮时触发的函数。

<br>
#### <b>第 6.12 步:为基元 B 添加散布按钮</b>
在 `Prim A`(基元 A)的 `Go`(执行)按钮下面,创建这个新按钮。
```python
# “Go”(执行)按钮
ui.Button("Scatter Prim B", clicked_fn=lambda:self._on_scatter(self._source_prim_model_b, self._scatter_prim_model_b))
```
此时,您的 `_build_fn` 应该与下面的示例相似:

<br>
保存 `window.py`,然后查看 Omniverse 中的用户界面是否相应更新。
## <span>✨</span> 太赞了! <span>✨</span>
您创建了一个新按钮,做的好!

<br>
### <b> 第 7 步:设置基元 A 和基元 B 并执行散布操作</b>
#### <b>第 7.1 步:设置基元 A 和基元 B 的来源</b>
按照第 2.5 步的操作,为基元 A 和基元 B 设置来源。

<br>
在设置基元 B 时,务必使用与基元 A 不同的基元。
例如,将基元 A 设置为 “TwistMarble”,将基元 B 设置为 “GummyBear”。

<br>
#### <b>第 7.2 步:为 X 轴、Y 轴和 Z 轴设置参数</b>
将 X 轴的 “Object Count”(对象数量)和 “Distance”(距离)分别设置为 5 和 25。
将 Y 轴的 “Object Count”(对象数量)和 “Distance”(距离)分别设置为 4 和 25。
将 Z 轴的 “Object Count”(对象数量)和 “Distance”(距离)分别设置为 4 和 25。

<br>
#### <b>第 7.3 步:对基元 A 执行散布操作</b>
单击 `Scatter Prim A`(散布基元 A)按钮。
屏幕上将会显示一个由基元 A 组成的正方形,而且 `Stage` 里会出现一个名为 `Scatter01` 的文件夹。
选择该文件夹中的第一个基元,再<b>按住 Shift 键单击</b>该文件夹中的最后一个基元,以选择 `Scatter 01` 中的所有基元。然后在视图中,将基元方阵移动到大碗的上方。

<br>
#### <b>第 7.4 步:对基元 A 执行散布操作</b>
单击`Scatter Prim B`(散布基元 B)按钮。
屏幕上将会显示一个由基元 B 组成的正方形,而且 `Stage` 中会出现一个名为 `Scatter 02` 的文件夹。
将这些基元留在原位。

<br>
#### <b>第 7.5 步:按下 `Play`(播放)按钮</b>
按下 `Play`(播放)按钮,观看基元掉入碗和瓶中!
完成后,按下 `Stop`(停止)按钮。

<br>
>### <span>🧠</span><b>第 8 步(自我挑战):在用户界面中设置范围参数</b>
><i>本培训中的所有自我挑战都是可选的。</i>
>
>代码中已经包含了用于确定基元散布范围的函数,您能为它创建相应的用户界面吗?
>
><b>提示:</b>请在 `_build_scatter` 中进行构建。
>
>[您可以在此处搜索 omni.ui 文档。](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html#omni.ui.StringField)
>
><details>
><summary> 单击此处获取答案 </summary>
>
>### 第 8.1 步(自我挑战):为范围功能构建用户界面
><i>本培训中的所有自我挑战都是可选的</i>
>
>按照第 6.9 步的操作,在 `window.py` 中找到 `_build_scatter`。
>
>将下面几行用于范围功能的代码添加到函数底部:
>
>```python
> with ui.HStack():
> ui.Label("Scale", name="attribute_name", width=self.label_width)
> for field in zip(["X:", "Y:", "Z:"], self._scale_models):
> ui.Label(field[0], width=0, style={"margin": 3.0})
> ui.FloatField(model=field[1], height=0, style={"margin": 3.0})
>```
>
>此时,您的 `_build_scatter` 函数应该与下面的示例相似:
>
>
>
>保存 `window.py`,然后查看 Omniverse 中的用户界面是否相应更新。
>
>新用户界面应如下图所示:
>
>
>
>设置新的范围和对象数量参数,然后单击 `Scatter Prim A`(散布基元 A),看看是否有效。
>
></details>
<br>
>### <span>⛔</span> 建议在此处暂停,思考一下,再继续学习第 III 部分
<br>
## 第 III 部分
<video width="560" height="315" controls>
<source src="https://dli-lms.s3.amazonaws.com/assets/x-ov-05-v1-zh/BuildUISection3_CN_v1.mp4" type="video/mp4">
</video>
### <b> 第 9 步:制作您自己的场景</b>
#### <b>第 9.1 步:尝试不同的参数</b>
使用多组不同的 X 轴、Y 轴和 Z 轴对象数量和距离参数,对基元执行散布操作。
#### <b>第 9.2 步:使用随机参数</b>
更改各个轴的 `Random`(随机)参数值,然后再次对基元执行散布操作。
`Random`(随机)参数有什么作用?
在`Scatter Tool`(散布工具)中,`Random`(随机)参数是一个标量因子,系统会用它乘以一个随机值,并将计算结果添加到每个对象的均匀分布值上。
例如:如果 `Distance`(距离)参数设置为 20,每个对象将被分配 0、20、40...(以此类推)的距离值。如果添加一个 15 左右的`Random`(随机)参数 ,则各个对象的距离值会变为 0 + (15 * random_number_gen)、20 + (15 * random_number_gen) 等等。
>💡 完成设置后,按下`Play`(播放)按钮
>
>
>### <span>🧠</span><b>第 10 步(自我挑战):瓶和碗里会有多少块大理石?</b>
>
><i>本培训中的所有自我挑战都是可选的。</i>
>
>您如何使用缩放工具,让尽可能多的大理石掉落到瓶和碗里?
>
><details>
><summary>单击此处查看建议</summary>
>
>与第 7.2 步类似,在对基元执行散布操作时,只需使用较小的`Distance`(距离)值,并设置较大的`Object Count`(对象数量)值来创建大量基元,然后将其移动到瓶或碗的上方,再按下`Play`(播放)键,观看基元落下即可!
>
>
>
></details>
<br>
## 恭喜!
您已完成本培训!希望您在学习和使用 Omniverse 的过程中找到乐趣!
[欢迎在 Discord 上加入我们,进行更深入的交流!](https://discord.com/invite/nvidiaomniverse)
| 15,066 | Markdown | 27.482042 | 170 | 0.696668 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.