file_path
stringlengths 20
207
| content
stringlengths 5
3.85M
| size
int64 5
3.85M
| lang
stringclasses 9
values | avg_line_length
float64 1.33
100
| max_line_length
int64 4
993
| alphanum_fraction
float64 0.26
0.93
|
---|---|---|---|---|---|---|
AshisGhosh/roboai/isaac_sim/humble_ws/src/navigation/isaac_ros_navigation_goal/isaac_ros_navigation_goal/goal_generators/random_goal_generator.py | import numpy as np
from .goal_generator import GoalGenerator
class RandomGoalGenerator(GoalGenerator):
"""
Random goal generator.
parameters
----------
grid_map: GridMap Object
distance: distance in meters to check vicinity for obstacles.
"""
def __init__(self, grid_map, distance):
self.__grid_map = grid_map
self.__distance = distance
def generate_goal(self, max_num_of_trials=1000):
"""
Generate the goal.
Parameters
----------
max_num_of_trials: maximum number of pose generations when generated pose keep is not a valid pose.
Returns
-------
[List][Pose]: Pose in format [pose.x,pose.y,orientaion.x,orientaion.y,orientaion.z,orientaion.w]
"""
range_ = self.__grid_map.get_range()
trial_count = 0
while trial_count < max_num_of_trials:
x = np.random.uniform(range_[0][0], range_[0][1])
y = np.random.uniform(range_[1][0], range_[1][1])
orient_x = np.random.uniform(0, 1)
orient_y = np.random.uniform(0, 1)
orient_z = np.random.uniform(0, 1)
orient_w = np.random.uniform(0, 1)
if self.__grid_map.is_valid_pose([x, y], self.__distance):
goal = [x, y, orient_x, orient_y, orient_z, orient_w]
return goal
trial_count += 1
| 1,405 | Python | 30.954545 | 107 | 0.560854 |
AshisGhosh/roboai/isaac_sim/humble_ws/src/navigation/isaac_ros_navigation_goal/isaac_ros_navigation_goal/goal_generators/__init__.py | from .random_goal_generator import RandomGoalGenerator
from .goal_reader import GoalReader
__all__ = ["RandomGoalGenerator", "GoalReader"]
| 140 | Python | 27.199995 | 54 | 0.785714 |
AshisGhosh/roboai/isaac_sim/humble_ws/src/navigation/isaac_ros_navigation_goal/isaac_ros_navigation_goal/goal_generators/goal_generator.py | from abc import ABC, abstractmethod
class GoalGenerator(ABC):
"""
Parent class for the Goal generators
"""
def __init__(self):
pass
@abstractmethod
def generate_goal(self, max_num_of_trials=2000):
"""
Generate the goal.
Parameters
----------
max_num_of_trials: maximum number of pose generations when generated pose keep is not a valid pose.
Returns
-------
[List][Pose]: Pose in format [pose.x,pose.y,orientaion.x,orientaion.y,orientaion.z,orientaion.w]
"""
pass
| 582 | Python | 21.423076 | 107 | 0.580756 |
AshisGhosh/roboai/isaac_sim/humble_ws/src/navigation/isaac_ros_navigation_goal/assets/carter_warehouse_navigation.yaml | image: carter_warehouse_navigation.png
resolution: 0.05
origin: [-11.975, -17.975, 0.0000]
negate: 0
occupied_thresh: 0.65
free_thresh: 0.196
| 142 | YAML | 19.428569 | 38 | 0.739437 |
AshisGhosh/roboai/isaac_sim/humble_ws/src/ros_utils/setup.py | import os
from setuptools import find_packages, setup
from glob import glob
package_name = "ros_utils"
setup(
name=package_name,
version="0.0.0",
packages=find_packages(exclude=["test"]),
data_files=[
("share/ament_index/resource_index/packages", ["resource/" + package_name]),
("share/" + package_name, ["package.xml"]),
(os.path.join("share", package_name, "launch"), glob("launch/*.launch.py")),
],
install_requires=["setuptools"],
zip_safe=True,
maintainer="root",
maintainer_email="[email protected]",
description="TODO: Package description",
license="TODO: License declaration",
tests_require=["pytest"],
entry_points={
"console_scripts": ["dynamic_repub = ros_utils.dynamic_repub:main"],
},
)
| 787 | Python | 28.185184 | 84 | 0.636595 |
AshisGhosh/roboai/isaac_sim/humble_ws/src/ros_utils/test/test_flake8.py | # Copyright 2017 Open Source Robotics Foundation, Inc.
#
# 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.
from ament_flake8.main import main_with_errors
import pytest
@pytest.mark.flake8
@pytest.mark.linter
def test_flake8():
rc, errors = main_with_errors(argv=[])
assert rc == 0, "Found %d code style errors / warnings:\n" % len(
errors
) + "\n".join(errors)
| 878 | Python | 32.807691 | 74 | 0.730068 |
AshisGhosh/roboai/isaac_sim/humble_ws/src/ros_utils/test/test_pep257.py | # Copyright 2015 Open Source Robotics Foundation, Inc.
#
# 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.
from ament_pep257.main import main
import pytest
@pytest.mark.linter
@pytest.mark.pep257
def test_pep257():
rc = main(argv=[".", "test"])
assert rc == 0, "Found code style errors / warnings"
| 803 | Python | 32.499999 | 74 | 0.743462 |
AshisGhosh/roboai/isaac_sim/humble_ws/src/ros_utils/test/test_copyright.py | # Copyright 2015 Open Source Robotics Foundation, Inc.
#
# 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.
from ament_copyright.main import main
import pytest
# Remove the `skip` decorator once the source file(s) have a copyright header
@pytest.mark.skip(
reason="No copyright header has been placed in the generated source file."
)
@pytest.mark.copyright
@pytest.mark.linter
def test_copyright():
rc = main(argv=[".", "test"])
assert rc == 0, "Found errors"
| 968 | Python | 33.607142 | 78 | 0.746901 |
AshisGhosh/roboai/isaac_sim/humble_ws/src/ros_utils/launch/launch_pointcloud.launch.py | from launch import LaunchDescription
from launch.actions import IncludeLaunchDescription
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import ThisLaunchFileDir
def generate_launch_description():
# Path to the first launch file
pointcloud_gen = IncludeLaunchDescription(
PythonLaunchDescriptionSource(
[ThisLaunchFileDir(), "/pointcloud_gen.launch.py"]
)
)
# Path to the second launch file
dynamic_repub = IncludeLaunchDescription(
PythonLaunchDescriptionSource([ThisLaunchFileDir(), "/dynamic_repub.launch.py"])
)
return LaunchDescription([pointcloud_gen, dynamic_repub])
| 696 | Python | 32.190475 | 88 | 0.755747 |
AshisGhosh/roboai/isaac_sim/humble_ws/src/ros_utils/launch/dynamic_repub.launch.py | from launch import LaunchDescription
from launch_ros.actions import Node
def generate_launch_description():
return LaunchDescription(
[
Node(
package="ros_utils",
executable="dynamic_repub",
name="dynamic_repub",
parameters=[
{
"topics": [
"/pointcloud",
"/instance_segmentation",
"/agentview/instance_segmentation",
]
}
], # Ensure this matches the expected type
),
]
)
| 674 | Python | 27.124999 | 63 | 0.412463 |
AshisGhosh/roboai/isaac_sim/humble_ws/src/ros_utils/launch/pointcloud_gen.launch.py | from launch import LaunchDescription
from launch_ros.actions import ComposableNodeContainer
from launch_ros.descriptions import ComposableNode
def generate_launch_description():
container = ComposableNodeContainer(
namespace="",
name="depth_image_proc_container",
package="rclcpp_components",
executable="component_container",
composable_node_descriptions=[
ComposableNode(
package="depth_image_proc",
plugin="depth_image_proc::PointCloudXyzrgbNode",
name="point_cloud_xyzrgb_node",
remappings=[
("rgb/camera_info", "/camera_info"),
("rgb/image_rect_color", "rgb"),
("depth_registered/image_rect", "depth"),
("points", "pointcloud"),
],
parameters=[
{
"use_sim_time": False,
"queue_size": 10,
"qos_overrides./parameter_events.publisher.durability": "transient_local",
}
],
),
],
)
return LaunchDescription([container])
| 1,210 | Python | 33.599999 | 98 | 0.516529 |
AshisGhosh/roboai/isaac_sim/humble_ws/src/ros_utils/ros_utils/dynamic_repub.py | #!/usr/bin/env python3
import numpy as np
import rclpy
from rclpy.node import Node
from rclpy.qos import QoSProfile, QoSReliabilityPolicy, QoSDurabilityPolicy
import rcl_interfaces
from sensor_msgs.msg import Image
class DynamicRepub(Node):
def __init__(self):
super().__init__("dynamic_repub")
self.custom_publishers = {}
self.initialized_topics = set()
# Retrieve the list of topics from the parameters
self.declare_parameter(
"topics",
rcl_interfaces.msg.ParameterValue(
type=rcl_interfaces.msg.ParameterType.PARAMETER_STRING_ARRAY
),
)
self.topics_to_handle = (
self.get_parameter("topics").get_parameter_value().string_array_value
)
# Check topics periodically to set up publishers and subscribers
self.timer = self.create_timer(
5.0, self.check_and_initialize_topics
) # Check every 5 seconds
def check_and_initialize_topics(self):
current_topics = self.get_topic_names_and_types()
self.get_logger().info(f"Expected topics: {self.topics_to_handle}")
self.get_logger().info(f"Current topics: {len(current_topics)}")
for required_topic in self.topics_to_handle:
if required_topic not in self.initialized_topics:
for topic_name, types in current_topics:
if topic_name == required_topic:
self.initialize_pub_sub(topic_name, types[0])
break
def initialize_pub_sub(self, topic_name, type_name):
if topic_name in self.initialized_topics:
return # Already initialized
# Dynamically import the message type
msg_type = self.load_message_type(type_name)
if msg_type is None:
self.get_logger().error(
f"Could not find or load message type for {type_name}"
)
return
sub_qos_profile = QoSProfile(
depth=10,
reliability=QoSReliabilityPolicy.BEST_EFFORT,
durability=QoSDurabilityPolicy.VOLATILE,
)
repub_topic_name = f"{topic_name}_repub" # Rename republished topic
self.custom_publishers[repub_topic_name] = self.create_publisher(
msg_type, repub_topic_name, QoSProfile(depth=10)
)
self.create_subscription(
msg_type,
topic_name,
lambda msg, repub_topic_name=repub_topic_name: self.repub_callback(
msg, repub_topic_name
),
sub_qos_profile,
)
self.initialized_topics.add(topic_name)
self.get_logger().info(
f"Set up republishing from {topic_name} to {repub_topic_name} with type {type_name}"
)
def load_message_type(self, type_name):
# Dynamically load message type from type name
try:
package_name, _, message_name = type_name.split("/")
relative_module = ".msg"
msg_module = __import__(
f"{package_name}{relative_module}", fromlist=[message_name]
)
return getattr(msg_module, message_name)
except (ValueError, ImportError, AttributeError) as e:
self.get_logger().error(f"Error loading message type {type_name}: {str(e)}")
return None
def repub_callback(self, msg, repub_topic_name):
if hasattr(msg, "header") and hasattr(msg.header, "stamp"):
msg.header.stamp = self.get_clock().now().to_msg()
if type(msg) == Image:
if msg.encoding == "32SC1":
msg = self._reencode_image(msg)
self.custom_publishers[repub_topic_name].publish(msg)
def _reencode_image(self, image):
if image.encoding == "32SC1":
# Convert the raw data to a numpy array of type int32
array = np.frombuffer(image.data, dtype=np.int32).reshape(
image.height, image.width
)
# Calculate local minimum and maximum values from the array
min_value = np.min(array)
max_value = np.max(array)
# Avoid division by zero if max_value equals min_value
if max_value == min_value:
max_value += 1 # Increment max_value to avoid zero division
# Normalize the array to the range 0-255
normalized_array = (array - min_value) / (max_value - min_value) * 255
clipped_array = np.clip(
normalized_array, 0, 255
) # Ensure all values are within 0 to 255
# Convert back to byte format and update the image data
image.data = clipped_array.astype(np.uint8).tobytes()
image.encoding = "mono8"
image.step = image.width # Number of bytes in a row
return image
def main(args=None):
rclpy.init(args=args)
node = DynamicRepub()
rclpy.spin(node)
node.destroy_node()
rclpy.shutdown()
if __name__ == "__main__":
main()
| 5,066 | Python | 34.683098 | 96 | 0.586261 |
AshisGhosh/roboai/isaac_sim/isaac_sim/planner.py | import numpy as np
from PIL import Image
from roboai.enums import CameraMode
from roboai.shared.utils.grasp_client import get_grasp_from_image # noqa: F401
from roboai.shared.utils.robotic_grasping_client import get_grasps_from_rgb_and_depth
class Planner:
def __init__(self, sim_manager, robot_actor):
self.sim_manager = sim_manager
self.robot_actor = robot_actor
def clean_plan(self):
"""
Get and image of the scene and get a plan to clean the environment
"""
pass
def grasp_plan(self):
"""
Get an image of the scene and get a plan to grasp an object
"""
img = self.sim_manager.get_image(camera_name="realsense", mode=CameraMode.RGB)
image = Image.fromarray(img)
depth = self.sim_manager.get_image(
camera_name="realsense", mode=CameraMode.DEPTH
)
squeezed_depth = np.squeeze(depth)
normalized_depth = (
(squeezed_depth - np.min(squeezed_depth))
/ (np.max(squeezed_depth) - np.min(squeezed_depth))
* 255
)
depth_uint8 = normalized_depth.astype(np.uint8)
depth_image = Image.fromarray(depth_uint8)
grasps = get_grasps_from_rgb_and_depth(image, depth_image)
grasp = grasps[0]
print(grasp)
# grasp = get_grasp_from_image(image)
return grasp
class GraspHandler:
def __init__(self, sim_manager, robot_actor):
self.sim_manager = sim_manager
self.robot_actor = robot_actor
def grasp_object(self, object_name):
"""
Grasp an object in the scene
"""
pass
def release_object(self, object_name):
"""
Release an object in the scene
"""
pass
| 1,776 | Python | 28.616666 | 86 | 0.603604 |
AshisGhosh/roboai/isaac_sim/isaac_sim/robosim.py | import os
import sys
import time
import carb
import omni
import numpy as np
from omni.isaac.kit import SimulationApp
from roboai.enums import CameraMode
from roboai.robot import RobotActor
from roboai.tasks import TaskManager
from roboai.planner import Planner
global \
World, \
Robot, \
Franka, \
extensions, \
nucleus, \
stage, \
prims, \
rotations, \
viewports, \
Gf, \
UsdGeom, \
ArticulationMotionPolicy, \
RMPFlowController, \
og
WORLD_STAGE_PATH = "/World"
FRANKA_STAGE_PATH = WORLD_STAGE_PATH + "/Franka"
FRANKA_USD_PATH = "/Isaac/Robots/Franka/franka_alt_fingers.usd"
CAMERA_PRIM_PATH = f"{FRANKA_STAGE_PATH}/panda_hand/geometry/realsense/realsense_camera"
BACKGROUND_STAGE_PATH = WORLD_STAGE_PATH + "/background"
BACKGROUND_USD_PATH = "/Isaac/Environments/Simple_Room/simple_room.usd"
GRAPH_PATH = "/ActionGraph"
REALSENSE_VIEWPORT_NAME = "realsense_viewport"
class SimManager:
def __init__(self):
self.sim = None
self.assets_root_path = None
self.world = None
self.cameras = {}
self.controller = None
self.robot_actor = None
self.task_manager = None
def start_sim(self, headless=True):
CONFIG = {
"renderer": "RayTracedLighting",
"headless": headless,
"window_width": 2560,
"window_height": 1440,
}
start_time = time.time()
self.sim = SimulationApp(CONFIG)
carb.log_warn(
f"Time taken to load simulation: {time.time() - start_time} seconds"
)
if headless:
self.sim.set_setting("/app/window/drawMouse", True)
self.sim.set_setting("/app/livestream/proto", "ws")
self.sim.set_setting("/app/livestream/websocket/framerate_limit", 120)
self.sim.set_setting("/ngx/enabled", False)
from omni.isaac.core.utils.extensions import enable_extension
enable_extension("omni.kit.livestream.native")
self._do_imports()
if self.assets_root_path is None:
self.assets_root_path = self._get_assets_root_path()
start_time = time.time()
self.world = World(stage_units_in_meters=1.0)
carb.log_warn(f"Time taken to create world: {time.time() - start_time} seconds")
self._load_stage()
self._load_robot()
self._load_objects()
# self._create_markers()
self._init_cameras()
self._enable_ros2_bridge_ext()
self._load_omnigraph()
franka = self.world.scene.get_object("franka")
self.controller = RMPFlowController(
name="target_follower_controller", robot_articulation=franka
)
articulation_controller = franka.get_articulation_controller()
self.robot_actor = RobotActor(
world=self.world,
robot=franka,
controller=self.controller,
articulator=articulation_controller,
)
self.task_manager = TaskManager(sim_manager=self, robot_actor=self.robot_actor)
self.planner = Planner(sim_manager=self, robot_actor=self.robot_actor)
def _do_imports(self):
global \
World, \
Robot, \
Franka, \
extensions, \
nucleus, \
stage, \
prims, \
rotations, \
viewports, \
Gf, \
UsdGeom, \
ArticulationMotionPolicy, \
RMPFlowController, \
og
from omni.isaac.core import World
from omni.isaac.core.robots import Robot
from omni.isaac.franka import Franka
from omni.isaac.core.utils import (
extensions,
nucleus,
stage,
prims,
rotations,
viewports,
)
from pxr import Gf, UsdGeom # noqa E402
from omni.isaac.motion_generation.articulation_motion_policy import (
ArticulationMotionPolicy,
)
from omni.isaac.franka.controllers.rmpflow_controller import RMPFlowController
import omni.graph.core as og
def _get_assets_root_path(self):
start_time = time.time()
assets_root_path = nucleus.get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
self.sim.close()
sys.exit()
carb.log_warn(
f"Time taken to get assets root path: {time.time() - start_time} seconds"
)
return assets_root_path
def _load_stage(self):
start_time = time.time()
stage.add_reference_to_stage(
self.assets_root_path + BACKGROUND_USD_PATH, BACKGROUND_STAGE_PATH
)
carb.log_warn(
f"Time taken to add reference to stage: {time.time() - start_time} seconds"
)
def _load_robot(self):
start_time = time.time()
stage.add_reference_to_stage(
self.assets_root_path + FRANKA_USD_PATH, FRANKA_STAGE_PATH
)
self.world.scene.add(
Franka(
prim_path=FRANKA_STAGE_PATH,
name="franka",
position=np.array([0, -0.64, 0]),
orientation=rotations.gf_rotation_to_np_array(
Gf.Rotation(Gf.Vec3d(0, 0, 1), 90)
),
)
)
carb.log_warn(
f"Time taken to create Franka: {time.time() - start_time} seconds"
)
self.sim.update()
def __rand_position_in_bounds(self, bounds, height):
x = np.random.uniform(bounds[0][0], bounds[1][0])
y = np.random.uniform(bounds[0][1], bounds[1][1])
z = height
return np.array([x, y, z])
def _load_objects(self):
start_time = time.time()
bounds = [[-0.5, -0.35], [0.5, 0.35]]
prims.create_prim(
WORLD_STAGE_PATH + "/cracker_box",
"Xform",
# position=np.array([-0.2, -0.25, 0.15]),
position=self.__rand_position_in_bounds(bounds, 0.15),
orientation=rotations.gf_rotation_to_np_array(
Gf.Rotation(Gf.Vec3d(1, 0, 0), -90)
),
usd_path=self.assets_root_path
+ "/Isaac/Props/YCB/Axis_Aligned_Physics/003_cracker_box.usd",
semantic_label="cracker_box",
)
prims.create_prim(
WORLD_STAGE_PATH + "/sugar_box",
"Xform",
# position=np.array([-0.07, -0.25, 0.1]),
position=self.__rand_position_in_bounds(bounds, 0.1),
orientation=rotations.gf_rotation_to_np_array(
Gf.Rotation(Gf.Vec3d(0, 1, 0), -90)
),
usd_path=self.assets_root_path
+ "/Isaac/Props/YCB/Axis_Aligned_Physics/004_sugar_box.usd",
semantic_label="sugar_box",
)
prims.create_prim(
WORLD_STAGE_PATH + "/soup_can",
"Xform",
# position=np.array([0.1, -0.25, 0.10]),
position=self.__rand_position_in_bounds(bounds, 0.10),
orientation=rotations.gf_rotation_to_np_array(
Gf.Rotation(Gf.Vec3d(1, 0, 0), -90)
),
usd_path=self.assets_root_path
+ "/Isaac/Props/YCB/Axis_Aligned_Physics/005_tomato_soup_can.usd",
semantic_label="soup_can",
)
prims.create_prim(
WORLD_STAGE_PATH + "/mustard_bottle",
"Xform",
# position=np.array([0.0, 0.15, 0.12]),
position=self.__rand_position_in_bounds(bounds, 0.12),
orientation=rotations.gf_rotation_to_np_array(
Gf.Rotation(Gf.Vec3d(1, 0, 0), -90)
),
usd_path=self.assets_root_path
+ "/Isaac/Props/YCB/Axis_Aligned_Physics/006_mustard_bottle.usd",
semantic_label="mustard_bottle",
)
carb.log_warn(f"Time taken to create prims: {time.time() - start_time} seconds")
self.sim.update()
def _create_markers(self):
from omni.isaac.core.objects import VisualCuboid
from omni.isaac.core.materials import OmniGlass
marker_cube = self.world.scene.add(
VisualCuboid(
prim_path=WORLD_STAGE_PATH + "/marker_cube",
name="marker_cube",
scale=np.array([0.025, 0.2, 0.05]),
position=np.array([0.0, 0.0, 0.0]),
color=np.array([1.0, 0.0, 0.0]),
)
)
material = OmniGlass(
prim_path="/World/material/glass", # path to the material prim to create
ior=1.25,
depth=0.001,
thin_walled=True,
color=np.array([1.5, 0.0, 0.0]),
)
marker_cube.apply_visual_material(material)
self.sim.update()
def _init_cameras(self):
viewports.create_viewport_for_camera(REALSENSE_VIEWPORT_NAME, CAMERA_PRIM_PATH)
realsense_prim = UsdGeom.Camera(
stage.get_current_stage().GetPrimAtPath(CAMERA_PRIM_PATH)
)
realsense_prim.GetHorizontalApertureAttr().Set(20.955)
realsense_prim.GetVerticalApertureAttr().Set(15.7)
# realsense_prim.GetFocalLengthAttr().Set(18.8)
realsense_prim.GetFocalLengthAttr().Set(12.7)
realsense_prim.GetFocusDistanceAttr().Set(400)
viewport = omni.ui.Workspace.get_window("Viewport")
rs_viewport = omni.ui.Workspace.get_window(REALSENSE_VIEWPORT_NAME)
rs_viewport.dock_in(viewport, omni.ui.DockPosition.RIGHT, ratio=0.3)
carb.log_warn(
f"{REALSENSE_VIEWPORT_NAME} docked in {viewport.title}: {rs_viewport.docked}"
)
from omni.isaac.sensor import Camera
render_product_path = rs_viewport.viewport_api.get_render_product_path()
self.cameras["realsense"] = Camera(
prim_path=CAMERA_PRIM_PATH,
name="realsense",
resolution=(640, 480),
render_product_path=render_product_path,
)
self.cameras["realsense"].add_distance_to_camera_to_frame()
self.cameras["realsense"].add_distance_to_image_plane_to_frame()
camera_rot = Gf.Rotation(Gf.Vec3d(0, 0, 1), -90) * Gf.Rotation(
Gf.Vec3d(1, 0, 0), 45
)
self.cameras["agentview"] = Camera(
prim_path="/World/agentview_camera",
name="agentview",
resolution=(1024, 768),
position=(0, 2.75, 2.67),
orientation=rotations.gf_rotation_to_np_array(camera_rot),
)
# viewports.create_viewport_for_camera("agentview", "/World/agentview_camera")
# agentview_prim = UsdGeom.Camera(
# stage.get_current_stage().GetPrimAtPath("/World/agentview_camera")
# )
# agentview_viewport = omni.ui.Workspace.get_window("agentview")
# render_product_path = agentview_viewport.viewport_api.get_render_product_path()
# self.cameras["agentview"].initialize(render_product_path)
self.world.reset()
for cam in self.cameras.values():
cam.initialize()
def _enable_ros2_bridge_ext(self):
extensions.enable_extension("omni.isaac.ros2_bridge")
def _load_omnigraph(self):
carb.log_warn("Loading Omnigraph")
try:
ros_domain_id = int(os.environ["ROS_DOMAIN_ID"])
print("Using ROS_DOMAIN_ID: ", ros_domain_id)
except ValueError:
print("Invalid ROS_DOMAIN_ID integer value. Setting value to 0")
ros_domain_id = 0
except KeyError:
print("ROS_DOMAIN_ID environment variable is not set. Setting value to 0")
ros_domain_id = 0
try:
og.Controller.edit(
{"graph_path": GRAPH_PATH, "evaluator_name": "execution"},
{
og.Controller.Keys.CREATE_NODES: [
("OnImpulseEvent", "omni.graph.action.OnImpulseEvent"),
(
"ReadSimTime",
"omni.isaac.core_nodes.IsaacReadSimulationTime",
),
("Context", "omni.isaac.ros2_bridge.ROS2Context"),
(
"PublishJointState",
"omni.isaac.ros2_bridge.ROS2PublishJointState",
),
(
"SubscribeJointState",
"omni.isaac.ros2_bridge.ROS2SubscribeJointState",
),
(
"ArticulationController",
"omni.isaac.core_nodes.IsaacArticulationController",
),
# Hand Controller Nodes
(
"SubscribeJointStateHand",
"omni.isaac.ros2_bridge.ROS2SubscribeJointState",
),
(
"ArticulationControllerHand",
"omni.isaac.core_nodes.IsaacArticulationController",
),
("PublishClock", "omni.isaac.ros2_bridge.ROS2PublishClock"),
("OnTick", "omni.graph.action.OnTick"),
# Realsense Camera Helper
("createViewport", "omni.isaac.core_nodes.IsaacCreateViewport"),
(
"getRenderProduct",
"omni.isaac.core_nodes.IsaacGetViewportRenderProduct",
),
(
"setCamera",
"omni.isaac.core_nodes.IsaacSetCameraOnRenderProduct",
),
("cameraHelperRgb", "omni.isaac.ros2_bridge.ROS2CameraHelper"),
("cameraHelperInfo", "omni.isaac.ros2_bridge.ROS2CameraHelper"),
(
"cameraHelperDepth",
"omni.isaac.ros2_bridge.ROS2CameraHelper",
),
(
"cameraHelperInstanceSegmentation",
"omni.isaac.ros2_bridge.ROS2CameraHelper",
),
# Agent View Camera Helper
(
"createAgentView",
"omni.isaac.core_nodes.IsaacCreateViewport",
),
(
"getRenderProductAgentView",
"omni.isaac.core_nodes.IsaacGetViewportRenderProduct",
),
(
"setCameraAgentView",
"omni.isaac.core_nodes.IsaacSetCameraOnRenderProduct",
),
(
"cameraHelperAgentViewRgb",
"omni.isaac.ros2_bridge.ROS2CameraHelper",
),
(
"cameraHelperAgentViewInfo",
"omni.isaac.ros2_bridge.ROS2CameraHelper",
),
(
"cameraHelperAgentViewDepth",
"omni.isaac.ros2_bridge.ROS2CameraHelper",
),
(
"cameraHelperAgentViewInstanceSegmentation",
"omni.isaac.ros2_bridge.ROS2CameraHelper",
),
],
og.Controller.Keys.CONNECT: [
(
"OnImpulseEvent.outputs:execOut",
"PublishJointState.inputs:execIn",
),
(
"OnImpulseEvent.outputs:execOut",
"SubscribeJointState.inputs:execIn",
),
(
"OnImpulseEvent.outputs:execOut",
"PublishClock.inputs:execIn",
),
(
"OnImpulseEvent.outputs:execOut",
"ArticulationController.inputs:execIn",
),
("Context.outputs:context", "PublishJointState.inputs:context"),
(
"Context.outputs:context",
"SubscribeJointState.inputs:context",
),
("Context.outputs:context", "PublishClock.inputs:context"),
(
"ReadSimTime.outputs:simulationTime",
"PublishJointState.inputs:timeStamp",
),
(
"ReadSimTime.outputs:simulationTime",
"PublishClock.inputs:timeStamp",
),
(
"SubscribeJointState.outputs:jointNames",
"ArticulationController.inputs:jointNames",
),
(
"SubscribeJointState.outputs:positionCommand",
"ArticulationController.inputs:positionCommand",
),
(
"SubscribeJointState.outputs:velocityCommand",
"ArticulationController.inputs:velocityCommand",
),
(
"SubscribeJointState.outputs:effortCommand",
"ArticulationController.inputs:effortCommand",
),
# Hand Controller Connects
(
"OnImpulseEvent.outputs:execOut",
"SubscribeJointStateHand.inputs:execIn",
),
(
"OnImpulseEvent.outputs:execOut",
"ArticulationControllerHand.inputs:execIn",
),
(
"Context.outputs:context",
"SubscribeJointStateHand.inputs:context",
),
(
"SubscribeJointStateHand.outputs:jointNames",
"ArticulationControllerHand.inputs:jointNames",
),
(
"SubscribeJointStateHand.outputs:positionCommand",
"ArticulationControllerHand.inputs:positionCommand",
),
(
"SubscribeJointStateHand.outputs:velocityCommand",
"ArticulationControllerHand.inputs:velocityCommand",
),
(
"SubscribeJointStateHand.outputs:effortCommand",
"ArticulationControllerHand.inputs:effortCommand",
),
# Realsense Camera Key Connects
("OnTick.outputs:tick", "createViewport.inputs:execIn"),
(
"createViewport.outputs:execOut",
"getRenderProduct.inputs:execIn",
),
(
"createViewport.outputs:viewport",
"getRenderProduct.inputs:viewport",
),
("getRenderProduct.outputs:execOut", "setCamera.inputs:execIn"),
(
"getRenderProduct.outputs:renderProductPath",
"setCamera.inputs:renderProductPath",
),
("setCamera.outputs:execOut", "cameraHelperRgb.inputs:execIn"),
("setCamera.outputs:execOut", "cameraHelperInfo.inputs:execIn"),
(
"setCamera.outputs:execOut",
"cameraHelperDepth.inputs:execIn",
),
(
"setCamera.outputs:execOut",
"cameraHelperInstanceSegmentation.inputs:execIn",
),
("Context.outputs:context", "cameraHelperRgb.inputs:context"),
("Context.outputs:context", "cameraHelperInfo.inputs:context"),
("Context.outputs:context", "cameraHelperDepth.inputs:context"),
(
"Context.outputs:context",
"cameraHelperInstanceSegmentation.inputs:context",
),
(
"getRenderProduct.outputs:renderProductPath",
"cameraHelperRgb.inputs:renderProductPath",
),
(
"getRenderProduct.outputs:renderProductPath",
"cameraHelperInfo.inputs:renderProductPath",
),
(
"getRenderProduct.outputs:renderProductPath",
"cameraHelperDepth.inputs:renderProductPath",
),
(
"getRenderProduct.outputs:renderProductPath",
"cameraHelperInstanceSegmentation.inputs:renderProductPath",
),
# Agent View Camera Key Connects
("OnTick.outputs:tick", "createAgentView.inputs:execIn"),
(
"createAgentView.outputs:execOut",
"getRenderProductAgentView.inputs:execIn",
),
(
"createAgentView.outputs:viewport",
"getRenderProductAgentView.inputs:viewport",
),
(
"getRenderProductAgentView.outputs:execOut",
"setCameraAgentView.inputs:execIn",
),
(
"getRenderProductAgentView.outputs:renderProductPath",
"setCameraAgentView.inputs:renderProductPath",
),
(
"setCameraAgentView.outputs:execOut",
"cameraHelperAgentViewRgb.inputs:execIn",
),
(
"setCameraAgentView.outputs:execOut",
"cameraHelperAgentViewInfo.inputs:execIn",
),
(
"setCameraAgentView.outputs:execOut",
"cameraHelperAgentViewDepth.inputs:execIn",
),
(
"setCameraAgentView.outputs:execOut",
"cameraHelperAgentViewInstanceSegmentation.inputs:execIn",
),
(
"Context.outputs:context",
"cameraHelperAgentViewRgb.inputs:context",
),
(
"Context.outputs:context",
"cameraHelperAgentViewInfo.inputs:context",
),
(
"Context.outputs:context",
"cameraHelperAgentViewDepth.inputs:context",
),
(
"Context.outputs:context",
"cameraHelperAgentViewInstanceSegmentation.inputs:context",
),
(
"getRenderProductAgentView.outputs:renderProductPath",
"cameraHelperAgentViewRgb.inputs:renderProductPath",
),
(
"getRenderProductAgentView.outputs:renderProductPath",
"cameraHelperAgentViewInfo.inputs:renderProductPath",
),
(
"getRenderProductAgentView.outputs:renderProductPath",
"cameraHelperAgentViewDepth.inputs:renderProductPath",
),
(
"getRenderProductAgentView.outputs:renderProductPath",
"cameraHelperAgentViewInstanceSegmentation.inputs:renderProductPath",
),
],
og.Controller.Keys.SET_VALUES: [
("Context.inputs:domain_id", ros_domain_id),
# Setting the /Franka target prim to Articulation Controller node
("ArticulationController.inputs:usePath", True),
("ArticulationController.inputs:robotPath", FRANKA_STAGE_PATH),
("PublishJointState.inputs:topicName", "isaac_joint_states"),
(
"SubscribeJointState.inputs:topicName",
"isaac_joint_commands",
),
# Hand Controller Set Values
("ArticulationControllerHand.inputs:usePath", True),
(
"ArticulationControllerHand.inputs:robotPath",
FRANKA_STAGE_PATH,
),
(
"SubscribeJointStateHand.inputs:topicName",
"isaac_hand_joint_commands",
),
# Realsense Camera Key Values
("createViewport.inputs:name", REALSENSE_VIEWPORT_NAME),
("createViewport.inputs:viewportId", 1),
("cameraHelperRgb.inputs:frameId", "sim_camera"),
("cameraHelperRgb.inputs:topicName", "rgb"),
("cameraHelperRgb.inputs:type", "rgb"),
("cameraHelperInfo.inputs:frameId", "sim_camera"),
("cameraHelperInfo.inputs:topicName", "camera_info"),
("cameraHelperInfo.inputs:type", "camera_info"),
("cameraHelperDepth.inputs:frameId", "sim_camera"),
("cameraHelperDepth.inputs:topicName", "depth"),
("cameraHelperDepth.inputs:type", "depth"),
(
"cameraHelperInstanceSegmentation.inputs:frameId",
"sim_camera",
),
(
"cameraHelperInstanceSegmentation.inputs:topicName",
"instance_segmentation",
),
(
"cameraHelperInstanceSegmentation.inputs:type",
"instance_segmentation",
),
# Agent View Camera Key Values
("createAgentView.inputs:name", "agentview"),
("createAgentView.inputs:viewportId", 2),
(
"setCameraAgentView.inputs:cameraPrim",
"/World/agentview_camera",
),
("cameraHelperAgentViewRgb.inputs:frameId", "agentview"),
("cameraHelperAgentViewRgb.inputs:topicName", "agentview/rgb"),
("cameraHelperAgentViewRgb.inputs:type", "rgb"),
("cameraHelperAgentViewInfo.inputs:frameId", "agentview"),
(
"cameraHelperAgentViewInfo.inputs:topicName",
"agentview/camera_info",
),
("cameraHelperAgentViewInfo.inputs:type", "camera_info"),
("cameraHelperAgentViewDepth.inputs:frameId", "agentview"),
(
"cameraHelperAgentViewDepth.inputs:topicName",
"agentview/depth",
),
("cameraHelperAgentViewDepth.inputs:type", "depth"),
(
"cameraHelperAgentViewInstanceSegmentation.inputs:frameId",
"agentview",
),
(
"cameraHelperAgentViewInstanceSegmentation.inputs:topicName",
"agentview/instance_segmentation",
),
(
"cameraHelperAgentViewInstanceSegmentation.inputs:type",
"instance_segmentation",
),
(
"cameraHelperAgentViewInstanceSegmentation.inputs:enableSemanticLabels",
True,
),
(
"cameraHelperAgentViewInstanceSegmentation.inputs:semanticLabelsTopicName",
"agentview/semantic_labels",
),
],
},
)
carb.log_warn("Omnigraph loaded successfully")
except Exception as e:
carb.log_error(e)
carb.log_warn("Failed to load Omnigraph")
from omni.isaac.core_nodes.scripts.utils import set_target_prims
set_target_prims(
primPath="/ActionGraph/PublishJointState",
targetPrimPaths=[FRANKA_STAGE_PATH],
)
prims.set_targets(
prim=stage.get_current_stage().GetPrimAtPath(GRAPH_PATH + "/setCamera"),
attribute="inputs:cameraPrim",
target_prim_paths=[CAMERA_PRIM_PATH],
)
def close_sim(self):
self.sim.close()
def run_sim(self):
while self.sim.is_running():
self.world.step(render=True)
if self.world.is_playing():
if self.world.current_time_step_index == 0:
self.world.reset()
self.controller.reset()
# Tick the Publish/Subscribe JointState, Publish TF and Publish Clock nodes each frame
og.Controller.set(
og.Controller.attribute(
"/ActionGraph/OnImpulseEvent.state:enableImpulse"
),
True,
)
# self.task_manager.do_tasks()
self.sim.update()
def get_image(self, camera_name="realsense", mode=CameraMode.RGB, visualize=False):
self.world.step(render=True)
camera = self.cameras[camera_name]
try:
if mode == CameraMode.RGB:
img = camera.get_rgb()
if mode == CameraMode.RGBA:
img = camera.get_rgba()
if mode == CameraMode.DEPTH:
img = camera.get_depth()
if visualize:
import cv2
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
cv2.imshow("Color", img)
cv2.waitKey(0)
return img
except Exception as e:
print(e)
if __name__ == "__main__":
sim_manager = SimManager()
sim_manager.start_sim(headless=False)
sim_manager.task_manager.test_task()
sim_manager.world.pause()
sim_manager.run_sim()
# sim_manager.get_image()
sim_manager.close_sim()
| 32,565 | Python | 41.403646 | 103 | 0.469461 |
AshisGhosh/roboai/isaac_sim/isaac_sim/test.py | import sys
import time
import carb
import omni
import numpy as np
from omni.isaac.kit import SimulationApp
WORLD_STAGE_PATH = "/World"
FRANKA_STAGE_PATH = WORLD_STAGE_PATH + "/Franka"
FRANKA_USD_PATH = "/Isaac/Robots/Franka/franka_alt_fingers.usd"
CAMERA_PRIM_PATH = f"{FRANKA_STAGE_PATH}/panda_hand/geometry/realsense/realsense_camera"
BACKGROUND_STAGE_PATH = WORLD_STAGE_PATH + "/background"
BACKGROUND_USD_PATH = "/Isaac/Environments/Simple_Room/simple_room.usd"
GRAPH_PATH = "/ActionGraph"
REALSENSE_VIEWPORT_NAME = "realsense_viewport"
CONFIG = {
"renderer": "RayTracedLighting",
"headless": False,
"window_width": 2560,
"window_height": 1440,
}
start_time = time.time()
sim = SimulationApp(CONFIG)
carb.log_warn(f"Time taken to load simulation: {time.time() - start_time} seconds")
from omni.isaac.core import World # noqa E402
from omni.isaac.core.utils import ( # noqa E402
nucleus,
stage,
prims,
rotations,
viewports,
)
from pxr import Gf, UsdGeom # noqa E402
start_time = time.time()
world = World(stage_units_in_meters=1.0)
carb.log_warn(f"Time taken to create world: {time.time() - start_time} seconds")
start_time = time.time()
assets_root_path = nucleus.get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
sim.close()
sys.exit()
carb.log_warn(f"Time taken to get assets root path: {time.time() - start_time} seconds")
start_time = time.time()
stage.add_reference_to_stage(
assets_root_path + BACKGROUND_USD_PATH, BACKGROUND_STAGE_PATH
)
carb.log_warn(
f"Time taken to add reference to stage: {time.time() - start_time} seconds"
)
start_time = time.time()
prims.create_prim(
FRANKA_STAGE_PATH,
"Xform",
position=np.array([0, -0.64, 0]),
orientation=rotations.gf_rotation_to_np_array(Gf.Rotation(Gf.Vec3d(0, 0, 1), 90)),
usd_path=assets_root_path + FRANKA_USD_PATH,
)
prims.create_prim(
WORLD_STAGE_PATH + "/cracker_box",
"Xform",
position=np.array([-0.2, -0.25, 0.15]),
orientation=rotations.gf_rotation_to_np_array(Gf.Rotation(Gf.Vec3d(1, 0, 0), -90)),
usd_path=assets_root_path
+ "/Isaac/Props/YCB/Axis_Aligned_Physics/003_cracker_box.usd",
)
prims.create_prim(
WORLD_STAGE_PATH + "/sugar_box",
"Xform",
position=np.array([-0.07, -0.25, 0.1]),
orientation=rotations.gf_rotation_to_np_array(Gf.Rotation(Gf.Vec3d(0, 1, 0), -90)),
usd_path=assets_root_path
+ "/Isaac/Props/YCB/Axis_Aligned_Physics/004_sugar_box.usd",
)
prims.create_prim(
WORLD_STAGE_PATH + "/soup_can",
"Xform",
position=np.array([0.1, -0.25, 0.10]),
orientation=rotations.gf_rotation_to_np_array(Gf.Rotation(Gf.Vec3d(1, 0, 0), -90)),
usd_path=assets_root_path
+ "/Isaac/Props/YCB/Axis_Aligned_Physics/005_tomato_soup_can.usd",
)
prims.create_prim(
WORLD_STAGE_PATH + "/mustard_bottle",
"Xform",
position=np.array([0.0, 0.15, 0.12]),
orientation=rotations.gf_rotation_to_np_array(Gf.Rotation(Gf.Vec3d(1, 0, 0), -90)),
usd_path=assets_root_path
+ "/Isaac/Props/YCB/Axis_Aligned_Physics/006_mustard_bottle.usd",
)
carb.log_warn(f"Time taken to create prims: {time.time() - start_time} seconds")
sim.update()
viewports.create_viewport_for_camera(REALSENSE_VIEWPORT_NAME, CAMERA_PRIM_PATH)
# Fix camera settings since the defaults in the realsense model are inaccurate
realsense_prim = camera_prim = UsdGeom.Camera(
stage.get_current_stage().GetPrimAtPath(CAMERA_PRIM_PATH)
)
realsense_prim.GetHorizontalApertureAttr().Set(20.955)
realsense_prim.GetVerticalApertureAttr().Set(15.7)
realsense_prim.GetFocalLengthAttr().Set(18.8)
realsense_prim.GetFocusDistanceAttr().Set(400)
viewport = omni.ui.Workspace.get_window("Viewport")
rs_viewport = omni.ui.Workspace.get_window(REALSENSE_VIEWPORT_NAME)
rs_viewport.dock_in(viewport, omni.ui.DockPosition.RIGHT, ratio=0.3)
carb.log_warn(
f"{REALSENSE_VIEWPORT_NAME} docked in {viewport.title}: {rs_viewport.docked}"
)
while sim.is_running():
world.step(render=True)
sim.close()
| 4,058 | Python | 30.465116 | 88 | 0.704041 |
AshisGhosh/roboai/isaac_sim/isaac_sim/standalone_stream_server.py | # Copyright (c) 2020-2023, 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 omni.isaac.kit import SimulationApp
class StreamServer:
def __init__(self):
pass
def start(self):
# This sample enables a livestream server to connect to when running headless
CONFIG = {
"width": 1280,
"height": 720,
"window_width": 1920,
"window_height": 1080,
"headless": True,
"renderer": "RayTracedLighting",
"display_options": 3286, # Set display options to show default grid
}
# Start the omniverse application
kit = SimulationApp(launch_config=CONFIG)
from omni.isaac.core.utils.extensions import enable_extension
# Default Livestream settings
kit.set_setting("/app/window/drawMouse", True)
kit.set_setting("/app/livestream/proto", "ws")
kit.set_setting("/app/livestream/websocket/framerate_limit", 120)
kit.set_setting("/ngx/enabled", False)
# Note: Only one livestream extension can be enabled at a time
# Enable Native Livestream extension
# Default App: Streaming Client from the Omniverse Launcher
enable_extension("omni.kit.livestream.native")
# Enable WebSocket Livestream extension(Deprecated)
# Default URL: http://localhost:8211/streaming/client/
# enable_extension("omni.services.streamclient.websocket")
# Enable WebRTC Livestream extension
# Default URL: http://localhost:8211/streaming/webrtc-client/
# enable_extension("omni.services.streamclient.webrtc")
# Run until closed
while kit._app.is_running() and not kit.is_exiting():
# Run in realtime mode, we don't specify the step size
kit.update()
kit.close()
| 2,196 | Python | 36.237288 | 85 | 0.664845 |
AshisGhosh/roboai/isaac_sim/isaac_sim/robot.py | from enum import Enum
import numpy as np
import time
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
def distance_between_quaternions(q1, q2):
q1 = np.array(q1)
q2 = np.array(q2)
dot_product = np.dot(q1, q2)
dot_product = np.clip(dot_product, -1.0, 1.0)
angle = 2 * np.arccos(np.abs(dot_product))
angle = min(angle, np.pi - angle)
return angle
class RobotStatus(Enum):
PENDING = 0
RUNNING = 1
COMPLETED = 2
FAILED = 3
class RobotActor:
POS_TOLERANCE = 0.01
ORI_TOLERANCE = 0.021 # radians, ~1.2deg
def __init__(self, world, robot, controller, articulator):
self.world = world
self.robot = robot
self.controller = controller
self.articulator = articulator
self.__goal_pos = None
self.__goal_ori = None
self.__pose_history = []
self.__moving_timeout = 3.0
def _get_end_effector_pose(self):
return self.robot.end_effector.get_world_pose()
def _goal_marker(self):
marker_cube = self.world.scene.get_object("marker_cube")
return marker_cube
def _check_if_goal_reached(self, pos, ori):
current_pos, current_ori = self._get_end_effector_pose()
pos_diff = np.linalg.norm(current_pos - pos)
ori_diff = distance_between_quaternions(current_ori, ori)
logger.warn(
f"Position difference: {pos_diff}, Orientation difference: {ori_diff}"
)
return pos_diff < self.POS_TOLERANCE and ori_diff < self.ORI_TOLERANCE
def _is_moving(self):
if len(self.__pose_history) == 0:
self.__pose_history = [time.time(), *self._get_end_effector_pose()]
return True
dt = time.time() - self.__pose_history[0]
if dt < self.__moving_timeout:
return True
current_pos, current_ori = self._get_end_effector_pose()
delta_pos = np.linalg.norm(current_pos - self.__pose_history[1])
logger.warn(f" delta_pos: {delta_pos}")
delta_ori = distance_between_quaternions(current_ori, self.__pose_history[2])
logger.warn(f" delta_ori: {delta_ori}")
if delta_pos < self.POS_TOLERANCE and delta_ori < self.ORI_TOLERANCE:
self.__pose_history = []
return False
self.__pose_history = [time.time(), *self._get_end_effector_pose()]
return True
def move(self, pos, ori):
if self.__goal_pos is None:
self.__goal_pos = pos
if self.__goal_ori is None:
self.__goal_ori = ori
goal_marker = self._goal_marker()
goal_marker.set_world_pose(position=pos, orientation=ori)
if self._check_if_goal_reached(pos, ori):
logger.warn("Goal reached")
self.__goal_pos = None
self.__goal_ori = None
return RobotStatus.COMPLETED
if not self._is_moving():
logger.error("Robot not moving")
self.__goal_pos = None
self.__goal_ori = None
return RobotStatus.FAILED
actions = self.controller.forward(
target_end_effector_position=pos,
target_end_effector_orientation=ori,
)
logger.debug(f"Actions: {actions}")
self.articulator.apply_action(actions)
return RobotStatus.RUNNING
def move_pos(self, pos):
if self.__goal_ori is None:
self.__goal_ori = self._get_end_effector_pose()[1]
return self.move(pos, self.__goal_ori)
def move_pos_relative(self, rel_pos=np.array([0.01, 0.01, 0.01])):
pos, ori = self._get_end_effector_pose()
if self.__goal_pos is None:
self.__goal_pos = pos + rel_pos
return self.move_pos(self.__goal_pos)
def move_to_preset(self, preset_name="pick_center"):
robot_presets = {
"pick_center": (
np.array([0.0, -0.25, 0.85]),
np.array([0.0, -0.707, 0.707, 0.0]),
),
}
pos, ori = robot_presets[preset_name]
return self.move(pos, ori)
| 4,099 | Python | 29.597015 | 85 | 0.577458 |
AshisGhosh/roboai/isaac_sim/isaac_sim/tasks.py | import carb
from enum import Enum
from roboai.robot import RobotStatus
class TaskClass(Enum):
CONTROL_TASK = 0
DATA_TASK = 1
ASYNC_DATA_TASK = 2
class TaskManagerStatus(Enum):
PENDING = 0
RUNNING = 1
COMPLETED = 2
FAILED = 3
class Task:
def __init__(self, name, function, task_class, *args, **kwargs):
self.name = name
self.function = function
self.task_class = task_class
self.args = args
self.kwargs = kwargs
def execute(self):
try:
return self.function(*self.args, **self.kwargs)
except Exception as e:
carb.log_error(f"Error executing task {self.name}: {e}")
def __str__(self):
return f"Task: {self.name}\n Function: {self.function}\n Args: {self.args}\n Kwargs: {self.kwargs}"
class TaskManager:
def __init__(self, sim_manager, robot_actor):
self.sim_manager = sim_manager
self.robot_actor = robot_actor
self.tasks = []
self._current_task = None
self.status = TaskManagerStatus.PENDING
def do_tasks(self):
if self._current_task is None:
if len(self.tasks) > 0:
self._current_task = self.tasks.pop(0)
carb.log_warn(f"Executing task {self._current_task.name}")
self.status = TaskManagerStatus.RUNNING
else:
self.status = TaskManagerStatus.COMPLETED
return self.status
if self._current_task.task_class == TaskClass.DATA_TASK:
result = self._current_task.execute()
carb.log_warn(
f"Task {self._current_task.name} completed with result {result}"
)
self._current_task = None
self.status = TaskManagerStatus.PENDING
if len(self.tasks) == 0:
carb.log_warn("All tasks completed")
self.status = TaskManagerStatus.COMPLETED
return self.status
status = self._current_task.execute()
if status == RobotStatus.COMPLETED:
self._current_task = None
self.status = TaskManagerStatus.PENDING
if len(self.tasks) == 0:
carb.log_warn("All tasks completed")
self.status = TaskManagerStatus.COMPLETED
elif status == RobotStatus.FAILED:
carb.log_error(f"Task {self._current_task.name} failed")
self._current_task = None
self.status = TaskManagerStatus.FAILED
return self.status
def add_task(self, task):
self.tasks.append(task)
def test_task(self):
self.add_task(
Task(
name="go to center",
function=self.robot_actor.move_to_preset,
task_class=TaskClass.CONTROL_TASK,
preset_name="pick_center",
)
)
self.add_task(
Task(
name="get grasp image",
function=self.sim_manager.planner.grasp_plan,
task_class=TaskClass.DATA_TASK,
)
)
| 3,103 | Python | 29.732673 | 116 | 0.557847 |
AshisGhosh/roboai/isaac_sim/isaac_sim/enums.py | from enum import Enum
class CameraMode(Enum):
RGB = 0
RGBA = 1
DEPTH = 2
| 87 | Python | 9.999999 | 23 | 0.597701 |
AshisGhosh/roboai/isaac_sim/isaac_sim/standalone_stream.py | # Copyright (c) 2020-2023, 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 omni.isaac.kit import SimulationApp
# This sample enables a livestream server to connect to when running headless
CONFIG = {
"width": 1280,
"height": 720,
"window_width": 1920,
"window_height": 1080,
"headless": True,
"renderer": "RayTracedLighting",
"display_options": 3286, # Set display options to show default grid
}
# Start the omniverse application
kit = SimulationApp(launch_config=CONFIG)
from omni.isaac.core.utils.extensions import enable_extension # noqa: E402
# Default Livestream settings
kit.set_setting("/app/window/drawMouse", True)
kit.set_setting("/app/livestream/proto", "ws")
kit.set_setting("/app/livestream/websocket/framerate_limit", 120)
kit.set_setting("/ngx/enabled", False)
# Note: Only one livestream extension can be enabled at a time
# Enable Native Livestream extension
# Default App: Streaming Client from the Omniverse Launcher
enable_extension("omni.kit.livestream.native")
# Enable WebSocket Livestream extension(Deprecated)
# Default URL: http://localhost:8211/streaming/client/
# enable_extension("omni.services.streamclient.websocket")
# Enable WebRTC Livestream extension
# Default URL: http://localhost:8211/streaming/webrtc-client/
# enable_extension("omni.services.streamclient.webrtc")
# Run until closed
while kit._app.is_running() and not kit.is_exiting():
# Run in realtime mode, we don't specify the step size
kit.update()
kit.close()
| 1,867 | Python | 33.592592 | 77 | 0.762721 |
AshisGhosh/roboai/isaac_sim/isaac_sim/quick_start.py | import sys
import time
import carb
import omni
import numpy as np
from omni.isaac.kit import SimulationApp
WORLD_STAGE_PATH = "/World"
FRANKA_STAGE_PATH = WORLD_STAGE_PATH + "/Franka"
FRANKA_USD_PATH = "/Isaac/Robots/Franka/franka_alt_fingers.usd"
CAMERA_PRIM_PATH = f"{FRANKA_STAGE_PATH}/panda_hand/geometry/realsense/realsense_camera"
BACKGROUND_STAGE_PATH = WORLD_STAGE_PATH + "/background"
BACKGROUND_USD_PATH = "/Isaac/Environments/Simple_Room/simple_room.usd"
GRAPH_PATH = "/ActionGraph"
REALSENSE_VIEWPORT_NAME = "realsense_viewport"
CONFIG = {
"renderer": "RayTracedLighting",
"headless": False,
"window_width": 2560,
"window_height": 1440,
}
start_time = time.time()
sim = SimulationApp(CONFIG)
carb.log_warn(f"Time taken to load simulation: {time.time() - start_time} seconds")
from omni.isaac.core import World # noqa E402
from omni.isaac.franka import Franka # noqa E402
from omni.isaac.core.utils import ( # noqa E402
nucleus,
stage,
prims,
rotations,
viewports,
)
from pxr import Gf, UsdGeom # noqa E402
from omni.isaac.franka.controllers.rmpflow_controller import RMPFlowController # noqa E402
from omni.isaac.core.objects import VisualCuboid # noqa E402
from omni.isaac.core.materials import OmniGlass # noqa E402
from omni.isaac.sensor import Camera # noqa E402
from roboai.robot import RobotActor # noqa E402
from roboai.tasks import TaskManager # noqa E402
# INITIALIZE WORLD
start_time = time.time()
world = World(stage_units_in_meters=1.0)
carb.log_warn(f"Time taken to create world: {time.time() - start_time} seconds")
# GET ASSET PATH
start_time = time.time()
assets_root_path = nucleus.get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
sim.close()
sys.exit()
carb.log_warn(f"Time taken to get assets root path: {time.time() - start_time} seconds")
# LOAD STAGE/BACKGROUND
start_time = time.time()
stage.add_reference_to_stage(
assets_root_path + BACKGROUND_USD_PATH, BACKGROUND_STAGE_PATH
)
carb.log_warn(
f"Time taken to add reference to stage: {time.time() - start_time} seconds"
)
# LOAD FRANKA
start_time = time.time()
stage.add_reference_to_stage(assets_root_path + FRANKA_USD_PATH, FRANKA_STAGE_PATH)
world.scene.add(Franka(prim_path=FRANKA_STAGE_PATH, name="franka"))
carb.log_warn(f"Time taken to create Franka: {time.time() - start_time} seconds")
sim.update()
# CREATE OBJECT PRIMS
start_time = time.time()
prims.create_prim(
WORLD_STAGE_PATH + "/cracker_box",
"Xform",
position=np.array([-0.2, -0.25, 0.15]),
orientation=rotations.gf_rotation_to_np_array(Gf.Rotation(Gf.Vec3d(1, 0, 0), -90)),
usd_path=assets_root_path
+ "/Isaac/Props/YCB/Axis_Aligned_Physics/003_cracker_box.usd",
)
prims.create_prim(
WORLD_STAGE_PATH + "/sugar_box",
"Xform",
position=np.array([-0.07, -0.25, 0.1]),
orientation=rotations.gf_rotation_to_np_array(Gf.Rotation(Gf.Vec3d(0, 1, 0), -90)),
usd_path=assets_root_path
+ "/Isaac/Props/YCB/Axis_Aligned_Physics/004_sugar_box.usd",
)
prims.create_prim(
WORLD_STAGE_PATH + "/soup_can",
"Xform",
position=np.array([0.1, -0.25, 0.10]),
orientation=rotations.gf_rotation_to_np_array(Gf.Rotation(Gf.Vec3d(1, 0, 0), -90)),
usd_path=assets_root_path
+ "/Isaac/Props/YCB/Axis_Aligned_Physics/005_tomato_soup_can.usd",
)
prims.create_prim(
WORLD_STAGE_PATH + "/mustard_bottle",
"Xform",
position=np.array([0.0, 0.15, 0.12]),
orientation=rotations.gf_rotation_to_np_array(Gf.Rotation(Gf.Vec3d(1, 0, 0), -90)),
usd_path=assets_root_path
+ "/Isaac/Props/YCB/Axis_Aligned_Physics/006_mustard_bottle.usd",
)
carb.log_warn(f"Time taken to create prims: {time.time() - start_time} seconds")
sim.update()
# CREATE MARKER OBJECTS
marker_cube = world.scene.add(
VisualCuboid(
prim_path=WORLD_STAGE_PATH + "/marker_cube",
name="marker_cube",
scale=np.array([0.025, 0.2, 0.05]),
position=np.array([0.0, 0.0, 0.0]),
color=np.array([1.0, 0.0, 0.0]),
)
)
material = OmniGlass(
prim_path="/World/material/glass", # path to the material prim to create
ior=1.25,
depth=0.001,
thin_walled=True,
color=np.array([1.5, 0.0, 0.0]),
)
marker_cube.apply_visual_material(material)
# prims.set_prim_attribute_value(WORLD_STAGE_PATH + "/marker_cube", "primvars:displayOpacity", [0.5])
sim.update()
# CREATE REALSENSE VIEWPORT & CAMERA
viewports.create_viewport_for_camera(REALSENSE_VIEWPORT_NAME, CAMERA_PRIM_PATH)
# Fix camera settings since the defaults in the realsense model are inaccurate
realsense_prim = camera_prim = UsdGeom.Camera(
stage.get_current_stage().GetPrimAtPath(CAMERA_PRIM_PATH)
)
realsense_prim.GetHorizontalApertureAttr().Set(20.955)
realsense_prim.GetVerticalApertureAttr().Set(15.7)
realsense_prim.GetFocalLengthAttr().Set(18.8)
realsense_prim.GetFocusDistanceAttr().Set(400)
viewport = omni.ui.Workspace.get_window("Viewport")
rs_viewport = omni.ui.Workspace.get_window(REALSENSE_VIEWPORT_NAME)
rs_viewport.dock_in(viewport, omni.ui.DockPosition.RIGHT, ratio=0.3)
carb.log_warn(
f"{REALSENSE_VIEWPORT_NAME} docked in {viewport.title}: {rs_viewport.docked}"
)
camera = Camera(prim_path=CAMERA_PRIM_PATH)
world.reset()
camera.initialize()
franka = world.scene.get_object("franka")
controller = RMPFlowController(
name="target_follower_controller", robot_articulation=franka
)
articulation_controller = franka.get_articulation_controller()
robot_actor = RobotActor(
world=world,
robot=franka,
controller=controller,
articulator=articulation_controller,
)
task_manager = TaskManager(robot_actor=robot_actor)
task_manager.test_task()
world.pause()
while sim.is_running():
world.step(render=True)
if world.is_playing():
if world.current_time_step_index == 0:
world.reset()
controller.reset()
task_manager.do_tasks()
sim.close()
| 5,964 | Python | 30.230366 | 101 | 0.707411 |
roadwarriorslive/AI-Room-Gen/README.md | # AI Room Generator Extension Sample

