file_path
stringlengths
22
162
content
stringlengths
19
501k
size
int64
19
501k
lang
stringclasses
1 value
avg_line_length
float64
6.33
100
max_line_length
int64
18
935
alphanum_fraction
float64
0.34
0.93
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/visibility/show-hide-prim/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 Sdf def hide_prim(prim_path: str): """Hide a prim Args: prim_path (str, required): The prim path of the prim to hide """ set_prim_visibility_attribute(prim_path, "invisible") def show_prim(prim_path: str): """Show a prim Args: prim_path (str, required): The prim path of the prim to show """ set_prim_visibility_attribute(prim_path, "inherited") def set_prim_visibility_attribute(prim_path: str, value: str): """Set the prim visibility attribute at prim_path to value Args: prim_path (str, required): The path of the prim to modify value (str, required): The value of the visibility attribute """ # You can reference attributes using the path syntax by appending the # attribute name with a leading `.` prop_path = f"{prim_path}.visibility" omni.kit.commands.execute( "ChangeProperty", prop_path=Sdf.Path(prop_path), value=value, prev=None ) """ Full Usage """ # Path to a prim in the open stage prim_path = "/World/Cube" stage = omni.usd.get_context().get_stage() prim = stage.GetPrimAtPath(prim_path) assert prim.IsValid() # Manually confirm that the prim is not visible in the viewport after calling # hide_prim. You should comment out the below show_prim call and assert. hide_prim(prim_path) assert prim.GetAttribute("visibility").Get() == "invisible" # Manually confirm that the prim is visible in the viewport after calling # show_prim show_prim(prim_path) assert prim.GetAttribute("visibility").Get() == "inherited"
1,738
Python
27.508196
98
0.698504
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/layers/add-sublayer/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 add_sub_layer(sub_layer_path: str, root_layer) -> Sdf.Layer: sub_layer: Sdf.Layer = Sdf.Layer.CreateNew(sub_layer_path) # You can use standard python list.insert to add the subLayer to any position in the list root_layer.subLayerPaths.append(sub_layer.identifier) return sub_layer ############# # Full Usage ############# from pxr import Usd # Get the root layer stage: Usd.Stage = Usd.Stage.CreateInMemory() root_layer: Sdf.Layer = stage.GetRootLayer() # Add the sub layer to the root layer sub_layer = add_sub_layer(r"C:/path/to/sublayer.usd", root_layer) usda = stage.GetRootLayer().ExportToString() print(usda) # Check to see if the sublayer is loaded loaded_layers = root_layer.GetLoadedLayers() assert sub_layer in loaded_layers
921
Python
28.741935
98
0.726384
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/layers/add-sublayer/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("CreateSublayer", layer_identifier=stage.GetRootLayer().identifier, # This example prepends to the subLayers list sublayer_position=0, new_layer_path=r"C:/path/to/sublayer.usd", transfer_root_content=False, # When True, it will create the layer file for you too. create_or_insert=True )
506
Python
30.687498
98
0.741107
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/references-payloads/create-payload/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 Usd, Sdf def create_payload(usd_context: omni.usd.UsdContext, path_to: Sdf.Path, asset_path: str, prim_path: Sdf.Path) -> Usd.Prim: omni.kit.commands.execute("CreatePayload", usd_context=usd_context, path_to=path_to, # Prim path for where to create the prim with the payload asset_path=asset_path, # The file path to the payload USD. Relative paths are accepted too. prim_path=prim_path # OPTIONAL: Prim path to a prim in the payloaded USD, if not provided the default prim is used ) return usd_context.get_stage().GetPrimAtPath(path_to) ############# # Full Usage ############# # Get the USD context from kit context: omni.usd.UsdContext = omni.usd.get_context() # Create and add external payload to specific prim payload_prim: Usd.Prim = create_payload(context, Sdf.Path("/World/payload_prim"), "C:/path/to/file.usd", Sdf.Path("/World/some/target")) # Get the existing USD stage from kit stage: Usd.Stage = context.get_stage() usda = stage.GetRootLayer().ExportToString() print(usda) # Check that the payload prims were created assert payload_prim.IsValid() assert payload_prim.GetPrimStack()[0].payloadList.prependedItems[0] == Sdf.Payload(assetPath="file:/C:/path/to/file.usd", primPath=Sdf.Path("/World/some/target"))
1,469
Python
39.833332
162
0.721579
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/references-payloads/add-payload/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 add_payload(prim: Usd.Prim, payload_asset_path: str, payload_target_path: Sdf.Path) -> None: payloads: Usd.Payloads = prim.GetPayloads() payloads.AddPayload( assetPath=payload_asset_path, primPath=payload_target_path # OPTIONAL: Payload a specific target prim. Otherwise, uses the payloadd layer's defaultPrim. ) ############# # Full Usage ############# from pxr import UsdGeom # Create new USD stage for this sample stage: Usd.Stage = Usd.Stage.CreateInMemory() # Create and define default prim default_prim = UsdGeom.Xform.Define(stage, Sdf.Path("/World")) stage.SetDefaultPrim(default_prim.GetPrim()) # Create an xform which should hold all payloads in this sample payload_prim: Usd.Prim = UsdGeom.Xform.Define(stage, Sdf.Path("/World/payload_prim")).GetPrim() # Add an external payload add_payload(payload_prim, "C:/path/to/file.usd", Sdf.Path("/World/some/target")) # Add other external payload to default prim add_payload(payload_prim, "C:/path/to/other/file.usd", Sdf.Path.emptyPath) usda = stage.GetRootLayer().ExportToString() print(usda) # Get a list of all prepended payloads payloads = [] for prim_spec in payload_prim.GetPrimStack(): payloads.extend(prim_spec.payloadList.prependedItems) # Check that the payload prim was created and that the payloads are correct assert payload_prim.IsValid() assert payloads[0] == Sdf.Payload(assetPath="C:/path/to/file.usd", primPath=Sdf.Path("/World/some/target")) assert payloads[1] == Sdf.Payload(assetPath="C:/path/to/other/file.usd")
1,698
Python
35.148935
130
0.73616
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/references-payloads/add-payload/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 Usd, Sdf def add_payload(prim: Usd.Prim, payload_asset_path: str, payload_target_path: Sdf.Path) -> None: omni.kit.commands.execute("AddPayload", stage=prim.GetStage(), prim_path = prim.GetPath(), # an existing prim to add the payload to. payload=Sdf.Payload( assetPath = payload_asset_path, primPath = payload_target_path ) ) ############# # Full Usage ############# from pxr import UsdGeom import omni.usd # Create new USD stage for this sample in OV context: omni.usd.UsdContext = omni.usd.get_context() success: bool = context.new_stage() stage: Usd.Stage = context.get_stage() # Create and define default prim, so this file can be easily payloaderenced again default_prim = UsdGeom.Xform.Define(stage, Sdf.Path("/World")) stage.SetDefaultPrim(default_prim.GetPrim()) # Create a xform which should hold all payloads in this sample payload_prim: Usd.Prim = UsdGeom.Xform.Define(stage, Sdf.Path("/World/payload_prim")).GetPrim() # Add an payload specific prim add_payload(payload_prim, "C:/path/to/file.usd", Sdf.Path("/World/some/target")) # Add other payload to default prim add_payload(payload_prim, "C:/path/to/other/file.usd", Sdf.Path.emptyPath) usda = stage.GetRootLayer().ExportToString() print(usda) # Get a list of all prepended payloads payloads = [] for prim_spec in payload_prim.GetPrimStack(): payloads.extend(prim_spec.payloadList.prependedItems) # Check that the payload prim was created and that the payloads are correct assert payload_prim.IsValid() assert payloads[0] == Sdf.Payload(assetPath="C:/path/to/file.usd", primPath=Sdf.Path("/World/some/target")) assert payloads[1] == Sdf.Payload(assetPath="C:/path/to/other/file.usd")
1,908
Python
35.018867
107
0.719078
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/references-payloads/add-reference/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 add_int_reference(prim: Usd.Prim, ref_target_path: Sdf.Path) -> None: references: Usd.References = prim.GetReferences() references.AddInternalReference(ref_target_path) def add_ext_reference(prim: Usd.Prim, ref_asset_path: str, ref_target_path: Sdf.Path) -> None: references: Usd.References = prim.GetReferences() references.AddReference( assetPath=ref_asset_path, primPath=ref_target_path # OPTIONAL: Reference a specific target prim. Otherwise, uses the referenced layer's defaultPrim. ) ############# # Full Usage ############# from pxr import UsdGeom # Create new USD stage for this sample stage: Usd.Stage = Usd.Stage.CreateInMemory() # Create and define default prim, so this file can be easily referenced again default_prim = UsdGeom.Xform.Define(stage, Sdf.Path("/World")) stage.SetDefaultPrim(default_prim.GetPrim()) # Create an xform which should hold all references in this sample ref_prim: Usd.Prim = UsdGeom.Xform.Define(stage, Sdf.Path("/World/ref_prim")).GetPrim() # Add an internal reference intern_target_path: Sdf.Path = Sdf.Path("/World/intern_target") target_prim: Usd.Prim = UsdGeom.Xform.Define(stage, intern_target_path).GetPrim() add_int_reference(ref_prim, intern_target_path) # Add an external reference to specific prim add_ext_reference(ref_prim, "C:/path/to/file.usd", Sdf.Path("/World/some/target")) # Add other external reference to default prim add_ext_reference(ref_prim, "C:/path/to/other/file.usd", Sdf.Path.emptyPath) usda = stage.GetRootLayer().ExportToString() print(usda) # Get a list of all prepended references references = [] for prim_spec in ref_prim.GetPrimStack(): references.extend(prim_spec.referenceList.prependedItems) # Check that the reference prim was created and that the references are correct assert ref_prim.IsValid() assert references[0] == Sdf.Reference(primPath=intern_target_path) assert references[1] == Sdf.Reference(assetPath="C:/path/to/file.usd", primPath=Sdf.Path("/World/some/target")) assert references[2] == Sdf.Reference(assetPath="C:/path/to/other/file.usd")
2,250
Python
38.491227
130
0.744
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/variant-sets/author-variant-data/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 shading_varset = prim.GetVariantSets().GetVariantSet("shading") selected_variant = shading_varset.GetVariantSelection() shading_varset.SetVariantSelection(variant_name) with shading_varset.GetVariantEditContext(): # Specs authored within this context are authored just for the variant. ... # Set the variant selection back to the previously selected variant. # Alternatively, you can use Usd.VariantSet.ClearVariantSelection() # if you know that there isn't a variant selection in the current EditTarget. if selected_variant: shading_varset.SetVariantSelection(selected_variant)
731
Python
42.058821
98
0.79617
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/variant-sets/select-variant/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 select_variant_from_varaint_set(prim: Usd.Prim, variant_set_name: str, variant_name: str) -> None: variant_set = prim.GetVariantSets().GetVariantSet(variant_set_name) variant_set.SetVariantSelection(variant_name) ############# # 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 the Variant Set shading_varset: Usd.VariantSet = default_prim.GetVariantSets().AddVariantSet("shading") # Add Variants to the Variant Set shading_varset.AddVariant("cell_shading") shading_varset.AddVariant("realistic") select_variant_from_varaint_set(default_prim, "shading", "realistic") usda = stage.GetRootLayer().ExportToString() print(usda) assert default_prim.GetVariantSets().GetVariantSet("shading").GetVariantSelection() == "realistic"
1,150
Python
33.878787
102
0.753043
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/variant-sets/create-variant-set/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 create_variant_set(prim: Usd.Prim, variant_set_name: str, variants: list) -> Usd.VariantSet: variant_set = prim.GetVariantSets().AddVariantSet(variant_set_name) for variant in variants: variant_set.AddVariant(variant) return variant_set ############# # 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 the variant set and add your variants to it. variants = ["red", "blue", "green"] shading_varset: Usd.VariantSet = create_variant_set(default_prim, "shading", variants) usda = stage.GetRootLayer().ExportToString() print(usda) assert default_prim.GetVariantSets().HasVariantSet("shading")
1,027
Python
33.266666
98
0.730282
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/specializes/add-specialize/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_specialize_to(base_prim: Usd.Prim, specializes: Usd.Specializes) -> bool: return specializes.AddSpecialize(base_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) prim: Usd.Prim = UsdGeom.Xform.Define(stage, default_prim.GetPath().AppendPath("prim")).GetPrim() base: Usd.Prim = UsdGeom.Xform.Define(stage, default_prim.GetPath().AppendPath("base")).GetPrim() specializes: Usd.Specializes = prim.GetSpecializes() added_successfully = add_specialize_to(base, specializes) usda = stage.GetRootLayer().ExportToString() print(usda) assert added_successfully
999
Python
34.714284
98
0.746747
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/prims/select-prim-by-path/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() # The second arg is unused. Any boolean can be used. ctx.get_selection().set_selected_prim_paths([prim_path], True)
328
Python
35.555552
98
0.75
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/prims/select-prim-by-path/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 prim_path = "/World/My/Prim" ctx = omni.usd.get_context() old_selection = ctx.get_selection().get_selected_prim_paths() omni.kit.commands.execute('SelectPrimsCommand', old_selected_paths=old_selection, new_selected_paths=[prim_path], expand_in_stage=True) #DEPRECATED: Used only for backwards compatibility.
500
Python
34.785712
98
0.76
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/prims/check-prim-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 def check_prim_exists(prim: Usd.Prim) -> bool: if prim.IsValid(): return True return False ############# # 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 one prim and cube: Usd.Prim = UsdGeom.Cube.Define(stage, Sdf.Path("/World/Cube")).GetPrim() empty_prim = Usd.Prim() usda = stage.GetRootLayer().ExportToString() print(usda) # Check if prims exist assert check_prim_exists(default_prim) assert check_prim_exists(cube) assert not check_prim_exists(empty_prim)
893
Python
26.937499
98
0.718925
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-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/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/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_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/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/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/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/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/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/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-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_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/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_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/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/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_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/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/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-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-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/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/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-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/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_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/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_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/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/omni/example/custom_ui/style.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["scatter_window_style"] from omni.ui import color as cl from omni.ui import constant as fl from omni.ui import url import omni.kit.app import omni.ui as ui import pathlib EXTENSION_FOLDER_PATH = pathlib.Path( omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) ) # Pre-defined constants. It's possible to change them runtime. cl.scatter_window_hovered = cl("#2b2e2e") cl.scatter_window_text = cl("#9e9e9e") fl.scatter_window_attr_hspacing = 10 fl.scatter_window_attr_spacing = 1 fl.scatter_window_group_spacing = 2 # The main style dict scatter_window_style = { "Label::attribute_name": { "color": cl.scatter_window_text, "margin_height": fl.scatter_window_attr_spacing, "margin_width": fl.scatter_window_attr_hspacing, }, "CollapsableFrame::group": {"margin_height": fl.scatter_window_group_spacing}, "CollapsableFrame::group:hovered": {"secondary_color": cl.scatter_window_hovered}, }
1,408
Python
35.128204
89
0.740767
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.custom_ui/omni/example/custom_ui/commands.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ScatterCreatePointInstancerCommand"] from pxr import Gf from pxr import Sdf from pxr import Usd from pxr import UsdGeom from typing import List from typing import Optional from typing import Tuple import omni.kit.commands import omni.usd.commands class ScatterCreatePointInstancerCommand(omni.kit.commands.Command, omni.usd.commands.stage_helper.UsdStageHelper): """ Create PointInstancer undoable **Command**. ### Arguments: `path_to: str` The path for the new prims `transforms: List` Pairs containing transform matrices and ids to apply to new objects `prim_names: List[str]` Prims to duplicate """ def __init__( self, path_to: str, transforms: List[Tuple[Gf.Matrix4d, int]], prim_names: List[str], stage: Optional[Usd.Stage] = None, context_name: Optional[str] = None, ): omni.usd.commands.stage_helper.UsdStageHelper.__init__(self, stage, context_name) self._path_to = path_to # We have it like [(tr, id), (tr, id), ...] # It will be transformaed to [[tr, tr, ...], [id, id, ...]] unzipped = list(zip(*transforms)) self._positions = [m.ExtractTranslation() for m in unzipped[0]] self._proto_indices = unzipped[1] self._prim_names = prim_names.copy() def do(self): stage = self._get_stage() # Set up PointInstancer instancer = UsdGeom.PointInstancer.Define(stage, Sdf.Path(self._path_to)) attr = instancer.CreatePrototypesRel() for name in self._prim_names: attr.AddTarget(Sdf.Path(name)) instancer.CreatePositionsAttr().Set(self._positions) instancer.CreateProtoIndicesAttr().Set(self._proto_indices) def undo(self): delete_cmd = omni.usd.commands.DeletePrimsCommand([self._path_to]) delete_cmd.do()
2,346
Python
32.056338
115
0.663257
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.custom_ui/omni/example/custom_ui/scatter.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["scatter"] from typing import List, Optional import random from pxr import Gf def scatter( count: List[int], distance: List[float], randomization: List[float], id_count: int = 1, seed: Optional[int] = None ): """ Returns generator with pairs containing transform matrices and ids to arrange multiple objects. ### Arguments: `count: List[int]` Number of matrices to generage per axis `distance: List[float]` The distance between objects per axis `randomization: List[float]` Random distance per axis `id_count: int` Count of differrent id `seed: int` If seed is omitted or None, the current system time is used. If seed is an int, it is used directly. """ # Initialize the random number generator. random.seed(seed) for i in range(count[0]): x = (i - 0.5 * (count[0] - 1)) * distance[0] for j in range(count[1]): y = (j - 0.5 * (count[1] - 1)) * distance[1] for k in range(count[2]): z = (k - 0.5 * (count[2] - 1)) * distance[2] # Create a matrix with position randomization result = Gf.Matrix4d(1) result.SetTranslate( Gf.Vec3d( x + random.random() * randomization[0], y + random.random() * randomization[1], z + random.random() * randomization[2], ) ) id = int(random.random() * id_count) yield (result, id)
2,076
Python
30
118
0.577553
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.custom_ui/omni/example/custom_ui/__init__.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ScatterCreatePointInstancerCommand", "ScatterWindowExtension", "ScatterWindow"] from .commands import ScatterCreatePointInstancerCommand from .extension import ScatterWindowExtension from .window import ScatterWindow
663
Python
46.428568
91
0.820513
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.custom_ui/omni/example/custom_ui/combo_box_model.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ComboBoxModel"] from typing import Optional import omni.ui as ui class ListItem(ui.AbstractItem): """Single item of the model""" def __init__(self, text): super().__init__() self.name_model = ui.SimpleStringModel(text) def __repr__(self): return f'"{self.name_model.as_string}"' @property def as_string(self): """Return the string of the name model""" return self.name_model.as_string class ComboBoxModel(ui.AbstractItemModel): """ Represents the model for lists. It's very easy to initialize it with any string list: string_list = ["Hello", "World"] model = ComboBoxModel(*string_list) ui.ComboBox(model) """ def __init__(self, *args, default=0): super().__init__() self._children = [ListItem(t) for t in args] self._default = ui.SimpleIntModel() self._default.as_int = default # Update the combo box when default is changed self._default.add_value_changed_fn(lambda _: self._item_changed(None)) def get_item_children(self, item): """Returns all the children when the widget asks it.""" if item is not None: # Since we are doing a flat list, we return the children of root only. # If it's not root we return. return [] return self._children def get_item_value_model_count(self, item): """The number of columns""" return 1 def get_item_value_model(self, item: Optional[ListItem], column_id): """ Return value model. It's the object that tracks the specific value. In our case we use ui.SimpleStringModel. """ if item is None: return self._default return item.name_model def get_current_item(self) -> ListItem: """Returns the currently selected item in ComboBox""" return self._children[self._default.as_int]
2,391
Python
30.893333
82
0.637808
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.custom_ui/omni/example/custom_ui/utils.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["get_selection", "duplicate_prims"] from typing import List import omni.usd import omni.kit.commands from pxr import Sdf from pxr import Gf def get_selection() -> List[str]: """Get the list of currently selected prims""" return omni.usd.get_context().get_selection().get_selected_prim_paths() def duplicate_prims(transforms: List = [], prim_names: List[str] = [], target_path: str = "", mode: str = "Copy", scale: List[float] = [1,1,1]): """ Returns generator with pairs containing transform matrices and ids to arrange multiple objects. ### Arguments: `transforms: List` Pairs containing transform matrices and ids to apply to new objects `prim_names: List[str]` Prims to duplicate `target_path: str` The parent for the new prims `mode: str` "Reference": Create a reference of the given prim path "Copy": Create a copy of the given prim path "PointInstancer": Create a PointInstancer """ if mode == "PointInstancer": omni.kit.commands.execute( "ScatterCreatePointInstancer", path_to=target_path, transforms=transforms, prim_names=prim_names, ) return usd_context = omni.usd.get_context() # Call commands in a single undo group. So the user will undo everything # with a single press of ctrl-z with omni.kit.undo.group(): # Create a group omni.kit.commands.execute("CreatePrim", prim_path=target_path, prim_type="Scope") for i, matrix in enumerate(transforms): id = matrix[1] matrix = matrix[0] path_from = Sdf.Path(prim_names[id]) path_to = Sdf.Path(target_path).AppendChild(f"{path_from.name}{i}") # Create a new prim if mode == "Copy": omni.kit.commands.execute("CopyPrims", paths_from=[path_from.pathString], paths_to=[path_to.pathString]) elif mode == "Reference": omni.kit.commands.execute( "CreateReference", usd_context=usd_context, prim_path=path_from, path_to=path_to, asset_path="" ) else: continue stage = usd_context.get_stage() prim = stage.GetPrimAtPath(path_to) trans_matrix = matrix[3] new_transform = Gf.Vec3d(trans_matrix[0], trans_matrix[1], trans_matrix[2]) omni.kit.commands.execute("TransformPrimSRT", path=path_to, new_translation=new_transform, new_scale=scale)
3,044
Python
34.823529
144
0.625493
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.custom_ui/omni/example/custom_ui/window.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ScatterWindow"] import omni.ui as ui from .style import scatter_window_style from .utils import get_selection from .combo_box_model import ComboBoxModel from .scatter import scatter from .utils import duplicate_prims LABEL_WIDTH = 120 SPACING = 4 class ScatterWindow(ui.Window): """The class that represents the window""" def __init__(self, title: str, delegate=None, **kwargs): self.__label_width = LABEL_WIDTH super().__init__(title, **kwargs) # Models self._source_prim_model_a = ui.SimpleStringModel() self._scatter_prim_model_a = ui.SimpleStringModel() ## Step 6.4: Add Prim Model B Here ## self._scatter_type_model = ComboBoxModel("Reference", "Copy", "PointInstancer") self._scatter_seed_model = ui.SimpleIntModel() self._scatter_count_models = [ui.SimpleIntModel(), ui.SimpleIntModel(), ui.SimpleIntModel()] self._scatter_distance_models = [ui.SimpleFloatModel(), ui.SimpleFloatModel(), ui.SimpleFloatModel()] self._scatter_random_models = [ui.SimpleFloatModel(), ui.SimpleFloatModel(), ui.SimpleFloatModel()] self._scale_models = [ui.SimpleFloatModel(), ui.SimpleFloatModel(), ui.SimpleFloatModel()] # Defaults self._scatter_prim_model_a.as_string = "/World/Scatter01" ## Step 6.6: Add Prim Model B Here ## self._scatter_count_models[0].as_int = 50 self._scatter_count_models[1].as_int = 1 self._scatter_count_models[2].as_int = 1 self._scatter_distance_models[0].as_float = 10 self._scatter_distance_models[1].as_float = 10 self._scatter_distance_models[2].as_float = 10 self._scale_models[0].as_float = 1 self._scale_models[1].as_float = 1 self._scale_models[2].as_float = 1 # Apply the style to all the widgets of this window self.frame.style = scatter_window_style # Set the function that is called to build widgets when the window is # visible self.frame.set_build_fn(self._build_fn) def destroy(self): # It will destroy all the children super().destroy() @property def label_width(self): """The width of the attribute label""" return self.__label_width @label_width.setter def label_width(self, value): """The width of the attribute label""" self.__label_width = value self.frame.rebuild() def _on_get_selection(self, model): """Called when the user presses the "Get From Selection" button""" model.as_string = ", ".join(get_selection()) def _on_scatter(self, source_model, scatter_model): """Called when the user presses the "Scatter Prim" button""" prim_names = [i.strip() for i in source_model.as_string.split(",")] if not prim_names: prim_names = get_selection() if not prim_names: return transforms = scatter( count=[m.as_int for m in self._scatter_count_models], distance=[m.as_float for m in self._scatter_distance_models], randomization=[m.as_float for m in self._scatter_random_models], id_count=len(prim_names), seed=self._scatter_seed_model.as_int, ) duplicate_prims( transforms=transforms, prim_names=prim_names, target_path=scatter_model.as_string, mode=self._scatter_type_model.get_current_item().as_string, scale=[self._scale_models[0].as_float, self._scale_models[1].as_float, self._scale_models[2].as_float] ) def _build_source(self): """Build the widgets of the "Source" group""" with ui.CollapsableFrame("Source", name="group"): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Prim A", name="attribute_name", width=self.label_width) ui.StringField(model=self._source_prim_model_a) # 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_a), tooltip="Get From Selection", ) ## Step 6.8: Add New HStack Below ## def _build_scatter(self): """Build the widgets of the "Scatter" group""" with ui.CollapsableFrame("Scatter", name="group"): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Prim A Path", name="attribute_name", width=self.label_width) ui.StringField(model=self._scatter_prim_model_a) ## Step 6.10: Add new ui.HStack Below ## with ui.HStack(): ui.Label("Prim Type", name="attribute_name", width=self.label_width) ui.ComboBox(self._scatter_type_model) with ui.HStack(): ui.Label("Seed", name="attribute_name", width=self.label_width) ui.IntDrag(model=self._scatter_seed_model, min=0, max=10000) def _build_axis(self, axis_id, axis_name): """Build the widgets of the "X" or "Y" or "Z" group""" with ui.CollapsableFrame(axis_name, name="group"): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Object Count", name="attribute_name", width=self.label_width) ui.IntDrag(model=self._scatter_count_models[axis_id], min=1, max=100) with ui.HStack(): ui.Label("Distance", name="attribute_name", width=self.label_width) ui.FloatDrag(self._scatter_distance_models[axis_id], min=0, max=10000) with ui.HStack(): ui.Label("Random", name="attribute_name", width=self.label_width) ui.FloatDrag(self._scatter_random_models[axis_id], min=0, max=10000) def _build_fn(self): """ The method that is called to build all the UI once the window is visible. """ with ui.ScrollingFrame(): with ui.VStack(height=0): self._build_source() self._build_scatter() self._build_axis(0, "X Axis") self._build_axis(1, "Y Axis") self._build_axis(2, "Z Axis") # The Go button ui.Button("Scatter Prim A", clicked_fn=lambda:self._on_scatter(self._source_prim_model_a, self._scatter_prim_model_a)) ## Step 6.12: Add Go Button Below ##
7,416
Python
43.148809
134
0.572816
NVIDIA-Omniverse/deep-dive-into-microservices/tools/scripts/link_app.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import argparse import os import packmanapi if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher.") parser.add_argument( "path", help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'", ) args = parser.parse_args() if not os.path.exists(args.path): print(f"Provided path doesn't exist: \"{args.path}\"") else: SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__)) packmanapi.link(f"{SCRIPT_ROOT}/../../app", args.path)
1,062
Python
36.964284
124
0.711864
NVIDIA-Omniverse/deep-dive-into-microservices/exts/omni.services.assets.convert/omni/services/assets/convert/extension.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import asyncio import carb import omni.ext from omni.services.core import main from omni.services.facilities.database.manager import DatabaseManagerFacility from .services import router class AssetConversionServiceExtension(omni.ext.IExt): """Asset conversion extension.""" def on_startup(self, ext_id) -> None: ext_name = ext_id.split("-")[0] url_prefix = carb.settings.get_settings_interface().get(f"exts/{ext_name}/url_prefix") # Setup the database facility: self._database_facility = DatabaseManagerFacility(ext_name=ext_name) self._db_ready = asyncio.ensure_future(self._initialize_db()) # Register the database facility with the router, so it can be used by service endpoints: router.register_facility("db_manager", self._database_facility) main.register_router(router=router, prefix=url_prefix, tags=["Assets"]) main.get_app().title = "Omniverse Farm" main.get_app().description = "A microservice-based framework for distributed task execution." tags_metadata = { "name": "Assets", "description": "Manage assets submitted to the Queue." } if not main.get_app().openapi_tags: main.get_app().openapi_tags = [] main.get_app().openapi_tags.append(tags_metadata) def on_shutdown(self) -> None: if self._db_ready: self._db_ready.cancel() self._db_ready = None main.deregister_router(router=router) async def _initialize_db(self) -> None: """Initialize the database to be used to store asset conversion results.""" async with self._database_facility.get("asset-conversions") as db: table_columns = [ "id INTEGER PRIMARY KEY AUTOINCREMENT", "source_asset VARCHAR(256) NOT NULL", "destination_asset VARCHAR(256) NOT NULL", "success BOOLEAN NOT NULL", ] await db.execute(query=f"CREATE TABLE IF NOT EXISTS AssetConversions ({', '.join(table_columns)});")
2,511
Python
39.516128
112
0.66826
NVIDIA-Omniverse/deep-dive-into-microservices/exts/omni.services.assets.convert/omni/services/assets/convert/services/convert.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. from typing import Dict from pydantic import BaseModel, Field from omni.services.client import AsyncClient from omni.services.core import routers import omni.usd router = routers.ServiceAPIRouter() class ConversionRequestModel(BaseModel): """Model describing the request to convert a given asset to a different format.""" import_path: str = Field( ..., title="Path of the source asset to be converted", description="Location where the asset to convert can be located by an Agent.", ) output_path: str = Field( ..., title="Output path where to store the converted asset", description="Location where to place the converted asset.", ) converter_settings: Dict = Field( {}, title="Converter settings", description="Settings to provide to the Kit Asset Converter extension in order to perform the conversion.", ) class ConversionResponseModel(BaseModel): """Model describing the response to the request to convert a given USD asset.""" status: str = Field( ..., title="Conversion status", description="Status of the conversion of the given asset.", ) @router.post( path="/convert", summary="Convert assets to a different format", description="Convert the given asset into a different format.", response_model=ConversionResponseModel, ) @router.post("/convert") async def run( req: ConversionRequestModel, db_manager=router.get_facility("db_manager"), ) -> ConversionResponseModel: # Convert the given asset: task = omni.kit.asset_converter.get_instance().create_converter_task( import_path=req.import_path, output_path=req.output_path, progress_callback=lambda current, total: print(f"Conversion progress: {current/total*100.0}%"), asset_converter_context=req.converter_settings,) success = await task.wait_until_finished() if not success: detailed_status_code = task.get_status() detailed_status_error_string = task.get_detailed_error() raise Exception(f"Failed to convert \"{req.import_path}\". Error: {detailed_status_code}, {detailed_status_error_string}") # Execute the validation service exposed by the "omni.service.assets.validate" extension: client = AsyncClient("local://") validation_result = await client.assets.validate( scene_path=req.import_path, expected_camera_count=5, ) # Record the result of the validation in the database: query = """ INSERT INTO AssetConversions (source_asset, destination_asset, success) VALUES (:source_asset, :destination_asset, :success) """ values = { "source_asset": req.import_path, "destination_asset": req.output_path, "success": 1 if validation_result["success"] else 0, } async with db_manager.get("asset-conversions") as db: await db.execute(query=query, values=values) return ConversionResponseModel(status="finished")
3,449
Python
35.315789
130
0.696724
NVIDIA-Omniverse/deep-dive-into-microservices/exts/omni.services.assets.validate/omni/services/assets/validate/extension.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import carb import omni.ext from omni.services.core import main from .services import router class AssetValidationServiceExtension(omni.ext.IExt): """Asset validation extension.""" def on_startup(self, ext_id) -> None: ext_name = ext_id.split("-")[0] url_prefix = carb.settings.get_settings_interface().get(f"exts/{ext_name}/url_prefix") main.register_router(router=router, prefix=url_prefix, tags=["Assets"]) main.get_app().title = "Omniverse Farm" main.get_app().description = "A microservice-based framework for distributed task execution." tags_metadata = { "name": "Assets", "description": "Manage assets submitted to the Queue." } if not main.get_app().openapi_tags: main.get_app().openapi_tags = [] main.get_app().openapi_tags.append(tags_metadata) def on_shutdown(self) -> None: main.deregister_router(router=router)
1,388
Python
35.552631
101
0.693804
NVIDIA-Omniverse/deep-dive-into-microservices/exts/omni.services.assets.validate/omni/services/assets/validate/services/validate.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import asyncio from typing import List, Optional from pxr import UsdGeom from pydantic import BaseModel, Field import carb from omni.services.core import routers import omni.usd router = routers.ServiceAPIRouter() class ValidationRequestModel(BaseModel): """Model describing the request to validate a given USD stage.""" scene_path: str = Field( ..., title="USD scene path", description="Full path to the USD scene to validate, hosted on a location accessible to the Agent.", ) expected_camera_count: int = Field( ..., title="Expected number of cameras", description="Expected number of cameras to find in the scene.", ) class ValidationResponsetModel(BaseModel): """Model describing the response to the request to validate a given USD stage.""" success: bool = Field( ..., title="Success", description="Flag indicating if the validation was successful.", ) actual_camera_count: int = Field( ..., title="Number of cameras found", description="Actual number of cameras found in the scene.", ) async def load_usd_stage(usd_file: str, stage_load_timeout: Optional[float] = None) -> bool: """ Load the given USD stage into the Kit runtime. Args: usd_file (str): Location of the stage to open. stage_load_timeout (Optional[float]): Maximum duration for which to wait before considering a loading timeout. Returns: bool: A flag indicating whether or not the given USD stage was successfully loaded. """ success, error = await omni.usd.get_context().open_stage_async(usd_file) if not success: carb.log_error(f"Unable to open \"{usd_file}\": {str(error)}") raise Exception(f"Unable to open \"{usd_file}\".") carb.log_info("Stage opened. Waiting for \"ASSETS_LOADED\" event.") usd_context = omni.usd.get_context() if usd_context.get_stage_state() != omni.usd.StageState.OPENED: while True: try: event, _ = await asyncio.wait_for(usd_context.next_stage_event_async(), timeout=stage_load_timeout) if event == int(omni.usd.StageEventType.ASSETS_LOADED): carb.log_info(f"Assets for \"{usd_file}\" loaded") return True except asyncio.TimeoutError: _, files_loaded, total_files = usd_context.get_stage_loading_status() if files_loaded == total_files: carb.log_warn("Timed out waiting for \"ASSETS_LOADED\" event but all files seem to have loaded.") return False raise Exception(f"Timed out waiting for \"ASSETS_LOADED\" event for \"{usd_file}\". Aborting.") def get_all_stage_cameras() -> List[UsdGeom.Camera]: """ Return the list of all USD cameras found the current USD stage. Args: None Returns: List[UsdGeom.Camera]: The list of all USD cameras found in the current USD stage. """ cameras: List[UsdGeom.Camera] = [] stage = omni.usd.get_context().get_stage() for prim in stage.TraverseAll(): if prim.IsA(UsdGeom.Camera): cameras.append(UsdGeom.Camera(prim)) return cameras @router.post( path="/validate", summary="Validate assets for conformity", description="Validate that the USD Stage at the given location conforms to pre-determined validation rules.", response_model=ValidationResponsetModel, ) async def run(req: ValidationRequestModel) -> ValidationResponsetModel: # Load the USD stage: await load_usd_stage(usd_file=req.scene_path) # Perform the validation. # # NOTE: For demonstration purposes, we are only considering the number of cameras present in the given USD scene to # demonstrate integration with tools and workflows. stage_cameras = get_all_stage_cameras() camera_count = len(stage_cameras) validation_success = camera_count == req.expected_camera_count # Return the validation results: return ValidationResponsetModel( success=validation_success, actual_camera_count=camera_count, )
4,606
Python
34.167939
119
0.668693
NVIDIA-Omniverse/kit-extension-sample-csv-reader/exts/omni.csv.reader/omni/csv/reader/extension.py
############################################################################### # # Copyright 2020 NVIDIA Corporation # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of # the Software, and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # ############################################################################### ############################################################################### # # Extension create by BB.CM.EB June 2022 for CSV Reader_extension # Target : read a CSV file and populate the 3D environment # with shapes at location X,Y,Z # Known limitations - June/07 # - CSV files must contains X,Y,Z and[optional] cluster columns # - nothing happens if no CSV file (not found/wrong type/etc...) # ############################################################################### import carb import omni.ext from .models import MainModel from .views import MainView # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) # will be instantiated when extension gets enabled and `on_startup(ext_id)` will be called. # Later when extension gets disabled on_shutdown() is called class MyExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): carb.log_info(f"[CSV_Reader] MyExtension startup") Model = MainModel() self._window = MainView(Model) def on_shutdown(self): carb.log_info(f"[CSV_Reader] MyExtension shutdown") self._window.destroy() self._window = None
2,630
Python
45.982142
119
0.647529
NVIDIA-Omniverse/kit-extension-sample-csv-reader/exts/omni.csv.reader/omni/csv/reader/models.py
# Model related # Python built-in import os.path import carb from pathlib import Path # external python lib import csv import itertools # USD imports from pxr import Gf, UsdGeom, UsdLux # omniverse import omni.client import omni.kit.app from omni.kit.window.file_importer import get_file_importer CURRENT_PATH = Path(__file__).parent DATA_PATH = CURRENT_PATH.parent.parent.parent.joinpath("data") category_colors = { 0: [(1, 0, 0)], 1: [(0, 1, 0)], 2: [(0, 0.4, 0)], 3: [(0, 0, 1)], 4: [(0.3, 0.5, 1)], 5: [(.5, .5, .5)], 6: [(0, 0, 0)], 7: [(0, 1, 1)], 8: [(.8, .5, .25)], 9: [(1, .5, 0)], 10: [(1, 1, 1)], } shape_usda_name = { "cube": "BasicCubeAsRef.usda", "sphere": "BasicSphereAsRef.usda", } class MainModel(): def __init__(self): #root prim paths self.root_path = '/World' self.cluster_layer_root_path = '/Class_' # stage_unit defines the number of unit per meter self.stage_unit_per_meter = 1 # Default CSV Path (sample file deployed with extension) self.csv_file_path = DATA_PATH.joinpath('CSVSample.csv') # path to basic shape self.shape_file_name = "BasicCubeAsRef.usda" self.shape_file_path = DATA_PATH.joinpath(self.shape_file_name) # Scale factor so that the shapes are well spaced self.scale_factor = 100.0 # limit the number of rows read self.max_elements = 5000 # whether or not the shapes should be grouped by cluster self.group_by_cluster = False # max number of different color clusters self.max_num_clusters = 10 def generate(self): # Clear the stage stage = omni.usd.get_context().get_stage() root_prim = stage.GetPrimAtPath(self.root_path) if (root_prim.IsValid()): stage.RemovePrim(self.root_path) # create a new stage with Y up and in meters if omni.usd.get_context().new_stage() is False: carb.log_warn(f"Failed creating a new stage.") return stage = omni.usd.get_context().get_stage() # set the up axis UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.y) # set the unit of the world UsdGeom.SetStageMetersPerUnit(stage, self.stage_unit_per_meter) stage.SetDefaultPrim(root_prim) # add a light light_prim_path = self.root_path + '/DistantLight' light_prim = UsdLux.DistantLight.Define(stage, light_prim_path) light_prim.CreateAngleAttr(0.53) light_prim.CreateColorAttr(Gf.Vec3f(1.0, 1.0, 0.745)) light_prim.CreateIntensityAttr(5000.0) # check that CSV exists if os.path.exists(self.csv_file_path): # Read CSV file with open(self.csv_file_path, newline='') as csvfile: csv_reader = csv.reader(csvfile, delimiter=',') i = 1 # Iterate over each row in the CSV file # Skip the header row # Don't read more than the max number of elements # Create the shape with the appropriate color at each coordinate for row in itertools.islice(csv_reader, 1, self.max_elements): name = row[0] x = float(row[1]) y = float(row[2]) z = float(row[3]) cluster = row[4] # root prim cluster_prim_path = self.root_path # add group to path if the user has selected that option if self.group_by_cluster: cluster_prim_path += self.cluster_layer_root_path + cluster cluster_prim = stage.GetPrimAtPath(cluster_prim_path) # create the prim if it does not exist if not cluster_prim.IsValid(): UsdGeom.Xform.Define(stage, cluster_prim_path) shape_prim_path = cluster_prim_path + '/box_%d' % i i += 1 # Create prim to add the reference to. ref_shape = stage.OverridePrim(shape_prim_path) # Add the reference ref_shape.GetReferences().AddReference(str(self.shape_file_path), '/MyRef/RefMesh') # Get mesh from shape instance next_shape = UsdGeom.Mesh.Get(stage, shape_prim_path) # Set location next_shape.AddTranslateOp().Set( Gf.Vec3f( self.scale_factor*x, self.scale_factor*y, self.scale_factor*z)) # Set Color next_shape.GetDisplayColorAttr().Set( category_colors[int(cluster) % self.max_num_clusters]) # Handles the change between a cube and sphere shape in the UI def shape_changed(self, choice): chosen_key = list(shape_usda_name.keys())[choice] self.shape_file_name = shape_usda_name[chosen_key] self.shape_file_path = DATA_PATH.joinpath(self.shape_file_name) # Handles the change of the 'group by cluster' checkbox def group_by_cluster_changed(self, do_clustering): self.group_by_cluster = do_clustering # Handles the click of the Load button def select_file(self): self.file_importer = get_file_importer() self.file_importer.show_window( title="Select a CSV File", import_button_label="Select", import_handler=self._on_click_open, file_extension_types=[(".csv", "CSV Files (*.csv)")], file_filter_handler=self._on_filter_item ) # Handles the click of the open button within the file importer dialog def _on_click_open(self, filename: str, dirname: str, selections): # File name should not be empty. filename = filename.strip() if not filename: carb.log_warn(f"Filename must be provided.") return # create the full path to csv file if dirname: fullpath = f"{dirname}{filename}" else: fullpath = filename self.csv_file_path = fullpath self.csv_field_model.set_value(str(fullpath)) # Handles the filtering of files within the file importer dialog def _on_filter_item(self, filename: str, filter_postfix: str, filter_ext: str) -> bool: if not filename: return True # Show only .csv files _, ext = os.path.splitext(filename) if ext == filter_ext: return True else: return False
6,976
Python
34.596939
103
0.544151
NVIDIA-Omniverse/kit-extension-sample-csv-reader/exts/omni.csv.reader/omni/csv/reader/views.py
# import from omniverse import omni.ui as ui from omni.ui.workspace_utils import TOP # import from other extension py from .models import MainModel class MainView(): def __init__(self, csvmodel: MainModel): self._window = ui.Window("CSV Reader", width=800, height=600, dockPreference=ui.DockPreference.RIGHT_TOP) self._window.visible = True csvmodel.csv_field_model = None with self._window.frame: with ui.VStack(alignment=TOP, style={"margin":5}): # 2 - parameters to be set, in case not default values with ui.VStack(): with ui.HStack(height=20): ui.Label("CSV file path:", height=10, width=120) self.csv_field = ui.StringField(height=10) self.csv_field.enabled = False self.csv_field.model.set_value(str(csvmodel.csv_file_path)) csvmodel.csv_field_model = self.csv_field.model ui.Button("Load", width=40, clicked_fn=lambda: csvmodel.select_file()) with ui.HStack(height=20): ui.Label("Shape:", height=0) shape_combo = ui.ComboBox(0, "cube", "sphere") shape_combo.model.add_item_changed_fn( lambda m, f=shape_combo: csvmodel.shape_changed(m.get_item_value_model().get_value_as_int())) with ui.HStack(height=20): ui.Label("Group By Cluster:", height=0) cluster_cb = ui.CheckBox(width=20) cluster_cb.model.add_value_changed_fn( lambda a: csvmodel.group_by_cluster_changed(a.get_value_as_bool())) ui.Line(style={"color": 0xff00b976}, height=20) # 3 - button to populate the 3D scene ui.Button( "Generate", height=50, clicked_fn=lambda: csvmodel.generate()) def destroy(self): self._window.destroy() self._window = None
2,199
Python
46.826086
113
0.51387
NVIDIA-Omniverse/usd-plugin-samples/src/kit-extension/exts/omni.example.schema/omni/example/schema/__init__.py
# Copyright 2023 NVIDIA CORPORATION # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from pxr import Plug # this extension is responsible for loading both plug-ins that represent the # example codeful and codeless schema extensions plugin_root = os.path.join(os.path.dirname(__file__), "..", "..", "..", "OmniExampleSchema", "resources") Plug.Registry().RegisterPlugins(plugin_root) plugin_root = os.path.join(os.path.dirname(__file__), "..", "..", "..", "OmniExampleCodelessSchema", "resources")
1,012
Python
41.208332
76
0.737154
NVIDIA-Omniverse/usd-plugin-samples/src/hydra-plugins/omniWarpSceneIndex/__init__.py
from pxr import Tf # PreparePythonModule didn't make it's way into USD # until 21.08 - older versions import the module # manually and call PrepareModule if hasattr(Tf, "PreparePythonModule"): Tf.PreparePythonModule() else: from . import _omniWarpSceneIndex Tf.PrepareModule(_omniWarpSceneIndex, locals()) del Tf
327
Python
24.230767
51
0.75841
NVIDIA-Omniverse/usd-plugin-samples/src/hydra-plugins/omniWarpSceneIndex/warpModules/particles.py
# Copyright 2023 NVIDIA CORPORATION # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os import warp as wp import warp.sim import warp.sim.render import numpy as np from pxr import Vt, Sdf wp.init() global_examples = {} # need radius of spehere class Example2: def __init__(self): self.frame_dt = 1.0 / 60 self.frame_count = 400 self.sim_substeps = 64 self.sim_dt = self.frame_dt / self.sim_substeps self.sim_steps = self.frame_count * self.sim_substeps self.sim_time = 0.0 self.radius = 0.1 self.builder = wp.sim.ModelBuilder() self.builder.default_particle_radius = self.radius def update(self): self.model.particle_grid.build(self.state_0.particle_q, self.radius * 2.0) for s in range(self.sim_substeps): self.state_0.clear_forces() self.integrator.simulate(self.model, self.state_0, self.state_1, self.sim_dt) # swap states (self.state_0, self.state_1) = (self.state_1, self.state_0) def terminate_sim(primPath: Sdf.Path): global global_examples global_examples[primPath] = None def initialize_sim_particles(primPath: Sdf.Path, src_positions: Vt.Vec3fArray, dep_mesh_indices: Vt.IntArray = None, dep_mesh_points: Vt.Vec3fArray = None, sim_params: dict = None): global global_examples global_examples[primPath] = Example2() for pt in src_positions: global_examples[primPath].builder.add_particle(pt, (5.0, 0.0, 0.0), 0.1) global_examples[primPath].model = global_examples[primPath].builder.finalize() global_examples[primPath].model.particle_kf = 25.0 global_examples[primPath].model.soft_contact_kd = 100.0 global_examples[primPath].model.soft_contact_kf *= 2.0 global_examples[primPath].state_0 = global_examples[primPath].model.state() global_examples[primPath].state_1 = global_examples[primPath].model.state() global_examples[primPath].integrator = wp.sim.SemiImplicitIntegrator() def exec_sim(primPath: Sdf.Path, sim_dt: float, dep_mesh_points: Vt.Vec3fArray = None, sim_params: dict = None): # Not respecting sim_dt at all, using internal time global global_examples global_examples[primPath].update() return Vt.Vec3fArray.FromNumpy(global_examples[primPath].state_0.particle_q.numpy())
2,841
Python
33.658536
136
0.697994
NVIDIA-Omniverse/usd-plugin-samples/src/hydra-plugins/omniWarpSceneIndex/warpModules/cloth.py
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. ########################################################################### # Example Sim Cloth # # Shows a simulation of an FEM cloth model colliding against a static # rigid body mesh using the wp.sim.ModelBuilder(). # ########################################################################### import os import math import numpy as np import warp as wp import warp.sim import warp.sim.render from pxr import Usd, UsdGeom, Vt, Sdf import sys wp.init() global_examples = {} class Example: def __init__(self, indices: Vt.IntArray, points: Vt.Vec3fArray): self.sim_width = 64 self.sim_height = 64 self.frame_dt = 1.0 / 60 self.frame_count = 400 self.sim_substeps = 32 self.sim_dt = self.frame_dt / self.sim_substeps self.sim_steps = self.frame_count * self.sim_substeps self.sim_time = 0.0 builder = wp.sim.ModelBuilder() # sim BCs clothEdgeBendingStiffness = 0.01 clothEdgeDampingStiffness = 0.0 clothTriAreaStiffness = 1000000.0 clothTriDampingStiffness = 100.0 clothTriElasticStiffness = 1000000.0 colliderContactDistance = 1.0 colliderContactQueryRange = 100.0 contactDampingStiffness = 10000.0 contactElasticStiffness = 500000.0 contactFrictionCoeff = 0.75 contactFrictionStiffness = 10000.0 globalScale = 0.01 # cloth grid builder.add_cloth_grid( pos=(0.0, 50.0, -25.0), rot=wp.quat_from_axis_angle((1.0, 0.0, 0.0), math.pi * 0.5), vel=(0.0, 0.0, 0.0), dim_x=self.sim_width, dim_y=self.sim_height, cell_x=1.0, cell_y=1.0, mass=0.1, fix_left=True, tri_ke=clothTriElasticStiffness * globalScale, tri_ka=clothTriAreaStiffness * globalScale, tri_kd=clothTriDampingStiffness * globalScale, edge_ke=clothEdgeBendingStiffness * globalScale, edge_kd=clothEdgeDampingStiffness * globalScale ) # add collider (must have identity transform until we xforms piped through Hydra plugin) mesh = wp.sim.Mesh(points, indices) builder.add_shape_mesh( body=-1, mesh=mesh, pos=(0.0, 0.0, 0.0), rot=wp.quat_identity(), scale=(1.0, 1.0, 1.0), ke=1.0e2, kd=1.0e2, kf=1.0e1, ) # set sim BCs self.model = builder.finalize() self.model.ground = True self.model.allocate_soft_contacts(self.model.particle_count) self.model.gravity = (0, -980, 0) self.model.soft_contact_ke = contactElasticStiffness * globalScale self.model.soft_contact_kf = contactFrictionStiffness * globalScale self.model.soft_contact_mu = contactFrictionCoeff self.model.soft_contact_kd = contactDampingStiffness * globalScale self.model.soft_contact_margin = colliderContactDistance * colliderContactQueryRange self.model.particle_radius = colliderContactDistance self.integrator = wp.sim.SemiImplicitIntegrator() self.state_0 = self.model.state() self.state_1 = self.model.state() def update(self, sim_time: float): wp.sim.collide(self.model, self.state_0) for s in range(self.sim_substeps): self.state_0.clear_forces() self.integrator.simulate(self.model, self.state_0, self.state_1, self.sim_dt) (self.state_0, self.state_1) = (self.state_1, self.state_0) def terminate_sim(primPath: Sdf.Path): global global_examples global_examples[primPath] = None def initialize_sim_mesh(primPath: Sdf.Path, src_indices: Vt.IntArray, src_points: Vt.Vec3fArray, dep_mesh_indices: Vt.IntArray = None, dep_mesh_points: Vt.Vec3fArray = None, sim_params: dict = None): global global_examples global_examples[primPath] = Example(dep_mesh_indices, dep_mesh_points) def exec_sim(primPath: Sdf.Path, sim_dt: float, dep_mesh_points: Vt.Vec3fArray = None, sim_params: dict = None): # Not respecting sim_dt at all, using internal time global global_examples global_examples[primPath].update(sim_dt) return Vt.Vec3fArray.FromNumpy(global_examples[primPath].state_0.particle_q.numpy())
4,791
Python
33.978102
112
0.625339
NVIDIA-Omniverse/usd-plugin-samples/src/hydra-plugins/omniWarpSceneIndex/warpModules/deform01.py
# Copyright 2023 NVIDIA CORPORATION # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import warp as wp import numpy as np from pxr import Vt, Sdf @wp.kernel def deform(positions: wp.array(dtype=wp.vec3), t: float): tid = wp.tid() x = positions[tid] offset = -wp.sin(x[0]) * 0.06 scale = wp.sin(t) x = x + wp.vec3(0.0, offset * scale, 0.0) positions[tid] = x class Example: def __init__(self, indices: Vt.IntArray, points: Vt.Vec3fArray): self.mesh = wp.Mesh( points=wp.array(points, dtype=wp.vec3), indices=wp.array(indices, dtype=int), ) def update(self, sim_time: float): wp.launch(kernel=deform, dim=len(self.mesh.points), inputs=[self.mesh.points, sim_time]) # refit the mesh BVH to account for the deformation self.mesh.refit() wp.init() global_examples = {} def terminate_sim(primPath: Sdf.Path): global global_examples global_examples[primPath] = None def initialize_sim_mesh(primPath: Sdf.Path, src_indices: Vt.IntArray, src_points: Vt.Vec3fArray, dep_mesh_indices: Vt.IntArray = None, dep_mesh_points: Vt.Vec3fArray = None, sim_params: dict = None): global global_examples global_examples[primPath] = Example(src_indices, src_points) def exec_sim(primPath: Sdf.Path, sim_dt: float, dep_mesh_points: Vt.Vec3fArray = None, sim_params: dict = None): global global_examples # Sim expects 60 samples per second (or hydra time of 1.0) global_examples[primPath].update(sim_dt / 60.0) return Vt.Vec3fArray.FromNumpy(global_examples[primPath].mesh.points.numpy()) def is_enabled(): return True
2,140
Python
31.439393
112
0.693458
NVIDIA-Omniverse/usd-plugin-samples/src/hydra-plugins/omniWarpSceneIndex/warpModules/ocean.py
# Copyright 2023 NVIDIA CORPORATION # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import warp as wp import numpy as np from pxr import Vt, Sdf wp.init() sim_params_global = { 'wave_amplitude': 1.5, 'wave_directionality': 0.0, 'wind_speed': 10.0, 'water_depth': 50.0, 'scale': 1.0, 'direction': 0.0, } #warp function definitions # fractional part of a (w.r.t. floor(a)) @wp.func def frac(a: float): return a - wp.floor(a) # square of a @wp.func def sqr(a: float): return a * a @wp.func def alpha_beta_spectrum(omega: float, peak_omega: float, alpha: float, beta: float, gravity: float): return ( (alpha * gravity * gravity / wp.pow(omega, 5.0)) * wp.exp(- beta * wp.pow(peak_omega/omega, 4.0)) ) @wp.func def jonswap_peak_sharpening(omega: float, peak_omega: float, gamma: float): sigma = float(0.07) if omega > peak_omega: sigma = float(0.09) return wp.pow(gamma, wp.exp(- 0.5 * sqr( (omega - peak_omega) / (sigma * peak_omega)) )) @wp.func def jonswap_spectrum(omega: float, gravity: float, wind_speed: float, fetch_km: float, gamma: float): #https://wikiwaves.org/Ocean-Wave_Spectra#JONSWAP_Spectrum fetch = 1000.0 * fetch_km alpha = 0.076 * wp.pow(wind_speed * wind_speed / (gravity * fetch), 0.22) peak_omega = 22.0 * wp.pow(wp.abs(gravity * gravity / (wind_speed * fetch)), 1.0/3.0) return (jonswap_peak_sharpening(omega, peak_omega, gamma) * alpha_beta_spectrum(omega, peak_omega, alpha, 1.25, gravity)) @wp.func def TMA_spectrum(omega: float, gravity: float, wind_speed: float, fetch_km: float, gamma: float, waterdepth: float): #https://dl.acm.org/doi/10.1145/2791261.2791267 omegaH = omega * wp.sqrt(waterdepth/gravity) omegaH = wp.max(0.0, wp.min(2.2, omegaH)) phi = 0.5 * omegaH * omegaH if omegaH > 1.0: phi = 1.0 - 0.5 * sqr(2.0 - omegaH) return phi * jonswap_spectrum(omega, gravity, wind_speed, fetch_km, gamma); #warp kernel definitions @wp.kernel def update_profile(profile: wp.array(dtype=wp.vec3), profile_res: int, profile_data_num: int, lambdaMin: float, lambdaMax: float, profile_extend: float, time: float, windspeed: float, waterdepth: float ): x = wp.tid() randself = wp.rand_init(7) # sampling parameters omega0 = wp.sqrt(2.0 * 3.14159 * 9.80665 / lambdaMin) omega1 = wp.sqrt(2.0 * 3.14159 * 9.80665 / lambdaMax) omega_delta = wp.abs(omega1 - omega0) / float(profile_data_num) # we blend three displacements for seamless spatial profile tiling space_pos_1 = profile_extend * float(x) / float(profile_res) space_pos_2 = space_pos_1 + profile_extend space_pos_3 = space_pos_1 - profile_extend p1 = wp.vec2(0.0,0.0) p2 = wp.vec2(0.0,0.0) p3 = wp.vec2(0.0,0.0) for i in range(0, profile_data_num): omega = wp.abs(omega0 + (omega1 - omega0) * float(i) / float(profile_data_num)) # linear sampling of omega k = omega * omega / 9.80665 phase = -time * omega + wp.randf(randself) * 2.0 * 3.14159 amplitude = float(10000.0) * wp.sqrt(wp.abs(2.0 * omega_delta * TMA_spectrum(omega, 9.80665, windspeed, 100.0, 3.3, waterdepth))) p1 = wp.vec2( p1[0] + amplitude * wp.sin(phase + space_pos_1 * k), p1[1] - amplitude * wp.cos(phase + space_pos_1 * k) ) p2 = wp.vec2( p2[0] + amplitude * wp.sin(phase + space_pos_2 * k), p2[1] - amplitude * wp.cos(phase + space_pos_2 * k) ) p3 = wp.vec2( p3[0] + amplitude * wp.sin(phase + space_pos_3 * k), p3[1] - amplitude * wp.cos(phase + space_pos_3 * k) ) # cubic blending coefficients s = float(float(x) / float(profile_res)) c1 = float(2.0 * s * s * s - 3.0 * s * s + 1.0) c2 = float(-2.0 * s * s * s + 3.0 * s * s) disp_out = wp.vec3( (p1[0] + c1 * p2[0] + c2 * p3[0]) / float(profile_data_num), (p1[1] + c1 * p2[1] + c2 * p3[1]) / float(profile_data_num), 0. ) wp.store(profile, x, disp_out) @wp.kernel def update_points(out_points: wp.array(dtype=wp.vec3), in_points: wp.array(dtype=wp.vec3), profile: wp.array(dtype=wp.vec3), profile_res: int, profile_extent: float, amplitude: float, directionality: float, direction: float, antiAlias: int, camPosX: float, camPosY: float, camPosZ: float): tid = wp.tid() p_crd = in_points[tid] p_crd = wp.vec3(p_crd[0], p_crd[2], p_crd[1]) randself = wp.rand_init(7) disp_x = float(0.) disp_y = float(0.) disp_z = float(0.) w_sum = float(0.) direction_count = (int)(128) for d in range(0, direction_count): r = float(d) * 2. * 3.14159265359 / float(direction_count) + 0.02 dir_x = wp.cos(r) dir_y = wp.sin(r) # directional amplitude t = wp.abs( direction - r ) if (t > 3.14159265359): t = 2.0 * 3.14159265359 - t t = pow(t, 1.2) dirAmp = (2.0 * t * t * t - 3.0 * t * t + 1.0) * 1.0 + (- 2.0 * t * t * t + 3.0 * t * t) * (1.0 - directionality) dirAmp = dirAmp / (1.0 + 10.0 * directionality) rand_phase = wp.randf(randself) x_crd = (p_crd[0] * dir_x + p_crd[2] * dir_y) / profile_extent + rand_phase pos_0 = int(wp.floor(x_crd * float(profile_res))) % profile_res if x_crd < 0.: pos_0 = pos_0 + profile_res - 1 pos_1 = int(pos_0 + 1) % profile_res p_disp_0 = profile[pos_0] p_disp_1 = profile[pos_1] w = frac( x_crd * float(profile_res) ) prof_height_x = dirAmp * float((1. - w) * p_disp_0[0] + w * p_disp_1[0]) prof_height_y = dirAmp * float((1. - w) * p_disp_0[1] + w * p_disp_1[1]) disp_x = disp_x + dir_x * prof_height_x disp_y = disp_y + prof_height_y disp_z = disp_z + dir_y * prof_height_x w_sum = w_sum + 1. # simple anti-aliasing: reduce amplitude with increasing distance to viewpoint if (antiAlias > 0): v1 = wp.normalize( wp.vec3( p_crd[0] - camPosX, max( 100.0, wp.abs(p_crd[1] - camPosY)), p_crd[2] - camPosZ) ) amplitude *= wp.sqrt( wp.abs(v1[1]) ) # write output vertex position outP = wp.vec3(p_crd[0] + amplitude * disp_x / w_sum, p_crd[1] + amplitude * disp_y / w_sum, p_crd[2] + amplitude * disp_z / w_sum) wp.store(out_points, tid, wp.vec3(outP[0], outP[2], outP[1])) class Example: def __init__(self, indices: Vt.IntArray, points: Vt.Vec3fArray): # profile buffer intializations print('[Ocean deformer] Initializing profile buffer.') self.profile_extent = 410.0 #physical size of profile, should be around half the resolution self.profile_res = int(8192) self.profile_wavenum = int(1000) self.profile_CUDA = wp.zeros(self.profile_res, dtype=wp.vec3, device="cuda:0") self.points_in = wp.array(points, dtype=wp.vec3, device="cuda:0") self.points_out = wp.array(points, dtype=wp.vec3, device="cuda:0") print(self.points_in) print(self.points_out) def update(self, sim_time: float): global sim_params_global # params wave_amplitude = sim_params_global["wave_amplitude"] wave_directionality = sim_params_global["wave_directionality"] wind_speed = sim_params_global["wind_speed"] water_depth = sim_params_global["water_depth"] scale = sim_params_global["scale"] direction = sim_params_global["direction"] # Parameters time = float(sim_time) amplitude = max(0.0001, min(1000.0, float(wave_amplitude))) minWavelength = 0.1 maxWavelength = 250.0 direction = float(direction) % 6.28318530718 directionality = max(0.0, min(1.0, 0.02 * float(wave_directionality))) windspeed = max(0.0, min(30.0, float(wind_speed))) waterdepth = max(1.0, min(1000.0, float(water_depth))) scale = min(10000.0, max(0.001, float(scale))) antiAlias = int(0) campos = [0.0, 0.0, 0.0] # create 1D profile buffer for this timestep using wave paramters stored in internal self CUDA memory wp.launch( kernel=update_profile, dim=self.profile_res, inputs=[self.profile_CUDA, int(self.profile_res), int(self.profile_wavenum), float(minWavelength), float(maxWavelength), float(self.profile_extent), float(time), float(windspeed), float(waterdepth)], outputs=[], device="cuda:0") # update point positions using the profile buffer created above wp.launch( kernel=update_points, dim=len(self.points_out), inputs=[self.points_out, self.points_in, self.profile_CUDA, int(self.profile_res), float(self.profile_extent*scale), float(amplitude), float(directionality), float(direction), int(antiAlias), float(campos[0]), float(campos[1]), float(campos[2]) ], outputs=[], device="cuda:0") global_examples = {} def terminate_sim(primPath: Sdf.Path): global global_examples global_examples[primPath] = None def initialize_sim_mesh(primPath: Sdf.Path, src_indices: Vt.IntArray, src_points: Vt.Vec3fArray, dep_mesh_indices: Vt.IntArray = None, dep_mesh_points: Vt.Vec3fArray = None, sim_params: dict = None): global global_examples global sim_params_global if sim_params: sim_params_global = sim_params global_examples[primPath] = Example(src_indices, src_points) def exec_sim(primPath: Sdf.Path, sim_dt: float, dep_mesh_points: Vt.Vec3fArray = None, sim_params: dict = None): global global_examples global sim_params_global if sim_params: sim_params_global = sim_params # Sim expects 60 samples per second (or hydra time of 1.0) global_examples[primPath].update(sim_dt / 60.0) return Vt.Vec3fArray.FromNumpy(global_examples[primPath].points_out.numpy())
11,029
Python
37.838028
260
0.580288
NVIDIA-Omniverse/usd-plugin-samples/src/hydra-plugins/omniWarpSceneIndex/oceanSim/preferences.py
# # Copyright 2016 Pixar # # Licensed under the Apache License, Version 2.0 (the "Apache License") # with the following modification; you may not use this file except in # compliance with the Apache License and the following modification to it: # Section 6. Trademarks. is deleted and replaced with: # # 6. Trademarks. This License does not grant permission to use the trade # names, trademarks, service marks, or product names of the Licensor # and its affiliates, except as required to comply with Section 4(c) of # the License and to reproduce the content of the NOTICE file. # # You may obtain a copy of the Apache License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Apache License with the above modification is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the Apache License for the specific # language governing permissions and limitations under the Apache License. # from pxr.Usdviewq.qt import QtCore, QtGui, QtWidgets from .preferencesUI import Ui_Preferences class Preferences(QtWidgets.QDialog): def __init__(self, parent, attr): super(Preferences, self).__init__(parent) self._ui = Ui_Preferences() self._ui.setupUi(self) self._attr = attr metadata = self._attr.GetMetadata("customData") self._ui.scaleSpinBox.setValue(metadata["scale"]) self._ui.directionSpinBox.setValue(metadata["direction"]) self._ui.windSpeedSpinBox.setValue(metadata["wind_speed"]) self._ui.waterDepthSpinBox.setValue(metadata["water_depth"]) self._ui.waveAmplitudeSpinBox.setValue(metadata["wave_amplitude"]) self._ui.waveDirectionalitySpinBox.setValue(metadata["wave_directionality"]) self._ui.buttonBox.clicked.connect(self._buttonBoxButtonClicked) def _apply(self): self._attr.SetMetadataByDictKey('customData', 'scale', self._ui.scaleSpinBox.value()) self._attr.SetMetadataByDictKey('customData', 'direction', self._ui.directionSpinBox.value()) self._attr.SetMetadataByDictKey('customData', 'wind_speed', self._ui.windSpeedSpinBox.value()) self._attr.SetMetadataByDictKey('customData', 'water_depth', self._ui.waterDepthSpinBox.value()) self._attr.SetMetadataByDictKey('customData', 'wave_amplitude', self._ui.waveAmplitudeSpinBox.value()) self._attr.SetMetadataByDictKey('customData', 'wave_directionality', self._ui.waveDirectionalitySpinBox.value()) def _buttonBoxButtonClicked(self, button): role = self._ui.buttonBox.buttonRole(button) Roles = QtWidgets.QDialogButtonBox.ButtonRole if role == Roles.AcceptRole or role == Roles.ApplyRole: self._apply() if role == Roles.AcceptRole or role == Roles.RejectRole: self.close()
2,923
Python
46.16129
120
0.718782
NVIDIA-Omniverse/usd-plugin-samples/src/hydra-plugins/omniWarpSceneIndex/oceanSim/__init__.py
from pxr import Tf from pxr.Usdviewq.plugin import PluginContainer from .preferences import Preferences def launchPreferences(usdviewApi): prim = usdviewApi.stage.GetPrimAtPath("/World/grid/Grid") attr = prim.GetAttribute("warp:sourceFile") _preferencesDlg = Preferences(usdviewApi.qMainWindow, attr) _preferencesDlg.show() _preferencesDlg = None class OceanSimPluginContainer(PluginContainer): def registerPlugins(self, plugRegistry, usdviewApi): self._launchPreferences = plugRegistry.registerCommandPlugin( "OceanSimPluginContainer.launchPreferences", "Launch Preferences", launchPreferences) def configureView(self, plugRegistry, plugUIBuilder): tutMenu = plugUIBuilder.findOrCreateMenu("OceanSim") tutMenu.addItem(self._launchPreferences) Tf.Type.Define(OceanSimPluginContainer)
878
Python
32.807691
69
0.749431
NVIDIA-Omniverse/usd-plugin-samples/src/hydra-plugins/omniWarpSceneIndex/oceanSim/preferencesUI_pyside6.py
# -*- coding: utf-8 -*- ################################################################################ ## Form generated from reading UI file 'preferencesUI.ui' ## ## Created by: Qt User Interface Compiler version 6.5.1 ## ## WARNING! All changes made in this file will be lost when recompiling UI file! ################################################################################ from PySide6.QtCore import (QCoreApplication, QDate, QDateTime, QLocale, QMetaObject, QObject, QPoint, QRect, QSize, QTime, QUrl, Qt) from PySide6.QtGui import (QBrush, QColor, QConicalGradient, QCursor, QFont, QFontDatabase, QGradient, QIcon, QImage, QKeySequence, QLinearGradient, QPainter, QPalette, QPixmap, QRadialGradient, QTransform) from PySide6.QtWidgets import (QAbstractButton, QApplication, QDialog, QDialogButtonBox, QDoubleSpinBox, QFrame, QHBoxLayout, QLabel, QSizePolicy, QSpacerItem, QVBoxLayout, QWidget) class Ui_Preferences(object): def setupUi(self, Ocean_Simulation_Settings): if not Ocean_Simulation_Settings.objectName(): Ocean_Simulation_Settings.setObjectName(u"Ocean_Simulation_Settings") Ocean_Simulation_Settings.resize(295, 99) self.verticalLayout = QVBoxLayout() self.verticalLayout.setObjectName(u"verticalLayout") self.prefsOverButtonsLayout = QVBoxLayout() self.prefsOverButtonsLayout.setObjectName(u"prefsOverButtonsLayout") self.horizontalLayout_3 = QHBoxLayout() self.horizontalLayout_3.setObjectName(u"horizontalLayout_3") self.scaleLabel = QLabel() self.scaleLabel.setObjectName(u"scaleLabel") self.horizontalLayout_3.addWidget(self.scaleLabel) self.horizontalSpacer_2a = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_3.addItem(self.horizontalSpacer_2a) self.scaleSpinBox = QDoubleSpinBox() self.scaleSpinBox.setObjectName(u"scaleSpinBox") self.scaleSpinBox.setDecimals(2) self.scaleSpinBox.setMinimum(0.000000000000000) self.scaleSpinBox.setValue(1.000000000000000) self.horizontalLayout_3.addWidget(self.scaleSpinBox) self.prefsOverButtonsLayout.addLayout(self.horizontalLayout_3) self.horizontalLayout_4 = QHBoxLayout() self.horizontalLayout_4.setObjectName(u"horizontalLayout_4") self.directionLabel = QLabel() self.directionLabel.setObjectName(u"directionLabel") self.horizontalLayout_4.addWidget(self.directionLabel) self.horizontalSpacer_2b = QSpacerItem(26, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_4.addItem(self.horizontalSpacer_2b) self.directionSpinBox = QDoubleSpinBox() self.directionSpinBox.setObjectName(u"directionSpinBox") self.directionSpinBox.setDecimals(2) self.directionSpinBox.setMinimum(0.000000000000000) self.directionSpinBox.setValue(0.000000000000000) self.horizontalLayout_4.addWidget(self.directionSpinBox) self.prefsOverButtonsLayout.addLayout(self.horizontalLayout_4) self.horizontalLayout_5 = QHBoxLayout() self.horizontalLayout_5.setObjectName(u"horizontalLayout_5") self.windSpeedLabel = QLabel() self.windSpeedLabel.setObjectName(u"windSpeedLabel") self.horizontalLayout_5.addWidget(self.windSpeedLabel) self.horizontalSpacer_2c = QSpacerItem(24, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_5.addItem(self.horizontalSpacer_2c) self.windSpeedSpinBox = QDoubleSpinBox() self.windSpeedSpinBox.setObjectName(u"windSpeedSpinBox") self.windSpeedSpinBox.setDecimals(2) self.windSpeedSpinBox.setMinimum(0.000000000000000) self.windSpeedSpinBox.setValue(10.000000000000000) self.horizontalLayout_5.addWidget(self.windSpeedSpinBox) self.prefsOverButtonsLayout.addLayout(self.horizontalLayout_5) self.horizontalLayout_6 = QHBoxLayout() self.horizontalLayout_6.setObjectName(u"horizontalLayout_6") self.waterDepthLabel = QLabel() self.waterDepthLabel.setObjectName(u"waterDepthLabel") self.horizontalLayout_6.addWidget(self.waterDepthLabel) self.horizontalSpacer_2d = QSpacerItem(24, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_6.addItem(self.horizontalSpacer_2d) self.waterDepthSpinBox = QDoubleSpinBox() self.waterDepthSpinBox.setObjectName(u"waterDepthSpinBox") self.waterDepthSpinBox.setDecimals(2) self.waterDepthSpinBox.setMinimum(0.000000000000000) self.waterDepthSpinBox.setValue(50.000000000000000) self.horizontalLayout_6.addWidget(self.waterDepthSpinBox) self.prefsOverButtonsLayout.addLayout(self.horizontalLayout_6) self.horizontalLayout_7 = QHBoxLayout() self.horizontalLayout_7.setObjectName(u"horizontalLayout_7") self.waveAmplitudeLabel = QLabel() self.waveAmplitudeLabel.setObjectName(u"waveAmplitudeLabel") self.horizontalLayout_7.addWidget(self.waveAmplitudeLabel) self.horizontalSpacer_2e = QSpacerItem(21, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_7.addItem(self.horizontalSpacer_2e) self.waveAmplitudeSpinBox = QDoubleSpinBox() self.waveAmplitudeSpinBox.setObjectName(u"waveAmplitudeSpinBox") self.waveAmplitudeSpinBox.setDecimals(2) self.waveAmplitudeSpinBox.setMinimum(0.000000000000000) self.waveAmplitudeSpinBox.setValue(1.500000000000000) self.horizontalLayout_7.addWidget(self.waveAmplitudeSpinBox) self.prefsOverButtonsLayout.addLayout(self.horizontalLayout_7) self.horizontalLayout_8 = QHBoxLayout() self.horizontalLayout_8.setObjectName(u"horizontalLayout_8") self.waveDirectionalityLabel = QLabel() self.waveDirectionalityLabel.setObjectName(u"waveDirectionalityLabel") self.horizontalLayout_8.addWidget(self.waveDirectionalityLabel) self.horizontalSpacer_2f = QSpacerItem(17, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_8.addItem(self.horizontalSpacer_2f) self.waveDirectionalitySpinBox = QDoubleSpinBox() self.waveDirectionalitySpinBox.setObjectName(u"waveDirectionalitySpinBox") self.waveDirectionalitySpinBox.setMinimum(0.000000000000000) self.waveDirectionalitySpinBox.setValue(0.000000000000000) self.horizontalLayout_8.addWidget(self.waveDirectionalitySpinBox) self.prefsOverButtonsLayout.addLayout(self.horizontalLayout_8) self.verticalSpacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.prefsOverButtonsLayout.addItem(self.verticalSpacer) self.line = QFrame() self.line.setObjectName(u"line") self.line.setFrameShape(QFrame.HLine) self.line.setFrameShadow(QFrame.Sunken) self.prefsOverButtonsLayout.addWidget(self.line) self.horizontalLayout_2 = QHBoxLayout() self.horizontalLayout_2.setObjectName(u"horizontalLayout_2") self.horizontalSpacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_2.addItem(self.horizontalSpacer) self.buttonBox = QDialogButtonBox() self.buttonBox.setObjectName(u"buttonBox") self.buttonBox.setStandardButtons(QDialogButtonBox.Apply|QDialogButtonBox.Cancel|QDialogButtonBox.Ok) self.horizontalLayout_2.addWidget(self.buttonBox) self.prefsOverButtonsLayout.addLayout(self.horizontalLayout_2) self.verticalLayout.addLayout(self.prefsOverButtonsLayout) self.retranslateUi(Ocean_Simulation_Settings) QMetaObject.connectSlotsByName(Ocean_Simulation_Settings) # setupUi def retranslateUi(self, Ocean_Simulation_Settings): Ocean_Simulation_Settings.setWindowTitle(QCoreApplication.translate("Preferences", u"Ocean Simulation Settings", None)) Ocean_Simulation_Settings.setProperty("comment", QCoreApplication.translate("Preferences", u"\n" " Copyright 2020 Pixar \n" " \n" " Licensed under the Apache License, Version 2.0 (the \"Apache License\") \n" " with the following modification; you may not use this file except in \n" " compliance with the Apache License and the following modification to it: \n" " Section 6. Trademarks. is deleted and replaced with: \n" " \n" " 6. Trademarks. This License does not grant permission to use the trade \n" " names, trademarks, service marks, or product names of the Licensor \n" " and its affiliates, except as required to comply with Section 4(c) of \n" " the License and to reproduce the content of the NOTI" "CE file. \n" " \n" " You may obtain a copy of the Apache License at \n" " \n" " http://www.apache.org/licenses/LICENSE-2.0 \n" " \n" " Unless required by applicable law or agreed to in writing, software \n" " distributed under the Apache License with the above modification is \n" " distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY \n" " KIND, either express or implied. See the Apache License for the specific \n" " language governing permissions and limitations under the Apache License. \n" " ", None)) self.scaleLabel.setText(QCoreApplication.translate("Preferences", u"Scale", None)) self.directionLabel.setText(QCoreApplication.translate("Preferences", u"Direction", None)) self.windSpeedLabel.setText(QCoreApplication.translate("Preferences", u"Wind Speed", None)) self.waterDepthLabel.setText(QCoreApplication.translate("Preferences", u"Water Depth", None)) self.waveAmplitudeLabel.setText(QCoreApplication.translate("Preferences", u"Wave Amplitude", None)) self.waveDirectionalityLabel.setText(QCoreApplication.translate("Preferences", u"Wave Directionality", None)) # retranslateUi
10,887
Python
46.134199
127
0.669055
NVIDIA-Omniverse/kit-osc/exts/omni.osc/omni/osc/extension.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. from typing import Any, List import carb import carb.events import carb.profiler import omni.ext import omni.kit.app from pythonosc.dispatcher import Dispatcher from .core import carb_event_payload_from_osc_message, push_to_osc_event_stream from .menu import OscMenu from .server import DaemonOSCUDPServer from .window import OscWindow class OmniOscExt(omni.ext.IExt): def on_startup(self, ext_id): def on_start(host: str, port: int) -> bool: return self.server.start(host, port) def on_stop() -> bool: return self.server.stop() def toggle_window_visible(_arg0, _arg1) -> None: """ Toggle the window visibility from the editor menu item """ self.window.visible = not self.window.visible self.server = OmniOscExt.create_server() # The main UI window default_addr = carb.settings.get_settings().get("exts/omni.osc/address") default_port = carb.settings.get_settings().get("exts/omni.osc/port") self.window = OscWindow( on_start=on_start, on_stop=on_stop, default_addr=default_addr, default_port=default_port ) # The editor menu entry that toggles the window visibility self.menu = OscMenu(on_click=toggle_window_visible) # Toggle the editor menu entry when the user closes the window self.window.set_visibility_changed_fn(lambda visible: self.menu.set_item_value(visible)) def on_shutdown(self): self.window = None self.menu = None if self.server is not None: self.server.stop() self.server = None def create_server() -> DaemonOSCUDPServer: """ Create a server that routes all OSC messages to a carbonite event stream """ @carb.profiler.profile def on_osc_msg(addr: str, *args: List[Any]) -> None: """ OSC message handler """ carb.log_verbose(f"OSC message: [{addr}, {args}]") payload = carb_event_payload_from_osc_message(addr, args) push_to_osc_event_stream(payload) # Server dispatcher = Dispatcher() dispatcher.set_default_handler(on_osc_msg) return DaemonOSCUDPServer(dispatcher)
2,714
Python
34.723684
100
0.658438
NVIDIA-Omniverse/kit-osc/exts/omni.osc/omni/osc/__init__.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import omni.kit.pipapi # python-osc: # - SWIPAT request: http://nvbugs/3684871 # - A copy of the source is forked to https://github.com/NVIDIA-Omniverse/python-osc # - The dependency vendored and installed from exts/omni.osc/vendor/python_osc-1.8.0-py3-none-any.whl omni.kit.pipapi.install( package="python-osc", module="pythonosc", use_online_index=False, ignore_cache=True, ignore_import_check=False ) from pythonosc import * # noqa: F401 from .core import * # noqa: F401,F403 from .extension import * # noqa: F401,F403 from .server import * # noqa: F401,F403 # NOTE(jshrake): omni.graph is an optional dependency so handle the case # that the below import fails try: from .ogn import * except Exception as e: print(f"omni.osc failed to import OGN due to {e}") pass
1,219
Python
37.124999
114
0.754717
NVIDIA-Omniverse/kit-osc/exts/omni.osc/omni/osc/core.py
## Copyright © 2022 NVIDIA CORPORATION & AFFILIATES. ALL RIGHTS RESERVED. ## ## This software product is a proprietary product of Nvidia Corporation and its affiliates ## (the "Company") and all right, title, and interest in and to the software ## product, including all associated intellectual property rights, are and ## shall remain exclusively with the Company. ## ## This software product is governed by the End User License Agreement ## provided with the software product. from typing import Callable, Tuple import carb import carb.events import omni.ext import omni.kit.app OSC_EVENT_TYPE_NAME: str = "omni.osc" OSC_EVENT_TYPE: int = carb.events.type_from_string(OSC_EVENT_TYPE_NAME) OSC_MESSAGE_ADDRESS_STR = "address" OSC_MESSAGE_ARGUMENTS_STR = "arguments" def get_osc_event_stream() -> carb.events._events.IEventStream: """ Returns the OSC event stream """ return omni.kit.app.get_app().get_message_bus_event_stream() def push_to_osc_event_stream(payload: dict) -> None: """ Push a payload to the OSC event stream """ get_osc_event_stream().push(OSC_EVENT_TYPE, sender=0, payload=payload) def subscribe_to_osc_event_stream( cb: Callable[[carb.events._events.IEvent], None] ) -> carb.events._events.ISubscription: """ Returns a Carbonite event subscription to the OSC event stream """ return get_osc_event_stream().create_subscription_to_pop_by_type(OSC_EVENT_TYPE, cb) def carb_event_payload_from_osc_message(address: str, args: list) -> dict: """ Return a carbonite event payload suitable for pushing to the OSC event stream """ return {OSC_MESSAGE_ADDRESS_STR: address, OSC_MESSAGE_ARGUMENTS_STR: args} def osc_message_from_carb_event(e: carb.events.IEvent) -> Tuple[str, list]: """ Return the OSC message address and arguments extracted from a carbonite event payload """ return (e.payload[OSC_MESSAGE_ADDRESS_STR], e.payload[OSC_MESSAGE_ARGUMENTS_STR])
1,961
Python
34.672727
90
0.7231
NVIDIA-Omniverse/kit-osc/exts/omni.osc/omni/osc/server.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import threading import carb import carb.events from pythonosc import osc_server from pythonosc.dispatcher import Dispatcher class DaemonOSCUDPServer: """ Run a python-osc BlockingOSCUDPServer in a separate thread. Usage:: import omni.osc.core as osc dispatcher = osc.Dispatcher() dispatcher.set_default_handler(lambda(path, args): print(f"{path}: {args}")) server = osc.DaemonOSCUDPServer(dispatcher) server.start("192.168.0.1", 3434) # ... server.stop() """ def __init__(self, dispatcher: Dispatcher): self.dispatcher: Dispatcher = dispatcher self.server: osc_server.BlockingOSCUDPServer = None self.thread: threading.Thread = None def running(self) -> bool: """ Returns true if the server is running """ return self.thread is not None and self.thread.is_alive() def start(self, addr: str, port: int) -> bool: """ Start the OSC server on the specified address and port. Does nothing if the server is already running. """ if not self.running(): carb.log_info(f"Starting OSC server on {addr}:{port}") try: self.server = osc_server.BlockingOSCUDPServer((addr, port), dispatcher=self.dispatcher) self.thread = threading.Thread(target=lambda: self.server.serve_forever()) # NOTE(jshrake): Running the thread in daemon mode ensures that the thread and server # are properly disposed of in the event that the main thread exits unexpectedly. self.thread.daemon = True self.thread.start() except Exception as e: carb.log_error(f"Error starting OSC server: {e}") else: carb.log_info("OSC server already running") return self.running() def stop(self) -> bool: """ Stops the OSC server. """ if self.running(): carb.log_info("Stopping OSC server") try: self.server.shutdown() self.thread.join() except Exception as e: carb.log_error(f"Error stopping OSC server: {e}") finally: self.server = None self.thread = None else: carb.log_info("OSC server not running") return self.running()
2,857
Python
34.28395
103
0.615681
NVIDIA-Omniverse/kit-osc/exts/omni.osc/omni/osc/menu.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import omni.kit.ui MENU_PATH = "Window/OSC" class OscMenu: def __init__(self, on_click): editor_menu = omni.kit.ui.get_editor_menu() if not editor_menu: return editor_menu.add_item(menu_path=MENU_PATH, on_click=on_click, toggle=True, value=True) def set_item_value(self, val: bool) -> None: editor_menu = omni.kit.ui.get_editor_menu() if not editor_menu: return editor_menu.set_value(MENU_PATH, val) def __del__(self): editor_menu = omni.kit.ui.get_editor_menu() if not editor_menu: return if editor_menu.has_item(MENU_PATH): editor_menu.remove_item(MENU_PATH)
1,125
Python
33.121211
93
0.672889
NVIDIA-Omniverse/kit-osc/exts/omni.osc/omni/osc/window.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. from typing import Callable import omni.ui as ui OnStartCallback = Callable[[str, int], bool] OnStopCallback = Callable[[], bool] class OscWindow(ui.Window): def __init__( self, default_addr: str, default_port: int, on_start: OnStartCallback, on_stop: OnStopCallback ) -> None: super().__init__("OSC UDP Server", width=300, height=300) def start() -> None: """ Callback when the user presses the start button """ is_running = on_start(addr.as_string, port.as_int) running.set_value(is_running) def stop() -> None: """ Callback when the user presses the stop button """ is_running = on_stop() running.set_value(is_running) def update_running_label(label: ui.Label, running: bool) -> None: """ Keep the UI label up to date with the state of the server """ if running: label.text = f"Running UDP server @ {addr.as_string}:{port.as_int}" label.set_style({"color": "green"}) else: label.text = "Stopped" label.set_style({"color": "red"}) def toggle_enabled(field: ui.AbstractField, running: bool) -> None: """ Enable or disable the input field based on the state of the server """ field.enabled = not running color = "gray" if running else "white" field.set_style({"color": color}) # Settings addr = ui.SimpleStringModel(default_addr) port = ui.SimpleIntModel(default_port) running = ui.SimpleBoolModel(False) with self.frame: with ui.VStack(): label = ui.Label("", height=20) update_running_label(label, running.get_value_as_bool()) running.add_value_changed_fn(lambda m: update_running_label(label, m.get_value_as_bool())) with ui.VStack(height=20): with ui.HStack(): ui.Label("Address:") addr_field = ui.StringField(addr) toggle_enabled(addr_field, running.get_value_as_bool()) running.add_value_changed_fn(lambda m: toggle_enabled(addr_field, m.get_value_as_bool())) ui.Spacer(height=2) with ui.HStack(): ui.Label("Port:") port_field = ui.IntField(port) toggle_enabled(port_field, running.get_value_as_bool()) running.add_value_changed_fn(lambda m: toggle_enabled(port_field, m.get_value_as_bool())) with ui.VStack(): ui.Button("Start", clicked_fn=start) ui.Button("Stop", clicked_fn=stop)
3,323
Python
39.536585
113
0.560036
NVIDIA-Omniverse/kit-osc/exts/omni.osc/omni/osc/ogn/__init__.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. """ Dynamically import every file in a directory tree that looks like a Python Ogn Node. This includes linked directories, which is the mechanism by which nodes can be hot-reloaded from the source tree. """ # Required to register nodes in Kit 104 try: import omni.graph.core as og og.register_ogn_nodes(__file__, "omni.osc") except Exception: # Swallow any exceptions pass
817
Python
37.952379
113
0.774786
NVIDIA-Omniverse/kit-osc/exts/omni.osc/omni/osc/ogn/nodes/OgnOnOscEvent.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. """ This is the implementation of the OGN node defined in OgnOnOscEvent.ogn This implementation is inspired by the OgnOnCustomEvent node See https://gitlab-master.nvidia.com/omniverse/kit/-/blob/master/kit/source/extensions/omni.graph.action/nodes/OgnOnCustomEvent.py # noqa E501 """ import re from typing import Any, List, Union import carb import carb.events import carb.profiler import omni.graph.core as og import omni.osc from omni.osc.core import OSC_MESSAGE_ADDRESS_STR, OSC_MESSAGE_ARGUMENTS_STR from .. import OgnOnOscEventDatabase class OgnOnOscEventInternalState: """Convenience class for maintaining per-node state information""" def __init__(self): """Instantiate the per-node state information.""" # This subscription object controls the lifetime of our callback, it will be # cleaned up automatically when our node is destroyed self.sub = None # Set when the callback has triggered self.is_set = False # The last event received self.event: Union[None, carb.events.IEvent] = None # The node instance handle self.node = None # The regex used to match the OSC address path self.osc_path_regex = "" # The compiled regex pattern self.osc_path_regex_pattern = None @carb.profiler.profile def on_event(self, event: carb.events.IEvent): """The event callback""" if event is None: return # Only handle messages with a path that matches the OSC address path regex osc_addr, _ = omni.osc.osc_message_from_carb_event(event) if self.osc_path_regex_pattern is None or not self.osc_path_regex_pattern.match(osc_addr): return self.is_set = True self.event = event # Tell the evaluator we need to be computed if self.node.is_valid(): self.node.request_compute() @carb.profiler.profile def first_time_subscribe(self, node: og.Node, osc_path_regex: str) -> bool: """Checked call to set up carb subscription Args: node: The node instance event_name: The name of the carb event Returns: True if we subscribed, False if we are already subscribed """ if self.osc_path_regex != osc_path_regex: # osc path regex changed since we last subscribed, re-compile try: self.osc_path_regex_pattern = re.compile(osc_path_regex) self.osc_path_regex = osc_path_regex except Exception as e: carb.log_error(f"Error compiling OSC Address Path Regex '{osc_path_regex}': {e}") if self.sub is None: self.sub = omni.osc.subscribe_to_osc_event_stream(self.on_event) self.node = node return True return False def try_pop_event(self) -> Union[None, carb.events.IEvent]: """Pop the last event received, or None if there is no event to pop""" if self.is_set: self.is_set = False event = self.event self.event = None return event return None # ====================================================================== class OgnOnOscEvent: """ This node triggers when an OSC event is received that matches the OSC address path regex. """ @staticmethod def internal_state(): """Returns an object that will contain per-node state information""" return OgnOnOscEventInternalState() @staticmethod def release(node): state = OgnOnOscEventDatabase.OgnOnOscEventDatabase.per_node_internal_state(node) if state.sub: state.sub.unsubscribe() state.sub = None @staticmethod def check_all_args_are_floats(args: List[Any]) -> bool: """ Returns true if the OSC message arguments has the shape of List[float] """ all_args_are_float = all(isinstance(arg, float) for arg in args) return all_args_are_float @staticmethod @carb.profiler.profile def compute(db: og.Database) -> bool: state: OgnOnOscEventInternalState = db.internal_state osc_path_regex = db.inputs.path state.first_time_subscribe(db.node, osc_path_regex) event = state.try_pop_event() if event is None: return False try: addr, args = omni.osc.osc_message_from_carb_event(event) # Populate the output bundle bundle: og._impl.bundles.BundleContents = db.outputs.message bundle.clear() # Update the address attribute addr_attribute = bundle.insert((og.Type(og.BaseDataType.TOKEN), OSC_MESSAGE_ADDRESS_STR)) addr_attribute.value = addr # Update the arguments attribute all_args_are_floats = OgnOnOscEvent.check_all_args_are_floats(args) # NOTE(jshrake): This node currently only supports OSC arguments shaped like a List[Float] if all_args_are_floats: if len(args) == 1: # Argument list contains a single element, write it as a double args_attribute = bundle.insert((og.Type(og.BaseDataType.DOUBLE), OSC_MESSAGE_ARGUMENTS_STR)) args_attribute.value = args[0] elif len(args) > 1: # Argument list contains multiple element, write it as a list args_attribute = bundle.insert((og.Type(og.BaseDataType.DOUBLE, tuple_count=len(args), array_depth=0), OSC_MESSAGE_ARGUMENTS_STR)) args_attribute.value = args else: carb.log_warn(f"OnOscMessage node expected OSC message arguments to be of type List[Float], instead got {args}") return False db.outputs.execOut = og.ExecutionAttributeState.ENABLED except Exception as e: carb.log_error(f"Error in OgnOnOscEvent::compute: {e}") return False return True
6,464
Python
37.254438
150
0.629332
NVIDIA-Omniverse/kit-osc/exts/omni.osc/omni/osc/tests/tests.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import asyncio import omni.kit.test import omni.osc class Test(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): pass # After running each test async def tearDown(self): pass async def test_can_start_and_stop_server(self): server = omni.osc.DaemonOSCUDPServer(None) is_running = server.start("localhost", 12345) self.assertTrue(is_running) await asyncio.sleep(0.1) is_running = server.running() self.assertTrue(is_running) is_running = server.stop() self.assertFalse(is_running) async def test_server_can_receive_messages(self): server = omni.osc.OmniOscExt.create_server() is_running = server.start("localhost", 3337) self.assertTrue(is_running) self.count = 0 def on_event(e) -> None: addr, _ = omni.osc.osc_message_from_carb_event(e) self.assertEqual(e.type, omni.osc.core.OSC_EVENT_TYPE) self.assertEqual(addr, "/filter") self.count += 1 sub = omni.osc.subscribe_to_osc_event_stream(on_event) total_msg_count = 10 def send_messages(): import random from pythonosc import udp_client client = udp_client.SimpleUDPClient(address="127.0.0.1", port=3337) self.assertTrue(client is not None) for _ in range(total_msg_count): client.send_message("/filter", random.random()) send_messages() # Wait a few seconds for the server to receive the messages await asyncio.sleep(3) # Manually pump the stream so our subscription callback executes omni.osc.get_osc_event_stream().pump() self.assertEqual(self.count, total_msg_count)
2,226
Python
34.919354
79
0.655436
AccelerationAgency/omniverse-extensions/exts/taa.google.spreadsheet.api/taa/google/spreadsheet/api/extension.py
import omni.ext import omni.ui as ui import omni.kit.commands from typing import List from pxr import Gf omni.kit.pipapi.install('google-api-python-client') omni.kit.pipapi.install('google-auth-httplib2') from googleapiclient.discovery import build from googleapiclient.errors import HttpError SPACING = 4 LABEL_WIDTH = 120 class MyExtension(omni.ext.IExt): data = {'translate_x': 0, 'translate_y': 0, 'translate_z': 0, 'rotate_x': 0, 'rotate_y': 0, 'rotate_z': 0, 'scale_x': 0, 'scale_y': 0, 'scale_z': 0} subscription = None stage = None google_sheet = None label_width = 50 _source_prim_model = ui.SimpleStringModel() # lifecycle def on_startup(self, ext_id): print("[taa.google.spreadsheet.api] Extension starting up") self.stage = omni.usd.get_context().get_stage() self._window = ui.Window("TAA Google Spreadsheet API", width=400, height=270) with self._window.frame: with ui.VStack(height=0, spacing=SPACING): with ui.CollapsableFrame("Source", name="group"): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Prim", name="attribute_name", width=LABEL_WIDTH) ui.StringField(model=self._source_prim_model) ui.Button(" S ", width=0, height=0, style={"margin": 0}, clicked_fn=self._on_get_selection, tooltip="Get From Selection") ui.Spacer(height= 12) with ui.CollapsableFrame("Settings", name="group"): with ui.VStack(height=0, spacing=SPACING): ui.Label('Spreadsheet ID', height=20) self.spreadsheet_id_field = ui.StringField(height=20) ui.Label('Range', height=20) self.range_field = ui.StringField(height=20) ui.Label('API Key', height=20) self.api_key_field = ui.StringField(height=20) ui.Spacer(height= 12) self.startButton = ui.Button("Start", height=54, clicked_fn=lambda: self.start(), style={"background_color": "green"}) self.stopButton = ui.Button("Stop", height=54, clicked_fn=lambda: self.stop(), style={"color": "red"}) ui.Spacer(height= 12) self.statusLabel = ui.Label('Click start to begin', height=14, style={"font_size": 12}) self.stopButton.visible = False print("[taa.google.spreadsheet.api] Extension start up complete") def on_shutdown(self): print("Extension shutting down") self.stop() print("Extension shutdown complete") # custom methods def _on_get_selection(self): print('_on_get_selection', self.get_selection()) self._source_prim_model.as_string = ", ".join(self.get_selection()) def get_selection(self) -> List[str]: return omni.usd.get_context().get_selection().get_selected_prim_paths() def apply_changes(self, frame): try: # load the data from Google Spreadsheet ever few seconds; this API is rate limited frameNumber = int(frame.payload["SWHFrameNumber"]) if(frameNumber % 180 != 0): return print('applying changes') self.read_data() # act on all selected prims paths = self.list_paths_of_selected_prims() for path in paths: # get reference to the prim on stage, making sure that it's valid prim = self.stage.GetPrimAtPath(path) if prim.IsValid() == False: continue # transform the prim based on the settings in the Google Spreadsheet self.move_prim(prim) self.rotate_prim(prim) self.scale_prim(prim) print('changes applied successfully') except Exception as err: print(err) def read_config(self): try: spreadsheetId = self.spreadsheet_id_field.model.get_value_as_string() range = self.range_field.model.get_value_as_string() api_key = self.api_key_field.model.get_value_as_string() return (spreadsheetId, range, api_key) except Exception as err: print(err) def read_data(self): try: spreadsheetId, range, api_key = self.read_config() if self.google_sheet == None: service = build('sheets', 'v4', developerKey=api_key) self.google_sheet = service.spreadsheets() result = self.google_sheet.values().get(spreadsheetId=spreadsheetId, range=range).execute() values = result.get('values', []) data = toJSON(values) # normalize and clean data self.data["shape"] = data.setdefault('shape', 'Cube') self.data["size"] = float(data.setdefault('size', 100)) self.data["radius"] = float(data.setdefault('radius', 100)) self.data["translate_x"] = float(data.setdefault('translate_x', 0)) self.data["translate_y"] = float(data.setdefault('translate_y', 0)) self.data["translate_z"] = float(data.setdefault('translate_z', 0)) self.data["rotate_x"] = float(data.setdefault('rotate_x', 0)) self.data["rotate_y"] = float(data.setdefault('rotate_y', 0)) self.data["rotate_z"] = float(data.setdefault('rotate_z', 0)) self.data["scale_x"] = float(data.setdefault('scale_x', 1)) self.data["scale_y"] = float(data.setdefault('scale_y', 1)) self.data["scale_z"] = float(data.setdefault('scale_z', 1)) except HttpError as err: print(err) def move_prim(self, prim): try: x = self.data.get('translate_x') y = self.data.get('translate_y') z = self.data.get('translate_z') omni.kit.commands.execute('TransformPrimSRT', path=prim.GetPath(), new_translation=Gf.Vec3d(x, y, z), ) except Exception as err: print("Failed to move prim", err) def rotate_prim(self, prim): try: x = self.data.get('rotate_x') y = self.data.get('rotate_y') z = self.data.get('rotate_z') omni.kit.commands.execute('TransformPrimSRT', path=prim.GetPath(), new_rotation_euler=Gf.Vec3d(x, y, z), ) except Exception as err: print("Failed to rotate prime", err) def scale_prim(self, prim): try: x = self.data.get('scale_x') y = self.data.get('scale_y') z = self.data.get('scale_z') omni.kit.commands.execute('TransformPrimSRT', path=prim.GetPath(), new_scale=Gf.Vec3d(x, y, z), ) except Exception as err: print("Failed to scale prim", err) def list_paths_of_selected_prims(self): try: paths = [i.strip() for i in self._source_prim_model.as_string.split(",")] if not paths: paths = self.get_selection() if not paths: pass return paths except Exception as err: print(err) def start(self): self.read_data() def on_update_apply(frame): self.apply_changes(frame) self.subscription = omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(on_update_apply) self.startButton.visible = False self.stopButton.visible = True self.statusLabel.text = "Status: started" def stop(self): if self.subscription: del self.subscription self.startButton.visible = True self.stopButton.visible = False self.statusLabel.text = "Status: stopped" """ Utility functions """ def toJSON(values): json = {} if not values: return json for row in values: key = row[0] value = row[1] if not key or not value: continue json[row[0]] = row[1] return json
8,802
Python
27.124601
152
0.527153
AccelerationAgency/omniverse-extensions/exts/taa.omniverse.cameracreator/taa/omniverse/cameracreator/extension.py
import omni.ext import omni.ui as ui import omni.kit.commands as commands class MyExtension(omni.ext.IExt): # Lifecycle def on_startup(self, ext_id): print("[taa.omniverse.viewport] Extension starting up") self._window = ui.Window("TAA Quick Camera", width=200, height = 200) with self._window.frame: with ui.VStack(height = 0, spacing = 4): self.perspectiveButton = ui.Button("Perspective", height=40, clicked_fn=lambda: self.create_perspective_camera(), style={"background_color":"black"}) self.topButton = ui.Button("Top", height=40, clicked_fn=lambda: self.create_top_camera(), style={"background_color":"black"}) self.frontButton = ui.Button("Front", height=40, clicked_fn=lambda: self.create_front_camera(), style={"background_color":"black"}) self.rightButton = ui.Button("Right", height=40, clicked_fn=lambda: self.create_right_camera(), style={"background_color":"black"}) print("[taa.omniverse.viewport] Extension start up complete") def on_shutdown(self): print("[taa.omniverse.viewport] Extension shutting down") self.stop() print("[taa.omniverse.viewport] Extension shutdown complete") # Custom methods def set_camera(self, path): omni.kit.viewport_legacy.get_viewport_interface().get_viewport_window().set_active_camera(path) def rename_camera(self, name): cameraPath = omni.kit.viewport_legacy.get_viewport_interface().get_viewport_window().get_active_camera() omni.kit.commands.execute('MovePrims', paths_to_move={cameraPath: f'/World/Camera_{name}'}) def create_perspective_camera(self): print("[taa.omniverse.viewport] Creating new perspective camera") self.set_camera("/OmniverseKit_Persp") commands.execute('DuplicateFromActiveViewportCameraCommand', viewport_name='Viewport') self.rename_camera("Perspective") def create_top_camera(self): print("[taa.omniverse.viewport] Creating new top-down camera") self.set_camera("/OmniverseKit_Top") commands.execute('DuplicateFromActiveViewportCameraCommand', viewport_name='Viewport') self.rename_camera("Top") def create_front_camera(self): print("[taa.omniverse.viewport] Creating new front view camera") self.set_camera("/OmniverseKit_Front") commands.execute('DuplicateFromActiveViewportCameraCommand', viewport_name='Viewport') self.rename_camera("Front") def create_right_camera(self): print("[taa.omniverse.viewport] Creating new right view camera") self.set_camera("/OmniverseKit_Right") commands.execute('DuplicateFromActiveViewportCameraCommand', viewport_name='Viewport') self.rename_camera("Right") def start(self): print("[taa.omniverse.viewport] Starting...") def stop(self): print("[taa.omniverse.viewport] Stopping...")
2,974
Python
44.76923
165
0.675521
ilanhuang/audio2face-streamgpt-public/exts/stream.gptchat/stream/gptchat/recording_transcription.py
#Stream-GPT #GNU - GLP Licence #Copyright (C) <year> <Huang I Lan & Erks - Virtual Studio> #This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. #This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. #You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. import os import pyaudio import wave import keyboard import time from time import sleep import openai import datetime def open_file(filepath): with open(filepath, 'r', encoding='utf-8') as infile: return infile.read() def save_file(filepath, content): with open(filepath, 'w', encoding='utf-8') as outfile: outfile.write(content) def timestamp_to_datetime(unix_time): return datetime.datetime.fromtimestamp(unix_time).strftime("%A, %B %d, %Y at %I:%M%p %Z") def record_client_voice(output_filename, recording_status): CHUNK = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 16000 frames = [] p = pyaudio.PyAudio() stream = None try: stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK) start_time = time.time() min_duration = 0.1 while recording_status() or time.time() - start_time < min_duration: data = stream.read(CHUNK) frames.append(data) except Exception as e: print(f"Error while recording audio: {e}") finally: if stream is not None: stream.stop_stream() stream.close() p.terminate() wf = wave.open(output_filename, 'wb') wf.setnchannels(CHANNELS) wf.setsampwidth(p.get_sample_size(FORMAT)) wf.setframerate(RATE) wf.writeframes(b''.join(frames)) wf.close() return output_filename def transcribe_audio_to_text(file_path): with open(file_path, 'rb') as audio_file: transcript_response = openai.Audio.transcribe("whisper-1", audio_file) return transcript_response["text"]
2,508
Python
32.013157
240
0.64673
ilanhuang/audio2face-streamgpt-public/exts/stream.gptchat/stream/gptchat/transmission.py
#Stream-GPT #GNU - GLP Licence #Copyright (C) <year> <Huang I Lan & Erks - Virtual Studio> #This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. #This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. #You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. import grpc import os import soundfile import numpy as np import audio2face_pb2 import audio2face_pb2_grpc import sounddevice as sd import time from typing import Iterator import requests import queue import threading import carb def generate_stream(text: str, voice_id: str, model_id: str, api_key: str, stream_chunk_size: int = 2048) -> Iterator[bytes]: url = f"https://api.elevenlabs.io/v1/text-to-speech/{voice_id}/stream" data = dict(text=text, model_id=model_id, voice_settings=None) headers = {"xi-api-key": api_key} response = requests.post(url, json=data, headers=headers, stream=True) for chunk in response.iter_content(chunk_size=stream_chunk_size): if chunk: yield chunk def read_api_key_from_file(file_path: str) -> str: with open(file_path, 'r') as f: return f.read().strip() def text_to_audio_stream(text, instance_name, api_key): print("text_to_audio_stream: start") settings = carb.settings.get_settings() voice_id = settings.get_as_string("/persistent/exts/omni.example.streamgpt/VOICE_ID") model_id = settings.get_as_string("/persistent/exts/omni.example.streamgpt/MODEL_ID") audio_stream = generate_stream(text, voice_id, model_id, api_key) current_dir = os.path.dirname(os.path.realpath(__file__)) audio_filename = os.path.join(current_dir, "temp_audio_response.mp3") with open(audio_filename, 'wb') as f: for chunk in audio_stream: f.write(chunk) audio_data, samplerate = soundfile.read(audio_filename, dtype="float32") if len(audio_data.shape) > 1: audio_data = np.average(audio_data, axis=1) url = "localhost:50051" audio_queue = queue.Queue() audio_queue.put(audio_data) def audio_streamer(): while not audio_queue.empty(): audio_chunk = audio_queue.get() push_audio_track_stream(url, audio_chunk, samplerate, instance_name) audio_thread = threading.Thread(target=audio_streamer) audio_thread.start() os.remove(audio_filename) print("text_to_audio_stream: end") def push_audio_track_stream(url, audio_data, samplerate, instance_name): print("push_audio_track_stream: start") chunk_size = samplerate // 10 sleep_between_chunks = 0.04 with grpc.insecure_channel(url) as channel: print("Channel created") stub = audio2face_pb2_grpc.Audio2FaceStub(channel) def make_generator(): start_marker = audio2face_pb2.PushAudioRequestStart( samplerate=samplerate, instance_name=instance_name, block_until_playback_is_finished=False, ) yield audio2face_pb2.PushAudioStreamRequest(start_marker=start_marker) for i in range(len(audio_data) // chunk_size + 1): try: time.sleep(sleep_between_chunks) chunk = audio_data[i * chunk_size : i * chunk_size + chunk_size] yield audio2face_pb2.PushAudioStreamRequest(audio_data=chunk.astype(np.float32).tobytes()) except Exception as e: print(f"Error in generator function: {e}") break request_generator = make_generator() print("Sending audio data...") response = stub.PushAudioStream(request_generator) if response.success: print("SUCCESS") else: print(f"ERROR: {response.message}") print("Channel closed")
4,203
Python
39.038095
240
0.66738
ilanhuang/audio2face-streamgpt-public/exts/stream.gptchat/stream/gptchat/extension.py
#Stream-GPT #GNU - GLP Licence #Copyright (C) <year> <Huang I Lan & Erks - Virtual Studio> #This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. #This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. #You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. import omni.ext import sys sys.path.append("C:\\Users\\ERKS 2\\Documents\\Omniverse\\ov\\pkg\\audio2face-2022.2.1\\exts\\omni.audio2face.player\omni\\audio2face\\player\\scripts\\streaming_server") import openai import carb from .window import AudioChatWindow def open_file(filepath): with open(filepath, 'r', encoding='utf-8') as infile: return infile.read() # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class MyExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): openai.api_key = AudioChatWindow.get_openai_api_key() self._window = AudioChatWindow("VIRTUAL ASSISTANT", width=400, height=525) def on_shutdown(self): self._window.destroy() self._window = None
1,821
Python
55.937498
240
0.741351
ilanhuang/audio2face-streamgpt-public/exts/stream.gptchat/stream/gptchat/chatbot.py
#Stream-GPT #GNU - GLP Licence #Copyright (C) <year> <Huang I Lan & Erks - Virtual Studio> #This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. #This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. #You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. import os import openai import json import numpy as np from numpy.linalg import norm import re from time import time,sleep from uuid import uuid4 import datetime def open_file(filepath): with open(filepath, 'r', encoding='utf-8') as infile: return infile.read() def save_file(filepath, content): with open(filepath, 'w', encoding='utf-8') as outfile: outfile.write(content) def load_json(filepath): with open(filepath, 'r', encoding='utf-8') as infile: return json.load(infile) def save_json(filepath, payload): with open(filepath, 'w', encoding='utf-8') as outfile: json.dump(payload, outfile, ensure_ascii=False, sort_keys=True, indent=2) def timestamp_to_datetime(unix_time): return datetime.datetime.fromtimestamp(unix_time).strftime("%A, %B %d, %Y at %I:%M%p %Z") def gpt3_embedding(content, engine='text-embedding-ada-002'): content = content.encode(encoding='ASCII',errors='ignore').decode() # fix any UNICODE errors response = openai.Embedding.create(input=content,engine=engine) vector = response['data'][0]['embedding'] # this is a normal list return vector def chatgpt_completion(messages, model="gpt-4", temp=0.0, top_p=1.0, tokens=400, freq_pen=0.0, pres_pen=0.0): response = openai.ChatCompletion.create( model=model, messages=messages, temperature=temp, max_tokens=tokens, top_p=top_p, frequency_penalty=freq_pen, presence_penalty=pres_pen,) text = response['choices'][0]['message']['content'] tokens_used = response['usage']['total_tokens'] filename = 'chat_%s_aibot.json' % time() script_dir = os.path.dirname(os.path.realpath(__file__)) chat_logs_path = os.path.join(script_dir, 'chat_logs') if not os.path.exists(chat_logs_path): os.makedirs(chat_logs_path) input_message = messages[-1]['content'] log_content = f"User:\n{input_message}\n\nAi_Bot:\n{text}\n\nTokens used: {tokens_used}" save_file(os.path.join(chat_logs_path, filename), log_content) return text def flatten_convo(conversation): convo = '' for i in conversation: convo += '%s: %s\n' % (i['role'].upper(), i['content']) return convo.strip() def set_openai_api_key(api_key): openai.api_key = api_key def set_system_content(content): global system_content system_content = content if __name__ == '__main__': convo_length = 30 set_openai_api_key(api_key) conversation = list() conversation.append({'role': 'system', 'content': system_content}) counter = 0 while True: # get user input, save to file a = input('\n\nCLIENT: ') conversation.append({'role': 'user', 'content': a}) filename = 'chat_%s_client.txt' % time() if not os.path.exists('chat_logs'): os.makedirs('chat_logs') save_file('chat_logs/%s' % filename, a) flat = flatten_convo(conversation) # generate a response response = chatgpt_completion(conversation) conversation.append({'role': 'assistant', 'content': response}) print('\n\nAI_Bot: %s' % response) # increment counter and consolidate memories counter += 2 if counter >= 10: # reset conversation conversation = list() conversation.append({'role': 'system', 'content': system_content})
4,226
Python
35.128205
240
0.643871
ilanhuang/audio2face-streamgpt-public/exts/stream.gptchat/stream/gptchat/window.py
#Stream-GPT #GNU - GLP Licence #Copyright (C) <year> <Huang I Lan & Erks - Virtual Studio> #This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. #This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. #You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. import os import omni.ui as ui import omni.kit.commands from omni.kit.window.popup_dialog.form_dialog import FormDialog from time import time from .recording_transcription import record_client_voice, transcribe_audio_to_text from .chatbot import chatgpt_completion, set_system_content from .transmission import text_to_audio_stream import threading import time import tempfile import datetime import carb def save_file(filepath, content): with open(filepath, 'w', encoding='utf-8') as outfile: outfile.write(content) def timestamp_to_datetime(unix_time): return datetime.datetime.fromtimestamp(unix_time).strftime("%A, %B %d, %Y at %I:%M%p %Z") class AudioChatWindow(ui.Window): def _build_fn(self): with self.frame: with ui.VStack(): with ui.ScrollingFrame(height=ui.Percent(75)): self.chat_log = ui.Label("", word_wrap=True) with ui.HStack(height=ui.Percent(10)): ui.StringField(model=self._prompt_model, multiline=True) with ui.HStack(height=ui.Percent(10)): self.record_audio_button = ui.Button("Record Audio", height=40, clicked_fn=lambda *_args, **_kwargs: self._toggle_record_audio()) ui.Button("Send", height=40, clicked_fn=lambda: self._send_text_prompt()) with ui.HStack(): ui.Button("Settings", tooltip="Configure API Key, Instance name and Default System", width=0, height=0, clicked_fn=lambda: self._open_settings()) system_settings_button = ui.Button("System", height=0, width=0) system_settings_button.set_clicked_fn(lambda: self.show_system_settings_menu()) def __init__(self, title: str, **kwargs) -> None: self.conversation = [{"role": "system", "content": ""}] self.system_content_model = ui.SimpleStringModel() self.lock = threading.Lock() super().__init__(title, **kwargs) self._prompt_model = ui.SimpleStringModel() self.frame.set_build_fn(self._build_fn) def show_system_settings_menu(self): self.system_settings_menu = ui.Menu("") with self.system_settings_menu: ui.StringField(model=self.system_content_model, multiline=True) self.system_settings_menu.show() def _toggle_record_audio(self): if not hasattr(self, "recording"): self.recording = False if not self.recording: self.recording = True threading.Thread(target=self._record_and_transcribe_audio).start() else: self.recording = False def _process_conversation(self, user_content): current_system_content = self.system_content_model.get_value_as_string().strip() if current_system_content != self.conversation[0]['content']: self.reset_chat() set_system_content(current_system_content) self.conversation.append({"role": "user", "content": user_content}) response = chatgpt_completion(self.conversation) self.chat_log.text += f"\nUser: {user_content}\nAssistant: {response}" settings = carb.settings.get_settings() instance_name = settings.get_as_string("/persistent/exts/omni.example.streamgpt/INSTANCE_NAME") threading.Thread(target=text_to_audio_stream, args=(response, instance_name, self.get_elevenlabs_api_key())).start() def _record_and_transcribe_audio(self): output_filename = "recorded_audio.wav" record_client_voice(output_filename) transcript = transcribe_audio_to_text(output_filename) self._send_audio_transcript(transcript) def _send_audio_transcript(self, transcript): self.chat_log.text += "\nThinking..." threading.Thread(target=self._process_conversation, args=(transcript,)).start() def reset_chat(self): self.chat_log.text = "" self.conversation = [{"role": "system", "content": self.system_content_model.get_value_as_string().strip()}] def _save_settings(self, dialog): values = dialog.get_values() settings = carb.settings.get_settings() settings.set_string("/persistent/exts/omni.example.streamgpt/APIKey_OPEN_AI", values["APIKey_OPEN_AI"]) settings.set_string("/persistent/exts/omni.example.streamgpt/APIKey_ELEVEN_LABS", values["APIKey_ELEVEN_LABS"]) settings.set_string("/persistent/exts/omni.example.streamgpt/VOICE_ID", values["ELEVEN_LABS_VOICE_ID"]) settings.set_string("/persistent/exts/omni.example.streamgpt/MODEL_ID", values["ELEVEN_LABS_MODEL_ID"]) settings.set_string("/persistent/exts/omni.example.streamgpt/INSTANCE_NAME", values["INSTANCE_NAME"]) dialog.hide() def _open_settings(self): settings = carb.settings.get_settings() apikey_open_ai = settings.get_as_string("/persistent/exts/omni.example.streamgpt/APIKey_OPEN_AI") apikey_eleven_labs = settings.get_as_string("/persistent/exts/omni.example.streamgpt/APIKey_ELEVEN_LABS") voice_id = settings.get_as_string("/persistent/exts/omni.example.streamgpt/VOICE_ID") model_id = settings.get_as_string("/persistent/exts/omni.example.streamgpt/MODEL_ID") instance_name = settings.get_as_string("/persistent/exts/omni.example.streamgpt/INSTANCE_NAME") if apikey_open_ai == "": apikey_open_ai = "Enter OPEN-AI API Key Here" if apikey_eleven_labs == "": apikey_eleven_labs = "Enter ELEVEN-LABS API Key Here" if instance_name == "": instance_name = "Enter Instance Name Here" if voice_id == "": voice_id = "Enter Eleven Labs Voice ID Here" if model_id == "": model_id = "Enter Eleven Labs Model ID Here" field_defs = [ FormDialog.FieldDef("APIKey_OPEN_AI", "OPEN-AI API Key: ", ui.StringField, apikey_open_ai), FormDialog.FieldDef("APIKey_ELEVEN_LABS", "ELEVEN-LABS API Key: ", ui.StringField, apikey_eleven_labs), FormDialog.FieldDef("ELEVEN_LABS_VOICE_ID", "Voice ID: ", ui.StringField, voice_id), FormDialog.FieldDef("ELEVEN_LABS_MODEL_ID", "Model ID: ", ui.StringField, model_id), FormDialog.FieldDef("INSTANCE_NAME", "Instance Name: ", ui.StringField, instance_name), ] dialog = FormDialog( title="Settings", message="Your Settings: ", field_defs=field_defs, ok_handler=lambda dialog: self._save_settings(dialog)) dialog.show() @staticmethod def get_openai_api_key(): settings = carb.settings.get_settings() return settings.get_as_string("/persistent/exts/omni.example.streamgpt/APIKey_OPEN_AI") def get_elevenlabs_api_key(self): settings = carb.settings.get_settings() return settings.get_as_string("/persistent/exts/omni.example.streamgpt/APIKey_ELEVEN_LABS") def _send_text_prompt(self): prompt = self._prompt_model.get_value_as_string() self.chat_log.text += "\nThinking..." threading.Thread(target=self._process_conversation, args=(prompt,)).start() self._prompt_model.set_value("") def _toggle_record_audio(self): if not hasattr(self, "recording"): self.recording = False self.recording = not self.recording if self.recording: self.record_audio_button.text = "Stop Recording" else: self.record_audio_button.text = "Record Audio" threading.Thread(target=self._record_and_transcribe_audio_alternative).start() def recording_status(self): return self.recording def _record_and_transcribe_audio_alternative(self): with self.lock: temp_audio_file = tempfile.NamedTemporaryFile(delete=False, suffix=".wav") temp_audio_filename = temp_audio_file.name temp_audio_file.close() recorded_audio_filename = record_client_voice(temp_audio_filename, self.recording_status) transcript = transcribe_audio_to_text(recorded_audio_filename) os.remove(temp_audio_filename) if transcript.strip(): self._send_audio_transcript(transcript) def destroy(self): super().destroy() self._prompt_model = None
9,174
Python
47.036649
240
0.645193
ilanhuang/audio2face-streamgpt-public/exts/stream.gptchat/stream/gptchat/pytransform/__init__.py
# These module alos are used by protection code, so that protection # code needn't import anything import os import platform import sys import struct # Because ctypes is new from Python 2.5, so pytransform doesn't work # before Python 2.5 # from ctypes import cdll, c_char, c_char_p, c_int, c_void_p, \ pythonapi, py_object, PYFUNCTYPE, CFUNCTYPE from fnmatch import fnmatch # # Support Platforms # plat_path = 'platforms' plat_table = ( ('windows', ('windows', 'cygwin*')), ('darwin', ('darwin',)), ('ios', ('ios',)), ('linux', ('linux*',)), ('freebsd', ('freebsd*', 'openbsd*', 'isilon onefs')), ('poky', ('poky',)), ) arch_table = ( ('x86', ('i?86', )), ('x86_64', ('x64', 'x86_64', 'amd64', 'intel')), ('arm', ('armv5',)), ('armv6', ('armv6l',)), ('armv7', ('armv7l',)), ('ppc64', ('ppc64le',)), ('mips32', ('mips',)), ('aarch32', ('aarch32',)), ('aarch64', ('aarch64', 'arm64')) ) # # Hardware type # HT_HARDDISK, HT_IFMAC, HT_IPV4, HT_IPV6, HT_DOMAIN = range(5) # # Global # _pytransform = None class PytransformError(Exception): pass def dllmethod(func): def wrap(*args, **kwargs): return func(*args, **kwargs) return wrap @dllmethod def version_info(): prototype = PYFUNCTYPE(py_object) dlfunc = prototype(('version_info', _pytransform)) return dlfunc() @dllmethod def init_pytransform(): major, minor = sys.version_info[0:2] # Python2.5 no sys.maxsize but sys.maxint # bitness = 64 if sys.maxsize > 2**32 else 32 prototype = PYFUNCTYPE(c_int, c_int, c_int, c_void_p) init_module = prototype(('init_module', _pytransform)) ret = init_module(major, minor, pythonapi._handle) if (ret & 0xF000) == 0x1000: raise PytransformError('Initialize python wrapper failed (%d)' % (ret & 0xFFF)) return ret @dllmethod def init_runtime(): prototype = PYFUNCTYPE(c_int, c_int, c_int, c_int, c_int) _init_runtime = prototype(('init_runtime', _pytransform)) return _init_runtime(0, 0, 0, 0) @dllmethod def encrypt_code_object(pubkey, co, flags, suffix=''): _pytransform.set_option(6, suffix.encode()) prototype = PYFUNCTYPE(py_object, py_object, py_object, c_int) dlfunc = prototype(('encrypt_code_object', _pytransform)) return dlfunc(pubkey, co, flags) @dllmethod def generate_license_key(prikey, keysize, rcode): prototype = PYFUNCTYPE(py_object, c_char_p, c_int, c_char_p) dlfunc = prototype(('generate_license_key', _pytransform)) return dlfunc(prikey, keysize, rcode) if sys.version_info[0] == 2 \ else dlfunc(prikey, keysize, rcode.encode()) @dllmethod def get_registration_code(): prototype = PYFUNCTYPE(py_object) dlfunc = prototype(('get_registration_code', _pytransform)) return dlfunc() @dllmethod def get_expired_days(): prototype = PYFUNCTYPE(py_object) dlfunc = prototype(('get_expired_days', _pytransform)) return dlfunc() @dllmethod def clean_obj(obj, kind): prototype = PYFUNCTYPE(c_int, py_object, c_int) dlfunc = prototype(('clean_obj', _pytransform)) return dlfunc(obj, kind) def clean_str(*args): tdict = { 'str': 0, 'bytearray': 1, 'unicode': 2 } for obj in args: k = tdict.get(type(obj).__name__) if k is None: raise RuntimeError('Can not clean object: %s' % obj) clean_obj(obj, k) def get_hd_info(hdtype, name=None): if hdtype not in range(HT_DOMAIN + 1): raise RuntimeError('Invalid parameter hdtype: %s' % hdtype) size = 256 t_buf = c_char * size buf = t_buf() cname = c_char_p(0 if name is None else name.encode('utf-8') if hasattr('name', 'encode') else name) if (_pytransform.get_hd_info(hdtype, buf, size, cname) == -1): raise PytransformError('Get hardware information failed') return buf.value.decode() def show_hd_info(): return _pytransform.show_hd_info() def assert_armored(*names): prototype = PYFUNCTYPE(py_object, py_object) dlfunc = prototype(('assert_armored', _pytransform)) def wrapper(func): def wrap_execute(*args, **kwargs): dlfunc(names) return func(*args, **kwargs) return wrap_execute return wrapper def check_armored(*names): try: prototype = PYFUNCTYPE(py_object, py_object) prototype(('assert_armored', _pytransform))(names) return True except RuntimeError: return False def get_license_info(): info = { 'ISSUER': None, 'EXPIRED': None, 'HARDDISK': None, 'IFMAC': None, 'IFIPV4': None, 'DOMAIN': None, 'DATA': None, 'CODE': None, } rcode = get_registration_code().decode() if rcode.startswith('*VERSION:'): index = rcode.find('\n') info['ISSUER'] = rcode[9:index].split('.')[0].replace('-sn-1.txt', '') rcode = rcode[index+1:] index = 0 if rcode.startswith('*TIME:'): from time import ctime index = rcode.find('\n') info['EXPIRED'] = ctime(float(rcode[6:index])) index += 1 if rcode[index:].startswith('*FLAGS:'): index += len('*FLAGS:') + 1 info['FLAGS'] = ord(rcode[index - 1]) prev = None start = index for k in ['HARDDISK', 'IFMAC', 'IFIPV4', 'DOMAIN', 'FIXKEY', 'CODE']: index = rcode.find('*%s:' % k) if index > -1: if prev is not None: info[prev] = rcode[start:index] prev = k start = index + len(k) + 2 info['CODE'] = rcode[start:] i = info['CODE'].find(';') if i > 0: info['DATA'] = info['CODE'][i+1:] info['CODE'] = info['CODE'][:i] return info def get_license_code(): return get_license_info()['CODE'] def get_user_data(): return get_license_info()['DATA'] def _match_features(patterns, s): for pat in patterns: if fnmatch(s, pat): return True def _gnu_get_libc_version(): try: prototype = CFUNCTYPE(c_char_p) ver = prototype(('gnu_get_libc_version', cdll.LoadLibrary('')))() return ver.decode().split('.') except Exception: pass def format_platform(platid=None): if platid: return os.path.normpath(platid) plat = platform.system().lower() mach = platform.machine().lower() for alias, platlist in plat_table: if _match_features(platlist, plat): plat = alias break if plat == 'linux': cname, cver = platform.libc_ver() if cname == 'musl': plat = 'musl' elif cname == 'libc': plat = 'android' elif cname == 'glibc': v = _gnu_get_libc_version() if v and len(v) >= 2 and (int(v[0]) * 100 + int(v[1])) < 214: plat = 'centos6' for alias, archlist in arch_table: if _match_features(archlist, mach): mach = alias break if plat == 'windows' and mach == 'x86_64': bitness = struct.calcsize('P'.encode()) * 8 if bitness == 32: mach = 'x86' return os.path.join(plat, mach) # Load _pytransform library def _load_library(path=None, is_runtime=0, platid=None, suffix='', advanced=0): path = os.path.dirname(__file__) if path is None \ else os.path.normpath(path) plat = platform.system().lower() for alias, platlist in plat_table: if _match_features(platlist, plat): plat = alias break name = '_pytransform' + suffix if plat == 'linux': filename = os.path.abspath(os.path.join(path, name + '.so')) elif plat in ('darwin', 'ios'): filename = os.path.join(path, name + '.dylib') elif plat == 'windows': filename = os.path.join(path, name + '.dll') elif plat in ('freebsd', 'poky'): filename = os.path.join(path, name + '.so') else: filename = None if platid is not None and os.path.isfile(platid): filename = platid elif platid is not None or not os.path.exists(filename) or not is_runtime: libpath = platid if platid is not None and os.path.isabs(platid) else \ os.path.join(path, plat_path, format_platform(platid)) filename = os.path.join(libpath, os.path.basename(filename)) if filename is None: raise PytransformError('Platform %s not supported' % plat) if not os.path.exists(filename): raise PytransformError('Could not find "%s"' % filename) try: m = cdll.LoadLibrary(filename) except Exception as e: if sys.flags.debug: print('Load %s failed:\n%s' % (filename, e)) raise # Removed from v4.6.1 # if plat == 'linux': # m.set_option(-1, find_library('c').encode()) if not os.path.abspath('.') == os.path.abspath(path): m.set_option(1, path.encode() if sys.version_info[0] == 3 else path) elif (not is_runtime) and sys.platform.startswith('cygwin'): path = os.environ['PYARMOR_CYGHOME'] m.set_option(1, path.encode() if sys.version_info[0] == 3 else path) # Required from Python3.6 m.set_option(2, sys.byteorder.encode()) if sys.flags.debug: m.set_option(3, c_char_p(1)) m.set_option(4, c_char_p(not is_runtime)) # Disable advanced mode by default m.set_option(5, c_char_p(not advanced)) # Set suffix for private package if suffix: m.set_option(6, suffix.encode()) return m def pyarmor_init(path=None, is_runtime=0, platid=None, suffix='', advanced=0): global _pytransform _pytransform = _load_library(path, is_runtime, platid, suffix, advanced) return init_pytransform() def pyarmor_runtime(path=None, suffix='', advanced=0): if _pytransform is not None: return try: pyarmor_init(path, is_runtime=1, suffix=suffix, advanced=advanced) init_runtime() except Exception as e: if sys.flags.debug or hasattr(sys, '_catch_pyarmor'): raise sys.stderr.write("%s\n" % str(e)) sys.exit(1) # ---------------------------------------------------------- # End of pytransform # ---------------------------------------------------------- # # Unused # @dllmethod def generate_license_file(filename, priname, rcode, start=-1, count=1): prototype = PYFUNCTYPE(c_int, c_char_p, c_char_p, c_char_p, c_int, c_int) dlfunc = prototype(('generate_project_license_files', _pytransform)) return dlfunc(filename.encode(), priname.encode(), rcode.encode(), start, count) if sys.version_info[0] == 3 \ else dlfunc(filename, priname, rcode, start, count) # # Not available from v5.6 # def generate_capsule(licfile): prikey, pubkey, prolic = _generate_project_capsule() capkey, newkey = _generate_pytransform_key(licfile, pubkey) return prikey, pubkey, capkey, newkey, prolic @dllmethod def _generate_project_capsule(): prototype = PYFUNCTYPE(py_object) dlfunc = prototype(('generate_project_capsule', _pytransform)) return dlfunc() @dllmethod def _generate_pytransform_key(licfile, pubkey): prototype = PYFUNCTYPE(py_object, c_char_p, py_object) dlfunc = prototype(('generate_pytransform_key', _pytransform)) return dlfunc(licfile.encode() if sys.version_info[0] == 3 else licfile, pubkey) # # Deprecated functions from v5.1 # @dllmethod def encrypt_project_files(proname, filelist, mode=0): prototype = PYFUNCTYPE(c_int, c_char_p, py_object, c_int) dlfunc = prototype(('encrypt_project_files', _pytransform)) return dlfunc(proname.encode(), filelist, mode) def generate_project_capsule(licfile): prikey, pubkey, prolic = _generate_project_capsule() capkey = _encode_capsule_key_file(licfile) return prikey, pubkey, capkey, prolic @dllmethod def _encode_capsule_key_file(licfile): prototype = PYFUNCTYPE(py_object, c_char_p, c_char_p) dlfunc = prototype(('encode_capsule_key_file', _pytransform)) return dlfunc(licfile.encode(), None) @dllmethod def encrypt_files(key, filelist, mode=0): t_key = c_char * 32 prototype = PYFUNCTYPE(c_int, t_key, py_object, c_int) dlfunc = prototype(('encrypt_files', _pytransform)) return dlfunc(t_key(*key), filelist, mode) @dllmethod def generate_module_key(pubname, key): t_key = c_char * 32 prototype = PYFUNCTYPE(py_object, c_char_p, t_key, c_char_p) dlfunc = prototype(('generate_module_key', _pytransform)) return dlfunc(pubname.encode(), t_key(*key), None) # # Compatible for PyArmor v3.0 # @dllmethod def old_init_runtime(systrace=0, sysprofile=1, threadtrace=0, threadprofile=1): '''Only for old version, before PyArmor 3''' pyarmor_init(is_runtime=1) prototype = PYFUNCTYPE(c_int, c_int, c_int, c_int, c_int) _init_runtime = prototype(('init_runtime', _pytransform)) return _init_runtime(systrace, sysprofile, threadtrace, threadprofile) @dllmethod def import_module(modname, filename): '''Only for old version, before PyArmor 3''' prototype = PYFUNCTYPE(py_object, c_char_p, c_char_p) _import_module = prototype(('import_module', _pytransform)) return _import_module(modname.encode(), filename.encode()) @dllmethod def exec_file(filename): '''Only for old version, before PyArmor 3''' prototype = PYFUNCTYPE(c_int, c_char_p) _exec_file = prototype(('exec_file', _pytransform)) return _exec_file(filename.encode())
13,587
Python
27.07438
79
0.60499
ilanhuang/audio2face-streamgpt-public/UE5_install_files/from pythonosc import udp_client.py
from pythonosc import udp_client blend = ["eyeBlinkLeft", "eyeLookDownLeft", "eyeLookInLeft", "eyeLookOutLeft", "eyeLookUpLeft", "eyeSquintLeft", "eyeWideLeft", "eyeBlinkRight", "eyeLookDownRight", "eyeLookInRight", "eyeLookOutRight", "eyeLookUpRight", "eyeSquintRight", "eyeWideRight", "jawForward", "jawLeft", "jawRight", "jawOpen", "mouthClose", "mouthFunnel", "mouthPucker", "mouthLeft", "mouthRight", "mouthSmileLeft", "mouthSmileRight", "mouthFrownLeft", "mouthFrownRight", "mouthDimpleLeft", "mouthDimpleRight", "mouthStretchLeft", "mouthStretchRight", "mouthRollLower", "mouthRollUpper", "mouthShrugLower", "mouthShrugUpper", "mouthPressLeft", "mouthPressRight", "mouthLowerDownLeft", "mouthLowerDownRight", "mouthUpperUpLeft", "mouthUpperUpRight", "browDownLeft", "browDownRight", "browInnerUp", "browOuterUpLeft", "browOuterUpRight", "cheekPuff", "cheekSquintLeft", "cheekSquintRight", "noseSneerLeft", "noseSneerRight", "tongueOut"] client = udp_client.SimpleUDPClient('127.0.0.1', 5008) osc_array = outWeight.tolist() count = 0 for i in osc_array: client.send_message('/' + str(blend[count]), i) count += 1 [python.pipapi] requirements = ['python-osc'] use_online_index = true
1,267
Python
89.571422
910
0.708761
ilanhuang/audio2face-streamgpt-public/UE5_install_files/facsSolver.py
import numpy as np from omni.audio2face.common import log_error, log_info, log_warn from scipy.optimize import lsq_linear from pythonosc import udp_client class FacsSolver: def __init__(self, neutral_mat, delta_mat): self.weightRegulCoeff = 3.5 self.weightRegulCoeff_scale = 10.0 self.prevRegulCoeff = 3.5 self.prevRegulCoeff_scale = 100.0 self.sparseRegulCoeff = 1.0 self.sparseRegulCoeff_scale = 0.25 self.symmetryRegulCoeff = 1.0 self.symmetryRegulCoeff_scale = 10.0 self.neutral_mat = neutral_mat self.delta_mat_orig = delta_mat self.delta_mat = delta_mat self.numPoses_orig = self.delta_mat_orig.shape[1] self.numPoses = self.numPoses_orig self.lb_orig = np.zeros(self.numPoses_orig) self.ub_orig = self.lb_orig + 1.0 self.lb = self.lb_orig.copy() self.ub = self.ub_orig.copy() self.activeIdxMap = range(self.numPoses_orig) self.activePosesBool = np.array([True for pi in range(self.numPoses_orig)], dtype=bool) self.cancelPoseIndices = np.array([-1 for pi in range(self.numPoses_orig)], dtype=int) self.symmetryPoseIndices = np.array([-1 for pi in range(self.numPoses_orig)], dtype=int) self.cancelList = [] self.symmetryList = [] self.symShapeMat = np.zeros((self.numPoses_orig, self.numPoses_orig)) self.prevWeights = np.zeros(self.numPoses_orig) # TODO L1 implementation l1RegulMat = np.ones((1, self.numPoses)) self.l1RegulMat = np.dot(l1RegulMat.T, l1RegulMat) self.compute_A_mat() def compute_A_mat(self): self.A = ( np.dot(self.delta_mat.T, self.delta_mat) + self.weightRegulCoeff * self.weightRegulCoeff_scale * np.eye(self.numPoses) + self.prevRegulCoeff * self.prevRegulCoeff_scale * np.eye(self.numPoses) + self.sparseRegulCoeff ** 2 * self.sparseRegulCoeff_scale * self.l1RegulMat + self.symmetryRegulCoeff * self.symmetryRegulCoeff_scale * self.symShapeMat ) self.A = self.A.astype(np.float64) def set_activePoses(self, activePosesBool): self.activePosesBool = activePosesBool # 1 - simple approach # self.ub *= np.array(self.activePosesBool) # 2- less computation way self.delta_mat = self.delta_mat_orig[:, self.activePosesBool] self.numPoses = self.delta_mat.shape[1] self.lb = self.lb_orig[self.activePosesBool] self.ub = self.ub_orig[self.activePosesBool] self.prevWeights = np.zeros(self.numPoses) self.activeIdxMap = [] cnt = 0 for idx in range(self.numPoses_orig): if self.activePosesBool[idx]: self.activeIdxMap.append(cnt) cnt += 1 else: self.activeIdxMap.append(-1) # update L1 regularization mat l1RegulMat = np.ones((1, self.numPoses)) self.l1RegulMat = np.dot(l1RegulMat.T, l1RegulMat) # update cancel pair index self.set_cancelPoses(self.cancelPoseIndices) # update symmetry pair index self.set_symmetryPoses(self.symmetryPoseIndices) # update self.A here def set_cancelPoses(self, cancelPoseIndices): self.cancelPoseIndices = cancelPoseIndices # filter out cancel shapes self.cancelList = [] maxIdx = np.max(self.cancelPoseIndices) if maxIdx < 0: return for ci in range(maxIdx + 1): cancelIndices = np.where(self.cancelPoseIndices == ci)[0] if len(cancelIndices) > 2: log_warn("There is more than 2 poses for a cancel index %d" % ci) break elif len(cancelIndices) < 2: log_warn("There is less than 2 poses for a cancel index %d" % ci) break self.cancelList.append(cancelIndices) # print ('cancel shape list', self.cancelList) activeCancelList = [] for pIdx1, pIdx2 in self.cancelList: if self.activePosesBool[pIdx1] and self.activePosesBool[pIdx2]: activeCancelList.append([self.activeIdxMap[pIdx1], self.activeIdxMap[pIdx2]]) # print (activeCancelList) self.cancelList = activeCancelList def set_symmetryPoses(self, symmetryPoseIndices): self.symmetryPoseIndices = symmetryPoseIndices self.symmetryList = [] maxIdx = np.max(self.symmetryPoseIndices) if maxIdx < 0: self.symShapeMat = np.zeros((self.numPoses, self.numPoses)) else: for ci in range(maxIdx + 1): symmetryIndices = np.where(self.symmetryPoseIndices == ci)[0] if len(symmetryIndices) > 2: log_warn("There is more than 2 poses for a cancel index %d" % ci) break elif len(symmetryIndices) < 2: log_warn("There is less than 2 poses for a cancel index %d" % ci) break self.symmetryList.append(symmetryIndices) activeSymmetryList = [] for pIdx1, pIdx2 in self.symmetryList: if self.activePosesBool[pIdx1] and self.activePosesBool[pIdx2]: activeSymmetryList.append([self.activeIdxMap[pIdx1], self.activeIdxMap[pIdx2]]) self.symmetryList = activeSymmetryList symShapeMat = np.zeros((len(self.symmetryList), self.numPoses)) for si, [pose1Idx, pose2Idx] in enumerate(self.symmetryList): symShapeMat[si, pose1Idx] = 1.0 symShapeMat[si, pose2Idx] = -1.0 self.symShapeMat = np.dot(symShapeMat.T, symShapeMat) self.compute_A_mat() def set_l2_regularization(self, L2=3.5): self.weightRegulCoeff = L2 self.compute_A_mat() def set_tempo_regularization(self, temporal=3.5): self.prevRegulCoeff = temporal self.compute_A_mat() def set_l1_regularization(self, L1=1.0): self.sparseRegulCoeff = L1 self.compute_A_mat() def set_symmetry_regularization(self, value=1.0): self.symmetryRegulCoeff = value self.compute_A_mat() def computeFacsWeights(self, point_mat): target_delta_mat = point_mat - self.neutral_mat B = ( np.dot(self.delta_mat.T, target_delta_mat).flatten() + self.prevRegulCoeff * self.prevRegulCoeff_scale * self.prevWeights ) B = B.astype(np.float64) res = lsq_linear(self.A, B, bounds=(self.lb, self.ub), lsmr_tol="auto", verbose=0, method="bvls") # print ('first pass:', res.x) if len(self.cancelList) > 0: # check cancelling poses - ub = self.ub.copy() lb = self.lb.copy() for pose1Idx, pose2Idx in self.cancelList: if res.x[pose1Idx] >= res.x[pose2Idx]: ub[pose2Idx] = 1e-10 else: ub[pose1Idx] = 1e-10 res = lsq_linear(self.A, B, bounds=(lb, ub), lsmr_tol="auto", verbose=0, method="bvls") self.prevWeights = res.x # print ('second pass:', res.x) outWeight = np.zeros(self.numPoses_orig) outWeight[self.activePosesBool] = res.x outWeight = outWeight * (outWeight > 1.0e-9) # print (outWeight) blend = ["eyeBlinkLeft", "eyeLookDownLeft", "eyeLookInLeft", "eyeLookOutLeft", "eyeLookUpLeft", "eyeSquintLeft", "eyeWideLeft", "eyeBlinkRight", "eyeLookDownRight", "eyeLookInRight", "eyeLookOutRight", "eyeLookUpRight", "eyeSquintRight", "eyeWideRight", "jawForward", "jawLeft", "jawRight", "jawOpen", "mouthClose", "mouthFunnel", "mouthPucker", "mouthLeft", "mouthRight", "mouthSmileLeft", "mouthSmileRight", "mouthFrownLeft", "mouthFrownRight", "mouthDimpleLeft", "mouthDimpleRight", "mouthStretchLeft", "mouthStretchRight", "mouthRollLower", "mouthRollUpper", "mouthShrugLower", "mouthShrugUpper", "mouthPressLeft", "mouthPressRight", "mouthLowerDownLeft", "mouthLowerDownRight", "mouthUpperUpLeft", "mouthUpperUpRight", "browDownLeft", "browDownRight", "browInnerUp", "browOuterUpLeft", "browOuterUpRight", "cheekPuff", "cheekSquintLeft", "cheekSquintRight", "noseSneerLeft", "noseSneerRight", "tongueOut"] try: client = udp_client.SimpleUDPClient('127.0.0.1', 27008) osc_array = outWeight.tolist() count = 0 for i in osc_array: client.send_message('/' + str(blend[count]), i) count += 1 except Exception as e: log_error(f"Error in OSC communication: {e}")
8,708
Python
41.276699
918
0.614378
matthias-research/omni.fun/exts/omni.fun/omni/fun/scripts/sim.py
# Copyright 2022 Matthias Müller - Ten Minute Physics, # https://www.youtube.com/c/TenMinutePhysics # www.matthiasMueller.info/tenMinutePhysics # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import numpy as np import math import warp as wp from pxr import Usd, UsdGeom, Gf, Sdf from .usdutils import * gravity = -9.81 @wp.struct class SimData: sphere_radius: wp.array(dtype=float) sphere_mass: wp.array(dtype=float) sphere_pos: wp.array(dtype=wp.vec3) sphere_rot: wp.array(dtype=wp.quat) sphere_lin_vel: wp.array(dtype=wp.vec3) sphere_ang_vel: wp.array(dtype=wp.vec3) sphere_pos_corr: wp.array(dtype=wp.vec3) sphere_lin_corr: wp.array(dtype=wp.vec3) sphere_ang_corr: wp.array(dtype=wp.vec3) sphere_num_corr: wp.array(dtype=int) sphere_lower_bounds: wp.array(dtype=wp.vec3) sphere_upper_bounds: wp.array(dtype=wp.vec3) sphere_bvh_id: wp.uint64 obj_mesh_id: wp.uint64 obj_tri_ids: wp.array(dtype=int) obj_orig_pos: wp.array(dtype=wp.vec3) obj_pos: wp.array(dtype=wp.vec3) obj_prev_pos: wp.array(dtype=wp.vec3) obj_transforms: wp.array(dtype=wp.mat44) obj_pos_transform_nr: wp.array(dtype=int) @wp.kernel def dev_integrate( dt: float, gravity: wp.vec3, bounds_margin: float, sim: SimData): sphere_nr = wp.tid() pos = sim.sphere_pos[sphere_nr] lin_vel = sim.sphere_lin_vel[sphere_nr] rot = sim.sphere_rot[sphere_nr] ang_vel = sim.sphere_ang_vel[sphere_nr] # move state forward in time lin_vel = lin_vel + gravity * dt pos = pos + lin_vel * dt qt = wp.quat(ang_vel[0], ang_vel[1], ang_vel[2], 0.0) * (dt * 0.5) rot = wp.normalize(rot + qt * rot) sim.sphere_pos[sphere_nr] = pos sim.sphere_lin_vel[sphere_nr] = lin_vel sim.sphere_rot[sphere_nr] = rot # compute bounding box for bvh pred_pos = pos + lin_vel * dt lower = wp.vec3(wp.min(pos[0], pred_pos[0]), wp.min(pos[1], pred_pos[1]), wp.min(pos[2], pred_pos[2])) upper = wp.vec3(wp.max(pos[0], pred_pos[0]), wp.max(pos[1], pred_pos[1]), wp.max(pos[2], pred_pos[2])) m = bounds_margin + sim.sphere_radius[sphere_nr] sim.sphere_lower_bounds[sphere_nr] = lower - wp.vec3(m, m, m) sim.sphere_upper_bounds[sphere_nr] = upper + wp.vec3(m, m, m) @wp.kernel def dev_handle_sphere_sphere_collisions( restitution: float, sim: SimData): sphere0 = wp.tid() eps = 0.00001 pos0 = sim.sphere_pos[sphere0] radius0 = sim.sphere_radius[sphere0] m0 = sim.sphere_mass[sphere0] w0 = 1.0 / (m0 + eps) vel0 = sim.lin_vel[sphere0] ang0 = sim.ang_vel[sphere0] lower = sim.sphere_lower_bounds[sphere0] upper = sim.sphere_upper_bounds[sphere0] query = wp.bvh_query_aabb(sim.spheres_bvh_id, lower, upper) sphere1 = int(0) while (wp.bvh_query_next(query, sphere1)): if sphere1 < sphere0: # handle each pair only once! pos1 = sim.sphere_pos[sphere1] radius1 = sim.sphere_radius[sphere1] m1 = sim.sphere_mass[sphere1] w1 = 1.0 / (m1 + eps) vel1 = sim.lin_vel[sphere1] ang1 = sim.ang_vel[sphere1] min_dist = radius0 + radius1 pos_normal = wp.normalize(pos1 - pos0) dist = wp.dot(pos_normal, pos1 - pos0) if dist < min_dist: # bounce wp.atomic_add(sim.sphere_num_corr, sphere0, 1) wp.atomic_add(sim.sphere_num_corr, sphere1, 1) pos_corr = pos_normal / (w0 + w1) * (min_dist - dist + eps) wp.atomic_add(sim.pos_corr, sphere0, -w0 * pos_corr) wp.atomic_add(sim.pos_corr, sphere1, +w1 * pos_corr) vn0 = wp.dot(vel0, pos_normal) vn1 = wp.dot(vel1, pos_normal) new_vn0 = (m0 * vn0 + m1 * vn1 - m1 * (vn0 - vn1) * restitution) / (m0 + m1) new_vn1 = (m0 * vn0 + m1 * vn1 - m0 * (vn1 - vn0) * restitution) / (m0 + m1) new_vn0 = wp.min(0.0, new_vn0) new_vn1 = wp.max(0.0, new_vn1) lin_corr0 = pos_normal * (new_vn0 - vn0) lin_corr1 = pos_normal * (new_vn1 - vn1) wp.atomic_add(sim.sphere_lin_corr, sphere0, lin_corr0) wp.atomic_add(sim.sphere_lin_corr, sphere1, lin_corr1) vel0 = vel0 + lin_corr0 vel1 = vel1 + lin_corr1 # friction ang_normal = wp.normalize(ang0 * m0 + ang1 * m1) ang_normal = wp.nomralize(ang_normal - pos_normal * wp.dot(pos_normal, ang_normal)) vt0 = wp.dot(vel0, wp.cross(ang_normal, pos_normal)) vt1 = wp.dot(vel1, wp.cross(ang_normal, pos_normal)) omega0 = wp.dot(ang0, ang_normal) omega1 = wp.dot(ang1, ang_normal) # v0 + (o0 - do*w0) * r0 = v1 + (o1 + do*w1) * r1 domega = (vt1 + omega1 * radius1 - vt0 - omega0 * radius0) / (radius0 * w0 + radius1 * w1) ang_corr0 = ang_normal * (omega0 - domega * w0) - ang0 ang_corr1 = ang_normal * (omega1 + domega * w1) - ang1 ang0 = ang0 + ang_corr0 ang1 = ang1 + ang_corr1 wp.atomic_add(sim.sphere_ang_corr, sphere0, ang_corr0) wp.atomic_add(sim.sphere_ang_corr, sphere1, ang_corr1) @wp.kernel def dev_update_obj_pos(sim: SimData): id = wp.tid() trans_nr = sim.pos_transform_nr[id] pos = sim.obj_transforms[trans_nr] * sim.orig_pos[id] sim.prev_pos[id] = sim.pos[id] sim.pos[id] = pos @wp.kernel def dev_handle_sphere_obj_collisions( dt: float, restitution: float, sim: SimData): sphere_nr = wp.tid() pos = sim.sphere_pos[sphere_nr] radius = sim.sphere_radius[sphere_nr] vel = sim.lin_vel[sphere_nr] ang = sim.ang_vel[sphere_nr] inside = float(0.0) face_nr = int(0) u = float(0.0) v = float(0.0) found = wp.mesh_query_point(sim.obj_mesh_id, pos, radius, inside, face_nr, u, v) if not found: return id0 = sim.obj_tri_ids[3 * face_nr] id1 = sim.obj_tri_ids[3 * face_nr + 1] id2 = sim.obj_tri_ids[3 * face_nr + 2] p0 = sim.obj_pos[id0] p1 = sim.obj_pos[id1] p2 = sim.obj_pos[id2] closest = u * p0 + v * p1 + (1.0 - u - v) * p2 pos_normal = wp.normalize(pos - closest) dist = wp.dot(pos_normal, pos - closest) if dist >= radius: return sim.sphere_pos[sphere_nr] = pos - pos_normal * (radius - dist) v0 = (p0 - sim.mesh_prev_points[id0]) / dt v1 = (p1 - sim.mesh_prev_points[id1]) / dt v2 = (p2 - sim.mesh_prev_points[id2]) / dt v_mesh = v0 + u * (v1 - v0) + v * (v2 - v0) v_mesh = u * v0 + v * v1 + (1.0 - u - v) * v2 vn_sphere = wp.dot(sim.sphere_lin_vel[sphere_nr], pos_normal) vn_mesh = wp.dot(v_mesh, pos_normal) new_vn = wp.min(vn_mesh - (vn_sphere - vn_mesh) * restitution, 0.0) sim.sphere_lin_vel[sphere_nr] = v + pos_normal * (new_vn - vn_sphere) # friction ang_normal = wp.normalize(ang) ang_normal = wp.nomralize(ang - pos_normal * wp.dot(pos_normal, ang_normal)) vt = wp.dot(vel, wp.cross(ang_normal, pos_normal)) omega = wp.dot(ang, ang_normal) # vel + (omega + do) * r = v_mesh domega = (vt + omega * radius - v_mesh) / radius ang = ang + ang_normal * (omega - domega) sim.sphere_ang_vel[sphere_nr] = ang @wp.kernel def dev_apply_corrections( sim: SimData): sphere_nr = wp.tid() num = sim.sphere_num_corr[sphere_nr] if num > 0: s = 1.0 / float(num) sim.sphere_pos[sphere_nr] += sim.sphere_pos_corr[sphere_nr] * s sim.sphere_lin_vel[sphere_nr] += sim.sphere_lin_corr[sphere_nr] * s sim.sphere_ang_vel[sphere_nr] += sim.sphere_ang_corr[sphere_nr] * s class Sim(): def __init__(self, stage): self.paused = True self.stage = stage self.device = 'cuda' self.prim_cache = UsdGeom.XformCache() self.dev_sim_data = SimData() self.host_sim_data = SimData() self.spheres_bvh = None self.obj_mesh = None self.sphere_usd_meshes = [] self.obj_usd_prims = [] self.obj_usd_transforms = [] self.initialized = False self.time_step = 1.0 / 30.0 self.num_substeps = 5 self.restitution = 0.1 self.jacobi_scale = 0.25 self.num_spheres = 0 self.frame_nr = 0 def init(self): if not self.stage: return obj_pos = [] obj_pos_transform_nr = [] obj_tri_ids = [] sphere_pos = [] sphere_radius = [] sphere_inv_mass = [] self.sphere_usd_meshes = [] self.sphere_usd_transforms = [] s = 4.0 / 3.0 * 3.141592 print("traversing stage") for prim in self.stage.Traverse(): if prim.GetTypeName() == "Mesh": mesh = UsdGeom.Mesh(prim) name = mesh.GetName() points = mesh.GetPointsAttr().Get(0.0) if name.find("sphere") != 0 or name.find("Sphere") != 0: # create a sphere trans_mat, trans_t = get_global_transform(prim, 0.0, False) trans_points = points @ trans_mat min = np.min(trans_points, axis = 0) max = np.max(trans_points, axis = 0) radius = np.max(max - min) * 0.5 sphere_radius.append(radius) sphere_pos.append(trans_t) mass = s * radius * radius * radius sphere_inv_mass.append(1.0 / mass) clone = clone_prim(self.stage, prim) self.sphere_usd_meshes.append(UsdGeom.Mesh(clone)) self.sphere_usd_transforms.append(clone.Get) else: obj_nr = len(self.obj_usd_prims) self.object_usd_prims.append(prim) # create obstacle points first_pos = len(obj_pos) for i in range(len(mesh_points)): p = mesh_points[i] obj_pos.append(wp.vec3(*p)) obj_pos_transform_nr.append(obj_nr) # create obstacle triangles mesh_poly_indices = mesh.GetFaceVertexIndicesAttr().Get(0.0) mesh_face_sizes = mesh.GetFaceVertexCountsAttr().Get(0.0) mesh_points = np.array(points) first_index = 0 for i in range(len(mesh_face_sizes)): face_size = mesh_face_sizes[i] for j in range(1, face_size-1): obj_tri_ids.append(first_pos + mesh_poly_indices[first_index]) obj_tri_ids.append(first_pos + mesh_poly_indices[first_index + j]) obj_tri_ids.append(first_pos + mesh_poly_indices[first_index + j + 1]) first_index += face_size # create objects warp buffers if len(obj_pos) > 0: self.dev_sim_data.obj_pos = wp.array(obj_pos, dtype=wp.vec3, device=self.device) self.dev_sim_data.pbj_prev_pos = wp.array(obj_pos, dtype=wp.vec3, device=self.device) self.dev_sim_data.obj_tri_ids = wp.array(obj_tri_ids, dtype=int, device=self.device) self.obj_mesh = wp.Mesh(self.dev_sim_data.obj_pos, self.dev_sim_data.obj_tri_ids) self.dev_sim_data.obj_mesh_id = self.obj_mesh.id num_objs = len(self.object_usd_prims) mat = wp.mat44() self.obj_transforms = np.array([mat] * num_objs) self.dev_sim_data.obj_transforms = wp.zeros(shape=(num_objs), dtype=wp.mat44, device=self.device) # create sphere warp buffers self.num_spheres = len(sphere_pos) if self.num_spheres > 0: self.dev_sim_data.sphere_radius = wp.array(sphere_radius, dtype=float, device=self.device) self.dev_sim_data.sphere_pos = wp.array(sphere_pos, dtype=wp.vec3, device=self.device) self.dev_sim_data.sphere_quat = wp.zeros(shape=(self.num_spheres), dtype=wp.quat, device=self.device) self.dev_sim_data.sphere_vel = wp.zeros(shape=(self.num_spheres), dtype=wp.vec3, device=self.device) self.dev_sim_data.sphere_omega = wp.zeros(shape=(self.num_spheres), dtype=wp.vec3, device=self.device) self.dev_sim_data.sphere_lower_bounds = wp.zeros(shape=(self.num_spheres), dtype=wp.vec3, device=self.device) self.dev_sim_data.sphere_upper_bounds = wp.zeros(shape=(self.num_spheres), dtype=wp.vec3, device=self.device) self.host_sim_data.sphere_pos = wp.array(sphere_pos, dtype=wp.vec3, device="cpu") self.host_sim_data.sphere_quat = wp.zeros(shape=(self.num_spheres), dtype=wp.quat, device="cpu") # zero time step to initialize sphere bounds wp.launch(kernel = self.dev_integrate, inputs = [0.0, wp.vec3(0.0, 0.0, 0.0), self.dev_sim_data], dim = self.num_spheres, device=self.device) self.sphere_bvh = wp.Bvh(self.dev_sim_data.sphere_lower_bounds, self.dev_sim_data.sphere_upper_bounds) self.dev_sim_data.sphere_bvh_id = self.sphere_bvh.id def simulate(self): if self.paused: return self.frame_nr += 1 print("simulating", self.frame_nr) return # update objects for i in range(len(self.object_usd_prims)): self.obj_transforms[i] = get_global_transform(self.object_usd_prims[i], 0.0, True) wp.copy(self.dev_sim_data.obj_transforms, wp.array(self.obj_transforms, dtype=wp.array(wp.mat44), copy=False, device="cpu")) wp.launch(kernel = dev_update_obj_pos, inputs = [self.dev_sim_data], dim = len(self.dev_sim_data.obj_pos), device=self.device) self.obj_mesh.refit() #simulate spheres wp.launch(kernel = dev_integrate, inputs = [self.time_step, self.gravity, self.dev_sim_data], dim = self.num_spheres, device=self.device) self.sphere_bvh.refit() self.dev_sim_data.sphere_pos_corr.zero_() self.dev_sim_data.sphere_lin_corr.zero_() self.dev_sim_data.sphere_ang_corr.zero_() self.dev_sim_data.sphere_num_corr.zero_() wp.launch(kernel = dev_handle_sphere_sphere_collisions, inputs = [self.restitution, self.dev_sim_data], dim = self.num_spheres, device=self.device) wp.launch(kernel = dev_apply_corrections, inputs = [self.dev_sim_data], dim = self.num_spheres, device=self.device) wp.launch(kernel = dev_handle_sphere_obj_collisions, inputs = [self.time_step, self.restitution, self.dev_sim_data], dim = self.num_spheres, device=self.device) # update stage wp.copy(self.host_sim_data.sphere_pos, self.dev_sim_data.sphere_pos) wp.copy(self.host_sim_data.sphere_quat, self.dev_sim_data.sphere_quat) pos = self.host_sim_data.numpy() quat = self.host_sim_data.numpy() for i in range(self.num_spheres): set_transform(self.sphere_usd_meshes, pos[i], quat[i]) def reset(self): hide_clones(self.stage) self.paused = True
16,580
Python
34.734914
462
0.5769
matthias-research/omni.fun/exts/omni.fun/omni/fun/scripts/extension.py
# Copyright 2022 Matthias Müller - Ten Minute Physics, # https://www.youtube.com/c/TenMinutePhysics # www.matthiasMueller.info/tenMinutePhysics # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import omni.ext import os import omni.usd from omni import ui from pxr import Usd from .controls import ControlsWindow from .sim import Sim EXAMPLES_PATH = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../../data/scenes")) class OmniFunExtension(omni.ext.IExt): def on_startup(self, ext_id): print("fun on_startup") setattr(self, "controls", None) setattr(self, "sim", None) stage = omni.usd.get_context().get_stage() self.sim = Sim(stage) self.sim.init() editor_menu = omni.kit.ui.get_editor_menu() self.menu_items = [] if editor_menu: self.controls_menu = editor_menu.add_item( f"Window/Fun/Controls", lambda _, value: self.show_controls(value), toggle=True, value=False ) self.menu_items.append(editor_menu.add_item( f"Window/Fun/SimpleScene", lambda _, value: self.load_example("simple.usd"), toggle=False, value=False )) # self.show_controls(True) # set callbacks self.update_event_stream = omni.kit.app.get_app_interface().get_update_event_stream() self.stage_event_sub = omni.usd.get_context().get_stage_event_stream().create_subscription_to_pop(self.on_event) def on_shutdown(self): print("fun on_shutdown") self.menu_items = None self.update_event_stream = None self.stage_event_sub = None if self.sim: self.sim.reset() self.show_controls(False) def init_callback(self, state): if state: stage = omni.usd.get_context().get_stage() if self.sim: self.sim = Sim(stage) self.update_event_sub = self.update_event_stream.create_subscription_to_pop(self.on_update) else: if self.sim: self.sim.reset() self.sim = None def play_callback(self, state): if self.sim: self.sim.paused = not state def on_update(self, dt): if self.sim: self.sim.simulate() def set_controls_menu(self, visible): omni.kit.ui.get_editor_menu().set_value(f"Window/Fun/Controls", visible) def show_controls(self, is_visible): if is_visible: if not hasattr(self, "controls"): setattr(self, "controls", None) if self.controls is None: self.controls = ControlsWindow( init_callback=self.init_callback, play_callback=self.play_callback) self.controls.create_window(lambda visible: self.set_controls_menu(visible)) self.controls.show_window() else: self.controls.show_window() elif self.controls: self.controls.destroy_window() self.controls = None def on_event(self, event): if event.type == int(omni.usd.StageEventType.CLOSED): if self.sim: self.sim.reset() if event.type == int(omni.usd.StageEventType.OPENED): if self.sim: self.sim.init() def load_example(self, scene_name): def new_stage(): stage_path = os.path.normpath(os.path.join(EXAMPLES_PATH, scene_name)) omni.usd.get_context().open_stage(stage_path) if self.sim: self.sim.init() omni.kit.window.file.prompt_if_unsaved_stage(new_stage)
4,788
Python
35.007519
462
0.618421