### About
This extension allows user's to generate 3D content using Generative AI, ChatGPT. Providing an area in the stage and a prompt the user can generate a room configuration designed by ChatGPT. This in turn can help end users automatically generate and place objects within their scene, saving hours of time that would typically be required to create a complex scene.
### [README](exts/omni.example.airoomgenerator)
See the [README for this extension](exts/omni.example.airoomgenerator) to learn more about it including how to use it.
## Adding This Extension
This folder is ready to be pushed to any git repository. Once pushed direct link to a git repository can be added to *Omniverse Kit* extension search paths.
Link might look like this: `git://github.com/NVIDIA-Omniverse/kit-extension-sample-airoomgenerator?branch=main&dir=exts`
Notice `exts` is repo subfolder with extensions. More information can be found in "Git URL as Extension Search Paths" section of developers manual.
To add a link to your *Omniverse Kit* based app go into: Extension Manager -> Gear Icon -> Extension Search Path
## Linking with an Omniverse app
If `app` folder link doesn't exist or broken it can be created again. For better developer experience it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. Convenience script to use is included.
Run:
```
> link_app.bat
```
If successful you should see `app` folder link in the root of this repo.
If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app:
```
> link_app.bat --app create
```
You can also just pass a path to create link to:
```
> link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4"
```
# Contributing
The source code for this repository is provided as-is and we are not accepting outside contributions.
| 2,024 | Markdown | 39.499999 | 363 | 0.772727 |
roadwarriorslive/AI-Room-Gen/tools/scripts/link_app.py | import os
import argparse
import sys
import json
import packmanapi
import urllib3
def find_omniverse_apps():
http = urllib3.PoolManager()
try:
r = http.request("GET", "http://127.0.0.1:33480/components")
except Exception as e:
print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}")
sys.exit(1)
apps = {}
for x in json.loads(r.data.decode("utf-8")):
latest = x.get("installedVersions", {}).get("latest", "")
if latest:
for s in x.get("settings", []):
if s.get("version", "") == latest:
root = s.get("launch", {}).get("root", "")
apps[x["slug"]] = (x["name"], root)
break
return apps
def create_link(src, dst):
print(f"Creating a link '{src}' -> '{dst}'")
packmanapi.link(src, dst)
APP_PRIORITIES = ["code", "create", "view"]
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'",
required=False,
)
parser.add_argument(
"--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False
)
args = parser.parse_args()
path = args.path
if not path:
print("Path is not specified, looking for Omniverse Apps...")
apps = find_omniverse_apps()
if len(apps) == 0:
print(
"Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers."
)
sys.exit(0)
print("\nFound following Omniverse Apps:")
for i, slug in enumerate(apps):
name, root = apps[slug]
print(f"{i}: {name} ({slug}) at: '{root}'")
if args.app:
selected_app = args.app.lower()
if selected_app not in apps:
choices = ", ".join(apps.keys())
print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}")
sys.exit(0)
else:
selected_app = next((x for x in APP_PRIORITIES if x in apps), None)
if not selected_app:
selected_app = next(iter(apps))
print(f"\nSelected app: {selected_app}")
_, path = apps[selected_app]
if not os.path.exists(path):
print(f"Provided path doesn't exist: {path}")
else:
SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__))
create_link(f"{SCRIPT_ROOT}/../../app", path)
print("Success!")
| 2,813 | Python | 32.5 | 133 | 0.562389 |
roadwarriorslive/AI-Room-Gen/tools/packman/config.packman.xml | <config remotes="cloudfront">
<remote2 name="cloudfront">
<transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" />
</remote2>
</config>
| 211 | XML | 34.333328 | 123 | 0.691943 |
roadwarriorslive/AI-Room-Gen/tools/packman/bootstrap/install_package.py | # Copyright 2019 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 logging
import zipfile
import tempfile
import sys
import shutil
__author__ = "hfannar"
logging.basicConfig(level=logging.WARNING, format="%(message)s")
logger = logging.getLogger("install_package")
class TemporaryDirectory:
def __init__(self):
self.path = None
def __enter__(self):
self.path = tempfile.mkdtemp()
return self.path
def __exit__(self, type, value, traceback):
# Remove temporary data created
shutil.rmtree(self.path)
def install_package(package_src_path, package_dst_path):
with zipfile.ZipFile(
package_src_path, allowZip64=True
) as zip_file, TemporaryDirectory() as temp_dir:
zip_file.extractall(temp_dir)
# Recursively copy (temp_dir will be automatically cleaned up on exit)
try:
# Recursive copy is needed because both package name and version folder could be missing in
# target directory:
shutil.copytree(temp_dir, package_dst_path)
except OSError as exc:
logger.warning(
"Directory %s already present, packaged installation aborted" % package_dst_path
)
else:
logger.info("Package successfully installed to %s" % package_dst_path)
install_package(sys.argv[1], sys.argv[2])
| 1,888 | Python | 31.568965 | 103 | 0.68697 |
roadwarriorslive/AI-Room-Gen/exts/omni.example.airoomgenerator/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.0.0"
# The title and description fields are primarily for displaying extension info in UI
title = "AI Room Generator Sample"
description="Generates Rooms using ChatGPT"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Icon to show in the extension manager
icon = "data/preview_icon.png"
# Preview to show in the extension manager
preview_image = "data/preview.png"
# Use omni.ui to build simple UI
[dependencies]
"omni.kit.uiapp" = {}
"omni.kit.ngsearch" = {}
"omni.kit.window.popup_dialog" = {}
# Main python module this extension provides, it will be publicly available as "import company.hello.world".
[[python.module]]
name = "omni.example.airoomgenerator"
[[test]]
# Extra dependencies only to be used during test run
dependencies = [
"omni.kit.ui_test" # UI testing extension
]
| 1,091 | TOML | 24.999999 | 108 | 0.731439 |
roadwarriorslive/AI-Room-Gen/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/priminfo.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# 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.
from pxr import Usd, UsdGeom, Gf
class PrimInfo:
# Class that stores the prim info
def __init__(self, prim: Usd.Prim, name: str = "") -> None:
self.prim = prim
self.child = prim.GetAllChildren()[0]
self.bbox: Gf.Range3d = self.compute_bbox()
self.length = self.GetLengthOfPrim()
self.width = self.GetWidthOfPrim()
self.origin = self.GetPrimOrigin()
self.area_name = name
def compute_bbox(self) -> Gf.Range3d:
"""
https://docs.omniverse.nvidia.com/prod_kit/prod_kit/programmer_ref/usd/transforms/compute-prim-bounding-box.html
"""
imageable = UsdGeom.Imageable(self.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
def GetLengthOfPrim(self):
return self.bbox.max[0] - self.bbox.min[0]
def GetWidthOfPrim(self):
return self.bbox.max[2] - self.bbox.min[2]
def GetPrimOrigin(self) -> str:
attr = self.prim.GetAttribute('xformOp:translate')
origin = Gf.Vec3d(0,0,0)
if attr:
origin = attr.Get()
phrase = str(origin[0]) + ", " + str(origin[1]) + ", " + str(origin[2])
return phrase | 2,044 | Python | 39.098038 | 120 | 0.663405 |
roadwarriorslive/AI-Room-Gen/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/widgets.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# 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 omni.ui as ui
from omni.ui import color as cl
import asyncio
import omni
import carb
class ProgressBar:
def __init__(self):
self.progress_bar_window = None
self.left = None
self.right = None
self._build_fn()
async def play_anim_forever(self):
fraction = 0.0
while True:
fraction = (fraction + 0.01) % 1.0
self.left.width = ui.Fraction(fraction)
self.right.width = ui.Fraction(1.0-fraction)
await omni.kit.app.get_app().next_update_async()
def _build_fn(self):
with ui.VStack():
self.progress_bar_window = ui.HStack(height=0, visible=False)
with self.progress_bar_window:
ui.Label("Processing", width=0, style={"margin_width": 3})
self.left = ui.Spacer(width=ui.Fraction(0.0))
ui.Rectangle(width=50, style={"background_color": cl("#76b900")})
self.right = ui.Spacer(width=ui.Fraction(1.0))
def show_bar(self, to_show):
self.progress_bar_window.visible = to_show
| 1,770 | Python | 34.419999 | 98 | 0.655367 |
roadwarriorslive/AI-Room-Gen/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/chatgpt_apiconnect.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# 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 json
import omni.usd
import carb
import os
import aiohttp
import asyncio
from pxr import Sdf
from .prompts import system_input, user_input, assistant_input
from .deep_search import query_items
from .item_generator import place_greyboxes, place_deepsearch_results
from .results_office import ds_office_1, ds_office_2, ds_office_3, gpt_office_1
async def chatGPT_call(prompt: str):
# Load your API key from an environment variable or secret management service
settings = carb.settings.get_settings()
apikey = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/APIKey")
my_prompt = prompt.replace("\n", " ")
# Send a request API
try:
parameters = {
"model": "gpt-3.5-turbo",
"messages": [
{"role": "system", "content": system_input},
{"role": "user", "content": user_input},
{"role": "assistant", "content": assistant_input},
{"role": "user", "content": my_prompt}
]
}
chatgpt_url = "https://api.openai.com/v1/chat/completions"
headers = {"Authorization": "Bearer %s" % apikey}
# Create a completion using the chatGPT model
async with aiohttp.ClientSession() as session:
async with session.post(chatgpt_url, headers=headers, json=parameters) as r:
response = await r.json()
text = response["choices"][0]["message"]['content']
except Exception as e:
carb.log_error("An error as occurred")
return None, str(e)
# Parse data that was given from API
try:
#convert string to object
data = json.loads(text)
except ValueError as e:
carb.log_error(f"Exception occurred: {e}")
return None, text
else:
# Get area_objects_list
object_list = data['area_objects_list']
return object_list, text
async def call_Generate(prim_info, prompt, use_gpt, use_deepsearch, progress_widget, target, agent_task_path):
try:
run_loop = asyncio.get_event_loop()
progress_widget.show_bar(True)
progress_bar_task = run_loop.create_task(progress_widget.play_anim_forever())
response = ""
#chain the prompt
area_name = prim_info.area_name
concat_prompt = area_name[-1].replace("_", " ") + ", " + str(prim_info.length) + "x" + str(prim_info.width) + ", origin at (0.0, 0.0, 0.0), generate a list of appropriate items in the correct places. " + prompt
if use_gpt: #when calling the API
objects, response = await chatGPT_call(concat_prompt)
else: #when testing and you want to skip the API call
data = json.loads(gpt_office_1)
objects = data['area_objects_list']
if objects is None:
return
agent_name = "kit"
# region Check if agent sub-layer exists else create
stage = omni.usd.get_context().get_stage()
root_layer: Sdf.Layer = stage.GetRootLayer()
root_directory = os.path.dirname(root_layer.realPath)
sub_layers = root_layer.subLayerPaths
sub_layer_path = root_directory + "/" + agent_name + ".usd"
# This looks for the agent sub_layer in the stage (not on the nucleus server)
# TODO: Make this relative path more flexible
sub_layer = None
for layer in sub_layers:
if layer == sub_layer_path or layer == "./" + agent_name + ".usd":
sub_layer = Sdf.Layer.Find(sub_layer_path)
break
#This assumes that if the agent sub_layer is not in the stage it does not exist on Nucleus
# HACK: This will fail if the layer with this name exists on nucleus next to the root scene
if not sub_layer:
sub_layer = Sdf.Layer.CreateNew(sub_layer_path)
root_layer.subLayerPaths.append(sub_layer.identifier)
# endregion
# set the agent layer as the edit target
stage.SetEditTarget(sub_layer)
target_variant_sets = target.GetVariantSets()
color_variant_set = target_variant_sets.GetVariantSet("Kit")
if not color_variant_set:
color_variant_set = target_variant_sets.AddVariantSet("Kit")
variant_count = len(color_variant_set.GetVariantNames())
variant_index = variant_count + 1
root_prim_path = target.GetPath().pathString + "/AIResults_" + "{:02d}".format(variant_index) + "/"
# HACK: Hard-coded leading zeros, should look at how many variant are there
# and then rename existing variants if necessary to add 0s as needed
variant_name = "Version_" + "{:02d}".format(variant_index)
color_variant_set.AddVariant(variant_name)
color_variant_set.SetVariantSelection(variant_name)
# With VariantContext
with color_variant_set.GetVariantEditContext():
if use_deepsearch:
settings = carb.settings.get_settings()
nucleus_path = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/deepsearch_nucleus_path")
if nucleus_path == "" or nucleus_path == "(ENTERPRISE ONLY) Enter Nucleus Path Here":
nucleus_path = "omniverse://ov-simready/"
filter_path = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/filter_path")
filter_paths = filter_path.split(',')
if len(filter_paths) == 0 or (len(filter_paths) == 1 and filter_paths[0] == ""):
filter_paths = ["/Projects/simready_content/common_assets/props/",
"/Projects/simready_content/common_assets/vehicle/toyota/forklift/",
"/Projects/simready_content/common_assets/props_vegetation/"]
queries = list()
for item in objects:
queries.append(item['object_name'])
query_result = await query_items(queries=queries, url=nucleus_path, paths=filter_paths)
# query_result = json.loads(ds_office_1)
if query_result is not None and len(query_result) > 0:
carb.log_info("placing deepsearch results")
place_deepsearch_results(
gpt_results=objects,
query_result=query_result,
root_prim_path=root_prim_path,
prim_info=prim_info)
else:
place_greyboxes(
gpt_results=objects,
root_prim_path=root_prim_path)
carb.log_info("results placed")
else:
place_greyboxes(
gpt_results=objects,
root_prim_path=root_prim_path)
# Change the layer edit target back to the root layer
stage.SetEditTarget(root_layer)
except:
carb.log_error("gpt or deepsearch failed")
finally:
progress_bar_task.cancel
await asyncio.sleep(1)
progress_widget.show_bar(False)
| 7,951 | Python | 42.217391 | 218 | 0.600302 |
roadwarriorslive/AI-Room-Gen/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/style.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# 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 omni.ui as ui
from pathlib import Path
icons_path = Path(__file__).parent.parent.parent.parent / "icons"
gen_ai_style = {
"HStack": {
"margin": 3
},
"Button.Image::create": {"image_url": f"{icons_path}/plus.svg", "color": 0xFF00B976},
"Button.Image::properties": {"image_url": f"{icons_path}/cog.svg", "color": 0xFF989898},
"Line": {
"margin": 3
},
"Label": {
"margin_width": 5
}
}
guide = """
Step 1: Select your Room
- Select your room and then click the '+' button. This will fill your room's path into the Area path box.
Step 2: Prompt
- Type in a prompt that you want to send along to ChatGPT. This can be information about what is inside of the room.
For example, "generate a comfortable reception area that contains a front desk and an area for guest to sit down".
Step 3: Generate
- Select 'use ChatGPT' if you want to recieve a response from ChatGPT otherwise it will use a premade response.
To use GPT you will need to enter an Open AI API key in the settings by clicking on the gear icon.
- Select 'use Deepsearch' if you want to use the deepsearch functionality.
To use Deepsearch you will need a connection to an enterprise nucleus server with deepsearch enabled.
Enter the path to this server in the "Nucleus Path" setting.
Enter folder paths with props (rather than scenes) separated by commas (no spaces) in the "Path Filter" setting.
When deepsearch is false it will spawn in cubes that greybox the scene.
- Hit Generate, after hitting generate it will start making the appropriate calls. Loading bar will be shown as api-calls are being made.
- Note: This extension assumes your scene is Y-up and that your assets are scaled in meters.
Step 4: More Rooms
- To add another room you can repeat Steps 1-3.
- If you do not like the items it generated, you can hit the generate button until you are satisfied with the items.
""" | 2,617 | Python | 43.372881 | 137 | 0.727933 |
roadwarriorslive/AI-Room-Gen/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/prompts.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# 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.
system_input='''You are an area generator expert. Given an area of a certain size, you can generate a list of items that are appropriate to that area, in the right place, and with a representative material.
You operate in a 3D Space. You work in a X,Y,Z coordinate system. X denotes width, Y denotes height, Z denotes depth. 0.0,0.0,0.0 is the default space origin.
You receive from the user the name of the area, the size of the area on X and Z axis in centimetres, the origin point of the area (which is at the center of the area).
You answer by only generating JSON files that contain the following information:
- area_name: name of the area
- X: coordinate of the area on X axis
- Y: coordinate of the area on Y axis
- Z: coordinate of the area on Z axis
- area_size_X: dimension in cm of the area on X axis
- area_size_Z: dimension in cm of the area on Z axis
- area_objects_list: list of all the objects in the area
For each object you need to store:
- object_name: name of the object
- X: coordinate of the object on X axis
- Y: coordinate of the object on Y axis
- Z: coordinate of the object on Z axis
- Length: dimension in cm of the object on X axis
- Width: dimension in cm of the object on Y axis
- Height: dimension in cm of the object on Z axis
- Material: a reasonable material of the object using an exact name from the following list: Plywood, Leather_Brown, Leather_Pumpkin, Leather_Black, Aluminum_Cast, Birch, Beadboard, Cardboard, Cloth_Black, Cloth_Gray, Concrete_Polished, Glazed_Glass, CorrugatedMetal, Cork, Linen_Beige, Linen_Blue, Linen_White, Mahogany, MDF, Oak, Plastic_ABS, Steel_Carbon, Steel_Stainless, Veneer_OU_Walnut, Veneer_UX_Walnut_Cherry, Veneer_Z5_Maple.
Each object name should include an appropriate adjective.
Keep in mind, objects should be disposed in the area to create the most meaningful layout possible, and they shouldn't overlap.
All objects must be within the bounds of the area size; Never place objects further than 1/2 the length or 1/2 the depth of the area from the origin.
Also keep in mind that the objects should be disposed all over the area in respect to the origin point of the area, and you can use negative values as well to display items correctly, since origin of the area is always at the center of the area.
Remember, you only generate JSON code, nothing else. It's very important.
'''
user_input="Warehouse, 1000x1000, origin at (0.0,0.0,0.0), generate a list of appropriate items in the correct places. Generate warehouse objects"
assistant_input='''{
"area_name": "Warehouse_Area",
"X": 0.0,
"Y": 0.0,
"Z": 0.0,
"area_size_X": 1000,
"area_size_Z": 1000,
"area_objects_list": [
{
"object_name": "Parts_Pallet_1",
"X": -150,
"Y": 0.0,
"Z": 250,
"Length": 100,
"Width": 100,
"Height": 10,
"Material": "Plywood"
},
{
"object_name": "Boxes_Pallet_2",
"X": -150,
"Y": 0.0,
"Z": 150,
"Length": 100,
"Width": 100,
"Height": 10,
"Material": "Plywood"
},
{
"object_name": "Industrial_Storage_Rack_1",
"X": -150,
"Y": 0.0,
"Z": 50,
"Length": 200,
"Width": 50,
"Height": 300,
"Material": "Steel_Carbon"
},
{
"object_name": "Empty_Pallet_3",
"X": -150,
"Y": 0.0,
"Z": -50,
"Length": 100,
"Width": 100,
"Height": 10,
"Material": "Plywood"
},
{
"object_name": "Yellow_Forklift_1",
"X": 50,
"Y": 0.0,
"Z": -50,
"Length": 200,
"Width": 100,
"Height": 250,
"Material": "Plastic_ABS"
},
{
"object_name": "Heavy_Duty_Forklift_2",
"X": 150,
"Y": 0.0,
"Z": -50,
"Length": 200,
"Width": 100,
"Height": 250,
"Material": "Steel_Stainless"
}
]
}'''
| 4,898 | Python | 37.880952 | 435 | 0.612903 |
roadwarriorslive/AI-Room-Gen/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/extension.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# 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 omni.ext
from .window import GenAIWindow
# 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):
self._window = GenAIWindow("Generate Room", width=400, height=525)
def on_shutdown(self):
self._window.destroy()
self._window = None
| 1,399 | Python | 44.161289 | 119 | 0.742673 |
roadwarriorslive/AI-Room-Gen/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/__init__.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# 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.
from .extension import *
| 705 | Python | 40.529409 | 98 | 0.770213 |
roadwarriorslive/AI-Room-Gen/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/materials.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# 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.
MaterialPresets = {
"Leather_Brown":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Leather_Brown.mdl',
"Leather_Pumpkin_01":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Leather_Pumpkin.mdl',
"Leather_Brown_02":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Leather_Brown.mdl',
"Leather_Black_01":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Leather_Black.mdl',
"Aluminum_cast":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Metals/Aluminum_Cast.mdl',
"Birch":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wood/Birch.mdl',
"Beadboard":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wood/Beadboard.mdl',
"Cardboard":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wall_Board/Cardboard.mdl',
"Cloth_Black":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Cloth_Black.mdl',
"Cloth_Gray":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Cloth_Gray.mdl',
"Concrete_Polished":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Masonry/Concrete_Polished.mdl',
"Glazed_Glass":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Glass/Glazed_Glass.mdl',
"CorrugatedMetal":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Metals/CorrugatedMetal.mdl',
"Cork":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wood/Cork.mdl',
"Linen_Beige":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Linen_Beige.mdl',
"Linen_Blue":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Linen_Blue.mdl',
"Linen_White":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Linen_White.mdl',
"Mahogany":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wood/Mahogany.mdl',
"MDF":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wall_Board/MDF.mdl',
"Oak":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wood/Oak.mdl',
"Plastic_ABS":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Plastics/Plastic_ABS.mdl',
"Steel_Carbon":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Metals/Steel_Carbon.mdl',
"Steel_Stainless":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Metals/Steel_Stainless.mdl',
"Veneer_OU_Walnut":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Plastics/Veneer_OU_Walnut.mdl',
"Veneer_UX_Walnut_Cherry":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Plastics/Veneer_UX_Walnut_Cherry.mdl',
"Veneer_Z5_Maple":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Plastics/Veneer_Z5_Maple.mdl',
"Plywood":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wood/Plywood.mdl',
"Concrete_Rough_Dirty":
'http://omniverse-content-production.s3.us-west-2.amazonaws.com/Materials/vMaterials_2/Concrete/Concrete_Rough.mdl'
} | 4,323 | Python | 58.232876 | 121 | 0.743234 |
roadwarriorslive/AI-Room-Gen/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/utils.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# 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 omni.kit.commands
from pxr import Gf, Sdf, UsdGeom
from .materials import *
import carb
def CreateCubeFromCurve(curve_path: str, area_name: str = ""):
ctx = omni.usd.get_context()
stage = ctx.get_stage()
min_coords, max_coords = get_coords_from_bbox(curve_path)
x,y,z = get_bounding_box_dimensions(curve_path)
xForm_scale = Gf.Vec3d(x, 1, z)
cube_scale = Gf.Vec3d(0.01, 0.01, 0.01)
prim = stage.GetPrimAtPath(curve_path)
origin = prim.GetAttribute('xformOp:translate').Get()
if prim.GetTypeName() == "BasisCurves":
origin = Gf.Vec3d(min_coords[0]+x/2, 0, min_coords[2]+z/2)
area_path = '/World/Layout/Area'
if len(area_name) != 0:
area_path = '/World/Layout/' + area_name.replace(" ", "_")
new_area_path = omni.usd.get_stage_next_free_path(stage, area_path, False)
new_cube_xForm_path = new_area_path + "/" + "Floor"
new_cube_path = new_cube_xForm_path + "/" + "Cube"
# Create xForm to hold all items
item_container = create_prim(new_area_path)
set_transformTRS_attrs(item_container, translate=origin)
# Create Scale Xform for floor
xform = create_prim(new_cube_xForm_path)
set_transformTRS_attrs(xform, scale=xForm_scale)
# Create Floor Cube
omni.kit.commands.execute('CreateMeshPrimWithDefaultXform',
prim_type='Cube',
prim_path=new_cube_path,
select_new_prim=True
)
cube = stage.GetPrimAtPath(new_cube_path)
set_transformTRS_attrs(cube, scale=cube_scale)
cube.CreateAttribute("primvar:area_name", Sdf.ValueTypeNames.String, custom=True).Set(area_name)
omni.kit.commands.execute('DeletePrims',
paths=[curve_path],
destructive=False)
apply_material_to_prim('Concrete_Rough_Dirty', new_area_path)
return new_area_path
def apply_material_to_prim(material_name: str, prim_path: str):
ctx = omni.usd.get_context()
stage = ctx.get_stage()
looks_path = '/World/Looks/'
mat_path = looks_path + material_name
mat_prim = stage.GetPrimAtPath(mat_path)
if MaterialPresets.get(material_name, None) is not None:
if not mat_prim.IsValid():
omni.kit.commands.execute('CreateMdlMaterialPrimCommand',
mtl_url=MaterialPresets[material_name],
mtl_name=material_name,
mtl_path=mat_path)
omni.kit.commands.execute('BindMaterialCommand',
prim_path=prim_path,
material_path=mat_path)
def create_prim(prim_path, prim_type='Xform'):
ctx = omni.usd.get_context()
stage = ctx.get_stage()
prim = stage.DefinePrim(prim_path)
if prim_type == 'Xform':
xform = UsdGeom.Xform.Define(stage, prim_path)
else:
xform = UsdGeom.Cube.Define(stage, prim_path)
create_transformOps_for_xform(xform)
return prim
def create_transformOps_for_xform(xform):
xform.AddTranslateOp()
xform.AddRotateXYZOp()
xform.AddScaleOp()
def set_transformTRS_attrs(prim, translate: Gf.Vec3d = Gf.Vec3d(0,0,0), rotate: Gf.Vec3d=Gf.Vec3d(0,0,0), scale: Gf.Vec3d=Gf.Vec3d(1,1,1)):
prim.GetAttribute('xformOp:translate').Set(translate)
prim.GetAttribute('xformOp:rotateXYZ').Set(rotate)
prim.GetAttribute('xformOp:scale').Set(scale)
def get_bounding_box_dimensions(prim_path: str):
min_coords, max_coords = get_coords_from_bbox(prim_path)
length = max_coords[0] - min_coords[0]
width = max_coords[1] - min_coords[1]
height = max_coords[2] - min_coords[2]
return length, width, height
def get_coords_from_bbox(prim_path: str):
ctx = omni.usd.get_context()
bbox = ctx.compute_path_world_bounding_box(prim_path)
min_coords, max_coords = bbox
return min_coords, max_coords
def scale_object_if_needed(prim_path):
stage = omni.usd.get_context().get_stage()
length, width, height = get_bounding_box_dimensions(prim_path)
largest_dimension = max(length, width, height)
if largest_dimension < 10:
prim = stage.GetPrimAtPath(prim_path)
# HACK: All Get Attribute Calls need to check if the attribute exists and add it if it doesn't
if prim.IsValid():
scale_attr = prim.GetAttribute('xformOp:scale')
if scale_attr.IsValid():
current_scale = scale_attr.Get()
new_scale = (current_scale[0] * 100, current_scale[1] * 100, current_scale[2] * 100)
scale_attr.Set(new_scale)
carb.log_info(f"Scaled object by 100 times: {prim_path}")
else:
carb.log_info(f"Scale attribute not found for prim at path: {prim_path}")
else:
carb.log_info(f"Invalid prim at path: {prim_path}")
else:
carb.log_info(f"No scaling needed for object: {prim_path}") | 5,463 | Python | 38.594203 | 139 | 0.663738 |
roadwarriorslive/AI-Room-Gen/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/deep_search.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# 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.
from omni.kit.ngsearch.client import NGSearchClient
import asyncio
import carb
async def query_items(queries, url: str, paths):
result = list(tuple())
for query in queries:
query_result = await _query_first(query, url, paths)
if query_result is not None:
result.append(query_result)
print(result)
return result
async def _query_first(query: str, url: str, paths):
filtered_query = "ext:usd,usdz,usda "
if len(paths) > 0:
filtered_query = filtered_query + " path:"
for path in paths:
filtered_query = filtered_query + "\"" + str(path) + "\","
filtered_query = filtered_query[:-1]
filtered_query = filtered_query + " "
filtered_query = filtered_query + query
search_result = await NGSearchClient.get_instance().find2(
query=filtered_query, url=url)
if search_result is not None:
if len(search_result.paths) > 2:
return (query, [search_result.paths[0].uri, search_result.paths[1].uri, search_result.paths[2].uri])
else:
carb.log_warn(f"Search Results came up with too few results for {query}. Make sure you've configured your nucleus path")
return None
async def query_all(query: str, url: str, paths):
filtered_query = "ext:usd,usdz,usda " + query
return await NGSearchClient.get_instance().find2(query=filtered_query, url=url)
| 2,126 | Python | 32.761904 | 128 | 0.674506 |
roadwarriorslive/AI-Room-Gen/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/item_generator.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# 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
#hotkey
# 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 sys
from pxr import Usd, Sdf, Gf
from .utils import scale_object_if_needed, apply_material_to_prim, create_prim, set_transformTRS_attrs
def place_deepsearch_results(gpt_results, query_result, root_prim_path, prim_info):
index = 0
max_x = sys.float_info.min
max_y = sys.float_info.min
index = 0
#region determine scaling
for item in query_result:
next_object = gpt_results[index]
index = index + 1
# find the furthest object out in each direction
x_bound = next_object['X']
y_bound = next_object['Z']
if abs(x_bound) > max_x:
max_x = abs(x_bound)
if abs(y_bound) > max_y:
max_y = abs(y_bound)
# multiply by to (from 'radius' to diameter)
max_x = max_x * 2
max_y = max_y * 2
# The factory is scaled up by 100....need to figure out how to get these global numbers...
x_scale = (prim_info.length * 0.65) / max_x / 100
y_scale = (prim_info.width * 0.65) / max_y / 100
#endregion
index = 0
for item in query_result:
item_name = item[0]
item_paths = item[1]
# Define Prim
prim_parent_path = root_prim_path + item_name.replace(" ", "_")
prim_path = prim_parent_path + "/" + item_name.replace(" ", "_")
parent_prim = create_prim(prim_parent_path)
item_variant_sets = parent_prim.GetVariantSets()
item_variant_set = item_variant_sets.GetVariantSet("Deepsearch")
if not item_variant_set:
item_variant_set = item_variant_sets.AddVariantSet("Deepsearch")
# region start variants here
for item_path in item_paths:
variant_count = len(item_variant_set.GetVariantNames())
variant_index = variant_count + 1
variant_name = "Version_" + "{:02d}".format(variant_index)
item_variant_set.AddVariant(variant_name)
item_variant_set.SetVariantSelection(variant_name)
with item_variant_set.GetVariantEditContext():
next_prim = create_prim(prim_path)
# Add reference to USD Asset
references: Usd.references = next_prim.GetReferences()
# TODO: The query results should returnt he full path of the prim
references.AddReference(
assetPath="omniverse://ov-simready" + item_path)
# Add reference for future search refinement
config = next_prim.CreateAttribute("DeepSearch:Query", Sdf.ValueTypeNames.String)
config.Set(item_name)
item_variant_set.SetVariantSelection("Version_01")
# endregion end variant here
# HACK: All "GetAttribute" calls should need to check if the attribute exists
# translate prim
next_object = gpt_results[index]
index = index + 1
x = next_object['X'] * x_scale * 100
y = next_object['Y'] * 1
z = next_object['Z'] * y_scale * 100
set_transformTRS_attrs(parent_prim, Gf.Vec3d(x, y, z), Gf.Vec3d(-90, 0, 0), Gf.Vec3d(1, 1, 1))
scale_object_if_needed(prim_parent_path)
def place_greyboxes(gpt_results, root_prim_path):
index = 0
for item in gpt_results:
# Define Prim
prim_parent_path = root_prim_path + item['object_name'].replace(" ", "_")
prim_path = prim_parent_path + "/" + item['object_name'].replace(" ", "_")
# Define Dimensions and material
length = item['Length']
width = item['Width']
height = item['Height']
x = item['X']
y = item['Z'] # shift bottom of object to y=0
z = item['Y'] + height / 2
material = item['Material']
# Create Prim
parent_prim = create_prim(prim_parent_path)
set_transformTRS_attrs(parent_prim)
prim = create_prim(prim_path, 'Cube')
set_transformTRS_attrs(prim, translate=Gf.Vec3d(x, z, y), scale=Gf.Vec3d(length, width, height), rotate=Gf.Vec3d(-90, 0, 0))
prim.GetAttribute('extent').Set([(-0.5, -0.5, -0.5), (0.5, 0.5, 0.5)])
prim.GetAttribute('size').Set(1)
index = index + 1
# Add Attribute and Material
attr = prim.CreateAttribute("object_name", Sdf.ValueTypeNames.String)
attr.Set(item['object_name'])
apply_material_to_prim(material, prim_path)
| 5,165 | Python | 36.708029 | 132 | 0.601162 |
roadwarriorslive/AI-Room-Gen/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/window.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# 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 omni.ui as ui
import omni.usd
import carb
import asyncio
import omni.kit.commands
from omni.kit.window.popup_dialog.form_dialog import FormDialog
from .utils import CreateCubeFromCurve
from .style import gen_ai_style, guide
from .chatgpt_apiconnect import call_Generate
from .priminfo import PrimInfo
from pxr import Sdf
from .widgets import ProgressBar
class GenAIWindow(ui.Window):
progress = None
use_deepsearch = None
use_chatgpt = None
def __init__(self, title: str, **kwargs) -> None:
super().__init__(title, **kwargs)
# Models
self._path_model = ui.SimpleStringModel()
self._prompt_model = ui.SimpleStringModel("generate warehouse objects")
GenAIWindow.use_deepsearch = ui.SimpleBoolModel(True)
GenAIWindow.use_chatgpt = ui.SimpleBoolModel(True)
self.response_log = None
self.current_index = -1
self.current_area = None
self.frame.set_build_fn(self._build_fn)
def _build_fn(self):
with self.frame:
with ui.ScrollingFrame():
with ui.VStack(style=gen_ai_style):
with ui.HStack(height=0):
ui.Label("Content Generatation with ChatGPT", style={"font_size": 18})
ui.Button(name="properties", tooltip="Configure API Key and Nucleus Path", width=30, height=30, clicked_fn=lambda: self._open_settings())
with ui.CollapsableFrame("Getting Started Instructions", height=0, collapsed=True):
ui.Label(guide, word_wrap=True)
ui.Line()
with ui.HStack(height=0):
ui.Label("Area Path", width=ui.Percent(30))
ui.StringField(model=self._path_model)
ui.Button(name="create", width=30, height=30, clicked_fn=lambda: self._get_area_path())
ui.Line()
with ui.HStack(height=ui.Percent(50)):
ui.Label("Prompt", width=0)
ui.StringField(model=self._prompt_model, multiline=True)
ui.Line()
with ui.HStack(height=0):
ui.Spacer()
ui.Label("Use ChatGPT: ")
ui.CheckBox(model=GenAIWindow.use_chatgpt)
ui.Label("Use Deepsearch: ", tooltip="ENTERPRISE USERS ONLY")
ui.CheckBox(model=GenAIWindow.use_deepsearch)
ui.Spacer()
with ui.HStack(height=0):
ui.Spacer(width=ui.Percent(10))
ui.Button("Generate", height=40,
clicked_fn=lambda: self._generate())
ui.Spacer(width=ui.Percent(10))
GenAIWindow.progress = ProgressBar()
with ui.CollapsableFrame("ChatGPT Response / Log", height=0, collapsed=True):
self.response_log = ui.Label("", word_wrap=True)
def _save_settings(self, dialog):
values = dialog.get_values()
settings = carb.settings.get_settings()
settings.set_string("/persistent/exts/omni.example.airoomgenerator/APIKey", values["APIKey"])
settings.set_string("/persistent/exts/omni.example.airoomgenerator/deepsearch_nucleus_path", values["deepsearch_nucleus_path"])
settings.set_string("/persistent/exts/omni.example.airoomgenerator/path_filter", values["path_filter"])
dialog.hide()
def _open_settings(self):
settings = carb.settings.get_settings()
apikey_value = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/APIKey")
nucleus_path = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/deepsearch_nucleus_path")
path_filter = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/path_filter")
if apikey_value == "":
apikey_value = "Enter API Key Here"
if nucleus_path == "":
nucleus_path = "(ENTERPRISE ONLY) Enter Nucleus Path Here"
if path_filter == "":
path_filter = ""
field_defs = [
FormDialog.FieldDef("APIKey", "API Key: ", ui.StringField, apikey_value),
FormDialog.FieldDef("deepsearch_nucleus_path", "Nucleus Path: ", ui.StringField, nucleus_path),
FormDialog.FieldDef("path_filter", "Path Filter: ", ui.StringField, path_filter)
]
dialog = FormDialog(
title="Settings",
message="Your Settings: ",
field_defs = field_defs,
ok_handler=lambda dialog: self._save_settings(dialog))
dialog.show()
def rebuild_frame(self):
# we do want to update the area name and possibly last prompt?
attr_prompt = self.get_prim().GetAttribute('genai:prompt')
if attr_prompt.IsValid():
self._prompt_model.set_value(attr_prompt.Get())
else:
self._prompt_model.set_value("")
self.frame.rebuild()
def _generate(self):
target = self.get_prim()
attr = target.GetAttribute('genai:prompt')
if not attr.IsValid():
attr = target.CreateAttribute('genai:prompt', Sdf.ValueTypeNames.String)
attr.Set(self.get_prompt())
run_loop = asyncio.get_event_loop()
run_loop.create_task(call_Generate(
get_prim_info(target, target.GetName()),
self.get_prompt(),
GenAIWindow.use_chatgpt.as_bool, # use chatGPT
GenAIWindow.use_deepsearch.as_bool, # use DeepSearch
GenAIWindow.progress,
target,
agent_task_path=""))
# # Get the selected area path
def _get_area_path(self):
self._path_model.set_value(self.get_prim_path())
# # Get the prim path specified
def get_prim_path(self):
ctx = omni.usd.get_context()
selection = ctx.get_selection().get_selected_prim_paths()
if len(selection) > 0:
return str(selection[0])
carb.log_warn("No Prim Selected")
return ""
# Get the prompt specified
def get_prompt(self):
if self._prompt_model == "":
carb.log_warn("No Prompt Provided")
return self._prompt_model.as_string
# Get the prim based on the Prim Path
def get_prim(self):
ctx = omni.usd.get_context()
stage = ctx.get_stage()
prim = stage.GetPrimAtPath(self._path_model.as_string)
if prim.IsValid() is None:
carb.log_warn("No valid prim in the scene")
return prim
def destroy(self):
super().destroy()
self._path_model = None
self._prompt_model = None
self._use_deepsearch = None
self._use_chatgpt = None
# Returns a PrimInfo object containing the Length, Width, Origin and Area Name
def get_prim_info(prim, area_name: str) -> PrimInfo:
prim_info = None
if prim.IsValid():
prim_info = PrimInfo(prim, area_name)
return prim_info
| 7,989 | Python | 41.275132 | 161 | 0.587433 |
roadwarriorslive/AI-Room-Gen/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/tests/__init__.py | from .test_hello_world import * | 31 | Python | 30.999969 | 31 | 0.774194 |
roadwarriorslive/AI-Room-Gen/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/tests/test_hello_world.py | # NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
import omni.kit.test
# Extnsion for writing UI tests (simulate UI interaction)
import omni.kit.ui_test as ui_test
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
import company.hello.world
# Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test
class Test(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
pass
# After running each test
async def tearDown(self):
pass
# Actual test, notice it is "async" function, so "await" can be used if needed
async def test_hello_public_function(self):
result = company.hello.world.some_public_function(4)
self.assertEqual(result, 256)
async def test_window_button(self):
# Find a label in our window
label = ui_test.find("My Window//Frame/**/Label[*]")
# Find buttons in our window
add_button = ui_test.find("My Window//Frame/**/Button[*].text=='Add'")
reset_button = ui_test.find("My Window//Frame/**/Button[*].text=='Reset'")
# Click reset button
await reset_button.click()
self.assertEqual(label.widget.text, "empty")
await add_button.click()
self.assertEqual(label.widget.text, "count: 1")
await add_button.click()
self.assertEqual(label.widget.text, "count: 2")
| 1,674 | Python | 34.638297 | 142 | 0.682198 |
roadwarriorslive/AI-Room-Gen/exts/omni.example.airoomgenerator/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.0] - 2021-04-26
- Initial version of extension UI template with a window
| 178 | Markdown | 18.888887 | 80 | 0.702247 |
roadwarriorslive/AI-Room-Gen/exts/omni.example.airoomgenerator/docs/README.md | # AI Room Generator Sample Extension (omni.sample.airoomgenerator)

## Overview
The AI Room Generator Sample Extension allows users to generate 3D content to populate a room using Generative AI. The user will specify what area that defines the room and a prompt that will get passed to ChatGPT.
> NOTE: To enable the extension you will need to have ngsearch module. By default it is already avaliable in Omniverse USD Composer. If using Omniverse Code follow these [instructions](https://docs.omniverse.nvidia.com/prod_nucleus/prod_services/services/deepsearch/client/using_deepsearch_ui.html#using-deepsearch-beta-in-usd-composer) to get ngsearch
This Sample Extension utilizes Omniverse's [Deepsearch](https://docs.omniverse.nvidia.com/prod_nucleus/prod_services/services/deepsearch/overview.html) functionality to search for models within a nucleus server. (ENTERPRISE USERS ONLY)
## UI Overview

1. Settings (Cog Button)
- Where the user can input their API Key from [OpenAI](https://platform.openai.com/account/api-keys)
- Enterprise users can input their Deepsearch Enabled Nucleus Path
2. Area Name
- The name that will be applied to the Area once added.
3. Add Area (Plus Button)
- With an area selected and an Area Name provided, it will remove the selected object and spawn in a cube resembling the dimensions of the selected area prim.
4. Current Room
- By default this will be empty. As you add rooms this combo box will populate and allow you to switch between each generated room maintaining the prompt (if the room items have been generated). This allows users to adjust their prompt later for an already generated room.
5. Prompt
- The prompt that will be sent to ChatGPT.
- Here is an example prompt for a reception area:
- "This is the room where we meet our customers. Make sure there is a set of comfortable armchairs, a sofa, and a coffee table"
6. Use ChatGPT
- This enables the extension to call ChatGPT, otherwise it will use a default assistant prompt which will be the same every time.
7. Use Deepsearch (ENTERPRISE USERS ONLY)
- This enables the extension to use Deepsearch
8. Generate
- With a room selected and a prompt, this will send all the related information to ChatGPT. A progress bar will show up indicating if the response is still going.
9. ChatGPT Reponse / Log
- Once you have hit *Generate* this collapsable frame will contain the output recieved from ChatGPT. Here you can view the JSON data or if any issues arise with ChatGPT.
## How it works
### Getting information about the 3D Scene
Everything starts with the USD scene in Omniverse. Users can easily circle an area using the Pencil tool in Omniverse or create a cube and scale it in the scene, type in the kind of room/environment they want to generate - for example, a warehouse, or a reception room - and with one click that area is created.

### Creating the Prompt for ChatGPT
The ChatGPT prompt is composed of four pieces; system input, user input example, assistant output example, and user prompt.
Let’s start with the aspects of the prompt that tailor to the user’s scenario. This includes text that the user inputs plus data from the scene.
For example, if the user wants to create a reception room, they specify something like “This is the room where we meet our customers. Make sure there is a set of comfortable armchairs, a sofa and a coffee table”. Or, if they want to add a certain number of items they could add “make sure to include a minimum of 10 items”.
This text is combined with scene information like the size and name of the area where we will place items as the User Prompt.
### Passing the results from ChatGPT

The items from the ChatGPT JSON response are then parsed by the extension and passed to the Omnivere DeepSearch API. DeepSearch allows users to search 3D models stored within an Omniverse Nucleus server using natural language queries.
This means that even if we don’t know the exact file name of a model of a sofa, for example, we can retrieve it just by searching for “Comfortable Sofa” which is exactly what we got from ChatGPT.
DeepSearch understands natural language and by asking it for a “Comfortable Sofa” we get a list of items that our helpful AI librarian has decided are best suited from the selection of assets we have in our current asset library. It is surprisingly good at this and so we often can use the first item it returns, but of course we build in choice in case the user wants to select something from the list.
### When not using Deepsearch

For those who are not Enterprise users or users that want to use greyboxing, by default as long as `use Deepsearch` is turned off the extension will generate cube of various shapes and sizes to best suit the response from ChatGPT. | 4,975 | Markdown | 73.268656 | 404 | 0.776482 |
MikeWise2718/sphereflake22/README.orig.md | # Extension Project Template
This project was automatically generated.
- `app` - It is a folder link to the location of your *Omniverse Kit* based app.
- `exts` - It is a folder where you can add new extensions. It was automatically added to extension search path. (Extension Manager -> Gear Icon -> Extension Search Path).
Open this folder using Visual Studio Code. It will suggest you to install few extensions that will make python experience better.
Look for "wise.sphereflake22" extension in extension manager and enable it. Try applying changes to any python files, it will hot-reload and you can observe results immediately.
Alternatively, you can launch your app from console with this folder added to search path and your extension enabled, e.g.:
```
> app\omni.code.bat --ext-folder exts --enable company.hello.world
```
# App Link Setup
If `app` folder link doesn't exist or broken it can be created again. For better developer experience it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. Convenience script to use is included.
Run:
```
> link_app.bat
```
If successful you should see `app` folder link in the root of this repo.
If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app:
```
> link_app.bat --app create
```
You can also just pass a path to create link to:
```
> link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4"
```
# Sharing Your Extensions
This folder is ready to be pushed to any git repository. Once pushed direct link to a git repository can be added to *Omniverse Kit* extension search paths.
Link might look like this: `git://github.com/[user]/[your_repo].git?branch=main&dir=exts`
Notice `exts` is repo subfolder with extensions. More information can be found in "Git URL as Extension Search Paths" section of developers manual.
To add a link to your *Omniverse Kit* based app go into: Extension Manager -> Gear Icon -> Extension Search Path
| 2,042 | Markdown | 37.547169 | 258 | 0.757591 |
MikeWise2718/sphereflake22/README.md | # Extension Project SphereFlake Benchmark for Omniverse
Tested and works with Python 3.7 and 3.10 and Omniverse Kit 104 and 105
# To use
- Add it to create or code by adding to the Extension Search Path:
- Under `Window/Extensions` then click on the gear (or lately the hamburger menu in the top middle part of the dialog box)
- in the general case: `(your ext subdir root)/sphereflake22/exts`
- in my case: `d:/nv/ov/ext/sphereflake22/exts`
# Program Structure
- The core are the objects in the subdir `sfgen`
- `SphereFlake` - in `sphereflake.py` an object that construcsts sphereflakes in various ways
- `SphereMesh` - in `spheremesh.py` an object that constructs a spheremesh when needed
- `sfut.MatMan` - in `sfut.py` an object that manages the materials, fetching them when needed
- Additionally there are two main control classes
- `sfwindow` - in `sfwindow.py` and does all the UI and the only file that imports `Omni.ui`
- `sfcontrol` - in `sfcontrol.py` anddoes all the control logic (it has gotten a bit big)
- For UI there are a number of files organized by tabs
- `sfwintabs.py` - Most tabs
- `sfwinsess.py` - the session tab
# Adding UI ELements
## Adding a tab
- Add tab class, to `sfwintabs` probably, or to its own file if it is large
- Add invocation to `sfwindow` build function
- No settings
## Adding a collapsable frame
- Example "Ground Settings" collapsable frame
- `sfwindow.py` -Add variables to class `SfWindow` as member variables
- `optgroundframe: ui.CollapsableFrame = None`
- `docollapse_optgroundframe = False`
- `sfwindow.py` - Add load/save functionality to `LoadSettings` and `SaveSettings` for collapsed state
- `self.docollapse_optgroundframe = get_setting("ui_opt_groundframe", False)`
- `save_setting("ui_opt_logframe", self.optlogframe.collapsed)`
- `sfwintabspy` - Add frame to tab class
- `sfw.optgroundframe = ui.CollapsableFrame("Ground Settings", collapsed=sfw.docollapse_optremoteframe)`
- `sfwintabspy` - Add additional ui code to tab class:
- `with sfw.optgroundframe:`
## Adding a button to do something
- Example "Reset Materials"
- `sfwindow.py` - Add variables to class `SfWindow` as member variables (not needed here)
- `sfwintabs.py` - Add button code with lambda function (might need to move it because of width)
```
sfw.reset_materials_but = ui.Button(f"Reset Materials",
style={'background_color': sfw.darkpurple},
clicked_fn=lambda: sfc.on_click_resetmaterials())
```
- Add click function:
```
def on_click_resetmaterials(self):
self._matman.Reinitialize()
nmat = self._matman.GetMaterialCount()
self.sfw.reset_materials_but.text = f"Reset Materials ({nmat} defined)"
```
## Adding a checkbox
- Example "Add Rand" checkbox
- Decide if control variable belongs in Controller or in an object (like SphereFlake)
- Here we are putting it in the Controller "SfControl" class
- `sfwindow.py` - Add variables to class `SfWindow` as member variables
- `addrand_checkbox: ui.CheckBox = None`
- `addrand_checkbox_model: ui.SimpleBoolModel = None`
- `sfcontrol.py` - Add state variable to class `SfControl` as member variable
- `p_addrand = False`
- `sfcontrol.py` - Add load/save functionality for state variable to class `SfControl` in `LoadSettings` and `SaveSettings`
- `self.p_addrand = get_setting("p_addrand", False)`
- `save_setting("p_addrand", self.p_addrand)`
- `sfwindow.py` - Add initialization code for `SimpleBoolModel`
- self.addrand_checkbox_model = ui.SimpleBoolModel(sfc.p_addrand)
- `sfwintabs.py` - Add checkbox functionality
## Adding a stringfield
## Adding a combobox
## Adding a slider
| 3,971 | Markdown | 42.648351 | 126 | 0.672878 |
MikeWise2718/sphereflake22/tools/scripts/link_app.py | import argparse
import json
import os
import sys
import packmanapi
import urllib3
def find_omniverse_apps():
http = urllib3.PoolManager()
try:
r = http.request("GET", "http://127.0.0.1:33480/components")
except Exception as e:
print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}")
sys.exit(1)
apps = {}
for x in json.loads(r.data.decode("utf-8")):
latest = x.get("installedVersions", {}).get("latest", "")
if latest:
for s in x.get("settings", []):
if s.get("version", "") == latest:
root = s.get("launch", {}).get("root", "")
apps[x["slug"]] = (x["name"], root)
break
return apps
def create_link(src, dst):
print(f"Creating a link '{src}' -> '{dst}'")
packmanapi.link(src, dst)
APP_PRIORITIES = ["code", "create", "view"]
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'",
required=False,
)
parser.add_argument(
"--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False
)
args = parser.parse_args()
path = args.path
if not path:
print("Path is not specified, looking for Omniverse Apps...")
apps = find_omniverse_apps()
if len(apps) == 0:
print(
"Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers."
)
sys.exit(0)
print("\nFound following Omniverse Apps:")
for i, slug in enumerate(apps):
name, root = apps[slug]
print(f"{i}: {name} ({slug}) at: '{root}'")
if args.app:
selected_app = args.app.lower()
if selected_app not in apps:
choices = ", ".join(apps.keys())
print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}")
sys.exit(0)
else:
selected_app = next((x for x in APP_PRIORITIES if x in apps), None)
if not selected_app:
selected_app = next(iter(apps))
print(f"\nSelected app: {selected_app}")
_, path = apps[selected_app]
if not os.path.exists(path):
print(f"Provided path doesn't exist: {path}")
else:
SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__))
create_link(f"{SCRIPT_ROOT}/../../app", path)
print("Success!")
| 2,814 | Python | 32.117647 | 133 | 0.562189 |
MikeWise2718/sphereflake22/tools/packman/config.packman.xml | <config remotes="cloudfront">
<remote2 name="cloudfront">
<transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" />
</remote2>
</config>
| 211 | XML | 34.333328 | 123 | 0.691943 |
MikeWise2718/sphereflake22/tools/packman/bootstrap/install_package.py | # Copyright 2019 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 logging
import shutil
import sys
import tempfile
import zipfile
__author__ = "hfannar"
logging.basicConfig(level=logging.WARNING, format="%(message)s")
logger = logging.getLogger("install_package")
class TemporaryDirectory:
def __init__(self):
self.path = None
def __enter__(self):
self.path = tempfile.mkdtemp()
return self.path
def __exit__(self, type, value, traceback):
# Remove temporary data created
shutil.rmtree(self.path)
def install_package(package_src_path, package_dst_path):
with zipfile.ZipFile(package_src_path, allowZip64=True) as zip_file, TemporaryDirectory() as temp_dir:
zip_file.extractall(temp_dir)
# Recursively copy (temp_dir will be automatically cleaned up on exit)
try:
# Recursive copy is needed because both package name and version folder could be missing in
# target directory:
shutil.copytree(temp_dir, package_dst_path)
except OSError as exc:
logger.warning("Directory %s already present, packaged installation aborted" % package_dst_path)
else:
logger.info("Package successfully installed to %s" % package_dst_path)
install_package(sys.argv[1], sys.argv[2])
| 1,844 | Python | 33.166666 | 108 | 0.703362 |
MikeWise2718/sphereflake22/exts/wise.sphereflake22/wise/sphereflake22/sfcontrols.py | import omni.kit.commands as okc
import omni.usd
import time
import datetime
import json
import socket
import psutil
from pxr import Gf, Sdf, Usd, UsdGeom, UsdShade
from pxr import UsdPhysics, PhysxSchema, Gf, PhysicsSchemaTools, UsdGeom
from .ovut import delete_if_exists, write_out_syspath, truncf
from .sfgen.sfut import MatMan
from .sfgen.spheremesh import SphereMeshFactory
from .sfgen.sphereflake import SphereFlakeFactory
import nvidia_smi
# import multiprocessing
import subprocess
import os
import carb
from .ovut import get_setting, save_setting
import asyncio
# import asyncio
# fflake8: noqa
def build_sf_set(stagestr: str,
sx: int = 0, nx: int = 1, nnx: int = 1,
sy: int = 0, ny: int = 1, nny: int = 1,
sz: int = 0, nz: int = 1, nnz: int = 1,
matname: str = "Mirror"):
# to test open a browser at http://localhost:8211/docs or 8011 or maybe 8111
# stageid = omni.usd.get_context().get_stage_id()
pid = os.getpid()
msg = f"GMP build_sf_set - x: {sx} {nx} {nnx} - y: {sy} {ny} {nny} - z: {sz} {nz} {nnz} mat:{matname}"
msg += f" - stagestr: {stagestr} pid:{pid}"
try:
loop = asyncio.get_event_loop()
except RuntimeError as e:
if str(e).startswith('There is no current event loop in thread'):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
else:
raise
# stage=Usd.Stage.Open(rootLayer=Sdf.Find('anon:0000014AF6CD0760:World0.usd'), sessionLayer=Sdf.Find('anon:0000014AF6CD0B20:World0-session.usda')),
print(msg)
matman = MatMan()
context = omni.usd.get_context()
stage = context.get_stage()
# stage = context.open_stage(stagestr)
smf = SphereMeshFactory(stage, matman)
sff = SphereFlakeFactory(stage, matman, smf)
sff.ResetStage(stage)
sff.p_sf_matname = matname
sff.p_nsfx = nnx
sff.p_nsfy = nny
sff.p_nsfz = nnz
sff.GenerateManySubcube(sx, sy, sz, nx, ny, nz)
return msg
def init_sf_set():
from omni.services.core import main
# there seems to be no main until a window is created
main.register_endpoint("get", "/sphereflake/build-sf-set", build_sf_set, tags=["Sphereflakes"])
print("init_sf_set - mail.registered_endpoint called")
class DummyGpuInfo:
total = 0
used = 0
free = 0
def __init__(self):
self.total = 0
self.used = 0
self.free = 0
# 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 SfControls():
# 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.
_stage = None
_total_quads: int = 0
_matman: MatMan = None
_floor_xdim = 5
_floor_zdim = 5
_bounds_visible = False
_sf_size = 50
_vsc_test8 = False
_gpuinfo = None
sfw = None # We can't give this a type because it would be a circular reference
p_writelog = True
p_logseriesname = "None"
p_doremote = False
p_doremoteurl = "http://localhost:8211"
p_doremotetype = "InProcess"
p_register_endpoint = False
p_doloadusd = False
p_doloadusd_url = "omniverse://localhost/sphereflake.usd"
p_doloadusd_session = False
p_doloadusd_sessionname = "None"
p_equipforphysics = False
p_addrand = False
currenttag = "Empty"
def __init__(self, matman: MatMan, smf: SphereMeshFactory, sff: SphereFlakeFactory):
print("SfControls __init__ (trc)")
self._matman = matman
self._count = 0
self._current_material_name = "Mirror"
self._current_alt_material_name = "Red_Glass"
self._current_bbox_material_name = "Blue_Glass"
self._current_floor_material_name = "Mirror"
self._matkeys = self._matman.GetMaterialNames()
self._total_quads = 0
self._sf_size = 50
# self._sf_matbox: ui.ComboBox = None
self._prims = ["Sphere", "Cube", "Cone", "Torus", "Cylinder", "Plane", "Disk", "Capsule",
"Billboard", "SphereMesh"]
self._curprim = self._prims[0]
self._sf_gen_modes = SphereFlakeFactory.GetGenModes()
self._sf_gen_mode = self._sf_gen_modes[0]
self._sf_gen_forms = SphereFlakeFactory.GetGenForms()
self._sf_gen_form = self._sf_gen_forms[0]
# self._genmodebox = ui.ComboBox(0, *self._sf_gen_modes).model
# self._genformbox = ui.ComboBox(0, *self._sf_gen_forms).model
self.smf = smf
self.sff = sff
self._remotetypes = sff.GetRemoteTypes()
self._write_out_syspath = False
if self._write_out_syspath:
write_out_syspath()
self.LoadSettings()
def LateInit(self):
# Register endpoints
try:
# D:\nv\ov\app\sfapp\_build\windows-x86_64\release\data\Kit\wise.sfapp.view\1.0>notepad user.config.json
# from omni.core.utils.extensions import enable_extension
# enable_extension("omni.services.core")
# from omni.kit.window.extensions import ext_controller, enable_extension
# enable_extension("omni.services.core")
# ext_controller.toggle_autoload("omni.services.core", True)
self.query_remote_settings()
if self.p_register_endpoint:
init_sf_set()
print("SfControls LateInit - registered endpoint")
else:
print("SfControls LateInit - did not register endpoint")
pass
except Exception as e:
print(f"sfc.LateInit - Exception registering endpoint: {e}")
def Close(self):
try:
from omni.services.core import main
main.deregister_endpoint("get", "/sphereflake/build-sf-set")
pass
except Exception as e:
print(f"Exception deregistering endpoint: {e}")
print("SfControls close")
def SaveSettings(self):
print("SfControls SaveSettings (trc)")
try:
self.query_write_log()
self.query_remote_settings()
self.query_physics()
save_setting("p_writelog", self.p_writelog)
save_setting("p_logseriesname", self.p_logseriesname)
save_setting("p_doremote", self.p_doremote)
save_setting("p_register_endpoint", self.p_register_endpoint)
save_setting("p_doremotetype", self.p_doremotetype)
save_setting("p_doremoteurl", self.p_doremoteurl)
save_setting("p_doloadusd", self.p_doloadusd)
save_setting("p_doloadusd_url", self.p_doloadusd_url)
save_setting("p_doloadusd_session", self.p_doloadusd_session)
save_setting("p_doloadusd_sessionname", self.p_doloadusd_sessionname)
save_setting("p_equipforphysics", self.p_equipforphysics)
save_setting("p_addrand", self.p_addrand)
if self.sff is not None:
self.sff.SaveSettings()
print(f"SaveSettings: p_equipforphysics:{self.p_equipforphysics} (trc)")
except Exception as e:
carb.log_error(f"Exception in sfcontrols.SaveSettings: {e}")
def LoadSettings(self):
print("SfControls LoadSettings (trc)")
self.p_writelog = get_setting("p_writelog", True)
self.p_logseriesname = get_setting("p_logseriesname", "None")
self.p_doremote = get_setting("p_doremote", False)
self.p_register_endpoint = get_setting("p_register_endpoint", False)
self.p_doremotetype = get_setting("p_doremotetype", SphereFlakeFactory.GetDefaultRemoteType())
self.p_doremoteurl = get_setting("p_doremoteurl", "http://localhost")
self.p_doloadusd = get_setting("p_doloadusd", False)
self.p_doloadusd_url = get_setting("p_doloadusd_url", "omniverse://localhost/sphereflake.usd")
self.p_doloadusd_session = get_setting("p_doloadusd_session", False)
self.p_doloadusd_sessionname = get_setting("p_doloadusd_sessionname", "None")
self.p_equipforphysics = get_setting("p_equipforphysics", False)
self.p_addrand = get_setting("p_addrand", False)
print(f"LoadSettings: p_equipforphysics:{self.p_equipforphysics} (trc)")
def setup_environment(self, extent3f: Gf.Vec3f, force: bool = False):
ppathstr = "/World/Floor"
if force:
delete_if_exists(ppathstr)
prim_path_sdf = Sdf.Path(ppathstr)
prim: Usd.Prim = self._stage .GetPrimAtPath(prim_path_sdf)
if not prim.IsValid():
okc.execute('CreateMeshPrimWithDefaultXform', prim_type="Plane", prim_path=ppathstr)
floormatname = self.get_curfloormat_name()
# omni.kit.commands.execute('BindMaterialCommand', prim_path='/World/Floor',
# material_path=f'/World/Looks/{floormatname}')
mtl = self._matman.GetMaterial(floormatname)
stage = omni.usd.get_context().get_stage()
prim: Usd.Prim = stage.GetPrimAtPath(ppathstr)
UsdShade.MaterialBindingAPI(prim).Bind(mtl)
if self.p_equipforphysics:
# rigid_api = UsdPhysics.RigidBodyAPI.Apply(prim)
# rigid_api.CreateRigidBodyEnabledAttr(True)
UsdPhysics.CollisionAPI.Apply(prim)
# self._floor_xdim = extent3f[0] / 10
# self._floor_zdim = extent3f[2] / 10
self._floor_xdim = extent3f[0] / 100
self._floor_zdim = extent3f[2] / 100
okc.execute('TransformMultiPrimsSRTCpp',
count=1,
paths=[ppathstr],
new_scales=[self._floor_xdim, 1, self._floor_zdim])
baseurl = 'https://omniverse-content-production.s3.us-west-2.amazonaws.com'
okc.execute('CreateDynamicSkyCommand',
sky_url=f'{baseurl}/Assets/Skies/2022_1/Skies/Dynamic/CumulusLight.usd',
sky_path='/Environment/sky')
# print(f"nvidia_smi.__file__:{nvidia_smi.__file__}")
# print(f"omni.ui.__file__:{omni.ui.__file__}")
# print(f"omni.ext.__file__:{omni.ext.__file__}")
def ensure_stage(self):
# print("ensure_stage")
self._stage = omni.usd.get_context().get_stage()
# if self._stage is None:
# self._stage = omni.usd.get_context().get_stage()
# # print(f"ensure_stage got stage:{self._stage}")
# UsdGeom.SetStageUpAxis(self._stage, UsdGeom.Tokens.y)
# self._total_quads = 0
# extent3f = self.sff.GetSphereFlakeBoundingBox()
# self.setup_environment(extent3f)
def create_billboard(self, primpath: str, w: float = 860, h: float = 290):
UsdGeom.SetStageUpAxis(self._stage, UsdGeom.Tokens.y)
billboard = UsdGeom.Mesh.Define(self._stage, primpath)
w2 = w/2
h2 = h/2
pts = [(-w2, -h2, 0), (w2, -h2, 0), (w2, h2, 0), (-w2, h2, 0)]
ext = [(-w2, -h2, 0), (w2, h2, 0)]
billboard.CreatePointsAttr(pts)
billboard.CreateFaceVertexCountsAttr([4])
billboard.CreateFaceVertexIndicesAttr([0, 1, 2, 3])
billboard.CreateExtentAttr(ext)
texCoords = UsdGeom.PrimvarsAPI(billboard).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray,
UsdGeom.Tokens.varying)
texCoords.Set([(0, 0), (1, 0), (1, 1), (0, 1)])
return billboard
self.ensure_stage()
# Tore:
# Remove _sf_size into smf (and sff?)
# def get_bool_model(self, option_name: str):
# bool_model = ui.SimpleBoolModel()
# return bool_model
def toggle_write_log(self):
self.p_writelog = not self.p_writelog
print(f"toggle_write_log is now:{self.p_writelog}")
def query_write_log(self):
self.p_writelog = self.sfw.writelog_checkbox_model.as_bool
self.p_logseriesname = self.sfw.writelog_seriesname_model.as_string
print(f"query_write_log is now:{self.p_writelog} name:{self.p_logseriesname}")
def query_physics(self):
self.p_equipforphysics = self.sfw.equipforphysics_checkbox_model.as_bool
print(f"sfc.p_equipforphysics is now:{self.p_equipforphysics}")
def query_remote_settings(self):
sfw = self.sfw
if sfw.doremote_checkbox_model is not None:
self.p_doremote = self.sfw.doremote_checkbox_model.as_bool
if sfw.doregister_remote_checkbox_model is not None:
self.p_register_endpoint = self.sfw.doregister_remote_checkbox_model.as_bool
if sfw.doremote_type_model is not None:
idx = self.sfw.doremote_type_model.as_int
self.p_doremotetype = self._remotetypes[idx]
if sfw.doremote_url_model is not None:
self.p_doremoteurl = self.sfw.doremote_url_model.as_string
print(f"query_remote_settings is now:{self.p_doremote} type:{self.p_doremotetype} url:{self.p_doremoteurl}")
def toggle_bounds(self):
self.ensure_stage()
self._bounds_visible = not self._bounds_visible
self.sfw._tog_bounds_but.text = f"Bounds:{self._bounds_visible}"
self.sff.ToggleBoundsVisiblity(self._bounds_visible)
def on_click_billboard(self):
self.ensure_stage()
primpath = f"/World/Prim_Billboard_{self._count}"
billboard = self.create_billboard(primpath)
material = self.get_curmat_mat()
UsdShade.MaterialBindingAPI(billboard).Bind(material)
def on_click_spheremesh(self):
self.ensure_stage()
self.smf.GenPrep()
matname = self.get_curmat_name()
cpt = Gf.Vec3f(0, self._sf_size, 0)
primpath = f"/World/SphereMesh_{self._count}"
self._count += 1
self.smf.CreateMesh(primpath, matname, cpt, self._sf_size)
def update_radratio(self):
if self.sfw._sf_radratio_slider_model is not None:
val = self.sfw._sf_radratio_slider_model.as_float
self.sff.p_radratio = val
def on_click_sphereflake(self):
self.ensure_stage()
start_time = time.time()
sff = self.sff
sff.p_genmode = self.get_sf_genmode()
sff.p_genform = self.get_sf_genform()
sff.p_rad = self._sf_size
# print(f"slider: {type(self._sf_radratio_slider)}")
# sff._radratio = self._sf_radratio_slider.get_value_as_float()
self.update_radratio()
sff.p_sf_matname = self.get_curmat_name()
sff.p_sf_alt_matname = self.get_curaltmat_name()
sff.p_bb_matname = self.get_curmat_bbox_name()
cpt = Gf.Vec3f(0, self._sf_size, 0)
primpath = f"/World/SphereFlake_{self._count}"
self._count += 1
sff.Generate(primpath, cpt)
elap = time.time() - start_time
self.sfw._statuslabel.text = f"SphereFlake took elapsed: {elap:.2f} s"
self.UpdateStuff()
async def generate_sflakes(self):
sff = self.sff
sff._matman = self._matman
sff.p_genmode = self.get_sf_genmode()
sff.p_genform = self.get_sf_genform()
sff.p_rad = self._sf_size
self.update_radratio()
sff.p_sf_matname = self.get_curmat_name()
sff.p_sf_alt_matname = self.get_curaltmat_name()
sff.p_make_bounds_visible = self._bounds_visible
sff.p_bb_matname = self.get_curmat_bbox_name()
sff.p_tag = self.currenttag
self.query_physics()
sff.p_equipforphysics = self.p_equipforphysics
if sff.p_parallelRender:
self.query_remote_settings()
self._stage = omni.usd.get_context().get_stage()
sff.ResetStage(self._stage)
await sff.GenerateManyParallel(doremote=self.p_doremote,
remotetype=self.p_doremotetype,
remoteurl=self.p_doremoteurl)
new_count = sff.p_nsfx*sff.p_nsfy*sff.p_nsfz
else:
new_count = sff.GenerateMany()
self._count += new_count
sff.SaveSettings()
self.SaveSettings()
def write_log(self, elap: float = 0.0):
self.query_write_log()
if self.p_writelog:
nflakes = self.sff.p_nsfx * self.sff.p_nsfz
ntris, nprims = self.sff.CalcTrisAndPrims()
dogpu = self._gpuinfo is not None
if dogpu:
gpuinfo = self._gpuinfo
else:
gpuinfo = {"total": 0, "used": 0, "free": 0}
om = float(1024*1024*1024)
hostname = socket.gethostname()
memused = psutil.virtual_memory().used
memtot = psutil.virtual_memory().total
memfree = psutil.virtual_memory().free
cores = psutil.cpu_count()
# msg = f"GPU Mem tot: {gpuinfo.total/om:.2f}: used: {gpuinfo.used/om:.2f} free: {gpuinfo.free/om:.2f} GB"
# msg += f"\nCPU cores: {cores}"
# msg += f"\nSys Mem tot: {memtot/om:.2f}: used: {memused/om:.2f} free: {memfree/om:.2f} GB"
rundict = {"0-seriesname": self.p_logseriesname,
"0-hostname": hostname,
"0-date": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"0-tag": self.currenttag,
"1-genmode": self.sff.p_genmode,
"1-genform": self.sff.p_genform,
"1-depth": self.sff.p_depth,
"1-rad": self.sff.p_rad,
"1-radratio": self.sff.p_radratio,
"1-nsfx": self.sff.p_nsfx,
"1-nsfy": self.sff.p_nsfy,
"1-nsfz": self.sff.p_nsfz,
"2-tris": ntris,
"2-prims": nprims,
"2-nflakes": nflakes,
"2-elapsed": truncf(elap, 3),
"3-gpu_gbmem_tot": truncf(gpuinfo.total/om, 3),
"3-gpu_gbmem_used": truncf(gpuinfo.used/om, 3),
"3-gpu_gbmem_free": truncf(gpuinfo.free/om, 3),
"4-sys_gbmem_tot": truncf(memtot/om, 3),
"4-sys_gbmem_used": truncf(memused/om, 3),
"4-sys_gbmem_free": truncf(memfree/om, 3),
"5-cpu_cores": cores,
}
self.WriteRunLog(rundict)
async def on_click_multi_sphereflake(self):
self.ensure_stage()
# extent3f = self.sff.GetSphereFlakeBoundingBox()
extent3f = self.sff.GetSphereFlakeBoundingBoxNxNyNz()
self.setup_environment(extent3f, force=True)
start_time = time.time()
self.sff.ResetStage(self._stage)
hostname = socket.gethostname()
datestr = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
self.currenttag = f"{hostname}-{datestr}"
await self.generate_sflakes()
elap = time.time() - start_time
nflakes = self.sff.p_nsfx * self.sff.p_nsfz
self.sfw._statuslabel.text = f"{nflakes} flakes took elapsed: {elap:.2f} s"
self.UpdateStuff()
self.write_log(elap)
def spawnprim(self, primtype):
self.ensure_stage()
extent3f = self.sff.GetSphereFlakeBoundingBox()
self.setup_environment(extent3f, force=True)
if primtype == "Billboard":
self.on_click_billboard()
return
elif primtype == "SphereMesh":
self.on_click_spheremesh()
return
primpath = f"/World/Prim_{primtype}_{self._count}"
okc.execute('CreateMeshPrimWithDefaultXform', prim_type=primtype, prim_path=primpath)
material = self.get_curmat_mat()
self._count += 1
okc.execute('TransformMultiPrimsSRTCpp',
count=1,
paths=[primpath],
new_scales=[1, 1, 1],
new_translations=[0, 50, 0])
prim: Usd.Prim = self._stage.GetPrimAtPath(primpath)
UsdShade.MaterialBindingAPI(prim).Bind(material)
def on_click_writerunlog(self):
self.p_writelog = not self.p_writelog
self.sfw._sf_writerunlog_but.text = f"Write Perf Log: {self.p_writelog}"
def round_increment(self, val: int, butval: bool, maxval: int, minval: int = 0):
inc = 1 if butval else -1
val += inc
if val > maxval:
val = minval
if val < minval:
val = maxval
return val
def UpdateStuff(self):
self.UpdateNQuads()
self.UpdateMQuads()
self.UpdateGpuMemory()
def on_click_sfdepth(self, x, y, button, modifier):
depth = self.round_increment(self.sff.p_depth, button == 1, 5, 0)
self.sfw._sf_depth_but.text = f"Depth:{depth}"
self.sff.p_depth = depth
self.UpdateStuff()
def on_click_nlat(self, x, y, button, modifier):
nlat = self.round_increment(self.smf.p_nlat, button == 1, 16, 3)
self._sf_nlat_but.text = f"Nlat:{nlat}"
self.smf.p_nlat = nlat
self.UpdateStuff()
def on_click_nlng(self, x, y, button, modifier):
nlng = self.round_increment(self.smf.p_nlng, button == 1, 16, 3)
self._sf_nlng_but.text = f"Nlng:{nlng}"
self.smf.p_nlng = nlng
self.UpdateStuff()
def on_click_sfx(self, x, y, button, modifier):
nsfx = self.round_increment(self.sff.p_nsfx, button == 1, 20, 1)
self.sfw._nsf_x_but.text = f"SF - x:{nsfx}"
self.sff.p_nsfx = nsfx
self.UpdateStuff()
def toggle_parallel_render(self):
self.sff.p_parallelRender = not self.sff.p_parallelRender
self.sfw._parallel_render_but.text = f"Parallel Render: {self.sff.p_parallelRender}"
def on_click_parallel_nxbatch(self, x, y, button, modifier):
tmp = self.round_increment(self.sff.p_parallel_nxbatch, button == 1, self.sff.p_nsfx, 1)
self.sfw._parallel_nxbatch_but.text = f"SF batch x: {tmp}"
self.sff.p_parallel_nxbatch = tmp
print(f"on_click_parallel_nxbatch:{tmp}")
self.UpdateStuff()
def on_click_parallel_nybatch(self, x, y, button, modifier):
tmp = self.round_increment(self.sff.p_parallel_nybatch, button == 1, self.sff.p_nsfy, 1)
self.sfw._parallel_nybatch_but.text = f"SF batch y: {tmp}"
self.sff.p_parallel_nybatch = tmp
self.UpdateStuff()
def on_click_parallel_nzbatch(self, x, y, button, modifier):
tmp = self.round_increment(self.sff.p_parallel_nzbatch, button == 1, self.sff.p_nsfz, 1)
self.sfw._parallel_nzbatch_but.text = f"SF batch z: {tmp}"
self.sff.p_parallel_nzbatch = tmp
self.UpdateStuff()
def toggle_partial_render(self):
self.sff.p_partialRender = not self.sff.p_partialRender
self.sfw._partial_render_but.text = f"Partial Render: {self.sff.p_partialRender}"
def on_click_parital_sfsx(self, x, y, button, modifier):
tmp = self.round_increment(self.sff.p_partial_ssfx, button == 1, self.sff.p_nsfx-1, 0)
self.sfw._part_nsf_sx_but.text = f"SF partial sx: {tmp}"
self.sff.p_partial_ssfx = tmp
self.UpdateStuff()
def on_click_parital_sfsy(self, x, y, button, modifier):
tmp = self.round_increment(self.sff.p_partial_ssfy, button == 1, self.sff.p_nsfy-1, 0)
self.sfw._part_nsf_sy_but.text = f"SF partial sy: {tmp}"
self.sff.p_partial_ssfy = tmp
self.UpdateStuff()
def on_click_parital_sfsz(self, x, y, button, modifier):
tmp = self.round_increment(self.sff.p_partial_ssfz, button == 1, self.sff.p_nsfz-1, 0)
self.sfw._part_nsf_sz_but.text = f"SF partial sz: {tmp}"
self.sff.p_partial_ssfz = tmp
self.UpdateStuff()
def on_click_parital_sfnx(self, x, y, button, modifier):
tmp = self.round_increment(self.sff.p_partial_nsfx, button == 1, self.sff.p_nsfx, 1)
self.sfw._part_nsf_nx_but.text = f"SF partial nx: {tmp}"
self.sff.p_partial_nsfx = tmp
self.UpdateStuff()
def on_click_parital_sfny(self, x, y, button, modifier):
tmp = self.round_increment(self.sff.p_partial_nsfy, button == 1, self.sff.p_nsfy, 1)
self.sfw._part_nsf_ny_but.text = f"SF partial ny: {tmp}"
self.sff.p_partial_nsfy = tmp
self.UpdateStuff()
def on_click_parital_sfnz(self, x, y, button, modifier):
tmp = self.round_increment(self.sff.p_partial_nsfz, button == 1, self.sff.p_nsfz, 1)
self.sfw._part_nsf_nz_but.text = f"SF partial nz: {tmp}"
self.sff.p_partial_nsfz = tmp
self.UpdateStuff()
def on_click_sfy(self, x, y, button, modifier):
nsfy = self.round_increment(self.sff.p_nsfy, button == 1, 20, 1)
self.sfw._nsf_y_but.text = f"SF - y:{nsfy}"
self.sff.p_nsfy = nsfy
self.UpdateStuff()
def on_click_sfz(self, x, y, button, modifier):
nsfz = self.round_increment(self.sff.p_nsfz, button == 1, 20, 1)
self.sfw._nsf_z_but.text = f"SF - z:{nsfz}"
self.sff.p_nsfz = nsfz
self.UpdateStuff()
def on_click_spawnprim(self):
self.spawnprim(self._curprim)
def xprocess():
pass
# print("xprocess started")
def on_click_launchxproc(self):
self.ensure_stage()
# cmdpath = "D:\\nv\\ov\\ext\\sphereflake-benchmark\\exts\\omni.sphereflake\\omni\\sphereflake"
subprocess.call(["python.exe"])
# subprocess.call([cmdpath,"hello.py"])
# print("launching xproc")
# p1 = multiprocessing.Process(target=self.xprocess)
# p1.start() # Casues app to stop servicing events
# self._xproc = XProcess(self._stage, self._curprim, self.smf, self.sff)
# self._xproc.start()
def on_click_clearprims(self):
self.ensure_stage()
# check and see what we have missed
worldprim = self._stage.GetPrimAtPath("/World")
for child_prim in worldprim.GetAllChildren():
cname = child_prim.GetName()
prefix = cname.split("_")[0]
dodelete = prefix in ["SphereFlake", "SphereMesh", "Prim"]
if dodelete:
# print(f"deleting {cname}")
cpath = child_prim.GetPrimPath()
self._stage.RemovePrim(cpath)
# okc.execute("DeletePrimsCommand", paths=[cpath])
self.smf.Clear()
self.sff.Clear()
self._count = 0
def on_click_changeprim(self):
idx = self._prims.index(self._curprim) + 1
if idx >= len(self._prims):
idx = 0
self._curprim = self._prims[idx]
self.sfw._sf_primtospawn_but.text = f"{self._curprim}"
matclickcount = 0
def on_click_resetmaterials(self):
self._matman.Reinitialize()
nmat = self._matman.GetMaterialCount()
self.sfw.reset_materials_but.text = f"Reset Materials ({nmat} defined) - {self.matclickcount}"
self.matclickcount += 1
def UpdateNQuads(self):
ntris, nprims = self.sff.CalcTrisAndPrims()
elap = SphereFlakeFactory.GetLastGenTime()
if self.sfw._sf_depth_but is not None:
self.sfw._sf_spawn_but.text = f"Spawn ShereFlake\n tris:{ntris:,} prims:{nprims:,}\ngen: {elap:.2f} s"
def UpdateMQuads(self):
ntris, nprims = self.sff.CalcTrisAndPrims()
tottris = ntris*self.sff.p_nsfx*self.sff.p_nsfz
if self.sfw._msf_spawn_but is not None:
self.sfw._msf_spawn_but.text = f"Multi ShereFlake\ntris:{tottris:,} prims:{nprims:,}"
def UpdateGpuMemory(self):
try:
nvidia_smi.nvmlInit()
handle = nvidia_smi.nvmlDeviceGetHandleByIndex(0)
# card id 0 hardcoded here, there is also a call to get all available card ids, so we could iterate
gpuinfo = nvidia_smi.nvmlDeviceGetMemoryInfo(handle)
except Exception:
gpuinfo = DummyGpuInfo()
self._gpuinfo = gpuinfo
om = float(1024*1024*1024)
msg = f"GPU Mem tot: {gpuinfo.total/om:.2f}: used: {gpuinfo.used/om:.2f} free: {gpuinfo.free/om:.2f} GB"
memused = psutil.virtual_memory().used
memtot = psutil.virtual_memory().total
memfree = psutil.virtual_memory().free
msg += f"\nSys Mem tot: {memtot/om:.2f}: used: {memused/om:.2f} free: {memfree/om:.2f} GB"
cores = psutil.cpu_count()
msg += f"\nCPU cores: {cores}"
refcnt = self._matman.refCount
ftccnt = self._matman.fetchCount
skpcnt = self._matman.skipCount
msg += f"\n Materials ref: {refcnt} fetched: {ftccnt} skipped: {skpcnt}"
self.sfw._memlabel.text = msg
def get_curmat_mat(self):
idx = self.sfw._sf_matbox_model.as_int
self._current_material_name = self._matkeys[idx]
return self._matman.GetMaterial(self._current_material_name)
def get_curmat_name(self):
idx = self.sfw._sf_matbox_model.as_int
self._current_material_name = self._matkeys[idx]
return self._current_material_name
def get_curaltmat_mat(self):
idx = self.sfw._sf_alt_matbox_model.as_int
self._current_alt_material_name = self._matkeys[idx]
return self._matman.GetMaterial(self._current_alt_material_name)
def get_curaltmat_name(self):
idx = self.sfw._sf_alt_matbox_model.as_int
self._current_alt_material_name = self._matkeys[idx]
return self._current_alt_material_name
def get_curfloormat_mat(self):
idx = self.sfw._sf_floor_matbox_model.as_int
self._current_floor_material_name = self._matkeys[idx]
return self._matman.GetMaterial(self._current_floor_material_name)
def get_curmat_bbox_name(self):
idx = self.sfw._bb_matbox_model.as_int
self._current_bbox_material_name = self._matkeys[idx]
return self._current_bbox_material_name
def get_curmat_bbox_mat(self):
idx = self.sfw._bb_matbox_model.as_int
self._current_bbox_material_name = self._matkeys[idx]
return self._matman.GetMaterial(self._current_bbox_material_name)
def get_curfloormat_name(self):
idx = self.sfw._sf_floor_matbox_model.as_int
self._current_floor_material_name = self._matkeys[idx]
return self._current_floor_material_name
def get_sf_genmode(self):
idx = self.sfw._genmodebox_model.as_int
return self._sf_gen_modes[idx]
def get_sf_genform(self):
idx = self.sfw._genformbox_model.as_int
return self._sf_gen_forms[idx]
def WriteRunLog(self, rundict=None):
if rundict is None:
rundict = {}
jline = json.dumps(rundict, sort_keys=True)
fname = "d:/nv/ov/log.txt"
with open(fname, "a") as f:
f.write(f"{jline}\n")
print("wrote log")
| 31,094 | Python | 39.174419 | 151 | 0.597897 |
MikeWise2718/sphereflake22/exts/wise.sphereflake22/wise/sphereflake22/styles.py | import omni.ui as ui
checkbox_group_style = {
"HStack::checkbox_row" : {
"margin_width": 18,
"margin": 2
},
"Label::cb_label": {
"margin_width": 10
}
}
tab_group_style = {
"TabGroupBorder": {
"background_color": ui.color.transparent,
"border_color": ui.color(25),
"border_width": 1
},
"Rectangle::TabGroupHeader" : {
"background_color": ui.color(20),
},
"ZStack::TabGroupHeader":{
"margin_width": 1
}
}
tab_style = {
"" : {
"background_color": ui.color(31),
"corner_flag": ui.CornerFlag.TOP,
"border_radius": 4,
"color": ui.color(127)
},
":selected": {
"background_color": ui.color(56),
"color": ui.color(203)
},
"Label": {
"margin_width": 5,
"margin_height": 3
}
} | 862 | Python | 19.547619 | 49 | 0.49768 |
MikeWise2718/sphereflake22/exts/wise.sphereflake22/wise/sphereflake22/sfwintabs.py | import omni.ui as ui
import asyncio
from ._widgets import BaseTab
from .sfgen.sphereflake import SphereFlakeFactory
from .sfcontrols import SfControls
from .sfwindow import SfWindow
class SfcTabMulti(BaseTab):
sfw: SfWindow
sfc: SfControls
def __init__(self, sfw: SfWindow):
super().__init__("Multi")
self.sfw = sfw
self.sfc = sfw.sfc
# print(f"SfcTabMulti.init {type(sfc)}")
def build_fn(self):
# print("SfcTabMulti.build_fn (trc)")
sfw: SfWindow = self.sfw
sfc: SfControls = self.sfc
sff: SphereFlakeFactory = self.sfw.sff
# print(f"SfcTabMulti.build_fn {type(sfc)}")
with ui.VStack(style={"margin": sfw.marg}):
with ui.VStack():
with ui.HStack():
clkfn = lambda: asyncio.ensure_future(sfc.on_click_multi_sphereflake()) # noqa : E731
sfw._msf_spawn_but = ui.Button("Multi ShereFlake",
style={'background_color': sfw.darkred},
clicked_fn=clkfn)
with ui.VStack(width=200):
clkfn = lambda x, y, b, m: sfc.on_click_sfx(x, y, b, m) # noqa : E731
sfw._nsf_x_but = ui.Button(f"SF x: {sff.p_nsfx}",
style={'background_color': sfw.darkblue},
mouse_pressed_fn=clkfn)
clkfn = lambda x, y, b, m: sfc.on_click_sfy(x, y, b, m) # noqa : E731
sfw._nsf_y_but = ui.Button(f"SF y: {sff.p_nsfy}",
style={'background_color': sfw.darkblue},
mouse_pressed_fn=clkfn)
clkfn = lambda x, y, b, m: sfc.on_click_sfz(x, y, b, m) # noqa : E731
sfw._nsf_z_but = ui.Button(f"SF z: {sff.p_nsfz}",
style={'background_color': sfw.darkblue},
mouse_pressed_fn=clkfn)
sfw._tog_bounds_but = ui.Button(f"Bounds:{sfc._bounds_visible}",
style={'background_color': sfw.darkcyan},
clicked_fn=sfc.toggle_bounds)
sfw.prframe = ui.CollapsableFrame("Partial Renders", collapsed=sfw.docollapse_prframe)
with sfw.prframe:
with ui.VStack():
sfw._partial_render_but = ui.Button(f"Partial Render {sff.p_partialRender}",
style={'background_color': sfw.darkcyan},
clicked_fn=sfc.toggle_partial_render)
with ui.HStack():
clkfn = lambda x, y, b, m: sfc.on_click_parital_sfsx(x, y, b, m) # noqa : E731
sfw._part_nsf_sx_but = ui.Button(f"SF partial sx: {sff.p_partial_ssfx}",
style={'background_color': sfw.darkblue},
mouse_pressed_fn=clkfn)
clkfn = lambda x, y, b, m: sfc.on_click_parital_sfsy(x, y, b, m) # noqa : E731
sfw._part_nsf_sy_but = ui.Button(f"SF partial sy: {sff.p_partial_ssfy}",
style={'background_color': sfw.darkblue},
mouse_pressed_fn=clkfn)
clkfn = lambda x, y, b, m: sfc.on_click_parital_sfsz(x, y, b, m) # noqa : E731
sfw._part_nsf_sz_but = ui.Button(f"SF partial sz: {sff.p_partial_ssfz}",
style={'background_color': sfw.darkblue},
mouse_pressed_fn=clkfn)
with ui.HStack():
clkfn = lambda x, y, b, m: sfc.on_click_parital_sfnx(x, y, b, m) # noqa : E731
sfw._part_nsf_nx_but = ui.Button(f"SF partial nx: {sff.p_partial_nsfx}",
style={'background_color': sfw.darkblue},
mouse_pressed_fn=clkfn)
clkfn = lambda x, y, b, m: sfc.on_click_parital_sfny(x, y, b, m) # noqa : E731
sfw._part_nsf_ny_but = ui.Button(f"SF partial ny: {sff.p_partial_nsfy}",
style={'background_color': sfw.darkblue},
mouse_pressed_fn=clkfn)
clkfn = lambda x, y, b, m: sfc.on_click_parital_sfnz(x, y, b, m) # noqa : E731
sfw._part_nsf_nz_but = ui.Button(f"SF partial nz: {sff.p_partial_nsfz}",
style={'background_color': sfw.darkblue},
mouse_pressed_fn=clkfn)
sfw.drframe = ui.CollapsableFrame("Distributed Renders", collapsed=sfw.docollapse_drframe)
with sfw.drframe:
with ui.VStack():
sfw._parallel_render_but = ui.Button(f"Distributed Render {sff.p_parallelRender}",
style={'background_color': sfw.darkcyan},
clicked_fn=sfc.toggle_parallel_render)
with ui.HStack():
clkfn = lambda x, y, b, m: sfc.on_click_parallel_nxbatch(x, y, b, m) # noqa : E731
sfw._parallel_nxbatch_but = ui.Button(f"SF batch x: {sff.p_parallel_nxbatch}",
style={'background_color': sfw.darkblue},
mouse_pressed_fn=clkfn)
clkfn = lambda x, y, b, m: sfc.on_click_parallel_nybatch(x, y, b, m) # noqa : E731
sfw._parallel_nybatch_but = ui.Button(f"SF batch y: {sff.p_parallel_nybatch}",
style={'background_color': sfw.darkblue},
mouse_pressed_fn=clkfn)
clkfn = lambda x, y, b, m: sfc.on_click_parallel_nzbatch(x, y, b, m) # noqa : E731
sfw._parallel_nzbatch_but = ui.Button(f"SF batch z: {sff.p_parallel_nzbatch}",
style={'background_color': sfw.darkblue},
mouse_pressed_fn=clkfn)
class SfcTabSphereFlake(BaseTab):
sfc: SfControls = None
def __init__(self, sfw: SfWindow):
super().__init__("SphereFlake")
self.sfw = sfw
self.sfc = sfw.sfc
def build_fn(self):
# print("SfcTabSphereFlake.build_fn (trc)")
sfw = self.sfw
sfc = self.sfc
sff = self.sfw.sff
smf = self.sfw.smf
# print(f"SfcTabMulti.build_fn sfc:{type(sfc)} ")
with ui.VStack(style={"margin": sfw.marg}):
with ui.VStack():
with ui.HStack():
sfw._sf_spawn_but = ui.Button("Spawn SphereFlake",
style={'background_color': sfw.darkred},
clicked_fn=lambda: sfc.on_click_sphereflake())
with ui.VStack(width=200):
sfw._sf_depth_but = ui.Button(f"Depth:{sff.p_depth}",
style={'background_color': sfw.darkgreen},
mouse_pressed_fn= # noqa : E251
lambda x, y, b, m: sfc.on_click_sfdepth(x, y, b, m))
with ui.HStack():
ui.Label("Radius Ratio: ",
style={'background_color': sfw.darkgreen},
width=50)
sfw._sf_radratio_slider = ui.FloatSlider(model=sfw._sf_radratio_slider_model,
min=0.0, max=1.0, step=0.01,
style={'background_color': sfw.darkblue}).model
# SF Gen Mode Combo Box
with ui.HStack():
ui.Label("Gen Mode:")
model = sfw._genmodebox_model
idx = model.as_int
sfw._genmodebox_model = ui.ComboBox(idx, *sff.GetGenModes()).model.get_item_value_model()
# SF Form Combo Box
with ui.HStack():
ui.Label("Gen Form1:")
model = sfw._genformbox_model
idx = model.as_int
sfw._genformbox_model = ui.ComboBox(idx, *sff.GetGenForms()).model.get_item_value_model()
with ui.VStack():
sfw._sf_nlat_but = ui.Button(f"Nlat:{smf.p_nlat}",
style={'background_color': sfw.darkgreen},
mouse_pressed_fn= # noqa : E251
lambda x, y, b, m: sfc.on_click_nlat(x, y, b, m))
sfw._sf_nlng_but = ui.Button(f"Nlng:{smf.p_nlng}",
style={'background_color': sfw.darkgreen},
mouse_pressed_fn= # noqa : E251
lambda x, y, b, m: sfc.on_click_nlng(x, y, b, m))
class SfcTabShapes(BaseTab):
sfw: SfWindow
sfc: SfControls
def __init__(self, sfw: SfWindow):
super().__init__("Shapes")
self.sfw = sfw
self.sfc = sfw.sfc
def build_fn(self):
# print("SfcTabShapes.build_fn (trc)")
sfc = self.sfc
sfw = self.sfw
# print(f"SfcTabShapes.build_fn {type(sfc)}")
with ui.VStack(style={"margin": sfw.marg}):
with ui.HStack():
sfw._sf_spawn_but = ui.Button("Spawn Prim",
style={'background_color': sfw.darkred},
clicked_fn=lambda: sfc.on_click_spawnprim())
sfw._sf_primtospawn_but = ui.Button(f"{sfc._curprim}",
style={'background_color': sfw.darkpurple},
clicked_fn=lambda: sfc.on_click_changeprim())
class SfcTabMaterials(BaseTab):
sfw: SfWindow
sfc: SfControls
def __init__(self, sfw: SfWindow):
super().__init__("Materials")
self.sfw = sfw
self.sfc = sfw.sfc
# print("SfcTabMaterials.build_fn {sfc}")
def build_fn(self):
# print("SfcTabMaterials.build_fn (trc)")
sfw = self.sfw
sfc = self.sfc
with ui.VStack(style={"margin": sfw.marg}):
# Material Combo Box
with ui.HStack():
ui.Label("SF Material 1:")
idx = sfc._matkeys.index(sfc._current_material_name)
sfw._sf_matbox = ui.ComboBox(idx, *sfc._matkeys)
sfw._sf_matbox_model = sfw._sf_matbox.model.get_item_value_model()
print("built sfw._sf_matbox")
with ui.HStack():
ui.Label("SF Material 2:")
# use the alternate material name
idx = sfc._matkeys.index(sfc._current_alt_material_name)
sfw._sf_alt_matbox = ui.ComboBox(idx, *sfc._matkeys)
sfw._sf_alt_matbox_model = sfw._sf_alt_matbox.model.get_item_value_model()
print("built sfw._sf_matbox")
# Bounds Material Combo Box
with ui.HStack():
ui.Label("Bounds Material:")
idx = sfc._matkeys.index(sfc._current_bbox_material_name)
sfw._bb_matbox = ui.ComboBox(idx, *sfc._matkeys)
sfw._bb_matbox_model = sfw._bb_matbox.model.get_item_value_model()
# Bounds Material Combo Box
with ui.HStack():
ui.Label("Floor Material:")
idx = sfc._matkeys.index(sfc._current_floor_material_name)
sfw._sf_floor_matbox = ui.ComboBox(idx, *sfc._matkeys)
sfw._sf_floor_matbox_model = sfw._sf_floor_matbox.model.get_item_value_model()
sfw.reset_materials_but = ui.Button(f"Reset Materials",
style={'background_color': sfw.darkpurple},
clicked_fn=lambda: sfc.on_click_resetmaterials())
class SfcTabOptions(BaseTab):
sfw: SfWindow
sfc: SfControls
def __init__(self, sfw: SfWindow):
super().__init__("Options")
self.sfw = sfw
self.sfc = sfw.sfc
# print("SfcTabOptions.build_fn {sfc}")
def build_fn(self):
# print("SfcTabOptions.build_fn (trc)")
sfw = self.sfw
sfc = self.sfc # noqa : F841
with ui.VStack(style={"margin": sfw.marg}):
sfw.optlogframe = ui.CollapsableFrame("Logging Parameters", collapsed=sfw.docollapse_optlogframe)
with sfw.optlogframe:
with ui.VStack(style={"margin": sfw.marg}):
with ui.HStack():
ui.Label("Write Perf Log: ")
sfw.writelog_checkbox = ui.CheckBox(model=sfw.writelog_checkbox_model,
width=40, height=10, name="writelog", visible=True)
with ui.HStack():
ui.Label("Log Series Name:")
sfw.writelog_seriesname = ui.StringField(model=sfw.writelog_seriesname_model,
width=200, height=20, visible=True)
sfw.optremoteframe = ui.CollapsableFrame("Remote Processing", collapsed=sfw.docollapse_optremoteframe)
with sfw.optremoteframe:
with ui.VStack(style={"margin": sfw.marg}):
with ui.HStack():
ui.Label("Do Remote: ")
sfw.doremote_checkbox = ui.CheckBox(model=sfw.doremote_checkbox_model,
width=40, height=10, name="doremote", visible=True)
with ui.HStack():
ui.Label("Register Remote Endpoints: ")
sfw.doregister_remote_checkbox = ui.CheckBox(model=sfw.doregister_remote_checkbox_model,
width=40, height=10,
name="register endpoint", visible=True)
with ui.HStack():
ui.Label("Remote Type:")
# idx = sfc._remotetypes.index(sfc.p_doremotetype)
idx = sfc._remotetypes.index(sfc.p_doremotetype)
sfw.doremote_type = ui.ComboBox(idx, *sfc._remotetypes)
sfw.doremote_type_model = sfw.doremote_type.model.get_item_value_model()
with ui.HStack():
ui.Label("Remote URL:")
sfw.doremote_url = ui.StringField(model=sfw.doremote_url_model,
width=400, height=20, visible=True)
sfw.optgroundframe = ui.CollapsableFrame("Ground Settings", collapsed=sfw.docollapse_optremoteframe)
with sfw.optgroundframe:
with ui.VStack(style={"margin": sfw.marg}):
with ui.HStack():
ui.Label("Add Rand")
sfw.addrand_checkbox = ui.CheckBox(model=sfw.addrand_checkbox_model,
width=40, height=10, name="addrand", visible=True)
class SfcTabPhysics(BaseTab):
sfw: SfWindow
sfc: SfControls
def __init__(self, sfw: SfWindow):
super().__init__("Physics")
self.sfw = sfw
self.sfc = sfw.sfc
# print("SfcTabOptions.build_fn {sfc}")
def build_fn(self):
# print("SfcTabOptions.build_fn (trc)")
sfw = self.sfw
sfc = self.sfc # noqa : F841
with ui.VStack(style={"margin": sfw.marg}):
sfw.physcollidersframe = ui.CollapsableFrame("Colliders", collapsed=sfw.docollapse_physcollidersframe)
with sfw.physcollidersframe:
with ui.VStack(style={"margin": sfw.marg}):
with ui.HStack():
ui.Label("Equip Objects for Phyics: ")
sfw.equipforphysics_checkbox = ui.CheckBox(model=sfw.equipforphysics_checkbox_model,
width=40, height=10, name="equipforphysics",
visible=True)
| 17,875 | Python | 53.334346 | 117 | 0.443413 |
MikeWise2718/sphereflake22/exts/wise.sphereflake22/wise/sphereflake22/extension.py | import omni.ext # this needs to be included in an extension's extension.py
from .ovut import write_out_syspath, write_out_path
from .sfgen.sfut import MatMan
from .sfgen.sphereflake import SphereMeshFactory, SphereFlakeFactory
from .sfcontrols import SfControls
from .sfwindow import SfWindow
import omni.kit.extensions
import carb
import carb.events
import time
from pxr import Usd
# Omni imports
# import omni.client
# import omni.usd_resolver
# import os
# import contextlib
# @contextlib.asynccontextmanager
update_count = -1
start_time = time.time()
last_update_time = start_time
triggered_show = False
initialized_objects = False
gap = 1.0
_instance_handle: omni.ext.IExt = None
def on_update_event(e: carb.events.IEvent):
global update_count, last_update_time, triggered_show, start_time, instance_handle, gap
update_count += 1
# if update_count % 50 == 0:
# print(f"Update: {e.payload} count: {update_count} (trc)")
elap = time.time() - last_update_time
if elap > gap:
last_update_time = time.time()
totelap = time.time() - start_time
# stage = omni.usd.get_context().get_stage()
# stagewd = stage if stage is not None else "None"
# print(f"on_update_event {update_count} {totelap:.3f}: typ:{e.type} pay:{e.payload} elap: {elap:.3f} stage:{stagewd} (trc)")
if not triggered_show and totelap > 10:
if _instance_handle is not None and _instance_handle._sfw is not None:
print("Triggering ShowTheDamnWindow (trc)")
_instance_handle._sfw.ShowTheDamnWindow()
_instance_handle._sfw.DockWindow()
triggered_show = True
gap = 5.0
def on_stage_event(e: carb.events.IEvent):
global initialized_objects, instance_handle, update_count, start_time
totelap = time.time() - start_time
print(f"on_stage_event {update_count} {totelap:.3f} typ:{e.type} pay:{e.payload} (trc1)")
if not initialized_objects:
stage = omni.usd.get_context().get_stage()
if stage is not None:
_instance_handle.InitializeObjects()
print("Initializing objectsw (trc)")
initialized_objects = True
# 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 SphereflakeBenchmarkExtension(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.
_window_sfcon = None
_matman: MatMan = None
_smf: SphereMeshFactory = None
_sff: SphereFlakeFactory = None
_sfc: SfControls = None
_sfw: SfWindow = None
_settings = None
_stage: Usd.Stage = None
def WriteOutPathAndSysPath(self, basename="d:/nv/ov/sphereflake_benchmark"):
write_out_syspath(f"{basename}_syspath.txt")
write_out_path(f"{basename}_path.txt")
def setup_event_handlers(self):
update_stream = omni.kit.app.get_app().get_update_event_stream()
self._sub1 = update_stream.create_subscription_to_pop(on_update_event, name="SFB_UpdateSub")
stage_stream = omni.usd.get_context().get_stage_event_stream()
self._sub2 = stage_stream.create_subscription_to_pop(on_stage_event, name="SFB_StageSub")
print("Setup on_stage_event handler")
def InitializeObjects(self):
self._stage = omni.usd.get_context().get_stage()
# sesslayer = self._stage.GetSessionLayer()
# rootlayer = self._stage.GetRootLayer()
# print(f"Sesslayer: {sesslayer} (trc)")
# print(f"Rootlayer: {rootlayer} (trc)")
print(f"SphereflakeBenchmarkExtension on_startup - stage:{self._stage} (trc)")
self._stageid = omni.usd.get_context().get_stage_id()
# pid = os.getpid()
# Write out syspath and path
# self.WriteOutPathAndSysPath()
# Model objects
self._matman = MatMan(self._stage)
self._smf = SphereMeshFactory(self._stage, self._matman)
self._sff = SphereFlakeFactory(self._stage, self._matman, self._smf)
self._sff.LoadSettings()
# Controller objects
self._sfc = SfControls(self._matman, self._smf, self._sff)
print("SphereflakeBenchmarkExtension - _sfc assigned (trc)")
# View objects
self._sfw = SfWindow(sfc=self._sfc)
print("SphereflakeBenchmarkExtension - _sfw assigned (trc)")
self._sfw.DockWindow()
self._sfw.ShowTheDamnWindow()
print("SphereflakeBenchmarkExtension - InitialzeObjects done (trc)")
def on_startup(self, ext_id):
global _instance_handle
_instance_handle = self
print(f"[{ext_id}] SphereflakeBenchmarkExtension on_startup (trc))")
self._ext_id = ext_id
self.setup_event_handlers()
print("Subscribing to update events")
print(f"[{self._ext_id}] SphereflakeBenchmarkExtension on_startup - done (trc))")
def on_shutdown(self):
global initialized_objects
try:
print(f"[{self._ext_id}] SphereflakeBenchmarkExtension on_shutdown objs_inited:{initialized_objects}")
if initialized_objects:
if self._sfc is not None:
self._sfc.SaveSettings()
self._sfc.Close()
else:
carb.log_error(f"on_shutdown - _sfc is Unexpectedly None objs_inited:{initialized_objects}")
if self._sfw is not None:
self._sfw.SaveSettings()
self._sfw.destroy()
else:
carb.log_error(f"on_shutdown - _sfw is Unexpectedly None objs_inited:{initialized_objects}")
except Exception as e:
carb.log_error(f"on_shutdown - Exception: {e}")
| 5,990 | Python | 38.156862 | 133 | 0.644073 |
MikeWise2718/sphereflake22/exts/wise.sphereflake22/wise/sphereflake22/__init__.py | from .extension import *
| 25 | Python | 11.999994 | 24 | 0.76 |
MikeWise2718/sphereflake22/exts/wise.sphereflake22/wise/sphereflake22/_widgets.py | from functools import partial
from typing import List
import omni.ui as ui
from . import styles
import carb
class CheckBoxGroupModel:
def __init__(self, option_names: List):
self.options = []
self.bool_models = []
self.subscriptions = []
self._single_callbacks = []
self._group_callbacks = []
for option in option_names:
self.add_checkbox_option(option)
def add_checkbox_option(self, option_name):
self.options.append(option_name)
bool_model = ui.SimpleBoolModel()
next_index = len(self.bool_models)
self.bool_models.append(bool_model)
self.subscriptions.append(bool_model.subscribe_value_changed_fn(partial(self.on_model_value_changed, next_index)))
return bool_model
def subscribe_value_changed_fn(self, callback_fn):
self._single_callbacks.append(callback_fn)
def subscribe_group_changed_fn(self, callback_fn):
self._group_callbacks.append(callback_fn)
def on_model_value_changed(self, index: int, model: ui.SimpleBoolModel):
for callback in self._single_callbacks:
option = self.options[index]
callback(option, model.as_bool)
for callback in self._group_callbacks:
checkbox_values = []
for name, bool_model in zip(self.options, self.bool_models):
checkbox_values.append((name, bool_model.as_bool))
callback(checkbox_values)
def get_bool_model(self, option_name):
index = self.options.index(option_name)
return self.bool_models[index]
def get_checkbox_options(self):
return self.options
def destroy(self):
self.subscriptions = None
self._single_callbacks = None
self._group_callbacks = None
class CheckBoxGroup:
def __init__(self, group_name: str, model: CheckBoxGroupModel):
self.group_name = group_name
self.model = model
self._build_widget()
def _build_widget(self):
with ui.VStack(width=0, height=0, style=styles.checkbox_group_style):
ui.Label(f"{self.group_name}:")
for option in self.model.get_checkbox_options():
with ui.HStack(name="checkbox_row", width=0, height=0):
ui.CheckBox(model=self.model.get_bool_model(option))
ui.Label(option, name="cb_label")
def destroy(self):
self.model.destroy()
class BaseTab:
def __init__(self, name):
self.name = name
def build_fn(self):
"""Builds the contents for the tab.
You must implement this function with the UI construction code that you want for
you tab. This is set to be called by a ui.Frame so it must have only a single
top-level widget.
"""
raise NotImplementedError("You must implement Tab.build_fn")
class TabGroup:
def __init__(self, tabs: List[BaseTab]):
self.frame = ui.Frame(build_fn=self._build_widget)
if not tabs:
raise ValueError("You must provide at least one BaseTab object.")
self.tabs = tabs
self.tab_containers = []
self.tab_headers = []
self.initial_selected_tab = 0
def _build_widget(self):
with ui.ZStack(style=styles.tab_group_style):
ui.Rectangle(style_type_name_override="TabGroupBorder")
with ui.VStack():
ui.Spacer(height=1)
with ui.ZStack(height=0, name="TabGroupHeader"):
ui.Rectangle(name="TabGroupHeader")
with ui.VStack():
ui.Spacer(height=2)
with ui.HStack(height=0, spacing=4):
for x, tab in enumerate(self.tabs):
tab_header = ui.ZStack(width=0, style=styles.tab_style)
self.tab_headers.append(tab_header)
with tab_header:
rect = ui.Rectangle()
rect.set_mouse_released_fn(partial(self._tab_clicked, x))
ui.Label(tab.name)
with ui.ZStack():
for x, tab in enumerate(self.tabs):
container_frame = ui.Frame(build_fn=tab.build_fn)
self.tab_containers.append(container_frame)
container_frame.visible = False
# Initialize first tab
self.select_tab(self.initial_selected_tab)
def select_tab(self, index: int):
print(f"Selecting tab:{index} (trc1)")
if self.tab_containers is None:
carb.log_error("Tab containers not allocated (none) (trc1)")
return
if len(self.tab_containers) == 0:
self.initial_selected_tab = index
carb.log_info(f"Tab containers are not initialized {index} (trc1)")
return
for x in range(len(self.tabs)):
if x == index:
self.tab_containers[x].visible = True
self.tab_headers[x].selected = True
else:
self.tab_containers[x].visible = False
self.tab_headers[x].selected = False
def get_selected_tab_index(self) -> int:
if len(self.tab_containers) == 0:
return self.initial_selected_tab
for x in range(len(self.tabs)):
if self.tab_containers[x].visible:
return x
return -1
def _tab_clicked(self, index, x, y, button, modifier):
if button == 0:
self.select_tab(index)
def append_tab(self, tab: BaseTab):
pass
def destroy(self):
self.frame.destroy()
| 5,743 | Python | 35.125786 | 122 | 0.572001 |
MikeWise2718/sphereflake22/exts/wise.sphereflake22/wise/sphereflake22/ovut.py | import omni.usd
import os
import sys
import math
import carb.settings
_settings = None
def _init_settings():
global _settings
if _settings is None:
_settings = carb.settings.get_settings()
return _settings
def get_setting(name, default, db=False):
settings = _init_settings()
key = f"/persistent/omni/sphereflake/{name}"
val = settings.get(key)
if db:
oval = val
if oval is None:
oval = "None"
if val is None:
val = default
if db:
print(f"get_setting {name} {oval} {val}")
return val
def save_setting(name, value):
settings = _init_settings()
key = f"/persistent/omni/sphereflake/{name}"
settings.set(key, value)
def truncf(number, digits) -> float:
# Improve accuracy with floating point operations, to avoid truncate(16.4, 2) = 16.39 or truncate(-1.13, 2) = -1.12
nbDecimals = len(str(number).split('.')[1])
if nbDecimals <= digits:
return number
stepper = 10.0 ** digits
return math.trunc(stepper * number) / stepper
def delete_if_exists(primpath: str) -> None:
ctx = omni.usd.get_context()
stage = ctx.get_stage()
if stage.GetPrimAtPath(primpath):
stage.RemovePrim(primpath)
# okc.execute("DeletePrimsCommand", paths=[primpath])
def write_out_path(fname: str = 'd:/nv/ov/path.txt') -> None:
# Write out the path to a file
path = os.environ["PATH"]
with open(fname, "w") as f:
npath = path.replace(";", "\n")
f.write(npath)
def write_out_syspath(fname: str = 'd:/nv/ov/syspath.txt', indent=False) -> None:
# Write out the python syspath to a file
# Indent should be True if to be used for the settings.json python.analsys.extraPaths setting
pplist = sys.path
with open(fname, 'w') as f:
for line in pplist:
nline = line.replace("\\", "/")
if indent:
nnline = f" \"{nline}\",\n"
else:
nnline = f"\"{nline}\",\n"
f.write(nnline)
def read_in_syspath(fname: str = 'd:/nv/ov/syspath.txt') -> None:
# Read in the python path from a file
with open(fname, 'r') as f:
for line in f:
nline = line.replace(',', '')
nline = nline.replace('"', '')
nline = nline.replace('"', '')
nline = nline.replace('\n', '')
nline = nline.replace(' ', '')
sys.path.append(nline)
| 2,463 | Python | 26.076923 | 119 | 0.577751 |
MikeWise2718/sphereflake22/exts/wise.sphereflake22/wise/sphereflake22/sfwindow.py | import omni.ui as ui
from omni.ui import color as clr
from .sfgen.sphereflake import SphereMeshFactory, SphereFlakeFactory
from .sfcontrols import SfControls
from ._widgets import TabGroup
from .ovut import get_setting, save_setting
import carb
class SfWindow(ui.Window):
darkgreen = clr("#004000")
darkblue = clr("#000040")
darkred = clr("#400000")
darkyellow = clr("#404000")
darkpurple = clr("#400040")
darkcyan = clr("#004040")
marg = 2
# Status
_statuslabel: ui.Label = None
_memlabel: ui.Label = None
# Sphereflake params
prframe: ui.CollapsableFrame = None
drframe: ui.CollapsableFrame = None
physcollidersframe: ui.CollapsableFrame = None
optlogframe: ui.CollapsableFrame = None
optremoteframe: ui.CollapsableFrame = None
optgroundframe: ui.CollapsableFrame = None
optstartupframe: ui.CollapsableFrame = None
docollapse_prframe = False
docollapse_drframe = False
docollapse_optlogframe = False
docollapse_physcollidersframe = False
docollapse_optremoteframe = False
docollapse_optgroundframe = False
docollapse_optstartupframe = False
_sf_depth_but: ui.Button = None
_sf_spawn_but: ui.Button = None
_sf_nlat_but: ui.Button = None
_sf_nlng_but: ui.Button = None
_sf_radratio_slider_model: ui.SimpleFloatModel = None
_genmodebox: ui.ComboBox = None
_genmodebox_model: ui.SimpleIntModel = None
_genformbox: ui.ComboBox = None
_genformbox_model: ui.SimpleIntModel = None
# Material tab
_sf_matbox: ui.ComboBox = None
_sf_matbox_model: ui.SimpleIntModel = None
_sf_alt_matbox: ui.ComboBox = None
_sf_alt_matbox_model: ui.SimpleIntModel = None
_bb_matbox: ui.ComboBox = None
_bb_matbox_model: ui.SimpleIntModel = None
_sf_floor_matbox: ui.ComboBox = None
_sf_floor_matbox_model: ui.SimpleIntModel = None
# Options
writelog_checkbox: ui.CheckBox = None
writelog_checkbox_model: ui.SimpleBoolModel = None
writelog_seriesname: ui.StringField = None
writelog_seriesname_model: ui.SimpleStringModel = None
doremote_checkbox: ui.CheckBox = None
doremote_checkbox_model: ui.SimpleBoolModel = None
doremote_type: ui.ComboBox = None
doremote_type_model: ui.SimpleIntModel = None
doremote_url: ui.StringField = None
doremote_url_model: ui.SimpleStringModel = None
doregister_remote_checkbox: ui.CheckBox = None
doregister_remote_checkbox_model: ui.SimpleBoolModel = None
doloadusd_checkbox: ui.CheckBox = None
doloadusd_checkbox_model: ui.SimpleBoolModel = None
doloadusd_url: ui.StringField = None
doloadusd_url_model: ui.SimpleStringModel = None
doloadusd_session_checkbox: ui.CheckBox = None
doloadusd_session_checkbox_model: ui.SimpleBoolModel = None
doloadusd_sessionname: ui.StringField = None
doloadusd_sessionname_model: ui.SimpleStringModel = None
# Ground
addrand_checkbox: ui.CheckBox = None
addrand_checkbox_model: ui.SimpleBoolModel = None
# Physics
equipforphysics_checkbox_model: ui.SimpleBoolModel = None
# state
sfc: SfControls
smf: SphereMeshFactory
sff: SphereFlakeFactory
def __init__(self, *args, **kwargs):
self.wintitle = "SphereFlake Controls"
super().__init__(title=self.wintitle, height=300, width=300, *args, **kwargs)
print("SfWindow.__init__ (trc)")
# print("SfWindow.__init__ (trc)")
self.sfc = kwargs["sfc"]
self.sfc.sfw = self # intentionally circular
self.smf = self.sfc.smf
self.sff = self.sfc.sff
self.LoadSettings()
self.BuildControlModels()
self.BuildWindow()
print("Calling sfc.LateInit")
self.sfc.LateInit()
def ShowTheDamnWindow(self):
ui.Workspace.show_window(self.wintitle, True)
def BuildControlModels(self):
# models for controls that are used in the logic need to be built outside the build_fn
# since that will only be called when the tab is selected and displayed
sfc = self.sfc
sff = sfc.sff
# sphereflake params
self._sf_radratio_slider_model = ui.SimpleFloatModel(sff.p_radratio)
idx = sff.GetGenModes().index(sff.p_genmode)
self._genmodebox_model = ui.SimpleIntModel(idx)
idx = sff.GetGenForms().index(sff.p_genform)
self._genformbox_model = ui.SimpleIntModel(idx)
# materials
matlist = sfc._matkeys
idx = matlist.index(sff.p_sf_matname)
self._sf_matbox_model = ui.SimpleIntModel(idx)
idx = matlist.index(sff.p_sf_alt_matname)
self._sf_alt_matbox_model = ui.SimpleIntModel(idx)
idx = matlist.index(sff.p_bb_matname)
self._bb_matbox_model = ui.SimpleIntModel(idx)
idx = matlist.index(sfc._current_floor_material_name)
self._sf_floor_matbox_model = ui.SimpleIntModel(idx)
# options
self.writelog_checkbox_model = ui.SimpleBoolModel(sfc.p_writelog)
self.writelog_seriesname_model = ui.SimpleStringModel(sfc.p_logseriesname)
self.doremote_checkbox_model = ui.SimpleBoolModel(sfc.p_doremote)
idx = sfc._remotetypes.index(sfc.p_doremotetype)
self.doremote_type_model = ui.SimpleIntModel(idx)
self.doloadusd_checkbox_model = ui.SimpleBoolModel(sfc.p_doloadusd)
self.doloadusd_session_checkbox_model = ui.SimpleBoolModel(sfc.p_doloadusd_session)
self.doremote_url_model = ui.SimpleStringModel(sfc.p_doremoteurl)
self.doloadusd_sessionname_model = ui.SimpleStringModel(sfc.p_doloadusd_sessionname)
self.doloadusd_url_model = ui.SimpleStringModel(sfc.p_doloadusd_url)
self.equipforphysics_checkbox_model = ui.SimpleBoolModel(sfc.p_equipforphysics)
self.doregister_remote_checkbox_model = ui.SimpleBoolModel(sfc.p_register_endpoint)
# Ground
self.addrand_checkbox_model = ui.SimpleBoolModel(sfc.p_addrand)
def BuildWindow(self):
print("SfWindow.BuildWindow (trc1)")
sfc = self.sfc
sfw = self
from .sfwintabs import SfcTabMulti, SfcTabSphereFlake, SfcTabShapes, SfcTabMaterials
from .sfwintabs import SfcTabOptions, SfcTabPhysics
from .sfwinsess import SfcTabSessionInfo
with self.frame:
with ui.VStack():
t1 = SfcTabMulti(self)
t2 = SfcTabSphereFlake(self)
t3 = SfcTabShapes(self)
t4 = SfcTabMaterials(self)
t5 = SfcTabOptions(self)
t6 = SfcTabPhysics(self)
t7 = SfcTabSessionInfo(self)
print("Creating Tab Group (trc1)")
self.tab_group = TabGroup([t1, t2, t3, t4, t5, t6, t7])
if self.start_tab_idx is not None:
self.tab_group.select_tab(self.start_tab_idx)
with ui.HStack():
ui.Button("Clear Primitives",
style={'background_color': self.darkyellow},
clicked_fn=lambda: sfc.on_click_clearprims())
clkfn = lambda x, y, b, m: sfw.on_click_save_settings(x, y, b, m) # noqa : E731
ui.Button("Save Settings",
style={'background_color': self.darkpurple},
mouse_pressed_fn=clkfn)
self._statuslabel = ui.Label("Status: Ready")
self._memlabel = ui.Button("Memory tot/used/free", clicked_fn=sfc.UpdateGpuMemory)
def on_click_setup_code_env(self, x, y, button, modifier):
from omni.kit.window.extensions import ext_controller
extid = "omni.kit.window.extensions"
ext_controller.toggle_autoload(extid, True)
showit = True if button == 0 else False
viewwintitle = "Viewport"
viewhandle = ui._ui.Workspace.get_window(viewwintitle)
extwintitle = "Extensions"
exthandle = ui._ui.Workspace.get_window(extwintitle)
# print(f"Set up environment (trc) exthandle: {exthandle} viewhandle:{viewhandle} showit: {showit}")
if viewhandle is not None:
if exthandle is not None:
exthandle.dock_in(viewhandle, ui._ui.DockPosition.SAME)
ui.Workspace.show_window(extwintitle, showit)
# Environment
brsid0 = "omni.kit.environment.core"
ext_controller.toggle_autoload(brsid0, True)
brsid1 = "omni.kit.property.environment"
ext_controller.toggle_autoload(brsid1, True)
brsid2 = "omni.kit.window.environment"
ext_controller.toggle_autoload(brsid2, True)
envwintitle = "Environments"
ui.Workspace.show_window(envwintitle, showit)
def on_click_save_settings(self, x, y, button, modifier):
self.SaveSettings()
self.sfc.SaveSettings()
print("Saved Settings")
def DockWindow(self, wintitle="Property"):
# print(f"Docking to {wintitle} (trc)")
handle = ui._ui.Workspace.get_window(wintitle)
self.dock_in(handle, ui._ui.DockPosition.SAME)
self.deferred_dock_in(wintitle, ui._ui.DockPolicy.TARGET_WINDOW_IS_ACTIVE)
def LoadSettings(self):
# print("SfWindow.LoadSettings (trc1)")
self.docollapse_prframe = get_setting("ui_pr_frame_collapsed", False)
self.docollapse_drframe = get_setting("ui_dr_frame_collapsed", False)
self.docollapse_physcollidersframe = get_setting("ui_phys_collidersframe", False)
self.docollapse_optlogframe = get_setting("ui_opt_logframe", False)
self.docollapse_optgroundframe = get_setting("ui_opt_groundframe", False)
self.docollapse_optremoteframe = get_setting("ui_opt_remoteframe", False)
self.docollapse_optstartupframe = get_setting("ui_opt_startupframe", False)
self.start_tab_idx = get_setting("ui_selected_tab", 0)
# print(f"SfWindow.LoadSettings start_tab_idx:{self.start_tab_idx} (trc1)")
def SafeSaveFrame(self, name, frame: ui.CollapsableFrame):
try:
if frame is not None:
save_setting(name, frame.collapsed)
except Exception as e:
carb.log_error(f"Exception in SfWindow.SafeSaveFrame - name:{name}: {e}")
def SaveSettings(self):
try:
# print("SfWindow.SaveSettings")
self.SafeSaveFrame("ui_pr_frame_collapsed", self.prframe)
self.SafeSaveFrame("ui_dr_frame_collapsed", self.drframe)
self.SafeSaveFrame("ui_phys_collidersframe", self.physcollidersframe)
self.SafeSaveFrame("ui_opt_logframe", self.optlogframe)
self.SafeSaveFrame("ui_opt_groundframe", self.optgroundframe)
self.SafeSaveFrame("ui_opt_remoteframe", self.optremoteframe)
self.SafeSaveFrame("ui_opt_startupframe", self.optstartupframe)
curidx = self.tab_group.get_selected_tab_index()
save_setting("ui_selected_tab", curidx)
print(f"SaveSettings - ui_selected_tab:{curidx} (trc1)")
except Exception as e:
carb.log_error(f"Exception in SfWindow.SaveSettings: {e}")
# print(f"docollapse_prframe: {self.prframe.collapsed} docollapse_drframe: {self.drframe.collapsed}")
| 11,266 | Python | 40.729629 | 117 | 0.654269 |
MikeWise2718/sphereflake22/exts/wise.sphereflake22/wise/sphereflake22/sfwinsess.py | import omni.ui as ui
from ._widgets import BaseTab
from .sfcontrols import SfControls
from .sfwindow import SfWindow
import os
import omni.client
import omni.usd_resolver
# Internal imports
import omni.kit.collaboration.channel_manager as cm
# import omni.kit.layers.live_session_channel_manager as lscm
class LiveSessionInfo:
""" Live Session Info class
This class attempts to collect all of the logic around the live session file paths and URLs.
It should be first instantiated with the stage URL (omniverse://server/folder/stage.usd), then
get_session_folder_path_for_stage() can be used to list the available sessions.
Once a session is selected, set_session_name() will finish the initialization of all of the paths
and the other methods can be used.
In the folder that contains the USD to be live-edited, there exists this folder structure:
<.live> / < my_usd_file.live> / <session_name> / root.live
get_session_folder_path_for_stage: <stage_folder> / <.live> / < my_usd_file.live>
get_live_session_folder_path: <stage_folder> / <.live> / < my_usd_file.live> / <session_name>
get_live_session_url: <stage_folder> / <.live> / < my_usd_file.live> / <session_name> / root.live
get_live_session_toml_url: <stage_folder> / <.live> / < my_usd_file.live> / <session_name> / __session__.toml
get_message_channel_url: <stage_folder> / <.live> / < my_usd_file.live> / <session_name> / __session__.channel
"""
def __init__(self, stage_url: str):
self.OMNIVERSE_CHANNEL_FILE_NAME = "__session__.channel"
self.LIVE_SUBFOLDER = "/.live"
self.LIVE_SUBFOLDER_SUFFIX = ".live"
self.DEFAULT_LIVE_FILE_NAME = "root.live"
self.SESSION_TOML_FILE_NAME = "__session__.toml"
self.stage_url = stage_url
self.live_file_url = None
self.channel_url = None
self.toml_url = None
self.session_name = None
self.omni_url = omni.client.break_url(self.stage_url)
# construct the folder that would contain sessions - <.live> / < my_usd_file.live> / <session_name> / root.live
self.omni_session_folder_path = os.path.dirname(self.omni_url.path) + self.LIVE_SUBFOLDER + "/" + self.get_stage_file_name() + self.LIVE_SUBFOLDER_SUFFIX
self.session_folder_string = omni.client.make_url(self.omni_url.scheme, self.omni_url.user, self.omni_url.host, self.omni_url.port, self.omni_session_folder_path)
def get_session_folder_path_for_stage(self):
return self.session_folder_string
def set_session_name(self, session_name):
self.session_name = session_name
def get_live_session_folder_path(self):
return self.omni_session_folder_path + "/" + self.session_name + self.LIVE_SUBFOLDER_SUFFIX
def get_stage_file_name(self):
# find the stage file's root name
usd_file_root = os.path.splitext(os.path.basename(self.omni_url.path))[0]
return usd_file_root
def get_live_session_url(self):
live_session_path = self.get_live_session_folder_path() + "/" + self.DEFAULT_LIVE_FILE_NAME
live_session_url = omni.client.make_url(self.omni_url.scheme, self.omni_url.user, self.omni_url.host, self.omni_url.port, live_session_path)
return live_session_url
def get_live_session_toml_url(self):
live_session_toml_path = self.get_live_session_folder_path() + "/" + self.SESSION_TOML_FILE_NAME
live_session_url = omni.client.make_url(self.omni_url.scheme, self.omni_url.user, self.omni_url.host, self.omni_url.port, live_session_toml_path)
return live_session_url
def get_message_channel_url(self):
live_session_channel_path = self.get_live_session_folder_path() + "/" + self.OMNIVERSE_CHANNEL_FILE_NAME
live_session_url = omni.client.make_url(self.omni_url.scheme, self.omni_url.user, self.omni_url.host, self.omni_url.port, live_session_channel_path)
return live_session_url
g_live_session_channel_manager = None
def list_session_users():
global g_live_session_channel_manager
# users are cm.PeerUser types
if g_live_session_channel_manager is None:
return ["Live session not initialized"]
users: set(cm.PeerUser)
users = g_live_session_channel_manager.get_users()
txtlst = ["Listing session users: "]
if len(users) == 0:
txtlst.append("No other users in session")
for user in users:
txtlst.append(f" - {user.user_name}[{user.from_app}")
return txtlst
class SfcTabSessionInfo(BaseTab):
sfw: SfWindow
sfc: SfControls
def __init__(self, sfw: SfWindow):
super().__init__("Session")
self.sfw = sfw
self.sfc = sfw.sfc
# print("SfcTabOptions.build_fn {sfc}")
def GetInfoText(self):
txt = "Session Info 1\nSession Info 2\nSession Info 3\n"
txt += "Session Info 4\nSession Info 5\nSession Info 6\n"
txt += "Session Info 7\nSession Info 8\nSession Info 9\n"
return txt
def build_fn(self):
# print("SfcTabOptions.build_fn (trc)")
sfw = self.sfw
sfc = self.sfc # noqa : F841
with ui.VStack(style={"margin": sfw.marg}, height=250):
with ui.ScrollingFrame():
with ui.VStack(style={"margin": sfw.marg}):
with ui.HStack():
txtlst = list_session_users()
txt = "/n".join(txtlst)
ui.Label(txt, word_wrap=True)
sfw.optstartupframe = ui.CollapsableFrame("Startup", collapsed=sfw.docollapse_optremoteframe)
with sfw.optstartupframe:
with ui.VStack(style={"margin": sfw.marg}):
with ui.HStack():
ui.Label("Load USD File on Startup: ")
sfw.doloadusd_checkbox = ui.CheckBox(model=sfw.doloadusd_checkbox_model,
width=40, height=10, name="loadusd", visible=True)
with ui.HStack():
ui.Label("USD URL:")
sfw.doloadusd_checkbox = ui.StringField(model=sfw.doloadusd_url_model,
width=400, height=20, visible=True)
with ui.HStack():
ui.Label("Start USD Session on Startup: ")
sfw.doloadusd_session_checkbox = ui.CheckBox(model=sfw.doloadusd_session_checkbox_model,
width=40, height=10, name="loadusd", visible=True)
with ui.HStack():
ui.Label("Session Name:")
sfw.doloadusd_sessionname = ui.StringField(model=sfw.doloadusd_sessionname_model,
width=400, height=20, visible=True)
| 6,879 | Python | 45.802721 | 170 | 0.616223 |
MikeWise2718/sphereflake22/exts/wise.sphereflake22/wise/sphereflake22/sfgen/sphereflake.py | import carb
import time
import asyncio
import math
import socket
from pxr import Gf, Usd, UsdGeom, UsdShade
from pxr import UsdPhysics, PhysxSchema, Gf, PhysicsSchemaTools, UsdGeom
from .spheremesh import SphereMeshFactory
from .sfut import MatMan, get_setting, save_setting
# import omni.services.client
latest_sf_gen_time = 0
def cross_product(v1: Gf.Vec3f, v2: Gf.Vec3f) -> Gf.Vec3f:
x = v1[1] * v2[2] - v1[2] * v2[1]
y = v1[2] * v2[0] - v1[0] * v2[2]
z = v1[0] * v2[1] - v1[1] * v2[0]
rv = Gf.Vec3f(x, y, z)
return rv
class SphereFlakeFactory():
_matman: MatMan = None
_smf: SphereMeshFactory = None
p_genmode = "UsdSphere"
p_genform = "Classic"
p_depth = 1
p_rad = 50
p_radratio = 0.3
p_nsfx = 1
p_nsfy = 1
p_nsfz = 1
p_partialRender = False
p_partial_ssfx = 0
p_partial_ssfy = 0
p_partial_ssfz = 0
p_partial_nsfx = 1
p_partial_nsfy = 1
p_partial_nsfz = 1
p_parallelRender = False
p_parallel_nxbatch = 1
p_parallel_nybatch = 1
p_parallel_nzbatch = 1
p_sf_matname = "Mirror"
p_sf_alt_matname = "Red_Glass"
p_bb_matname = "Blue_Glass"
p_make_bounds_visible = False
p_tag = None
p_equipforphysics = False
_start_time = 0
_createlist: list = []
_bbcubelist: list = []
_org = Gf.Vec3f(0, 0, 0)
_xax = Gf.Vec3f(1, 0, 0)
_yax = Gf.Vec3f(0, 1, 0)
_zax = Gf.Vec3f(0, 0, 1)
def __init__(self, stage: Usd.Stage, matman: MatMan, smf: SphereMeshFactory) -> None:
# self._stage = omni.usd.get_context().get_stage()
self._count = 0
self._matman = matman
self._smf = smf
self._stage = stage
print(f"SFF initialized with stage:{stage} (trc1)")
def ResetStage(self, stage: Usd.Stage):
self._stage = stage
self._smf.ResetStage(stage)
def GenPrep(self):
self._smf.GenPrep()
pass
def LoadSettings(self):
print("SphereFlakeFactory.LoadSettings (trc)")
self.p_genmode = get_setting("p_genmode", self.p_genmode)
self.p_genform = get_setting("p_genform", self.p_genform)
self.p_depth = get_setting("p_depth", self.p_depth)
self.p_rad = get_setting("p_rad", self.p_rad)
self.p_radratio = get_setting("p_radratio", self.p_radratio)
self.p_nsfx = get_setting("p_nsfx", self.p_nsfx, db=True)
self.p_nsfy = get_setting("p_nsfy", self.p_nsfy, db=True)
self.p_nsfz = get_setting("p_nsfz", self.p_nsfz, db=True)
self.p_partialRender = get_setting("p_partialRender", self.p_partialRender)
self.p_partial_ssfx = get_setting("p_partial_ssfx", self.p_partial_ssfx)
self.p_partial_ssfy = get_setting("p_partial_ssfy", self.p_partial_ssfy)
self.p_partial_ssfz = get_setting("p_partial_ssfz", self.p_partial_ssfz)
self.p_partial_nsfx = get_setting("p_partial_nsfx", self.p_partial_nsfx)
self.p_partial_nsfy = get_setting("p_partial_nsfy", self.p_partial_nsfy)
self.p_partial_nsfz = get_setting("p_partial_nsfz", self.p_partial_nsfz)
self.p_parallelRender = get_setting("p_parallelRender", self.p_parallelRender)
self.p_parallel_nxbatch = get_setting("p_parallel_nxbatch", self.p_parallel_nxbatch)
self.p_parallel_nybatch = get_setting("p_parallel_nybatch", self.p_parallel_nybatch)
self.p_parallel_nzbatch = get_setting("p_parallel_nzbatch", self.p_parallel_nzbatch)
self.p_sf_matname = get_setting("p_sf_matname", self.p_sf_matname)
self.p_sf_alt_matname = get_setting("p_sf_alt_matname", self.p_sf_alt_matname)
self.p_bb_matname = get_setting("p_bb_matname", self.p_bb_matname)
self.p_bb_matname = get_setting("p_bb_matname", self.p_bb_matname)
self.p_make_bounds_visible = get_setting("p_make_bounds_visible", self.p_make_bounds_visible)
print(f"SphereFlakeFactory.LoadSettings: p_nsfx:{self.p_nsfx} p_nsfy:{self.p_nsfy} p_nsfz:{self.p_nsfz}")
def SaveSettings(self):
print("SphereFlakeFactory.SaveSettings (trc)")
save_setting("p_genmode", self.p_genmode)
save_setting("p_genform", self.p_genform)
save_setting("p_depth", self.p_depth)
save_setting("p_rad", self.p_rad)
save_setting("p_radratio", self.p_radratio)
save_setting("p_nsfx", self.p_nsfx)
save_setting("p_nsfy", self.p_nsfy)
save_setting("p_nsfz", self.p_nsfz)
save_setting("p_partialRender", self.p_partialRender)
save_setting("p_partial_ssfx", self.p_partial_ssfx)
save_setting("p_partial_ssfy", self.p_partial_ssfy)
save_setting("p_partial_ssfz", self.p_partial_ssfz)
save_setting("p_partial_nsfx", self.p_partial_nsfx)
save_setting("p_partial_nsfy", self.p_partial_nsfy)
save_setting("p_partial_nsfz", self.p_partial_nsfz)
save_setting("p_parallelRender", self.p_parallelRender)
save_setting("p_parallel_nxbatch", self.p_parallel_nxbatch)
save_setting("p_parallel_nybatch", self.p_parallel_nybatch)
save_setting("p_parallel_nzbatch", self.p_parallel_nzbatch)
save_setting("p_sf_matname", self.p_sf_matname)
save_setting("p_sf_alt_matname", self.p_sf_alt_matname)
save_setting("p_bb_matname", self.p_bb_matname)
save_setting("p_make_bounds_visible", self.p_make_bounds_visible)
@staticmethod
def GetGenModes():
return ["UsdSphere", "DirectMesh", "AsyncMesh", "OmniSphere"]
@staticmethod
def GetGenForms():
return ["Classic", "Flat-8"]
@staticmethod
def GetRemoteTypes():
return ["InProcess", "RemoteUrl", "RemoteProcess", "RemoteBatchFile"]
@staticmethod
def GetDefaultRemoteType():
return "RemoteBatchFile"
def Clear(self):
self._createlist = []
self._bbcubelist = []
def Set(self, attname: str, val: float):
if hasattr(self, attname):
self.__dict__[attname] = val
else:
carb.log.error(f"SphereFlakeFactory.Set: no attribute {attname}")
def CalcQuadsAndPrims(self):
nring = 9 if self.p_genform == "Classic" else 8
nlat = self._smf.p_nlat
nlng = self._smf.p_nlng
totquads = 0
totprims = 0
for i in range(self.p_depth+1):
nspheres = nring**(i)
nquads = nspheres * nlat * nlng
totquads += nquads
totprims += nspheres
return totquads, totprims
def CalcTrisAndPrims(self):
totquads, totprims = self.CalcQuadsAndPrims()
return totquads * 2, totprims
def GetCenterPosition(self, ix: int, iy: int, iz: int,
extentvec: Gf.Vec3f, gap: float = 1.1):
nx = self.p_nsfx
# ny = self.p_nsfy
nz = self.p_nsfz
ixoff = (nx-1)/2
iyoff = -0.28 # wierd offset to make it have the same height as single sphereflake
izoff = (nz-1)/2
x = (ix-ixoff) * extentvec[0] * gap * 2
y = (iy-iyoff) * extentvec[1] * gap * 2
# y = extentvec[1]
z = (iz-izoff) * extentvec[2] * gap * 2
return Gf.Vec3f(x, y, z)
@staticmethod
def GetLastGenTime():
global latest_sf_gen_time
return latest_sf_gen_time
def SpawnBBcube(self, primpath, cenpt, extent, bbmatname):
# stage = omni.usd.get_context().get_stage()
stage = self._stage
xformPrim = UsdGeom.Xform.Define(stage, primpath)
UsdGeom.XformCommonAPI(xformPrim).SetTranslate((cenpt[0], cenpt[1], cenpt[2]))
UsdGeom.XformCommonAPI(xformPrim).SetScale((extent[0], extent[1], extent[2]))
cube = UsdGeom.Cube.Define(stage, primpath)
mtl = self._matman.GetMaterial(bbmatname)
UsdShade.MaterialBindingAPI(cube).Bind(mtl)
return cube
def GetSphereFlakeBoundingBox(self) -> Gf.Vec3f:
# sz = rad + (1+(radratio))**depth # old method
sz = self.p_rad
nrad = sz
for i in range(self.p_depth):
nrad = self.p_radratio*nrad
sz += 2*nrad
return Gf.Vec3f(sz, sz, sz)
def GetSphereFlakeBoundingBoxNxNyNz(self, gap: float = 1.1) -> Gf.Vec3f:
# sz = rad + (1+(radratio))**depth # old method
ext = self.GetSphereFlakeBoundingBox()
fx = -1
fy = -1
fz = -1
lx = self.p_nsfx
ly = self.p_nsfy
lz = self.p_nsfz
lcorn = self.GetCenterPosition(fx, fy, fz, ext, gap)
rcorn = self.GetCenterPosition(lx, ly, lz, ext, gap)
rv = rcorn - lcorn
return rv
def RemoteInit(self, remoteurl):
self.tasks = []
if self.remotetype == "RemoteUrl":
self.baseurl = remoteurl
import aiohttp # late import to keep it from dying at startup - probably a Kit 105 bug
self.session = aiohttp.ClientSession()
elif self.remotetype == "RemoteBatchFile":
self.process_cmd_list = []
self.urlname = "omniverse://localhost/Users/mike/SfBase.usda"
self.sessname = "base1"
if self.p_tag is None:
hostname = socket.gethostname()
datestr = time.datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
self.p_tag = f"{hostname}-{datestr}"
rlayer = self._stage.GetRootLayer()
realpath = rlayer.identifier
if realpath is not None:
if realpath.startswith("omniverse://"):
self.urlname = realpath
from .sfsession import fish_out_session_name
self.sessname = fish_out_session_name(self._stage)
print(f"RemoteInit: urlname:{self.urlname} fished-out sessname:{self.sessname}")
else:
carb.log_error(f"RemoteInit Error - stage is not from a nucleus session: {realpath}")
async def RemoteFetch(self, sx, sy, sz, nx, ny, nz, nnx, nny, nnz):
url = f"{self.baseurl}"
url += f"?stagestr={self._stage}"
url += f"&matname={self.p_sf_matname}"
url += f"&sx={sx}&nx={nx}&nnx={nnx}"
url += f"&sy={sy}&ny={ny}&nny={nny}"
url += f"&sz={sz}&nz={nz}&nnz={nnz}"
print(f"GMP sf_ - url:{url}")
async with self.session.get(url) as response:
return await response.text()
def RemoteCreateTask(self, ib, sx, sy, sz, nx, ny, nz, nnx, nny, nnz):
if self.remotetype == "RemoteUrl":
t = asyncio.create_task(self.RemoteFetch(sx, sy, sz, nx, ny, nz, nnx, nny, nnz))
t.add_done_callback(self.tasks.remove)
self.tasks.append(t)
elif self.remotetype == "RemoteBatchFile":
cmd = f"start /b \"{ib}\" run_sfseeder -u {self.urlname} -n {self.sessname} -p "
cmd += f"i={ib},matname={self.p_sf_matname},bbmatname={self.p_bb_matname}"
cmd += f",sx={sx},nx={nx},nnx={nnx}"
cmd += f",sy={sy},ny={ny},nny={nny}"
cmd += f",sz={sz},nz={nz},nnz={nnz}"
cmd += f",form={self.p_genform},mode={self.p_genmode},depth={self.p_depth}"
cmd += f",rad={self.p_rad},radratio={self.p_radratio:.4f}"
cmd += f",tag={self.p_tag},logdir=d:/nv/ov/log/"
self.process_cmd_list.append(cmd)
async def RemoteClose(self):
print(f"GMP: sf_ waiting for tasks to complete ln:{len(self.tasks)}")
rettxts = await asyncio.gather(*self.tasks)
print(f"GMP: sf_ tasks {len(rettxts)} completed")
i = 0
for txt in rettxts:
print(f"GMP: sf_ txt {i}:{txt}")
i += 1
if self.remotetype == "RemoteUrl":
await self.session.close()
elif self.remotetype == "RemoteBatchFile":
cmds = "\n".join(self.process_cmd_list)
path = "d:/nv/ov/app/ovcon/"
filename = f"{path}sphereflake_cmdlist.bat"
with open(filename, "w") as f:
f.write(cmds)
async def GenerateManyParallel(self, doremote: bool = False, remotetype: str = "---",
remoteurl: str = "http://localhost:8211/sphereflake/build-sf-set"):
nxchunk = math.ceil(self.p_nsfx / self.p_parallel_nxbatch)
nychunk = math.ceil(self.p_nsfy / self.p_parallel_nybatch)
nzchunk = math.ceil(self.p_nsfz / self.p_parallel_nzbatch)
nnx = self.p_nsfx
nny = self.p_nsfy
nnz = self.p_nsfz
print(f"GMP: nnx:{nnx} nny:{nny} nnz:{nnz} remote:{doremote} type:{remotetype} url:{remoteurl} (trc))")
# realize all configured materials
self._matman.GetMaterial(self.p_sf_matname)
self._matman.GetMaterial(self.p_sf_alt_matname)
self._matman.GetMaterial(self.p_bb_matname)
original_matname = self.p_sf_matname
original_alt_matname = self.p_sf_alt_matname
omatname = self.p_sf_matname
amatname = self.p_sf_alt_matname
ibatch = 0
sfcount = 0
print(f"GenerateManyParallel: nxchunk:{nxchunk} nychunk:{nychunk} nzchunk:{nzchunk}")
# available_trans_sync = omni.services.client.get_available_transports(is_async=False)
# available_trans_async = omni.services.client.get_available_transports(is_async=True)
# # availprot = omni.services.client.get_available_protocols()
# client = omni.services.client.AsyncClient("http://localhost:8211/sphereflake")
self._createlist = []
self._bbcubelist = []
if doremote:
self.remotetype = remotetype
self.RemoteInit(remoteurl)
for iix in range(self.p_parallel_nxbatch):
for iiy in range(self.p_parallel_nybatch):
for iiz in range(self.p_parallel_nzbatch):
iixyz = iix + iiy + iiz
if iixyz % 2 == 0:
self.p_sf_matname = omatname
else:
self.p_sf_matname = amatname
print(f" GenerateManyParallel: batch:{ibatch} mat:{self.p_sf_matname}")
sx = iix*nxchunk
sy = iiy*nychunk
sz = iiz*nzchunk
nx = nxchunk
ny = nychunk
nz = nzchunk
nnx = self.p_nsfx
nny = self.p_nsfy
nnz = self.p_nsfz
nx = min(nx, nnx-sx)
ny = min(ny, nny-sy)
nz = min(nz, nnz-sz)
if doremote:
self.RemoteCreateTask(ibatch, sx, sy, sz, nx, ny, nz, nnx, nny, nnz)
sfcount += nx*ny*nz
else:
sfcount += self.GenerateManySubcube(sx, sy, sz, nx, ny, nz)
ibatch += 1
if doremote:
await self.RemoteClose()
self.p_sf_matname = original_matname
self.p_sf_alt_matname = original_alt_matname
return sfcount
def GenerateMany(self):
if self.p_partialRender:
sx = self.p_partial_ssfx
sy = self.p_partial_ssfy
sz = self.p_partial_ssfz
nx = self.p_partial_nsfx
ny = self.p_partial_nsfy
nz = self.p_partial_nsfz
else:
sx = 0
sy = 0
sz = 0
nx = self.p_nsfx
ny = self.p_nsfy
nz = self.p_nsfz
self._createlist = []
self._bbcubelist = []
sfcount = self.GenerateManySubcube(sx, sy, sz, nx, ny, nz)
return sfcount
def GenerateManySubcube(self, sx: int, sy: int, sz: int, nx: int, ny: int, nz: int) -> int:
self.GenPrep()
cpt = Gf.Vec3f(0, self.p_rad, 0)
# extentvec = self.GetFlakeExtent(depth, self._rad, self._radratio)
extentvec = self.GetSphereFlakeBoundingBox()
count = self._count
for iix in range(nx):
for iiy in range(ny):
for iiz in range(nz):
ix = iix+sx
iy = iiy+sy
iz = iiz+sz
count += 1
# primpath = f"/World/SphereFlake_{count}"
primpath = f"/World/SphereFlake_{ix}_{iy}_{iz}__{nx}_{ny}_{nz}"
cpt = self.GetCenterPosition(ix, iy, iz, extentvec)
self.Generate(primpath, cpt)
self._createlist.append(primpath)
bnd_cubepath = primpath+"/bounds"
bnd_cube = self.SpawnBBcube(bnd_cubepath, cpt, extentvec, self.p_bb_matname)
self._bbcubelist.append(bnd_cubepath)
if self.p_make_bounds_visible:
UsdGeom.Imageable(bnd_cube).MakeVisible()
else:
UsdGeom.Imageable(bnd_cube).MakeInvisible()
return count
def ToggleBoundsVisiblity(self, soll: bool):
# print(f"ToggleBoundsVisiblity: {self._bbcubelist}")
# okc.execute('ToggleVisibilitySelectedPrims', selected_paths=self._bbcubelist)
for path in self._bbcubelist:
prim = self._stage.GetPrimAtPath(path)
if prim is not None:
if soll:
# UsdGeom.Imageable(prim).MakeVisible()
UsdGeom.Imageable(prim).GetVisibilityAttr().Set('inherited')
else:
UsdGeom.Imageable(prim).MakeInvisible()
def Generate(self, sphflkname: str, cenpt: Gf.Vec3f):
global latest_sf_gen_time
self._start_time = time.time()
self._total_quads = 0
self._nring = 8
# ovut.delete_if_exists(sphflkname)
# stage = omni.usd.get_context().get_stage()
stage = self._stage
xformPrim = UsdGeom.Xform.Define(stage, sphflkname)
UsdGeom.XformCommonAPI(xformPrim).SetTranslate((0, 0, 0))
UsdGeom.XformCommonAPI(xformPrim).SetRotate((0, 0, 0))
mxdepth = self.p_depth
basept = cenpt
matname = self.p_sf_matname
self.GenRecursively(sphflkname, matname, mxdepth, self.p_depth, basept, cenpt, self.p_rad)
elap = time.time() - self._start_time
# print(f"GenerateSF {sphflkname} {matname} {depth} {cenpt} totquads:{self._total_quads} in {elap:.3f} secs")
latest_sf_gen_time = elap
def GenRecursively(self, sphflkname: str, matname: str, mxdepth: int, depth: int, basept: Gf.Vec3f,
cenpt: Gf.Vec3f, rad: float):
# xformPrim = UsdGeom.Xform.Define(self._stage, sphflkname)
# UsdGeom.XformCommonAPI(xformPrim).SetTranslate((0, 0, 0))
# UsdGeom.XformCommonAPI(xformPrim).SetRotate((0, 0, 0))
meshname = sphflkname + "/SphereMesh"
# spheremesh = UsdGeom.Mesh.Define(self._stage, meshname)
if self.p_genmode == "AsyncMesh":
meshname = sphflkname + "/SphereMeshAsync"
asyncio.ensure_future(self._smf.CreateMeshAsync(meshname, matname, cenpt, rad))
elif self.p_genmode == "DirectMesh":
meshname = sphflkname + "/SphereMesh"
self._smf.CreateMesh(meshname, matname, cenpt, rad)
elif self.p_genmode == "OmniSphere":
import omni.kit.commands as okc
meshname = sphflkname + "/OmniSphere"
okc.execute('CreateMeshPrimWithDefaultXform', prim_type="Sphere", prim_path=meshname)
sz = rad/50 # 50 is the default radius of the sphere prim
okc.execute('TransformMultiPrimsSRTCpp',
count=1,
paths=[meshname],
new_scales=[sz, sz, sz],
new_translations=[cenpt[0], cenpt[1], cenpt[2]])
mtl = self._matman.GetMaterial(matname)
# stage = omni.usd.get_context().get_stage()
stage = self._stage
prim: Usd.Prim = stage.GetPrimAtPath(meshname)
UsdShade.MaterialBindingAPI(prim).Bind(mtl)
elif self.p_genmode == "UsdSphere":
meshname = sphflkname + "/UsdSphere"
# stage = omni.usd.get_context().get_stage()
stage = self._stage
xformPrim = UsdGeom.Xform.Define(stage, meshname)
sz = rad
UsdGeom.XformCommonAPI(xformPrim).SetTranslate((cenpt[0], cenpt[1], cenpt[2]))
UsdGeom.XformCommonAPI(xformPrim).SetScale((sz, sz, sz))
spheregeom = UsdGeom.Sphere.Define(stage, meshname)
mtl = self._matman.GetMaterial(matname)
UsdShade.MaterialBindingAPI(spheregeom).Bind(mtl)
print(f"GenRecursively - equipforphysics: {self.p_equipforphysics}")
if self.p_equipforphysics:
spherePrim = stage.GetPrimAtPath(meshname)
rigid_api = UsdPhysics.RigidBodyAPI.Apply(spherePrim)
# rigid_api.SetMassAttr(1.0)
# rigid_api.SetRestitutionAttr(0.5)
rigid_api.CreateRigidBodyEnabledAttr(True)
UsdPhysics.CollisionAPI.Apply(spherePrim)
if depth > 0:
form = self.p_genform
if form == "Classic":
thoff = 0
phioff = -20*math.pi/180
self._nring = 6
self.GenRing(sphflkname, "r1", matname, mxdepth, depth, basept, cenpt, 6, rad, thoff, phioff)
thoff = 30*math.pi/180
phioff = 55*math.pi/180
self._nring = 3
self.GenRing(sphflkname, "r2", matname, mxdepth, depth, basept, cenpt, 3, rad, thoff, phioff)
else:
thoff = 0
phioff = 0
self._nring = 8
self.GenRing(sphflkname, "r1", matname, mxdepth, depth, basept, cenpt, self._nring, rad, thoff, phioff)
def GenRing(self, sphflkname: str, ringname: str, matname: str, mxdepth: int, depth: int,
basept: Gf.Vec3f, cenpt: Gf.Vec3f,
nring: int, rad: float,
thoff: float, phioff: float):
offvek = cenpt - basept
len = offvek.GetLength()
if len > 0:
lxax = cross_product(offvek, self._yax)
if lxax.GetLength() == 0:
lxax = cross_product(offvek, self._zax)
lxax.Normalize()
lzax = cross_product(offvek, lxax)
lzax.Normalize()
lyax = offvek
lyax.Normalize()
else:
lxax = self._xax
lyax = self._yax
lzax = self._zax
nrad = rad * self.p_radratio
offfak = 1 + self.p_radratio
sphi = math.sin(phioff)
cphi = math.cos(phioff)
for i in range(nring):
theta = thoff + (i*2*math.pi/nring)
x = cphi*rad*math.sin(theta)
y = sphi*rad
z = cphi*rad*math.cos(theta)
npt = x*lxax + y*lyax + z*lzax
subname = f"{sphflkname}/{ringname}_sf_{i}"
self.GenRecursively(subname, matname, mxdepth, depth-1, cenpt, cenpt+offfak*npt, nrad)
| 23,071 | Python | 40.571171 | 119 | 0.566339 |
MikeWise2718/sphereflake22/exts/wise.sphereflake22/wise/sphereflake22/sfgen/sfsession.py | # import omni.kit.commands as okc
# import omni.usd
import os
import omni.client
class LiveSessionInfo:
""" Live Session Info class
This class attempts to collect all of the logic around the live session file paths and URLs.
It should be first instantiated with the stage URL (omniverse://server/folder/stage.usd), then
get_session_folder_path_for_stage() can be used to list the available sessions.
Once a session is selected, set_session_name() will finish the initialization of all of the paths
and the other methods can be used.
In the folder that contains the USD to be live-edited, there exists this folder structure:
<.live> / < my_usd_file.live> / <session_name> / root.live
get_session_folder_path_for_stage: <stage_folder> / <.live> / < my_usd_file.live>
get_live_session_folder_path: <stage_folder> / <.live> / < my_usd_file.live> / <session_name>
get_live_session_url: <stage_folder> / <.live> / < my_usd_file.live> / <session_name> / root.live
get_live_session_toml_url: <stage_folder> / <.live> / < my_usd_file.live> / <session_name> / __session__.toml
get_message_channel_url: <stage_folder> / <.live> / < my_usd_file.live> / <session_name> / __session__.channel
"""
def __init__(self, stage_url: str):
self.OMNIVERSE_CHANNEL_FILE_NAME = "__session__.channel"
self.LIVE_SUBFOLDER = "/.live"
self.LIVE_SUBFOLDER_SUFFIX = ".live"
self.DEFAULT_LIVE_FILE_NAME = "root.live"
self.SESSION_TOML_FILE_NAME = "__session__.toml"
self.stage_url = stage_url
self.live_file_url = None
self.channel_url = None
self.toml_url = None
self.session_name = None
self.omni_url = omni.client.break_url(self.stage_url)
# construct the folder that would contain sessions - <.live> / < my_usd_file.live> / <session_name> / root.live
self.omni_session_folder_path = os.path.dirname(self.omni_url.path) + self.LIVE_SUBFOLDER + "/" + self.get_stage_file_name() + self.LIVE_SUBFOLDER_SUFFIX
self.session_folder_string = omni.client.make_url(self.omni_url.scheme, self.omni_url.user, self.omni_url.host, self.omni_url.port, self.omni_session_folder_path)
def get_session_folder_path_for_stage(self):
return self.session_folder_string
def set_session_name(self, session_name):
self.session_name = session_name
def get_live_session_folder_path(self):
return self.omni_session_folder_path + "/" + self.session_name + self.LIVE_SUBFOLDER_SUFFIX
def get_stage_file_name(self):
# find the stage file's root name
usd_file_root = os.path.splitext(os.path.basename(self.omni_url.path))[0]
return usd_file_root
def get_live_session_url(self):
live_session_path = self.get_live_session_folder_path() + "/" + self.DEFAULT_LIVE_FILE_NAME
live_session_url = omni.client.make_url(self.omni_url.scheme, self.omni_url.user, self.omni_url.host, self.omni_url.port, live_session_path)
return live_session_url
def get_live_session_toml_url(self):
live_session_toml_path = self.get_live_session_folder_path() + "/" + self.SESSION_TOML_FILE_NAME
live_session_url = omni.client.make_url(self.omni_url.scheme, self.omni_url.user, self.omni_url.host, self.omni_url.port, live_session_toml_path)
return live_session_url
def get_message_channel_url(self):
live_session_channel_path = self.get_live_session_folder_path() + "/" + self.OMNIVERSE_CHANNEL_FILE_NAME
live_session_url = omni.client.make_url(self.omni_url.scheme, self.omni_url.user, self.omni_url.host, self.omni_url.port, live_session_channel_path)
return live_session_url
def fish_out_session_name(stage):
slayer = stage.GetSessionLayer()
slayersubs = slayer.GetLoadedLayers()
for sl in slayersubs:
if sl.identifier.endswith(".live"):
chunks = sl.identifier.split("/")
session_name = chunks[-2].split(".")[0]
return session_name
return None
| 4,097 | Python | 49.592592 | 170 | 0.662436 |
MikeWise2718/sphereflake22/exts/wise.sphereflake22/wise/sphereflake22/sfgen/sfut.py | # import omni.kit.commands as okc
# import omni.usd
import os
import sys
import math
from pxr import Sdf, UsdShade
from typing import Tuple, List
import carb.settings
_settings = None
def _init_settings():
global _settings
if _settings is None:
_settings = carb.settings.get_settings()
return _settings
def get_setting(name, default, db=False):
settings = _init_settings()
key = f"/persistent/omni/sphereflake/{name}"
val = settings.get(key)
if db:
oval = val
if oval is None:
oval = "None"
if val is None:
val = default
if db:
print(f"get_setting {name} {oval} {val}")
return val
def save_setting(name, value):
settings = _init_settings()
key = f"/persistent/omni/sphereflake/{name}"
settings.set(key, value)
def truncf(number, digits) -> float:
# Improve accuracy with floating point operations, to avoid truncate(16.4, 2) = 16.39 or truncate(-1.13, 2) = -1.12
nbDecimals = len(str(number).split('.')[1])
if nbDecimals <= digits:
return number
stepper = 10.0 ** digits
return math.trunc(stepper * number) / stepper
def delete_if_exists(primpath: str) -> None:
ctx = omni.usd.get_context()
stage = ctx.get_stage()
if stage.GetPrimAtPath(primpath):
stage.RemovePrim(primpath)
# okc.execute("DeletePrimsCommand", paths=[primpath])
def write_out_path(fname: str = 'd:/nv/ov/path.txt') -> None:
# Write out the path to a file
path = os.environ["PATH"]
with open(fname, "w") as f:
npath = path.replace(";", "\n")
f.write(npath)
def write_out_syspath(fname: str = 'd:/nv/ov/syspath.txt', indent=False) -> None:
# Write out the python syspath to a file
# Indent should be True if to be used for the settings.json python.analsys.extraPaths setting
pplist = sys.path
with open(fname, 'w') as f:
for line in pplist:
nline = line.replace("\\", "/")
if indent:
nnline = f" \"{nline}\",\n"
else:
nnline = f"\"{nline}\",\n"
f.write(nnline)
def read_in_syspath(fname: str = 'd:/nv/ov/syspath.txt') -> None:
# Read in the python path from a file
with open(fname, 'r') as f:
for line in f:
nline = line.replace(',', '')
nline = nline.replace('"', '')
nline = nline.replace('"', '')
nline = nline.replace('\n', '')
nline = nline.replace(' ', '')
sys.path.append(nline)
class MatMan():
matlib = {}
_stage = None
def __init__(self, stage) -> None:
self.CreateMaterials()
self._stage = stage
def ResetStage(self, stage):
self._stage = stage
def MakePreviewSurfaceTexMateral(self, matname: str, fname: str):
# This is all materials
matpath = "/World/Looks"
mlname = f'{matpath}/boardMat_{fname.replace(".","_")}'
# stage = omni.usd.get_context().get_stage()
stage = self._stage
material = UsdShade.Material.Define(stage, mlname)
pbrShader = UsdShade.Shader.Define(stage, f'{mlname}/PBRShader')
pbrShader.CreateIdAttr("UsdPreviewSurface")
pbrShader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(0.4)
pbrShader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(0.0)
material.CreateSurfaceOutput().ConnectToSource(pbrShader.ConnectableAPI(), "surface")
stReader = UsdShade.Shader.Define(stage, f'{matpath}/stReader')
stReader.CreateIdAttr('UsdPrimvarReader_float2')
diffuseTextureSampler = UsdShade.Shader.Define(stage, f'{matpath}/diffuseTexture')
diffuseTextureSampler.CreateIdAttr('UsdUVTexture')
ASSETS_DIRECTORY = os.path.dirname(os.path.realpath(__file__))
# print(f"ASSETS_DIRECTORY {ASSETS_DIRECTORY}")
texfile = f"{ASSETS_DIRECTORY}\\{fname}"
# print(texfile)
# print(os.path.exists(texfile))
diffuseTextureSampler.CreateInput('file', Sdf.ValueTypeNames.Asset).Set(texfile)
diffuseTextureSampler.CreateInput("st", Sdf.ValueTypeNames.Float2).ConnectToSource(stReader.ConnectableAPI(),
'result')
diffuseTextureSampler.CreateOutput('rgb', Sdf.ValueTypeNames.Float3)
pbrShader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).ConnectToSource(
diffuseTextureSampler.ConnectableAPI(), 'rgb')
stInput = material.CreateInput('frame:stPrimvarName', Sdf.ValueTypeNames.Token)
stInput.Set('st')
stReader.CreateInput('varname', Sdf.ValueTypeNames.Token).ConnectToSource(stInput)
self.matlib[matname]["mat"] = material
return material
def SplitRgb(self, rgb: str) -> Tuple[float, float, float]:
sar = rgb.split(",")
r = float(sar[0])
g = float(sar[1])
b = float(sar[2])
return (r, g, b)
def MakePreviewSurfaceMaterial(self, matname: str, rgb: str):
mtl_path = Sdf.Path(f"/World/Looks/Presurf_{matname}")
# stage = omni.usd.get_context().get_stage()
stage = self._stage
mtl = UsdShade.Material.Define(stage, mtl_path)
shader = UsdShade.Shader.Define(stage, mtl_path.AppendPath("Shader"))
shader.CreateIdAttr("UsdPreviewSurface")
rgbtup = self.SplitRgb(rgb)
shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set(rgbtup)
shader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(0.5)
shader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(0.0)
mtl.CreateSurfaceOutput().ConnectToSource(shader.ConnectableAPI(), "surface")
# self.matlib[matname] = {"name": matname, "typ": "mtl", "mat": mtl}
self.matlib[matname]["mat"] = mtl
return mtl
refCount: int = 0
fetchCount: int = 0
skipCount: int = 0
def CopyRemoteMaterial(self, matname, urlbranch, force=False):
print(f"CopyRemoteMaterial matname:{matname} urlbranch:{urlbranch} force:{force}")
# stage = omni.usd.get_context().get_stage()
stage = self._stage
baseurl = 'https://omniverse-content-production.s3.us-west-2.amazonaws.com'
url = f'{baseurl}/Materials/{urlbranch}.mdl'
mpath = f'/World/Looks/{matname}'
action = ""
# Note we should not execute the next command if the material already exists
if force or not stage.GetPrimAtPath(mpath):
import omni.kit.commands as okc
okc.execute('CreateMdlMaterialPrimCommand', mtl_url=url, mtl_name=matname, mtl_path=mpath)
action = "fetch"
self.fetchCount += 1
else:
action = "skip"
self.skipCount += 1
mtl: UsdShade.Material = UsdShade.Material(stage.GetPrimAtPath(mpath))
print(f"CopyRemoteMaterial {mpath} mtl:{mtl} action:{action}")
# self.matlib[matname] = {"name": matname, "typ": "rgb", "mat": mtl}
self.matlib[matname]["mat"] = mtl
return mtl
def RealizeMaterial(self, matname: str):
try:
typ = self.matlib[matname]["typ"]
spec = self.matlib[matname]["spec"]
if typ == "mtl":
self.CopyRemoteMaterial(matname, spec)
elif typ == "tex":
self.MakePreviewSurfaceTexMateral(matname, spec)
else:
self.MakePreviewSurfaceMaterial(matname, spec)
self.matlib[matname]["realized"] = True
except Exception as e:
carb.log_error(f"Exception in RealizeMaterial {matname} : {e}")
def SetupMaterial(self, matname: str, typ: str, spec: str):
# print(f"SetupMaterial {matname} {typ} {spec}")
matpath = f"/World/Looks/{matname}"
self.matlib[matname] = {"name": matname,
"typ": typ,
"mat": None,
"path": matpath,
"realized": False,
"spec": spec}
def CreateMaterials(self):
self.SetupMaterial("red", "rgb", "1,0,0")
self.SetupMaterial("green", "rgb", "0,1,0")
self.SetupMaterial("blue", "rgb", "0,0,1")
self.SetupMaterial("yellow", "rgb", "1,1,0")
self.SetupMaterial("cyan", "rgb", "0,1,1")
self.SetupMaterial("magenta", "rgb", "1,0,1")
self.SetupMaterial("white", "rgb", "1,1,1")
self.SetupMaterial("black", "rgb", "0,0,0")
self.SetupMaterial("Blue_Glass", "mtl", "Base/Glass/Blue_Glass")
self.SetupMaterial("Red_Glass", "mtl", "Base/Glass/Red_Glass")
self.SetupMaterial("Green_Glass", "mtl", "Base/Glass/Green_Glass")
self.SetupMaterial("Clear_Glass", "mtl", "Base/Glass/Clear_Glass")
self.SetupMaterial("Bronze", "mtl", "Base/Metals/Bronze")
self.SetupMaterial("Brass", "mtl", "Base/Metals/Brass")
self.SetupMaterial("Gold", "mtl", "Base/Metals/Gold")
self.SetupMaterial("Silver", "mtl", "Base/Metals/Silver")
self.SetupMaterial("Iron", "mtl", "Base/Metals/Iron")
self.SetupMaterial("Steel_Stainless", "mtl", "Base/Metals/Steel_Stainless")
self.SetupMaterial("Orange_Glass", "mtl", "vMaterials_2/Glass/Glass_Colored")
self.SetupMaterial("Mirror", "mtl", "Base/Glass/Mirror")
self.SetupMaterial("sunset_texture", "tex", "sunset.png")
self.SetupMaterial("Andromeda", "mtl", "vMaterials_2/Paint/Carpaint/Carpaint_Shifting_Flakes")
def GetMaterialCount(self):
return len(self.matlib)
def Reinitialize(self):
for key in self.matlib:
self.matlib[key]["realized"] = False
def GetMaterialNames(self) -> List[str]:
return list(self.matlib.keys())
def GetMaterial(self, key):
self.refCount += 1
if key in self.matlib:
if not self.matlib[key]["realized"]:
self.RealizeMaterial(key)
rv = self.matlib[key]["mat"]
else:
rv = None
return rv
| 10,150 | Python | 37.89272 | 119 | 0.599113 |
MikeWise2718/sphereflake22/exts/wise.sphereflake22/wise/sphereflake22/sfgen/spheremesh.py | import math
import numpy as np
from pxr import Gf, Sdf, Usd, UsdGeom, UsdShade, Vt
from .sfut import MatMan
class SphereMeshFactory():
_show_normals = False
_matman: MatMan = None
p_nlat = 8
p_nlng = 8
_total_quads = 0
_dotexcoords = True
def __init__(self, stage: Usd.Stage, matman: MatMan) -> None:
self._matman = matman
self._stage = stage
# self._stageid = stageid
# if stageid>0:
# self._stage = omni.usd.get_context().
# else:
# self._stage = omni.usd.get_context().get_stage()
def ResetStage(self, stage: Usd.Stage):
self._stage = stage
self._matman.ResetStage(stage)
def GenPrep(self):
self._nquads = self.p_nlat*self.p_nlng
self._nverts = (self.p_nlat+1)*(self.p_nlng)
self._normbuf = np.zeros((self._nverts, 3), dtype=np.float32)
self._txtrbuf = np.zeros((self._nverts, 2), dtype=np.float32)
self._facebuf = np.zeros((self._nquads, 1), dtype=np.int32)
self._vidxbuf = np.zeros((self._nquads, 4), dtype=np.int32)
self.MakeArrays()
def Clear(self):
pass
def MakeMarker(self, name: str, matname: str, cenpt: Gf.Vec3f, rad: float):
primpath = f"/World/markers/{name}"
# stage = omni.usd.get_context().get_stage()
stage = self._stage
xformPrim = UsdGeom.Xform.Define(stage, primpath)
sz = rad
UsdGeom.XformCommonAPI(xformPrim).SetTranslate((cenpt[0], cenpt[1], cenpt[2]))
UsdGeom.XformCommonAPI(xformPrim).SetScale((sz, sz, sz))
spheremesh = UsdGeom.Sphere.Define(stage, primpath)
mtl = self._matman.GetMaterial(matname)
UsdShade.MaterialBindingAPI(spheremesh).Bind(mtl)
def MakeArrays(self):
nlat = self.p_nlat
nlong = self.p_nlng
for i in range(nlat):
offset = i * nlong
for j in range(nlong):
if j < nlong - 1:
i1 = offset+j
i2 = offset+j+1
i3 = offset+j+nlong+1
i4 = offset+j+nlong
else:
i1 = offset+j
i2 = offset
i3 = offset+nlong
i4 = offset+j+nlong
vidx = i*nlong+j
self._facebuf[vidx] = 4
self._vidxbuf[vidx] = [i1, i2, i3, i4]
polegap = 0.01 # prevents the vertices from being exactly on the poles
for i in range(nlat+1):
theta = polegap + (i * (math.pi-2*polegap) / float(nlat))
st = math.sin(theta)
ct = math.cos(theta)
for j in range(nlong):
phi = j * 2 * math.pi / float(nlong)
sp = math.sin(phi)
cp = math.cos(phi)
nx = st*cp
ny = ct
nz = st*sp
nrmvek = Gf.Vec3f(nx, ny, nz)
vidx = i*nlong+j
self._normbuf[vidx] = nrmvek
self._txtrbuf[vidx] = (nx, ny)
# print("MakeArrays done")
def ShowNormals(self, vertbuf):
nlat = self.p_nlat
nlong = self.p_nlng
for i in range(nlat+1):
for j in range(nlong):
vidx = i*nlong+j
ptname = f"ppt_{i}_{j}"
(x, y, z) = vertbuf[vidx]
(nx, ny, nz) = self._nromtbuf[vidx]
pt = Gf.Vec3f(x, y, z)
npt = Gf.Vec3f(x+nx, y+ny, z+nz)
nmname = f"npt_{i}_{j}"
self.MakeMarker(ptname, "red", pt, 1)
self.MakeMarker(nmname, "blue", npt, 1)
def CreateMesh(self, name: str, matname: str, cenpt: Gf.Vec3f, radius: float):
# This will create nlat*nlog quads or twice that many triangles
# it will need nlat+1 vertices in the latitude direction and nlong vertices in the longitude direction
# so a total of (nlat+1)*(nlong) vertices
# stage = omni.usd.get_context().get_stage()
stage = self._stage
spheremesh = UsdGeom.Mesh.Define(stage, name)
# note that vertbuf is local to this function allowing it to be changed in a multithreaded environment
vertbuf = self._normbuf*radius + cenpt
if self._show_normals:
self.ShowNormals(vertbuf)
if self._dotexcoords:
texCoords = UsdGeom.PrimvarsAPI(spheremesh).CreatePrimvar("st",
Sdf.ValueTypeNames.TexCoord2fArray,
UsdGeom.Tokens.varying)
texCoords.Set(Vt.Vec2fArray.FromNumpy(self._txtrbuf))
spheremesh.CreatePointsAttr(Vt.Vec3dArray.FromNumpy(vertbuf))
spheremesh.CreateNormalsAttr(Vt.Vec3dArray.FromNumpy(self._normbuf))
spheremesh.CreateFaceVertexCountsAttr(Vt.IntArrayFromBuffer(self._facebuf))
spheremesh.CreateFaceVertexIndicesAttr(Vt.IntArrayFromBuffer(self._vidxbuf))
mtl = self._matman.GetMaterial(matname)
UsdShade.MaterialBindingAPI(spheremesh).Bind(mtl)
self._total_quads += self._nquads # face vertex counts
return None
async def CreateVertBuf(self, radius, cenpt):
vertbuf = self._normbuf*radius + cenpt
return vertbuf
async def CreateStuff(self, spheremesh, vertbuf, normbuf, facebuf, vidxbuf):
spheremesh.CreatePointsAttr(Vt.Vec3dArray.FromNumpy(vertbuf))
spheremesh.CreateNormalsAttr(Vt.Vec3dArray.FromNumpy(normbuf))
spheremesh.CreateFaceVertexCountsAttr(Vt.IntArrayFromBuffer(facebuf))
spheremesh.CreateFaceVertexIndicesAttr(Vt.IntArrayFromBuffer(vidxbuf))
return
async def CreateMeshAsync(self, name: str, matname: str, cenpt: Gf.Vec3f, radius: float):
# This will create nlat*nlog quads or twice that many triangles
# it will need nlat+1 vertices in the latitude direction and nlong vertices in the longitude direction
# so a total of (nlat+1)*(nlong) vertices
# stage = omni.usd.get_context().get_stage()
stage = self._stage
spheremesh = UsdGeom.Mesh.Define(stage, name)
# note that vertbuf is local to this function allowing it to be changed in a multithreaded environment
vertbuf = await self.CreateVertBuf(radius, cenpt)
if self._show_normals:
self.ShowNormals(vertbuf)
if self._dotexcoords:
texCoords = UsdGeom.PrimvarsAPI(spheremesh).CreatePrimvar("st",
Sdf.ValueTypeNames.TexCoord2fArray,
UsdGeom.Tokens.varying)
texCoords.Set(Vt.Vec2fArray.FromNumpy(self._txtrbuf))
await self.CreateStuff(spheremesh, vertbuf, self._normbuf, self._facebuf, self._vidxbuf)
mtl = self._matman.GetMaterial(matname)
UsdShade.MaterialBindingAPI(spheremesh).Bind(mtl)
self._total_quads += self._nquads # face vertex counts
return None
| 7,116 | Python | 38.538889 | 110 | 0.568859 |
MikeWise2718/sphereflake22/exts/wise.sphereflake22/wise/sphereflake22/tests/__init__.py | from .test_hello_world import * | 31 | Python | 30.999969 | 31 | 0.774194 |
MikeWise2718/sphereflake22/exts/wise.sphereflake22/wise/sphereflake22/tests/test_hello_world.py | # NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
import omni.kit.test
# Extnsion for writing UI tests (simulate UI interaction)
import omni.kit.ui_test as ui_test
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
import wise.sphereflake22
# Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test
class Test(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
pass
# After running each test
async def tearDown(self):
pass
# Actual test, notice it is "async" function, so "await" can be used if needed
async def test_hello_public_function(self):
result = wise.sphereflake22.some_public_function(4)
self.assertEqual(result, 256)
async def test_window_button(self):
# Find a label in our window
label = ui_test.find("My Window//Frame/**/Label[*]")
# Find buttons in our window
add_button = ui_test.find("My Window//Frame/**/Button[*].text=='Add'")
reset_button = ui_test.find("My Window//Frame/**/Button[*].text=='Reset'")
# Click reset button
await reset_button.click()
self.assertEqual(label.widget.text, "empty")
await add_button.click()
self.assertEqual(label.widget.text, "count: 1")
await add_button.click()
self.assertEqual(label.widget.text, "count: 2")
| 1,672 | Python | 34.595744 | 142 | 0.683014 |
MikeWise2718/sphereflake22/exts/wise.sphereflake22/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.0.0"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["mike-wise"]
# The title and description fields are primarily for displaying extension info in UI
title = "Wise Sphereflake22"
description="Spawn SphereFlakes in the scene using different techniques for benchmarking purposes"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Example"
# Keywords for the extension
keywords = ["kit", "sphereflake", "benchmark"]
# Location of change log file in target (final) folder of extension, relative to the root.
# More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# Use omni.ui to build simple UI
[dependencies]
"omni.kit.uiapp" = {}
# Main python module this extension provides, it will be publicly available as "import wise.sphereflake22".
[[python.module]]
name = "wise.sphereflake22"
[[test]]
# Extra dependencies only to be used during test run
dependencies = [
"omni.kit.ui_test" # UI testing extension
]
[python.pipapi]
requirements = ["nvidia-smi","nvidia-ml-py3"]
use_online_index = true | 1,691 | TOML | 31.538461 | 118 | 0.747487 |
MikeWise2718/sphereflake22/exts/wise.sphereflake22/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.0] - 2021-04-26
- Initial version of extension UI template with a window
| 178 | Markdown | 18.888887 | 80 | 0.702247 |
MikeWise2718/sphereflake22/exts/wise.sphereflake22/docs/README.md | # Python Extension Example [wise.sphereflake22]
This is an example of pure python Kit extension. It is intended to be copied and serve as a template to create new extensions.
| 177 | Markdown | 34.599993 | 126 | 0.79096 |
MikeWise2718/sphereflake22/exts/wise.sphereflake22/docs/index.rst | wise.sphereflake22
#############################
Example of Python only extension
.. toctree::
:maxdepth: 1
README
CHANGELOG
.. automodule::"wise.sphereflake22"
:platform: Windows-x86_64, Linux-x86_64
:members:
:undoc-members:
:show-inheritance:
:imported-members:
:exclude-members: contextmanager
| 337 | reStructuredText | 15.095237 | 43 | 0.623145 |
MikeWise2718/sfapp/VERSION.md | 104.0
| 6 | Markdown | 2.499999 | 5 | 0.666667 |
MikeWise2718/sfapp/repo.toml | ########################################################################################################################
# Repo tool base settings
########################################################################################################################
[repo]
# Use the Kit Template repo configuration as a base. Only override things specific to the repo.
import_configs = [
"${root}/_repo/deps/repo_kit_tools/kit-template/repo.toml",
"${root}/_repo/deps/repo_kit_tools/kit-template/repo-app.toml"
]
# Repository Name
name = "sfapp"
[repo_kit_link_app]
app_name = "code" # App name.
app_version = "" # App version. Empty means latest. Specify to lock version, e.g. "2022.2.0-rc.3"
########################################################################################################################
# Documentation building
########################################################################################################################
[repo_docs]
#name = "SfApp"
# kit-manual doc
[[repo_docs.kit.custom_project]]
name = "sfapp"
root = "${root}"
config_path = "${root}/docs/docs.toml"
[repo_docs.kit]
extensions = [
]
| 1,169 | TOML | 28.999999 | 120 | 0.39521 |
MikeWise2718/sfapp/README.md | # Omniverse Kit App Template
[Omniverse Kit App Template](https://github.com/NVIDIA-Omniverse/kit-app-template) - is the place to start learning about developing Omniverse Apps.
This project contains everything necessary to develop and package an Omniverse App.
## Links
* [Repository](https://github.com/NVIDIA-Omniverse/kit-app-template)
* [Full Documentation](https://docs.omniverse.nvidia.com/kit/docs/kit-app-template)
## What Is an App?
Ultimately, an Omniverse Kit app is a `.kit` file. It is a single file extension. You can think of it as the tip of a dependencies pyramid, a final extension that pulls in everything.
Extensive documentation detailing what extensions are and how they work can be found [here](https://docs.omniverse.nvidia.com/py/kit/docs/guide/extensions.html).
## Getting Started
### Install Omniverse and some Apps
1. Install *Omniverse Launcher*: [download](https://www.nvidia.com/en-us/omniverse/download)
2. Install and launch one of *Omniverse* apps in the Launcher. This repo requires the latest *Create* installed.
### Build
1. Clone [this repo](https://github.com/NVIDIA-Omniverse/kit-app-template) to your local machine.
2. Open a command prompt and navigate to the root of your cloned repo.
3. Run `build.bat` to bootstrap your dev environment and build an example app.
4. Run `_build\windows-x86_64\release\my_name.my_app.bat` (or other apps) to open an example kit application.
You should have now launched your simple kit-based application!
### Package
To package, run `package.bat`. The package will be created in the `_build/packages` folder.
To use the package, unzip and run `link_app.bat` inside the package once before running.
Packaging just zips everything in the `_build/[platform]/release` folder, using it as a root. Linked app (`baseapp`) and kit (`kit`) folders are skipped.
### Changing a Base App
When building 2 folder links are created:
* `_build/[platform]/release/baseapp` link to Omniverse App (e.g. Create)
* `_build/[platform]/release/kit` links to kit inside of the app above (same as `_build/[platform]/release/baseapp/kit`)
In `repo.toml`, the baseapp name and version are specified and can be changed:
```toml
[repo_kit_link_app]
app_name = "create" # App name.
app_version = "" # App version. Empty means latest. Specify to lock version, e.g. "2022.2.0-rc.3"
```
After editing `repo.toml`, run `build.bat` again to create new app links.
## Keep Learning: Launching Apps
If you look inside the `bat`/`sh` app script runner file it just launches kit and passes a kit file (`my_name.my_app.kit`).
Application kit files define app configuration. *Omniverse Kit* is the core application runtime for Omniverse Applications. Think of it as `python.exe`. It is a small runtime, that enables all the basics like settings, python, logging and searches for extensions. **Everything else is an extension.** You can run only this new extension without running any big *App* like *Create*:
There are 2 other app examples: `my_name.my_app.viewport.kit` and `my_name.my_app.editor.kit`. Try running them.
## Contributing
The source code for this repository is provided as-is and we are not accepting outside contributions.
| 3,213 | Markdown | 47.696969 | 381 | 0.752879 |
MikeWise2718/sfapp/deps/repo-deps.packman.xml | <project toolsVersion="5.0">
<dependency name="repo_man" linkPath="../_repo/deps/repo_man">
<package name="repo_man" version="1.10.1"/>
</dependency>
<dependency name="repo_build" linkPath="../_repo/deps/repo_build">
<package name="repo_build" version="0.27.1"/>
</dependency>
<dependency name="repo_changelog" linkPath="../_repo/deps/repo_changelog">
<package name="repo_changelog" version="0.2.20"/>
</dependency>
<dependency name="repo_docs" linkPath="../_repo/deps/repo_docs">
<package name="repo_docs" version="0.9.17"/>
</dependency>
<dependency name="repo_kit_tools" linkPath="../_repo/deps/repo_kit_tools">
<package name="repo_kit_tools" version="0.8.13"/>
</dependency>
<dependency name="repo_source" linkPath="../_repo/deps/repo_source">
<package name="repo_source" version="0.3.0" />
</dependency>
<dependency name="repo_package" linkPath="../_repo/deps/repo_package">
<package name="repo_package" version="5.6.8" />
</dependency>
<dependency name="repo_docs" linkPath="../_repo/deps/repo_docs">
<package name="repo_docs" version="0.10.1" />
</dependency>
</project>
| 1,143 | XML | 41.370369 | 76 | 0.661417 |
MikeWise2718/sfapp/deps/host-deps.packman.xml | <project toolsVersion="5.0">
<dependency name="premake" linkPath="../_build/host-deps/premake">
<package name="premake" version="5.0.0-alpha15.dev+pipeline3388156.1f299ea4-${platform}"/>
</dependency>
<dependency name="msvc" linkPath="../_build/host-deps/msvc">
<package name="msvc" version="2019-16.7.6-license" platforms="windows-x86_64"/>
</dependency>
<dependency name="winsdk" linkPath="../_build/host-deps/winsdk">
<package name="winsdk" version="10.0.18362.0-license" platforms="windows-x86_64"/>
</dependency>
</project>
| 555 | XML | 38.714283 | 94 | 0.693694 |
MikeWise2718/sfapp/deps/kit-sdk-deps.packman.xml | <project toolsVersion="5.0">
<!-- Only edit this file to pull kit depedencies. -->
<!-- Put all extension-specific dependencies in `ext-deps.packman.xml`. -->
<!-- This file contains shared Kit SDK dependencies used by most kit extensions. -->
<!-- Import Kit SDK all-deps xml file to steal some deps from it: -->
<import path="../_build/${platform}/${config}/kit/dev/all-deps.packman.xml">
<filter include="pybind11" />
<filter include="fmt" />
<filter include="python" />
<filter include="carb_sdk_plugins" />
</import>
<!-- Pull those deps of the same version as in Kit SDK. Override linkPath to point correctly, other properties can also be override, including version. -->
<dependency name="carb_sdk_plugins" linkPath="../_build/target-deps/carb_sdk_plugins" tags="non-redist" />
<dependency name="pybind11" linkPath="../_build/target-deps/pybind11" />
<dependency name="fmt" linkPath="../_build/target-deps/fmt" />
<dependency name="python" linkPath="../_build/target-deps/python" />
</project>
| 1,041 | XML | 51.099997 | 157 | 0.682997 |
MikeWise2718/sfapp/deps/ext-deps.packman.xml | <project toolsVersion="5.0">
<!-- Use this file to include any dependencies for your extension beyond those in `kit-sdk-deps.packman.xml`. -->
</project>
| 157 | XML | 30.599994 | 115 | 0.713376 |
MikeWise2718/sfapp/tools/repoman/repoman.py | import os
import sys
import io
import contextlib
import packmanapi
REPO_ROOT = os.path.join(os.path.dirname(os.path.realpath(__file__)), "../..")
REPO_DEPS_FILE = os.path.join(REPO_ROOT, "deps/repo-deps.packman.xml")
def bootstrap():
"""
Bootstrap all omni.repo modules.
Pull with packman from repo.packman.xml and add them all to python sys.path to enable importing.
"""
#with contextlib.redirect_stdout(io.StringIO()):
deps = packmanapi.pull(REPO_DEPS_FILE)
for dep_path in deps.values():
if dep_path not in sys.path:
sys.path.append(dep_path)
if __name__ == "__main__":
bootstrap()
import omni.repo.man
omni.repo.man.main(REPO_ROOT)
| 703 | Python | 23.275861 | 100 | 0.661451 |
MikeWise2718/sfapp/tools/packman/packmanconf.py | # Use this file to bootstrap packman into your Python environment (3.7.x). Simply
# add the path by doing sys.insert to where packmanconf.py is located and then execute:
#
# >>> import packmanconf
# >>> packmanconf.init()
#
# It will use the configured remote(s) and the version of packman in the same folder,
# giving you full access to the packman API via the following module
#
# >> import packmanapi
# >> dir(packmanapi)
import os
import platform
import sys
def init():
"""Call this function to initialize the packman configuration.
Calls to the packman API will work after successfully calling this function.
Note:
This function only needs to be called once during the execution of your
program. Calling it repeatedly is harmless but wasteful.
Compatibility with your Python interpreter is checked and upon failure
the function will report what is required.
Example:
>>> import packmanconf
>>> packmanconf.init()
>>> import packmanapi
>>> packmanapi.set_verbosity_level(packmanapi.VERBOSITY_HIGH)
"""
major = sys.version_info[0]
minor = sys.version_info[1]
if major != 3 or minor != 7:
raise RuntimeError(
f"This version of packman requires Python 3.7.x, but {major}.{minor} was provided"
)
conf_dir = os.path.dirname(os.path.abspath(__file__))
os.environ["PM_INSTALL_PATH"] = conf_dir
packages_root = get_packages_root(conf_dir)
version = get_version(conf_dir)
module_dir = get_module_dir(conf_dir, packages_root, version)
sys.path.insert(1, module_dir)
def get_packages_root(conf_dir: str) -> str:
root = os.getenv("PM_PACKAGES_ROOT")
if not root:
platform_name = platform.system()
if platform_name == "Windows":
drive, _ = os.path.splitdrive(conf_dir)
root = os.path.join(drive, "packman-repo")
elif platform_name == "Darwin":
# macOS
root = os.path.join(
os.path.expanduser("~"), "/Library/Application Support/packman-cache"
)
elif platform_name == "Linux":
try:
cache_root = os.environ["XDG_HOME_CACHE"]
except KeyError:
cache_root = os.path.join(os.path.expanduser("~"), ".cache")
return os.path.join(cache_root, "packman")
else:
raise RuntimeError(f"Unsupported platform '{platform_name}'")
# make sure the path exists:
os.makedirs(root, exist_ok=True)
return root
def get_module_dir(conf_dir, packages_root: str, version: str) -> str:
module_dir = os.path.join(packages_root, "packman-common", version)
if not os.path.exists(module_dir):
import tempfile
tf = tempfile.NamedTemporaryFile(delete=False)
target_name = tf.name
tf.close()
url = f"http://bootstrap.packman.nvidia.com/packman-common@{version}.zip"
print(f"Downloading '{url}' ...")
import urllib.request
urllib.request.urlretrieve(url, target_name)
from importlib.machinery import SourceFileLoader
# import module from path provided
script_path = os.path.join(conf_dir, "bootstrap", "install_package.py")
ip = SourceFileLoader("install_package", script_path).load_module()
print("Unpacking ...")
ip.install_package(target_name, module_dir)
os.unlink(tf.name)
return module_dir
def get_version(conf_dir: str):
path = os.path.join(conf_dir, "packman")
if not os.path.exists(path): # in dev repo fallback
path += ".sh"
with open(path, "rt", encoding="utf8") as launch_file:
for line in launch_file.readlines():
if line.startswith("PM_PACKMAN_VERSION"):
_, value = line.split("=")
return value.strip()
raise RuntimeError(f"Unable to find 'PM_PACKMAN_VERSION' in '{path}'")
| 3,930 | Python | 35.398148 | 94 | 0.632316 |
MikeWise2718/sfapp/tools/packman/config.packman.xml | <config remotes="cloudfront">
<remote2 name="cloudfront">
<transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" />
</remote2>
</config>
| 211 | XML | 34.333328 | 123 | 0.691943 |
MikeWise2718/sfapp/tools/packman/bootstrap/install_package.py | # Copyright 2019 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 logging
import zipfile
import tempfile
import sys
import os
import stat
import time
from typing import Any, Callable
RENAME_RETRY_COUNT = 100
RENAME_RETRY_DELAY = 0.1
logging.basicConfig(level=logging.WARNING, format="%(message)s")
logger = logging.getLogger("install_package")
def remove_directory_item(path):
if os.path.islink(path) or os.path.isfile(path):
try:
os.remove(path)
except PermissionError:
# make sure we have access and try again:
os.chmod(path, stat.S_IRWXU)
os.remove(path)
else:
# try first to delete the dir because this will work for folder junctions, otherwise we would follow the junctions and cause destruction!
clean_out_folder = False
try:
# make sure we have access preemptively - this is necessary because recursing into a directory without permissions
# will only lead to heart ache
os.chmod(path, stat.S_IRWXU)
os.rmdir(path)
except OSError:
clean_out_folder = True
if clean_out_folder:
# we should make sure the directory is empty
names = os.listdir(path)
for name in names:
fullname = os.path.join(path, name)
remove_directory_item(fullname)
# now try to again get rid of the folder - and not catch if it raises:
os.rmdir(path)
class StagingDirectory:
def __init__(self, staging_path):
self.staging_path = staging_path
self.temp_folder_path = None
os.makedirs(staging_path, exist_ok=True)
def __enter__(self):
self.temp_folder_path = tempfile.mkdtemp(prefix="ver-", dir=self.staging_path)
return self
def get_temp_folder_path(self):
return self.temp_folder_path
# this function renames the temp staging folder to folder_name, it is required that the parent path exists!
def promote_and_rename(self, folder_name):
abs_dst_folder_name = os.path.join(self.staging_path, folder_name)
os.rename(self.temp_folder_path, abs_dst_folder_name)
def __exit__(self, type, value, traceback):
# Remove temp staging folder if it's still there (something went wrong):
path = self.temp_folder_path
if os.path.isdir(path):
remove_directory_item(path)
def rename_folder(staging_dir: StagingDirectory, folder_name: str):
try:
staging_dir.promote_and_rename(folder_name)
except OSError as exc:
# if we failed to rename because the folder now exists we can assume that another packman process
# has managed to update the package before us - in all other cases we re-raise the exception
abs_dst_folder_name = os.path.join(staging_dir.staging_path, folder_name)
if os.path.exists(abs_dst_folder_name):
logger.warning(
f"Directory {abs_dst_folder_name} already present, package installation already completed"
)
else:
raise
def call_with_retry(
op_name: str, func: Callable, retry_count: int = 3, retry_delay: float = 20
) -> Any:
retries_left = retry_count
while True:
try:
return func()
except (OSError, IOError) as exc:
logger.warning(f"Failure while executing {op_name} [{str(exc)}]")
if retries_left:
retry_str = "retry" if retries_left == 1 else "retries"
logger.warning(
f"Retrying after {retry_delay} seconds"
f" ({retries_left} {retry_str} left) ..."
)
time.sleep(retry_delay)
else:
logger.error("Maximum retries exceeded, giving up")
raise
retries_left -= 1
def rename_folder_with_retry(staging_dir: StagingDirectory, folder_name):
dst_path = os.path.join(staging_dir.staging_path, folder_name)
call_with_retry(
f"rename {staging_dir.get_temp_folder_path()} -> {dst_path}",
lambda: rename_folder(staging_dir, folder_name),
RENAME_RETRY_COUNT,
RENAME_RETRY_DELAY,
)
def install_package(package_path, install_path):
staging_path, version = os.path.split(install_path)
with StagingDirectory(staging_path) as staging_dir:
output_folder = staging_dir.get_temp_folder_path()
with zipfile.ZipFile(package_path, allowZip64=True) as zip_file:
zip_file.extractall(output_folder)
# attempt the rename operation
rename_folder_with_retry(staging_dir, version)
print(f"Package successfully installed to {install_path}")
if __name__ == "__main__":
executable_paths = os.getenv("PATH")
paths_list = executable_paths.split(os.path.pathsep) if executable_paths else []
target_path_np = os.path.normpath(sys.argv[2])
target_path_np_nc = os.path.normcase(target_path_np)
for exec_path in paths_list:
if os.path.normcase(os.path.normpath(exec_path)) == target_path_np_nc:
raise RuntimeError(f"packman will not install to executable path '{exec_path}'")
install_package(sys.argv[1], target_path_np)
| 5,776 | Python | 36.270968 | 145 | 0.645083 |
MikeWise2718/sfapp/source/extensions/my_name.my_app.setup/my_name/my_app/setup/__init__.py | from .setup import *
| 21 | Python | 9.999995 | 20 | 0.714286 |
MikeWise2718/sfapp/source/extensions/my_name.my_app.setup/my_name/my_app/setup/setup.py | import asyncio
from pathlib import Path
import carb.imgui as _imgui
import carb.settings
import carb.tokens
import omni.ext
import omni.kit.menu.utils
from omni.kit.menu.utils import MenuLayout
from omni.kit.quicklayout import QuickLayout
from omni.kit.window.title import get_main_window_title
async def _load_layout(layout_file: str):
"""this private methods just help loading layout, you can use it in the Layout Menu"""
await omni.kit.app.get_app().next_update_async()
QuickLayout.load_file(layout_file)
# This extension is mostly loading the Layout updating menu
class SetupExtension(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):
# get the settings
self._settings = carb.settings.get_settings()
self._await_layout = asyncio.ensure_future(self._delayed_layout())
# setup the menu and their layout
self._setup_menu()
# setup the Application Title
window_title = get_main_window_title()
window_title.set_app_version(self._settings.get("/app/titleVersion"))
async def _delayed_layout(self):
# few frame delay to allow automatic Layout of window that want their own positions
for i in range(4):
await omni.kit.app.get_app().next_update_async()
settings = carb.settings.get_settings()
# setup the Layout for your app
layouts_path = carb.tokens.get_tokens_interface().resolve("${my_name.my_app.setup}/layouts")
layout_file = Path(layouts_path).joinpath(f"{settings.get('/app/layout/name')}.json")
asyncio.ensure_future(_load_layout(f"{layout_file}"))
# using imgui directly to adjust some color and Variable
imgui = _imgui.acquire_imgui()
# DockSplitterSize is the variable that drive the size of the Dock Split connection
imgui.push_style_var_float(_imgui.StyleVar.DockSplitterSize, 2)
def _setup_menu(self):
editor_menu = omni.kit.ui.get_editor_menu()
# you can have some file Menu
self._file_open = editor_menu.add_item("File/Open", self._open_file)
# some Menu Item
self._help_menu = editor_menu.add_item("Help/Show", self._show_help)
# from omni.kit.menu.utils import MenuLayout
# self._menu_layout = [
# MenuLayout.Menu("Window", [
# MenuLayout.Item("MyWindow"),
# ]),
# ]
# omni.kit.menu.utils.add_layout(self._menu_layout)
def _show_help(self, menu, toggled):
print("Help is Coming")
def _open_file(self, menu, toggled):
print("Open the File you want")
def on_shutdown(self):
pass
| 2,821 | Python | 34.721519 | 119 | 0.659341 |
MikeWise2718/sfapp/source/extensions/my_name.my_app.setup/config/extension.toml | [package]
# Semantic Versionning is used: https://semver.org/
version = "1.0.0"
# The title and description fields are primarily for displaying extension info in UI
title = "Setup Extension for My App"
description = "an extensions that Setup my App"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = "https://github.com/NVIDIA-Omniverse/kit-app-template"
# One of categories for UI.
category = "setup"
# Keywords for the extension
keywords = ["kit", "app", "setup"]
# Icon to show in the extension manager
icon = "data/icon.png"
# Preview to show in the extension manager
preview_image = "data/preview.png"
# Use omni.ui to build simple UI
[dependencies]
"omni.kit.quicklayout" = {}
"omni.kit.window.title" = {}
# Main python module this extension provides, it will be publicly available as "import omni.hello.world".
[[python.module]]
name = "my_name.my_app.setup"
| 980 | TOML | 27.028571 | 105 | 0.732653 |
MikeWise2718/sfapp/source/extensions/my_name.my_app.setup/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.0] - 2021-04-26
- Initial version of extension UI template with a window
| 178 | Markdown | 18.888887 | 80 | 0.702247 |
MikeWise2718/sfapp/source/extensions/my_name.my_app.setup/docs/README.md | # Application Setup Extension Template
This extension simply sets up the Application | 85 | Markdown | 27.666657 | 45 | 0.847059 |
MikeWise2718/sfapp/source/extensions/my_name.my_app.window/my_name/my_app/window/extension.py | import asyncio
import omni.ext
import omni.kit.ui
import carb
from .window import MyWindow
async def _load_layout(layout_file: str, keep_windows_open=True):
try:
from omni.kit.quicklayout import QuickLayout
# few frames delay to avoid the conflict with the layout of omni.kit.mainwindow
for i in range(3):
await omni.kit.app.get_app().next_update_async()
QuickLayout.load_file(layout_file, keep_windows_open)
print(f"Loaded layout: {layout_file}")
except Exception as exc:
pass
QuickLayout.load_file(layout_file)
class WindowExtension(omni.ext.IExt):
MENU_PATH = "Window/MyWindow"
def on_startup(self, ext_id):
editor_menu = omni.kit.ui.get_editor_menu()
# Most application have an Window Menu, See MenuLayout to re-organize it
self._window = None
self._menu = editor_menu.add_item(WindowExtension.MENU_PATH, self._on_menu_click, toggle=True, value=True)
self.show_window(True)
layout_file = carb.tokens.get_tokens_interface().resolve("${my_name.my_app.setup}/layouts/viewport1.json")
asyncio.ensure_future(_load_layout(layout_file))
def _on_menu_click(self, menu, toggled):
self.show_window(toggled)
def show_window(self, toggled):
if toggled:
if self._window is None:
self._window = MyWindow()
self._window.set_visibility_changed_fn(self._visiblity_changed_fn)
else:
self._window.show()
else:
if self._window is not None:
self._window.hide()
def _visiblity_changed_fn(self, visible):
if self._menu:
omni.kit.ui.get_editor_menu().set_value(WindowExtension.MENU_PATH, visible)
self.show_window(visible)
def on_shutdown(self):
if self._window is not None:
self._window.destroy()
self._window = None
if self._menu is not None:
editor_menu = omni.kit.ui.get_editor_menu()
editor_menu.remove_item(self._menu)
self._menu = None
| 2,127 | Python | 30.761194 | 114 | 0.618242 |
MikeWise2718/sfapp/source/extensions/my_name.my_app.window/my_name/my_app/window/__init__.py | from .extension import *
| 25 | Python | 11.999994 | 24 | 0.76 |
MikeWise2718/sfapp/source/extensions/my_name.my_app.window/my_name/my_app/window/window.py | __all__ = ["MyWindow"]
import omni.ui as ui
class MyWindow(ui.Window):
"""Sfapp Window"""
title = "My Window"
def __init__(self, **kwargs):
super().__init__(MyWindow.title, **kwargs)
# here you build the content of the window
with self.frame:
with ui.VStack():
ui.Label("Generic Label 1", height=0, style={"font_size": 48, "alignment": ui.Alignment.CENTER})
ui.Spacer()
ui.Label(
"Generic Label 2",
height=0,
style={"font_size": 32, "alignment": ui.Alignment.CENTER},
)
ui.Spacer()
with ui.HStack(height=50, style={"font_size": 24}):
ui.Button("Add")
ui.Button("Reset")
def show(self):
self.visible = True
def hide(self):
self.visible = False
| 922 | Python | 23.945945 | 112 | 0.476139 |
MikeWise2718/sfapp/source/extensions/my_name.my_app.window/config/extension.toml | [package]
# Semantic Versionning is used: https://semver.org/
version = "1.0.0"
# The title and description fields are primarily for displaying extension info in UI
title = "My Application Main Window"
description = "A Window for my Application"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = "https://github.com/NVIDIA-Omniverse/kit-app-template"
# One of categories for UI.
category = "window"
# Keywords for the extension
keywords = ["kit", "window"]
# Icon to show in the extension manager
icon = "data/icon.png"
# Preview to show in the extension manager
preview_image = "data/preview.png"
# Use omni.ui to build simple UI
[dependencies]
"omni.ui" = {}
# Main python module this extension provides, it will be publicly available as "import omni.hello.world".
[[python.module]]
name = "my_name.my_app.window"
| 930 | TOML | 26.382352 | 105 | 0.737634 |
MikeWise2718/sfapp/source/extensions/my_name.my_app.window/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.0] - 2021-04-26
- Initial version of extension UI template with a window
| 178 | Markdown | 18.888887 | 80 | 0.702247 |
MikeWise2718/sfapp/source/extensions/my_name.my_app.window/docs/README.md | # Simple UI Extension Template
The simplest python extension example. Use it as a starting point for your extensions.
| 119 | Markdown | 28.999993 | 86 | 0.806723 |
MikeWise2718/sfapp/docs/apps.md | # Example Apps
## Simple App Window: `my_name.my_app.kit`

The simple application showcases how to create a very basic Kit-based application showing a simple window.
It leverages the kit compatibility mode for the UI that enables it to run on virtually any computer with a GPU.
It uses the window extension example that shows how you can create an extension that shows the window in your application.
## Editor App: `my_name.my_app.editor.kit`

The simple Editor application showcases how you can start leveraging more of the Omniverse Shared Extensions around USD editing to create an application that has the basic features of an app like Create.
It will require an RTX compatible GPU, Turing or above.
You can see how it uses the kit.QuickLayout to setup the example Window at the bottom next to the Content Browser, of course you can choose your own layout and add more functionality and Windows.
## Simple Viewport App: `my_name.my_app.viewport.kit`

This simple viewport application showcases how to create an application that leverages the RTX Renderer and the Kit Viewport to visualize USD files.
It will require an RTX compatible GPU, Turing or above.
The functionality is very limited to mostly viewing the data, and is just a starting point for something you might want to build from.
You can see how it uses the kit.QuickLayout to setup the example Window on the right of the Viewport but you can setup any layout that you need.
| 1,604 | Markdown | 44.857142 | 203 | 0.786783 |
MikeWise2718/sfapp/docs/names.md | # Choosing Names
In this repository we use the `my_name` and `my_app` token for our app and extensions naming, the purpose is to outline where you should use `your company/name id` and `name for your app`
## Brand (Company/Person) Name: `my_name`
For example, for extensions or applications created by the Omniverse team `my_name` is `omni` like `omni.kit.window.extensions` for an extension or `omni.create` for an application.
We recommend that you use a clear and unique name for that and use it for all your apps and extensions.
### A few rules to follow when selecting it
1. Don't use a generic name like `bob` or `cloud`
2. Don't use `omni` as this is reserved for NVIDIA Applications or Extensions
3. Be consistent. Select one and stick to it
## App Name: `my_app`
When building applications you might want to *namespace* the extension within the app name they belong to like `omni.code` for an application where we have then `omni.code.setup` etc.
For that name you have more freedom as it is already in your `my_name` namespace so it should not clash with someone else's "editor" or "viewer".
It would then be acceptable to have `my_name.editor` or `my_name.player` but you still want to think about giving your application some good identity.
## Shared Extensions
Aside from the extension you build specifically for your App there might be some that you want to make more generic and reuse across applications.
That is very possible and even recommended. That is how Omniverse Shared Extensions are built. We have them in namespaces like `omni.kit.widget.` or `omni.kit.window.`
Similarly, you can have `<my_name>.widget.` and use that namespace to have your great ComboBox or advanced List selection widget. Those names will be very useful when other developers or users want to start using your extensions, it will make it clear those come from you (`<my_name>`) and your can outline in the `extension.toml` repository field where they are coming from.
| 1,979 | Markdown | 60.874998 | 375 | 0.769075 |
MikeWise2718/sfapp/docs/docs.toml | # this config makes kit kernel pretend to be an extension for the purpose of building docs.
# format is exactly like extension.toml, but only what is required to build docs
[package]
version = "104.0"
keywords = ["omniverse", "kit", "manual", "developer", "start"]
[documentation]
title = "Omniverse Kit App Template"
[documentation.pages]
"Getting Started" = "docs/overview.md"
"Example Apps" = "docs/apps.md"
"Shared Extensions" = "docs/extensions.md"
"Choosing Names" = "docs/names.md"
| 491 | TOML | 31.799998 | 91 | 0.731161 |
MikeWise2718/sfapp/docs/extensions.md | # Shared Extensions
The repository contains a few extensions that are shared amongst the sample applications that we showcase.
## Setup Extension: `my_name.my_app.setup`
It is standard practice when building applications to have a setup extension that enables you to set up the layout of the relevant windows and configure the menu and various things that happen on startup.
Look at the documentation for **my_name.my_app.setup** to see more details. Its code is also deeply documented so you can review what each part is doing.
## Window Extension: `my_name.my_app.window`
This example extension creates a window for your application.
The Window content itself is just for demonstration purposes and doesn't do anything but it is used in the various applications to show how it can be added to a collection of other Extensions coming from Kit or Code.
Similar to the setup extension, check the window extension's included documentation and review the code for more details
| 981 | Markdown | 56.764703 | 216 | 0.800204 |
MikeWise2718/sfapp/docs/overview.md |
```{include} ../../../../README.md
```
| 40 | Markdown | 9.249998 | 34 | 0.375 |
MarqRazz/c3pzero/CONTRIBUTING.md | Any contribution that you make to this repository will
be under the 3-Clause BSD License, as dictated by that
[license](https://opensource.org/licenses/BSD-3-Clause).
| 167 | Markdown | 40.99999 | 56 | 0.790419 |
MarqRazz/c3pzero/README.md | # c3pzero mobile manipulator
[](https://github.com/MarqRazz/c3pzero/actions/workflows/format.yaml)
Description: This is a ROS 2 package for the C3pzero robot which consists of a Permobile C300 diff drive base and Kinova Gen3 manipulator. This Package support the physical hardware, Ignition Gazebo and Nvidia Isaac simulation.
<img src="doc/c3pzero.png" width="50%" >
<img src="doc/c300_isaac.png" width="60%" >
https://github.com/MarqRazz/c3pzero/assets/25058794/35301ba1-e443-44ff-b6ba-0fabae138205
## Documentation
- [Installation](doc/installation.md)
- [User Guide](doc/user.md)
- [Developers Guide](doc/developer.md)
- [c3pzero Simulation hand hardware Bringup Guide](c3pzero_bringup/README.md)
- [C300 Mobile Base Guide](c300/README.md)
| 846 | Markdown | 41.349998 | 227 | 0.77305 |
MarqRazz/c3pzero/docker-compose.yaml | # Docker Compose file for the C3pzero Robot
#
# Usage:
#
# To build the images:
# docker compose build cpu
# or
# docker compose build gpu
#
# To start up a specific service by name [cpu or gpu]:
# docker compose up <name>
#
# To open an interactive shell to a running container:
# (You can tab complete to get the container name)
# docker exec -it c3pzero bash
services:
cpu:
image: c3pzero:latest
container_name: c3pzero
build:
context: .
dockerfile: .docker/Dockerfile
# Interactive shell
stdin_open: true
tty: true
# Networking and IPC for ROS 2
network_mode: host
ipc: host
privileged: true
command: /bin/bash
device_cgroup_rules:
- "c 81:* rmw"
- "c 189:* rmw"
environment:
# Default the ROS_DOMAIN_ID to zero if not set on the host
- ROS_DOMAIN_ID=${ROS_DOMAIN_ID:-0}
# Allows graphical programs in the container
- DISPLAY=${DISPLAY}
- QT_X11_NO_MITSHM=1
volumes:
# Mount the colcon workspace containing the source code
- ../../:/root/c3pzero_ws/:rw
# Allow access to host hardware e.g. joystick & sensors
- /dev:/dev
# Allows graphical programs in the container
- /tmp/.X11-unix:/tmp/.X11-unix:rw
- ${XAUTHORITY:-$HOME/.Xauthority}:/root/.Xauthority
gpu:
extends: cpu
container_name: c3pzero
command: /bin/bash
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: 1
capabilities: [gpu]
environment:
QT_X11_NO_MITSHM: 1
NVIDIA_VISIBLE_DEVICES: all
NVIDIA_DRIVER_CAPABILITIES: all
| 1,669 | YAML | 25.09375 | 64 | 0.618933 |
MarqRazz/c3pzero/c300/README.md | # c300 Mobile Base
## To visualize this robot's URDF run:
``` bash
ros2 launch c300_description view_base_urdf.launch.py
```
## To start the `c300` mobile base in Gazebo run the following command:
``` bash
ros2 launch c300_bringup gazebo_c300.launch.py
```
## To teleoperate the robot with a Logitech F710 joystick run:
``` bash
ros2 launch c300_driver teleop.launch.py
```
> NOTE: in simulation the `cmd_vel` topic is on `/diff_drive_base_controller/cmd_vel_unstamped`
| 473 | Markdown | 25.333332 | 95 | 0.733615 |
MarqRazz/c3pzero/c300/c300_bringup/launch/gazebo_c300.launch.py | # -*- coding: utf-8 -*-
# Author: Marq Rasmussen
from launch import LaunchDescription
from launch.actions import (
DeclareLaunchArgument,
ExecuteProcess,
IncludeLaunchDescription,
RegisterEventHandler,
)
from launch.event_handlers import OnProcessExit
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.conditions import IfCondition
from launch.substitutions import (
Command,
FindExecutable,
LaunchConfiguration,
PathJoinSubstitution,
)
from launch_ros.actions import Node
from launch_ros.substitutions import FindPackageShare
def generate_launch_description():
declared_arguments = []
# Simulation specific arguments
declared_arguments.append(
DeclareLaunchArgument(
"sim_ignition",
default_value="true",
description="Use Ignition for simulation",
)
)
# General arguments
declared_arguments.append(
DeclareLaunchArgument(
"runtime_config_package",
default_value="c300_bringup",
description='Package with the controller\'s configuration in "config" folder. \
Usually the argument is not set, it enables use of a custom setup.',
)
)
declared_arguments.append(
DeclareLaunchArgument(
"description_package",
default_value="c300_description",
description="Description package with robot URDF/XACRO files. Usually the argument \
is not set, it enables use of a custom description.",
)
)
declared_arguments.append(
DeclareLaunchArgument(
"description_file",
default_value="c300_base.urdf",
description="URDF/XACRO description file with the robot.",
)
)
declared_arguments.append(
DeclareLaunchArgument(
"robot_name",
default_value="c300",
description="Robot name.",
)
)
declared_arguments.append(
DeclareLaunchArgument(
"diff_drive_controller",
default_value="diff_drive_base_controller",
description="Diff drive base controller to start.",
)
)
declared_arguments.append(
DeclareLaunchArgument(
"launch_rviz", default_value="true", description="Launch RViz?"
)
)
declared_arguments.append(
DeclareLaunchArgument(
"use_sim_time",
default_value="True",
description="Use simulation (Gazebo) clock if true",
)
)
# Initialize Arguments
sim_ignition = LaunchConfiguration("sim_ignition")
# General arguments
runtime_config_package = LaunchConfiguration("runtime_config_package")
description_package = LaunchConfiguration("description_package")
description_file = LaunchConfiguration("description_file")
robot_name = LaunchConfiguration("robot_name")
prefix = LaunchConfiguration("prefix")
diff_drive_controller = LaunchConfiguration("diff_drive_controller")
launch_rviz = LaunchConfiguration("launch_rviz")
use_sim_time = LaunchConfiguration("use_sim_time")
rviz_config_file = PathJoinSubstitution(
[FindPackageShare(runtime_config_package), "rviz", "bringup_config.rviz"]
)
robot_description_content = Command(
[
PathJoinSubstitution([FindExecutable(name="xacro")]),
" ",
PathJoinSubstitution(
[FindPackageShare(description_package), "urdf", description_file]
),
" ",
"sim_ignition:=",
sim_ignition,
" ",
]
)
robot_state_publisher_node = Node(
package="robot_state_publisher",
executable="robot_state_publisher",
output="both",
parameters=[
{
"use_sim_time": use_sim_time,
"robot_description": robot_description_content,
}
],
)
rviz_node = Node(
package="rviz2",
executable="rviz2",
name="rviz2",
output="log",
arguments=["-d", rviz_config_file],
condition=IfCondition(launch_rviz),
)
joint_state_broadcaster_spawner = Node(
package="controller_manager",
executable="spawner",
parameters=[{"use_sim_time": use_sim_time}],
arguments=[
"joint_state_broadcaster",
"--controller-manager",
"/controller_manager",
],
)
# Delay rviz start after `joint_state_broadcaster`
delay_rviz_after_joint_state_broadcaster_spawner = RegisterEventHandler(
event_handler=OnProcessExit(
target_action=joint_state_broadcaster_spawner,
on_exit=[rviz_node],
)
)
diff_drive_controller_spawner = Node(
package="controller_manager",
executable="spawner",
arguments=[diff_drive_controller, "-c", "/controller_manager"],
)
ignition_spawn_entity = Node(
package="ros_gz_sim",
executable="create",
output="screen",
arguments=[
"-string",
robot_description_content,
"-name",
robot_name,
"-allow_renaming",
"true",
"-x",
"0.0",
"-y",
"0.0",
"-z",
"0.3",
"-R",
"0.0",
"-P",
"0.0",
"-Y",
"0.0",
],
condition=IfCondition(sim_ignition),
)
ignition_launch_description = IncludeLaunchDescription(
PythonLaunchDescriptionSource(
[FindPackageShare("ros_gz_sim"), "/launch/gz_sim.launch.py"]
),
# TODO (marqrazz): fix the hardcoded path to the gazebo world
# -v is the verbose level
# 0: No output, 1: Error, 2: Error and warning, 3: Error, warning, and info, 4: Error, warning, info, and debug.
# -s launches Gazebo headless
launch_arguments={
"gz_args": " -r -v 3 -s /root/c3pzero_ws/src/c3pzero/c300/c300_bringup/worlds/depot.sdf"
}.items(),
condition=IfCondition(sim_ignition),
)
# Bridge
gazebo_bridge = Node(
package="ros_gz_bridge",
executable="parameter_bridge",
parameters=[{"use_sim_time": use_sim_time}],
arguments=[
"/scan@sensor_msgs/msg/LaserScan[ignition.msgs.LaserScan",
"/clock@rosgraph_msgs/msg/Clock[ignition.msgs.Clock",
],
output="screen",
)
nodes_to_start = [
robot_state_publisher_node,
joint_state_broadcaster_spawner,
delay_rviz_after_joint_state_broadcaster_spawner,
diff_drive_controller_spawner,
ignition_launch_description,
ignition_spawn_entity,
gazebo_bridge,
]
return LaunchDescription(declared_arguments + nodes_to_start)
| 6,925 | Python | 29.782222 | 121 | 0.591625 |
MarqRazz/c3pzero/c300/c300_bringup/launch/isaac_c300.launch.py | # -*- coding: utf-8 -*-
# Author: Marq Rasmussen
from launch import LaunchDescription
from launch.actions import (
DeclareLaunchArgument,
ExecuteProcess,
IncludeLaunchDescription,
RegisterEventHandler,
)
from launch.event_handlers import OnProcessExit
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.conditions import IfCondition
from launch.substitutions import (
Command,
FindExecutable,
LaunchConfiguration,
PathJoinSubstitution,
)
from launch_ros.actions import Node
from launch_ros.substitutions import FindPackageShare
def generate_launch_description():
declared_arguments = []
# Simulation specific arguments
declared_arguments.append(
DeclareLaunchArgument(
"sim_isaac",
default_value="true",
description="Use Ignition for simulation",
)
)
# General arguments
declared_arguments.append(
DeclareLaunchArgument(
"runtime_config_package",
default_value="c300_bringup",
description='Package with the controller\'s configuration in "config" folder. \
Usually the argument is not set, it enables use of a custom setup.',
)
)
declared_arguments.append(
DeclareLaunchArgument(
"controllers_file",
default_value="c300_isaac_controllers.yaml",
description="YAML file with the controllers configuration.",
)
)
declared_arguments.append(
DeclareLaunchArgument(
"description_package",
default_value="c300_description",
description="Description package with robot URDF/XACRO files. Usually the argument \
is not set, it enables use of a custom description.",
)
)
declared_arguments.append(
DeclareLaunchArgument(
"description_file",
default_value="c300_base.urdf",
description="URDF/XACRO description file with the robot.",
)
)
declared_arguments.append(
DeclareLaunchArgument(
"robot_name",
default_value="c300",
description="Robot name.",
)
)
declared_arguments.append(
DeclareLaunchArgument(
"prefix",
default_value='""',
description="Prefix of the joint names, useful for \
multi-robot setup. If changed than also joint names in the controllers' configuration \
have to be updated.",
)
)
declared_arguments.append(
DeclareLaunchArgument(
"diff_drive_controller",
default_value="diff_drive_base_controller",
description="Diff drive base controller to start.",
)
)
declared_arguments.append(
DeclareLaunchArgument(
"launch_rviz", default_value="true", description="Launch RViz?"
)
)
declared_arguments.append(
DeclareLaunchArgument(
"use_sim_time",
default_value="True",
description="Use simulation (Isaac) clock if true",
)
)
# General arguments
runtime_config_package = LaunchConfiguration("runtime_config_package")
controllers_file = LaunchConfiguration("controllers_file")
description_package = LaunchConfiguration("description_package")
description_file = LaunchConfiguration("description_file")
robot_name = LaunchConfiguration("robot_name")
prefix = LaunchConfiguration("prefix")
diff_drive_controller = LaunchConfiguration("diff_drive_controller")
launch_rviz = LaunchConfiguration("launch_rviz")
sim_isaac = LaunchConfiguration("sim_isaac")
use_sim_time = LaunchConfiguration("use_sim_time")
robot_controllers = PathJoinSubstitution(
[FindPackageShare(runtime_config_package), "config", controllers_file]
)
rviz_config_file = PathJoinSubstitution(
[FindPackageShare(runtime_config_package), "rviz", "bringup_config.rviz"]
)
robot_description_content = Command(
[
PathJoinSubstitution([FindExecutable(name="xacro")]),
" ",
PathJoinSubstitution(
[FindPackageShare(description_package), "urdf", description_file]
),
" ",
"prefix:=",
prefix,
" ",
"sim_isaac:=",
sim_isaac,
" ",
]
)
robot_description = {"robot_description": robot_description_content}
control_node = Node(
package="controller_manager",
executable="ros2_control_node",
parameters=[
{"use_sim_time": use_sim_time},
robot_description,
robot_controllers,
],
remappings=[
("/diff_drive_base_controller/cmd_vel_unstamped", "/cmd_vel"),
("/diff_drive_base_controller/odom", "/odom"),
],
output="both",
)
robot_state_publisher_node = Node(
package="robot_state_publisher",
executable="robot_state_publisher",
output="both",
parameters=[
{
"use_sim_time": use_sim_time,
"robot_description": robot_description_content,
}
],
)
rviz_node = Node(
package="rviz2",
executable="rviz2",
name="rviz2",
output="log",
parameters=[{"use_sim_time": use_sim_time}],
arguments=["-d", rviz_config_file],
condition=IfCondition(launch_rviz),
)
joint_state_broadcaster_spawner = Node(
package="controller_manager",
executable="spawner",
parameters=[{"use_sim_time": use_sim_time}],
arguments=[
"joint_state_broadcaster",
"--controller-manager",
"/controller_manager",
],
)
# Delay rviz start after `joint_state_broadcaster`
delay_rviz_after_joint_state_broadcaster_spawner = RegisterEventHandler(
event_handler=OnProcessExit(
target_action=joint_state_broadcaster_spawner,
on_exit=[rviz_node],
)
)
diff_drive_controller_spawner = Node(
package="controller_manager",
executable="spawner",
arguments=[diff_drive_controller, "-c", "/controller_manager"],
)
nodes_to_start = [
control_node,
robot_state_publisher_node,
joint_state_broadcaster_spawner,
delay_rviz_after_joint_state_broadcaster_spawner,
diff_drive_controller_spawner,
]
return LaunchDescription(declared_arguments + nodes_to_start)
| 6,604 | Python | 30.452381 | 96 | 0.609479 |
MarqRazz/c3pzero/c300/c300_bringup/config/c300_gz_controllers.yaml | controller_manager:
ros__parameters:
update_rate: 500 # Hz (this should match the gazebo rate)
joint_state_broadcaster:
type: joint_state_broadcaster/JointStateBroadcaster
diff_drive_base_controller:
type: diff_drive_controller/DiffDriveController
diff_drive_base_controller:
ros__parameters:
left_wheel_names: ["drivewhl_l_joint"]
right_wheel_names: ["drivewhl_r_joint"]
wheels_per_side: 1
wheel_separation: 0.61 # outside distance between the wheels
wheel_radius: 0.1715
wheel_separation_multiplier: 1.0
left_wheel_radius_multiplier: 1.0
right_wheel_radius_multiplier: 1.0
publish_rate: 50.0
odom_frame_id: odom
base_frame_id: base_link
pose_covariance_diagonal : [0.001, 0.001, 0.0, 0.0, 0.0, 0.01]
twist_covariance_diagonal: [0.001, 0.0, 0.0, 0.0, 0.0, 0.01]
open_loop: false
position_feedback: true
enable_odom_tf: true
cmd_vel_timeout: 0.5
#publish_limited_velocity: true
use_stamped_vel: false
#velocity_rolling_window_size: 10
# Velocity and acceleration limits
# Whenever a min_* is unspecified, default to -max_*
linear.x.has_velocity_limits: true
linear.x.has_acceleration_limits: true
linear.x.has_jerk_limits: false
linear.x.max_velocity: 2.0
linear.x.min_velocity: -2.0
linear.x.max_acceleration: 0.5
linear.x.max_jerk: 0.0
linear.x.min_jerk: 0.0
angular.z.has_velocity_limits: true
angular.z.has_acceleration_limits: true
angular.z.has_jerk_limits: false
angular.z.max_velocity: 2.0
angular.z.min_velocity: -2.0
angular.z.max_acceleration: 1.0
angular.z.min_acceleration: -1.0
angular.z.max_jerk: 0.0
angular.z.min_jerk: 0.0
| 1,735 | YAML | 28.423728 | 66 | 0.680115 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.