file_path
stringlengths
22
162
content
stringlengths
19
501k
size
int64
19
501k
lang
stringclasses
1 value
avg_line_length
float64
6.33
100
max_line_length
int64
18
935
alphanum_fraction
float64
0.34
0.93
matthias-research/omni.fun/exts/omni.fun/omni/fun/scripts/gpu.py
# Copyright 2022 Matthias Müller - Ten Minute Physics, # https://www.youtube.com/c/TenMinutePhysics # www.matthiasMueller.info/tenMinutePhysics # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import numpy as np import warp as wp @wp.struct class SimData: spheres_pos: wp.array(dtype=wp.vec3) spheres_prev_pos: wp.array(dtype=wp.vec3) spheres_pos_corr: wp.array(dtype=wp.vec3) spheres_vel: wp.array(dtype=wp.vec3) spheres_radius: wp.array(dtype=float) spheres_inv_mass: wp.array(dtype=float) mesh_id: wp.uint64 mesh_verts: wp.array(dtype=wp.vec3) mesh_tri_ids: wp.array(dtype=int) @wp.func def closest_point_on_triangle( p: wp.vec3, p0: wp.vec3, p1: wp.vec3, p2: wp.vec3): e0 = p1 - p0 e1 = p2 - p0 tmp = p0 - p a = wp.dot(e0, e0) b = wp.dot(e0, e1) c = wp.dot(e1, e1) d = wp.dot(e0, tmp) e = wp.dot(e1, tmp) coords = wp.vec3(b*e - c*d, b*d - a*e, a*c - b*b) x = 0.0 y = 0.0 z = 0.0 if coords[0] <= 0.0: if c != 0.0: y = -e / c elif coords[1] <= 0.0: if a != 0.0: x = -d / a elif coords[0] + coords[1] > coords[2]: den = a + c - b - b num = c + e - b - d if den != 0.0: x = num / den y = 1.0 - x else: if coords[2] != 0.0: x = coords[0] / coords[2] y = coords[1] / coords[2] x = wp.clamp(x, 0.0, 1.0) y = wp.clamp(y, 0.0, 1.0) bary = wp.vec3(1.0 - x - y, x, y) return bary @wp.kernel def dev_integrate_spheres( dt: float, gravity: wp.vec3, data: SimData): sphere_nr = wp.tid() w = data.spheres_inv_mass[sphere_nr] if w > 0.0: data.spheres_vel[sphere_nr] += gravity * dt data.spheres_prev_pos[sphere_nr] = data.spheres_pos[sphere_nr] data.spheres_pos[sphere_nr] += data.spheres_vel[sphere_nr] * dt def integrate_spheres(num_spheres: int, dt: float, gravity: wp.vec3, data: SimData, device): wp.launch(kernel = dev_integrate_spheres, inputs = [dt, gravity, data], dim=num_spheres, device=device) @wp.kernel def dev_update_spheres( dt: float, jacobi_scale: float, data: SimData): sphere_nr = wp.tid() w = data.spheres_inv_mass[sphere_nr] if w > 0.0: data.spheres_pos[sphere_nr] = data.spheres_pos[sphere_nr] + jacobi_scale * data.spheres_pos_corr data.spheres_vel[sphere_nr] = (data.spheres_pos[sphere_nr] - data.spheres_prev_pos[sphere_nr]) / dt def update_spheres(num_spheres: int, dt: float, jacobi_scale: float, data: SimData, device): wp.launch(kernel = dev_update_spheres, inputs = [dt, jacobi_scale, data], dim=num_spheres, device=device) @wp.kernel def dev_solve_mesh_collisions( data: SimData): sphere_nr = wp.tid() w = data.spheres_inv_mass[sphere_nr] if w > 0.0: pos = data.spheres_pos[sphere_nr] r = data.spheres_radius[sphere_nr] # query bounding volume hierarchy bounds_lower = pos - wp.vec3(r, r, r) bounds_upper = pos + wp.vec3(r, r, r) query = wp.mesh_query_aabb(data.mesh_id, bounds_lower, bounds_upper) tri_nr = int(0) while (wp.mesh_query_aabb_next(query, tri_nr)): p0 = data.mesh_verts[data.mesh_tri_ids[3*tri_nr]] p1 = data.mesh_verts[data.mesh_tri_ids[3*tri_nr + 1]] p2 = data.mesh_verts[data.mesh_tri_ids[3*tri_nr + 2]] hit = closest_point_on_triangle(pos, p0, p1, p2) n = pos - hit d = wp.length(n) if d < r: n = wp.normalize(n) data.spheres_pos[sphere_nr] = data.spheres_pos[sphere_nr] + n * (r - d) def solve_mesh_collisions(num_spheres: int, data: SimData, device): wp.launch(kernel = dev_solve_mesh_collisions, inputs = [data], dim=num_spheres, device=device) @wp.kernel def dev_solve_sphere_collisions( num_spheres: int, data: SimData): i0 = wp.tid() p0 = data.spheres_pos[i0] r0 = data.spheres_radius[i0] w0 = data.spheres_inv_mass[i0] # simpe O(n^2) collision detection for i1 in range(num_spheres): if i1 > i0: p1 = data.spheres_pos[i1] r1 = data.spheres_radius[i1] w1 = data.spheres_inv_mass[i1] w = w0 + w1 if w > 0.0: n = p1 - p0 d = wp.length(n) n = wp.noramlize(n) if d < r0 + r1: corr = n * (r0 + r1 - d) / w data.spheres_corr[i0] = data.spheres_corr[i0] - corr * w0 data.spheres_corr[i1] = data.spheres_corr[i1] - corr * w0 def solve_sphere_collisions(num_spheres: int, data: SimData, device): wp.launch(kernel = dev_solve_sphere_collisions, inputs = [num_spheres, data], dim=num_spheres, device=device)
6,034
Python
32.342541
462
0.586841
matthias-research/omni.fun/exts/omni.fun/omni/fun/scripts/controls.py
import carb import omni.ui import omni.usd import omni.kit.app from pxr import Usd, Sdf from .sim import gravity class ControlsWindow: def __init__(self, init_callback=None, play_callback=None): self._window = None self.buttons = [ [None, init_callback, False, "Init", "Reset"], [None, play_callback, False, "Play", "Pause"]] def __bool__(self): return self._window is not None def create_window(self, visibility_changed_fn): window_flags = omni.ui.WINDOW_FLAGS_NO_SCROLLBAR self._window = omni.ui.Window("Fun Controls", flags=window_flags, width=400, height=400, dockPreference=omni.ui.DockPreference.RIGHT_TOP) self._window.set_visibility_changed_fn(visibility_changed_fn) self.rebuild_ui() def show_window(self): self._window.visible = True def hide_window(self): self._window.visible = False def destroy_window(self): if self._window: self._window.visible = False self._window.destroy() self._window = None def button_pressed(self, button): state = not button[2] button[2] = state button[0].text = button[4] if state else button[3] button[1](state) def set_parameter(self, param_name, val): if param_name == "gravity": gravity = val def rebuild_ui(self): ui = omni.ui row_height = 20 v_spacing = 10 h_spacing = 20 if self._window and self._window.visible: with self._window.frame: with ui.VStack(spacing=v_spacing, padding=50): with ui.HStack(spacing=h_spacing, height=row_height): for button in self.buttons: button[0] = ui.Button( button[3], width=100, height=15, margin=10, clicked_fn=lambda button=button: self.button_pressed(button)) with ui.HStack(spacing=h_spacing, height=row_height): ui.Label("Gravity", width=ui.Percent(50), height=10, name="Gravity") slider = ui.FloatSlider(min=0.0,max=10.0, width=ui.Percent(50)) slider.model.add_value_changed_fn( lambda val, param_name="gravity": self.set_parameter(param_name, val.get_value_as_float()))
2,487
Python
29.341463
145
0.554483
matthias-research/omni.fun/exts/omni.fun/omni/fun/scripts/usdutils.py
from pxr import Usd, UsdGeom, Gf, UsdShade import numpy as np import warp as wp prim_cache = None def get_global_transform(prim, time, return_mat44): if prim_cache is None: prim_cache = UsdGeom.XformCache() prim_cache.SetTime(time) m = prim_cache.GetLocalToWorldTransform(prim) if return_mat44: return wp.mat44( m[0][0], m[1][0], m[2][0], m[3][0], m[0][1], m[1][1], m[2][1], m[3][1], m[0][2], m[1][2], m[2][2], m[3][2], m[0][3], m[1][3], m[2][3], m[3][3]) else: A = np.array([[m[0][0], m[0][1], m[0][2]], [m[1][0], m[1][1], m[1][2]], [m[2][0], m[2][1], m[2][2]]]) b = np.array([m[3][0], m[3][1], m[3][2]]) return A, b def set_transform(mesh, trans, quat): usd_mat = Gf.Matrix4d() usd_mat.SetRotateOnly(Gf.Quatd(*quat)) usd_mat.SetTranslateOnly(Gf.Vec3d(*trans)) xform = UsdGeom.Xform(mesh) xform.GetOrderedXformOps()[0].Set(usd_mat) def clone_primvar(self, prim, prim_clone, name, time=0.0): try: attr = UsdGeom.Primvar(prim.GetAttribute(name)) prim_clone.CreatePrimvar(name, attr.GetTypeName(), attr.GetInterpolation()).Set(attr.Get(time)) except: pass def clone_prim(stage, prim): vis = prim.GetAttribute("visibility") if vis: vis.Set("invisible") mesh = UsdGeom.Mesh(prim) clone_prim_path = '/' + str(prim.GetPath()).replace("/", "_") + '_clone' UsdGeom.Mesh.Define(stage, clone_prim_path) prim_clone = UsdGeom.Mesh(stage.GetPrimAtPath(clone_prim_path)) mesh_clone = UsdGeom.Mesh(prim_clone) stage.GetPrimAtPath(clone_prim_path).SetActive(True) xform = UsdGeom.Xform(mesh_clone) xform.ClearXformOpOrder() xform.AddXformOp(UsdGeom.XformOp.TypeTransform) trans_mat, trans_t = get_global_transform(prim, 0.0, True) trans_points = mesh.GetPointsAttr().Get(0.0) @ trans_mat + trans_t normal_mat = np.array([\ trans_mat[0,:] / np.linalg.norm(trans_mat[0,:]), \ trans_mat[1,:] / np.linalg.norm(trans_mat[1,:]), \ trans_mat[2,:] / np.linalg.norm(trans_mat[2,:])]) trans_normals = mesh.GetNormalsAttr().Get(0.0) @ normal_mat mesh_clone.GetPointsAttr().Set(trans_points) mesh_clone.GetNormalsAttr().Set(trans_normals) mesh_clone.SetNormalsInterpolation(mesh.GetNormalsInterpolation()) mesh_clone.GetFaceVertexIndicesAttr().Set(mesh.GetFaceVertexIndicesAttr().Get(0.0)) mesh_clone.GetFaceVertexCountsAttr().Set(mesh.GetFaceVertexCountsAttr().Get(0.0)) mesh_clone.GetCornerIndicesAttr().Set(mesh.GetCornerIndicesAttr().Get(0.0)) mesh_clone.GetCornerSharpnessesAttr().Set(mesh.GetCornerSharpnessesAttr().Get(0.0)) mesh_clone.GetCreaseIndicesAttr().Set(mesh.GetCreaseIndicesAttr().Get(0.0)) mesh_clone.GetCreaseLengthsAttr().Set(mesh.GetCreaseLengthsAttr().Get(0.0)) mesh_clone.GetCreaseSharpnessesAttr().Set(mesh.GetCreaseSharpnessesAttr().Get(0.0)) mesh_clone.GetSubdivisionSchemeAttr().Set(mesh.GetSubdivisionSchemeAttr().Get(0.0)) mesh_clone.GetInterpolateBoundaryAttr().Set(mesh.GetInterpolateBoundaryAttr().Get(0.0)) mesh_clone.GetFaceVaryingLinearInterpolationAttr().Set(mesh.GetFaceVaryingLinearInterpolationAttr().Get(0.0)) mesh_clone.GetTriangleSubdivisionRuleAttr().Set(mesh.GetTriangleSubdivisionRuleAttr().Get(0.0)) mesh_clone.GetHoleIndicesAttr().Set(mesh.GetHoleIndicesAttr().Get(0.0)) for attr in prim.GetAttributes(): type = str(attr.GetTypeName()) if type.find("texCoord") >= 0: clone_primvar(prim, prim_clone, attr.GetName()) try: mat = UsdShade.MaterialBindingAPI(prim).GetDirectBinding().GetMaterial() UsdShade.MaterialBindingAPI(prim_clone).Bind(mat) except: pass return prim_clone def hide_clones(stage): if stage is None: return for prim in stage.Traverse(): if str(prim.GetName()).find("_clone") >= 0: prim.SetActive(False) else: vis = prim.GetAttribute("visibility") if vis: vis.Set("inherited")
4,122
Python
34.543103
113
0.643862
qcr/benchbot_sim_omni/pip_package_fix.py
import subprocess import sys print("HACK FIX FOR BROKEN PACKAGES") def install(package): subprocess.check_call([sys.executable, "-m", "pip", "install", package]) def uninstall(package): subprocess.check_call([sys.executable, "-m", "pip", "uninstall", "--yes", package]) uninstall("click") install("click") uninstall("typing-extensions") install("typing-extensions")
375
Python
27.923075
87
0.717333
qcr/benchbot_sim_omni/run.py
import flask import numpy as np import os import signal from builtins import print as bprint from gevent import event, pywsgi, signal from pathlib import Path from spatialmath import SE3, UnitQuaternion print("STARTING RUN.PY IN BENCHBOT_SIM_OMNI") DEFAULT_POSE = np.array([1, 0, 0, 0, 0, 0, 0]) DIRTY_EPSILON_DIST = 1 DIRTY_EPSILON_YAW = 2 DIRTY_FILE = '/tmp/benchbot_dirty' MAP_PRIM_PATH = '/env' ROBOT_NAME = 'robot' ROBOT_PRIM_PATH = '/%s' % ROBOT_NAME ROBOT_COMPONENTS = { 'clock': '/ROS_Clock', 'diff_base': '%s/ROS_DifferentialBase' % ROBOT_PRIM_PATH, 'lidar': '%s/ROS_Lidar' % ROBOT_PRIM_PATH, 'rgbd': '%s/ROS_Camera_Stereo_Left' % ROBOT_PRIM_PATH, 'tf_sensors': '%s/ROS_Carter_Sensors_Broadcaster' % ROBOT_PRIM_PATH, 'tf': '%s/ROS_Carter_Broadcaster' % ROBOT_PRIM_PATH } UPDATE_DELAY_SECS = 3.0 def _dc_tf_to_SE3(tf): r = np.array(tf.r) return SE3(np.array(tf.p)) * UnitQuaternion(r[3], r[0:3]).SE3() def _to_SE3(pose): return SE3(pose[4::]) * UnitQuaternion(pose[0], pose[1:4]).SE3() def disable_component(prop_path): from omni.kit.commands import execute from pxr import Sdf print("DISABLING '%s.enabled'" % prop_path) execute("ChangeProperty", prop_path=Sdf.Path("%s.enabled" % prop_path), value=False, prev=None) def print(*args, **kwargs): bprint(*args, **kwargs, flush=True) class SimulatorDaemon: def __init__(self, port): self.address = 'localhost:%s' % port self.inst = None self.sim = None self.sim_i = 0 self.sim_collided = False self.sim_dirty = False self.map_usd = None self.robot_usd = None self.start_pose = None self._map_usd = None self._robot_usd = None self._start_pose = None self._dc = None self._robot = None self._robot_dc = None def check_dirty(self): delta = (_to_SE3(self.start_pose).inv() * _dc_tf_to_SE3(self._dc.get_rigid_body_pose(self._robot_dc))) return (np.linalg.norm(delta.t[0:2]) > DIRTY_EPSILON_DIST or np.abs(delta.rpy(unit='deg')[2]) > DIRTY_EPSILON_YAW) def check_collided(self): return False def open_usd(self): # Bail early if we can't act if self.inst is None: print("No simulator running. " "Stored environment USD, but not opening.") return if self.map_usd is None: print("No environment USD selected. Returning.") return # Imports must go after bail early checks pass as they throw errors # when called in an "inappropriate state" (no idea what that # corresponds to...) from omni.isaac.core.utils.stage import open_stage, update_stage # Stop simulation if running self.stop_simulation() # Update the map if self.map_usd != self._map_usd: self._dc = None self._start_pose = None self._robot = None self._robot_dc = None self._robot_usd = None open_stage(usd_path=self.map_usd) update_stage() self._map_usd = self.map_usd else: print("Skipping map load; already loaded.") # Attempt to replace the robot self.place_robot() def place_robot(self): # Bail early if we can't act if self.inst is None: print("No simulator running. " "Stored robot USD & pose, but not opening.") return if self.robot_usd is None: print("No robot USD selected. Returning.") return # Imports must go after bail early checks pass as they throw errors # when called in an "inappropriate state" (no idea what that # corresponds to...) from omni.isaac.core.robots import Robot from omni.isaac.core.utils.stage import (add_reference_to_stage, update_stage) # Stop simulation if running self.stop_simulation() # Add robot to the environment at the requested pose p = DEFAULT_POSE if self.start_pose is None else self.start_pose if self.robot_usd != self._robot_usd: add_reference_to_stage(usd_path=self.robot_usd, prim_path=ROBOT_PRIM_PATH) self._robot = Robot(prim_path=ROBOT_PRIM_PATH, name=ROBOT_NAME) update_stage() self._robot_usd = self.robot_usd else: print("Skipping robot load; already loaded.") if (p != self._start_pose).any(): self._robot.set_world_pose(position=p[4::], orientation=p[:4]) update_stage() self._start_pose = p else: print("Skipping robot move; already at requested pose.") # Disable auto-publishing of all robot components (we'll manually # publish at varying frequencies instead) for p in ROBOT_COMPONENTS.values(): disable_component(p) # Attempt to start the simulation self.start_simulation() def run(self): f = flask.Flask('benchbot_sim_omni') @f.route('/', methods=['GET']) def __hello(): return flask.jsonify("Hello, I am the Omniverse Sim Daemon") @f.route('/open_environment', methods=['POST']) def __open_env(): r = flask.request.json if 'environment' in r: self.map_usd = r['environment'] self.open_usd() return flask.jsonify({}) @f.route('/place_robot', methods=['POST']) def __place_robot(): r = flask.request.json if 'robot' in r: self.robot_usd = r['robot'] if 'start_pose' in r: # Probably should be regexing... self.start_pose = np.array([ float(x.strip()) for x in r['start_pose'].replace( '[', '').replace(']', '').split(',') ]) self.place_robot() return flask.jsonify({}) @f.route('/restart_sim', methods=['POST']) def __restart_sim(): self.stop_simulation() self.start_simulation() return flask.jsonify({}) @f.route('/start', methods=['POST']) def __start_inst(): self.start_instance() return flask.jsonify({}) @f.route('/start_sim', methods=['POST']) def __start_sim(): self.start_simulation() return flask.jsonify({}) @f.route('/started', methods=['GET']) def __started(): # TODO note there is a race condition (returns true before a /start # job finishes) return flask.jsonify({'started': self.inst is not None}) @f.route('/stop_sim', methods=['POST']) def __stop_sim(): self.stop_simulation() return flask.jsonify({}) # Start long-running server server = pywsgi.WSGIServer(self.address, f) evt = event.Event() for s in [signal.SIGINT, signal.SIGQUIT, signal.SIGTERM]: signal.signal(s, lambda n, frame: evt.set()) server.start() while not evt.is_set(): evt.wait(0.001) self.tick_simulator() # Cleanup self.stop_instance() def start_instance(self): print("STARTING INSTANCE!!") if not self.inst is None: print("Instance already running. Please /stop first.") return env = {} if self.map_usd is None else {"open_usd": self.map_usd} from omni.isaac.kit import SimulationApp # Start the simulator self.inst = SimulationApp({ "renderer": "RayTracedLighting", "headless": False, **env }) # Import all required modules, and configure application from omni.isaac.core.utils.extensions import enable_extension enable_extension("omni.isaac.ros_bridge") # Attempt to place the robot if we had a map if env: self.place_robot() def start_simulation(self): if self.sim is not None: self.stop_simulation() if self.inst is None or self.map_usd is None or self.robot_usd is None: print("Can't start simulation. Missing some required state.") return from omni.isaac.core import SimulationContext self.sim_i = 0 self.sim_collided = False self.sim_dirty = False self.sim = SimulationContext() self.sim.play() from omni.isaac.dynamic_control import _dynamic_control self._dc = _dynamic_control.acquire_dynamic_control_interface() self._robot_dc = self._dc.get_articulation_root_body( self._dc.get_object(ROBOT_PRIM_PATH)) def stop_instance(self): if self.inst is None: print("No instance is running to stop.") return self.stop_simulation() self.inst.close() self.inst = None def stop_simulation(self): if self.sim is None: print("Skipping. No running simulation to stop") return if self.inst is None: print("Skipping. No running simulator found.") return self.sim.stop() self.sim = None # TODO maybe could reuse with more guarding logic? def tick_simulator(self): # Tick simulator steps. Does less now than in 2021.2.1 due to new action graph if self.inst is None: return if self.sim is None: self.inst.update() return self.sim.step() # Tick at 10Hz CHECK DIRTY if self.sim_i % 6 == 0: if not self.sim_dirty: self.sim_dirty = self.check_dirty() if self.sim_dirty: Path(DIRTY_FILE).touch() # Tick at 1Hz CHECK COLLIDED if self.sim_i % 60 == 0: self.sim_collided = self.check_collided() self.sim_i += 1 if __name__ == '__main__': print("inside run.py __main__") sd = SimulatorDaemon(port=os.environ.get('PORT')) sd.run()
10,394
Python
30.122754
86
0.554166
AndrePatri/OmniRoboGym/omni_robo_gym/envs/isaac_env.py
# Copyright (C) 2023 Andrea Patrizi (AndrePatri, andreapatrizi1b6e6@gmail.com) # # This file is part of OmniRoboGym and distributed under the General Public License version 2 license. # # OmniRoboGym is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # OmniRoboGym is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with OmniRoboGym. If not, see <http://www.gnu.org/licenses/>. # from omni.isaac.kit import SimulationApp import os import signal import carb import torch from abc import ABC, abstractmethod from typing import Union, Tuple, Dict from SharsorIPCpp.PySharsorIPC import VLevel from SharsorIPCpp.PySharsorIPC import LogType from SharsorIPCpp.PySharsorIPC import Journal import numpy as np # import gymnasium as gym # class IsaacSimEnv(gym.Env): class IsaacSimEnv(): def __init__( self, headless: bool, sim_device: int = 0, enable_livestream: bool = False, enable_viewport: bool = False, debug = False ) -> None: """ Initializes RL and task parameters. Args: headless (bool): Whether to run training headless. sim_device (int): GPU device ID for running physics simulation. Defaults to 0. enable_livestream (bool): Whether to enable running with livestream. enable_viewport (bool): Whether to enable rendering in headless mode. """ self.debug = debug experience = f'{os.environ["EXP_PATH"]}/omni.isaac.sim.python.omnirobogym.kit' # experience = "" if headless: info = f"Will run in headless mode." Journal.log(self.__class__.__name__, "__init__", info, LogType.STAT, throw_when_excep = True) if enable_livestream: experience = "" elif enable_viewport: exception = f"Using viewport is not supported yet." Journal.log(self.__class__.__name__, "__init__", exception, LogType.EXCEP, throw_when_excep = True) else: experience = f'{os.environ["EXP_PATH"]}/omni.isaac.sim.python.omnirobogym.headless.kit' # experience = f'{os.environ["EXP_PATH"]}/omni.isaac.sim.python.gym.headless.kit' self._simulation_app = SimulationApp({"headless": headless, "physics_gpu": sim_device}, experience=experience) info = "Using IsaacSim experience file @ " + experience Journal.log(self.__class__.__name__, "__init__", info, LogType.STAT, throw_when_excep = True) # carb.settings.get_settings().set("/persistent/omnihydra/useSceneGraphInstancing", True) if enable_livestream: info = "Livestream enabled" Journal.log(self.__class__.__name__, "__init__", info, LogType.STAT, throw_when_excep = True) from omni.isaac.core.utils.extensions import enable_extension self._simulation_app.set_setting("/app/livestream/enabled", True) self._simulation_app.set_setting("/app/window/drawMouse", True) self._simulation_app.set_setting("/app/livestream/proto", "ws") self._simulation_app.set_setting("/app/livestream/websocket/framerate_limit", 120) self._simulation_app.set_setting("/ngx/enabled", False) enable_extension("omni.kit.livestream.native") enable_extension("omni.services.streaming.manager") # handle ctrl+c event signal.signal(signal.SIGINT, self.signal_handler) self._render = not headless or enable_livestream or enable_viewport self._record = False self.step_counter = 0 # step counter self._world = None self.metadata = None self.gpu_pipeline_enabled = False def signal_handler(self, sig, frame): self.close() def set_task(self, task, backend="torch", sim_params=None, init_sim=True) -> None: """ Creates a World object and adds Task to World. Initializes and registers task to the environment interface. Triggers task start-up. Args: task (RLTask): The task to register to the env. backend (str): Backend to use for task. Can be "numpy" or "torch". Defaults to "numpy". sim_params (dict): Simulation parameters for physics settings. Defaults to None. init_sim (Optional[bool]): Automatically starts simulation. Defaults to True. """ from omni.isaac.core.world import World # parse device based on sim_param settings if sim_params and "sim_device" in sim_params: device = sim_params["sim_device"] else: device = "cpu" physics_device_id = carb.settings.get_settings().get_as_int("/physics/cudaDevice") gpu_id = 0 if physics_device_id < 0 else physics_device_id if sim_params and "use_gpu_pipeline" in sim_params: # GPU pipeline must use GPU simulation if sim_params["use_gpu_pipeline"]: device = "cuda:" + str(gpu_id) elif sim_params and "use_gpu" in sim_params: if sim_params["use_gpu"]: device = "cuda:" + str(gpu_id) self.gpu_pipeline_enabled = sim_params["use_gpu_pipeline"] info = "Using device: " + str(device) Journal.log(self.__class__.__name__, "__init__", info, LogType.STAT, throw_when_excep = True) if (sim_params is None): info = f"No sim params provided -> defaults will be used." Journal.log(self.__class__.__name__, "set_task", info, LogType.STAT, throw_when_excep = True) sim_params = {} # defaults for integration and rendering dt if not("physics_dt" in sim_params): sim_params["physics_dt"] = 1.0/60.0 dt = sim_params["physics_dt"] info = f"Using default integration_dt of {dt} s." Journal.log(self.__class__.__name__, "set_task", info, LogType.STAT, throw_when_excep = True) if not("rendering_dt" in sim_params): sim_params["rendering_dt"] = sim_params["physics_dt"] dt = sim_params["rendering_dt"] info = f"Using default rendering_dt of {dt} s." Journal.log(self.__class__.__name__, "set_task", info, LogType.STAT, throw_when_excep = True) self._world = World( stage_units_in_meters=1.0, physics_dt=sim_params["physics_dt"], rendering_dt=sim_params["rendering_dt"], # dt between rendering steps. Note: rendering means rendering a frame of # the current application and not only rendering a frame to the viewports/ cameras. # So UI elements of Isaac Sim will be refereshed with this dt as well if running non-headless backend=backend, device=str(device), physics_prim_path="/physicsScene", set_defaults = False, # set to True to use the defaults settings [physics_dt = 1.0/ 60.0, # stage units in meters = 0.01 (i.e in cms), rendering_dt = 1.0 / 60.0, gravity = -9.81 m / s # ccd_enabled, stabilization_enabled, gpu dynamics turned off, # broadcast type is MBP, solver type is TGS] sim_params=sim_params ) self._sim_params = sim_params big_info = "[World] Creating task " + task.name + "\n" + \ "use_gpu_pipeline: " + str(sim_params["use_gpu_pipeline"]) + "\n" + \ "device: " + str(device) + "\n" +\ "backend: " + str(backend) + "\n" +\ "integration_dt: " + str(sim_params["physics_dt"]) + "\n" + \ "rendering_dt: " + str(sim_params["rendering_dt"]) + "\n" \ Journal.log(self.__class__.__name__, "set_task", big_info, LogType.STAT, throw_when_excep = True) ## we get the physics context to expose additional low-level ## # settings of the simulation self._physics_context = self._world.get_physics_context() self._physics_scene_path = self._physics_context.prim_path self._physics_context.enable_gpu_dynamics(True) self._physics_context.enable_stablization(True) self._physics_scene_prim = self._physics_context.get_current_physics_scene_prim() self._solver_type = self._physics_context.get_solver_type() # we set parameters, depending on sim_params dict if "gpu_max_rigid_contact_count" in sim_params: self._physics_context.set_gpu_max_rigid_contact_count(sim_params["gpu_max_rigid_contact_count"]) if "gpu_max_rigid_patch_count" in sim_params: self._physics_context.set_gpu_max_rigid_patch_count(sim_params["gpu_max_rigid_patch_count"]) if "gpu_found_lost_pairs_capacity" in sim_params: self._physics_context.set_gpu_found_lost_pairs_capacity(sim_params["gpu_found_lost_pairs_capacity"]) if "gpu_found_lost_aggregate_pairs_capacity" in sim_params: self._physics_context.set_gpu_found_lost_aggregate_pairs_capacity(sim_params["gpu_found_lost_aggregate_pairs_capacity"]) if "gpu_total_aggregate_pairs_capacity" in sim_params: self._physics_context.set_gpu_total_aggregate_pairs_capacity(sim_params["gpu_total_aggregate_pairs_capacity"]) if "gpu_max_soft_body_contacts" in sim_params: self._physics_context.set_gpu_max_soft_body_contacts(sim_params["gpu_max_soft_body_contacts"]) if "gpu_max_particle_contacts" in sim_params: self._physics_context.set_gpu_max_particle_contacts(sim_params["gpu_max_particle_contacts"]) if "gpu_heap_capacity" in sim_params: self._physics_context.set_gpu_heap_capacity(sim_params["gpu_heap_capacity"]) if "gpu_temp_buffer_capacity" in sim_params: self._physics_context.set_gpu_temp_buffer_capacity(sim_params["gpu_temp_buffer_capacity"]) if "gpu_max_num_partitions" in sim_params: self._physics_context.set_gpu_max_num_partitions(sim_params["gpu_max_num_partitions"]) # overwriting defaults # self._physics_context.set_gpu_max_rigid_contact_count(2 * self._physics_context.get_gpu_max_rigid_contact_count()) # self._physics_context.set_gpu_max_rigid_patch_count(2 * self._physics_context.get_gpu_max_rigid_patch_count()) # self._physics_context.set_gpu_found_lost_pairs_capacity(2 * self._physics_context.get_gpu_found_lost_pairs_capacity()) # self._physics_context.set_gpu_found_lost_aggregate_pairs_capacity(20 * self._physics_context.get_gpu_found_lost_aggregate_pairs_capacity()) # self._physics_context.set_gpu_total_aggregate_pairs_capacity(20 * self._physics_context.get_gpu_total_aggregate_pairs_capacity()) # self._physics_context.set_gpu_heap_capacity(2 * self._physics_context.get_gpu_heap_capacity()) # self._physics_context.set_gpu_temp_buffer_capacity(20 * self._physics_context.get_gpu_heap_capacity()) # self._physics_context.set_gpu_max_num_partitions(20 * self._physics_context.get_gpu_temp_buffer_capacity()) # GPU buffers self._gpu_max_rigid_contact_count = self._physics_context.get_gpu_max_rigid_contact_count() self._gpu_max_rigid_patch_count = self._physics_context.get_gpu_max_rigid_patch_count() self._gpu_found_lost_pairs_capacity = self._physics_context.get_gpu_found_lost_pairs_capacity() self._gpu_found_lost_aggregate_pairs_capacity = self._physics_context.get_gpu_found_lost_aggregate_pairs_capacity() self._gpu_total_aggregate_pairs_capacity = self._physics_context.get_gpu_total_aggregate_pairs_capacity() self._gpu_max_soft_body_contacts = self._physics_context.get_gpu_max_soft_body_contacts() self._gpu_max_particle_contacts = self._physics_context.get_gpu_max_particle_contacts() self._gpu_heap_capacity = self._physics_context.get_gpu_heap_capacity() self._gpu_temp_buffer_capacity = self._physics_context.get_gpu_temp_buffer_capacity() # self._gpu_max_num_partitions = physics_context.get_gpu_max_num_partitions() # BROKEN->method does not exist big_info2 = "[physics context]:" + "\n" + \ "gpu_max_rigid_contact_count: " + str(self._gpu_max_rigid_contact_count) + "\n" + \ "gpu_max_rigid_patch_count: " + str(self._gpu_max_rigid_patch_count) + "\n" + \ "gpu_found_lost_pairs_capacity: " + str(self._gpu_found_lost_pairs_capacity) + "\n" + \ "gpu_found_lost_aggregate_pairs_capacity: " + str(self._gpu_found_lost_aggregate_pairs_capacity) + "\n" + \ "gpu_total_aggregate_pairs_capacity: " + str(self._gpu_total_aggregate_pairs_capacity) + "\n" + \ "gpu_max_soft_body_contacts: " + str(self._gpu_max_soft_body_contacts) + "\n" + \ "gpu_max_particle_contacts: " + str(self._gpu_max_particle_contacts) + "\n" + \ "gpu_heap_capacity: " + str(self._gpu_heap_capacity) + "\n" + \ "gpu_temp_buffer_capacity: " + str(self._gpu_temp_buffer_capacity) Journal.log(self.__class__.__name__, "set_task", big_info2, LogType.STAT, throw_when_excep = True) self._scene = self._world.scene from omni.usd import get_context self._stage = get_context().get_stage() from pxr import UsdLux, Sdf, Gf, UsdPhysics, PhysicsSchemaTools # add lighting distantLight = UsdLux.DistantLight.Define(self._stage, Sdf.Path("/World/DistantLight")) distantLight.CreateIntensityAttr(500) self._world._current_tasks = dict() # resets registered tasks self._task = task self._task.set_world(self._world) self._task.configure_scene() self._world.add_task(self._task) self._num_envs = self._task.num_envs if sim_params and "enable_viewport" in sim_params: self._render = sim_params["enable_viewport"] Journal.log(self.__class__.__name__, "set_task", "[render]: " + str(self._render), LogType.STAT, throw_when_excep = True) # if init_sim: # self._world.reset() # after the first reset we get get all quantities # # from the scene # self._task.post_initialization_steps() # performs initializations # # steps after the fisrt world reset was called def render(self, mode="human") -> None: """ Step the renderer. Args: mode (str): Select mode of rendering based on OpenAI environments. """ if mode == "human": self._world.render() return None elif mode == "rgb_array": # check if viewport is enabled -- if not, then complain because we won't get any data if not self._render or not self._record: exception = f"Cannot render '{mode}' when rendering is not enabled. Please check the provided" + \ "arguments to the environment class at initialization." Journal.log(self.__class__.__name__, "__init__", exception, LogType.EXCEP, throw_when_excep = True) # obtain the rgb data rgb_data = self._rgb_annotator.get_data() # convert to numpy array rgb_data = np.frombuffer(rgb_data, dtype=np.uint8).reshape(*rgb_data.shape) # return the rgb data return rgb_data[:, :, :3] else: # gym.Env.render(self, mode=mode) return None def create_viewport_render_product(self, resolution=(1280, 720)): """Create a render product of the viewport for rendering.""" try: import omni.replicator.core as rep # create render product self._render_product = rep.create.render_product("/OmniverseKit_Persp", resolution) # create rgb annotator -- used to read data from the render product self._rgb_annotator = rep.AnnotatorRegistry.get_annotator("rgb", device="cpu") self._rgb_annotator.attach([self._render_product]) self._record = True except Exception as e: carb.log_info("omni.replicator.core could not be imported. Skipping creation of render product.") carb.log_info(str(e)) def close(self) -> None: """ Closes simulation. """ if self._simulation_app.is_running(): self._simulation_app.close() return @abstractmethod def step(self, actions = None): """ Basic implementation for stepping simulation""" pass @abstractmethod def reset(self): """ Usually resets the task and updates observations + # other custom operations. """ pass @property def num_envs(self): """ Retrieves number of environments. Returns: num_envs(int): Number of environments. """ return self._num_envs @property def simulation_app(self): """Retrieves the SimulationApp object. Returns: simulation_app(SimulationApp): SimulationApp. """ return self._simulation_app @property def get_world(self): """Retrieves the World object for simulation. Returns: world(World): Simulation World. """ return self._world @property def task(self): """Retrieves the task. Returns: task(BaseTask): Task. """ return self._task @property def render_enabled(self): """Whether rendering is enabled. Returns: render(bool): is render enabled. """ return self._render
19,383
Python
39.299376
149
0.579735
AndrePatri/OmniRoboGym/omni_robo_gym/tasks/isaac_task.py
# Copyright (C) 2023 Andrea Patrizi (AndrePatri, andreapatrizi1b6e6@gmail.com) # # This file is part of OmniRoboGym and distributed under the General Public License version 2 license. # # OmniRoboGym is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # OmniRoboGym is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with OmniRoboGym. If not, see <http://www.gnu.org/licenses/>. # from omni.isaac.core.tasks.base_task import BaseTask from omni.isaac.core.articulations import ArticulationView from omni.isaac.core.utils.viewports import set_camera_view from omni.isaac.core.world import World import omni.kit import numpy as np import torch from omni.importer.urdf import _urdf from omni.isaac.core.utils.prims import move_prim from omni.isaac.cloner import GridCloner import omni.isaac.core.utils.prims as prim_utils # from omni.isaac.sensor import ContactSensor from omni.isaac.core.utils.stage import get_current_stage from omni.isaac.core.scenes.scene import Scene from omni_robo_gym.utils.jnt_imp_cntrl import OmniJntImpCntrl from omni_robo_gym.utils.homing import OmniRobotHomer from omni_robo_gym.utils.contact_sensor import OmniContactSensors from omni_robo_gym.utils.terrains import RlTerrains from omni_robo_gym.utils.math_utils import quat_to_omega, quaternion_difference, rel_vel from abc import abstractmethod from typing import List, Dict from SharsorIPCpp.PySharsorIPC import LogType from SharsorIPCpp.PySharsorIPC import Journal class IsaacTask(BaseTask): def __init__(self, name: str, integration_dt: float, robot_names: List[str], robot_pkg_names: List[str] = None, contact_prims: Dict[str, List] = None, contact_offsets: Dict[str, Dict[str, np.ndarray]] = None, sensor_radii: Dict[str, Dict[str, np.ndarray]] = None, num_envs = 1, device = "cuda", cloning_offset: np.array = None, fix_base: List[bool] = None, self_collide: List[bool] = None, merge_fixed: List[bool] = None, replicate_physics: bool = True, solver_position_iteration_count: int = 4, solver_velocity_iteration_count: int = 1, solver_stabilization_thresh: float = 1e-5, offset=None, env_spacing = 5.0, spawning_radius = 1.0, use_flat_ground = True, default_jnt_stiffness = 300.0, default_jnt_damping = 20.0, default_wheel_stiffness = 0.0, default_wheel_damping = 10.0, override_art_controller = False, dtype = torch.float64, debug_enabled: bool = False, verbose = False, use_diff_velocities = False) -> None: self.torch_dtype = dtype self._debug_enabled = debug_enabled self._verbose = verbose self.use_diff_velocities = use_diff_velocities self.num_envs = num_envs self._override_art_controller = override_art_controller self._integration_dt = integration_dt # just used for contact reporting self.torch_device = torch.device(device) # defaults to "cuda" ("cpu" also valid) self.using_gpu = False if self.torch_device == torch.device("cuda"): self.using_gpu = True self.robot_names = robot_names # these are (potentially) custom names to self.robot_pkg_names = robot_pkg_names # will be used to search for URDF and SRDF packages self.scene_setup_completed = False if self.robot_pkg_names is None: self.robot_pkg_names = self.robot_names # if not provided, robot_names are the same as robot_pkg_names else: # check dimension consistency if len(robot_names) != len(robot_pkg_names): exception = "The provided robot names list must match the length " + \ "of the provided robot package names" raise Exception(exception) if fix_base is None: self._fix_base = [False] * len(self.robot_names) else: # check dimension consistency if len(fix_base) != len(robot_pkg_names): exception = "The provided fix_base list of boolean must match the length " + \ "of the provided robot package names" raise Exception(exception) self._fix_base = fix_base if self_collide is None: self._self_collide = [False] * len(self.robot_names) else: # check dimension consistency if len(self_collide) != len(robot_pkg_names): exception = "The provided self_collide list of boolean must match the length " + \ "of the provided robot package names" raise Exception(exception) self._self_collide = self_collide if merge_fixed is None: self._merge_fixed = [False] * len(self.robot_names) else: # check dimension consistency if len(merge_fixed) != len(robot_pkg_names): exception = "The provided merge_fixed list of boolean must match the length " + \ "of the provided robot package names" raise Exception(exception) self._merge_fixed = merge_fixed self._urdf_paths = {} self._srdf_paths = {} self._robots_art_views = {} self._robots_articulations = {} self._robots_geom_prim_views = {} self._solver_position_iteration_count = solver_position_iteration_count # solver position iteration count # -> higher number makes simulation more accurate self._solver_velocity_iteration_count = solver_velocity_iteration_count self._solver_stabilization_thresh = solver_stabilization_thresh # threshold for kin. energy below which an articulatiion # "goes to sleep", i.e. it's not simulated anymore until some action wakes him up # potentially, each robot could have its own setting for the solver (not supported yet) self._solver_position_iteration_counts = {} self._solver_velocity_iteration_counts = {} self._solver_stabilization_threshs = {} self.robot_bodynames = {} self.robot_n_links = {} self.robot_n_dofs = {} self.robot_dof_names = {} self._root_p = {} self._root_q = {} self._jnts_q = {} self._root_p_prev = {} # used for num differentiation self._root_q_prev = {} # used for num differentiation self._jnts_q_prev = {} # used for num differentiation self._root_p_default = {} self._root_q_default = {} self._jnts_q_default = {} self._root_v = {} self._root_v_default = {} self._root_omega = {} self._root_omega_default = {} self._jnts_v = {} self._jnts_v_default = {} self._jnts_eff_default = {} self._root_pos_offsets = {} self._root_q_offsets = {} self.distr_offset = {} # decribed how robots within each env are distributed self.jnt_imp_controllers = {} self.homers = {} # default jnt impedance settings self.default_jnt_stiffness = default_jnt_stiffness self.default_jnt_damping = default_jnt_damping self.default_wheel_stiffness = default_wheel_stiffness self.default_wheel_damping = default_wheel_damping self.use_flat_ground = use_flat_ground self.spawning_radius = spawning_radius # [m] -> default distance between roots of robots in a single # environment self._calc_robot_distrib() # computes the offsets of robots withing each env. self._env_ns = "/World/envs" self._env_spacing = env_spacing # [m] self._template_env_ns = self._env_ns + "/env_0" self._cloner = GridCloner(spacing=self._env_spacing) self._cloner.define_base_env(self._env_ns) prim_utils.define_prim(self._template_env_ns) self._envs_prim_paths = self._cloner.generate_paths(self._env_ns + "/env", self.num_envs) self._cloning_offset = cloning_offset if self._cloning_offset is None: self._cloning_offset = np.array([[0, 0, 0]] * self.num_envs) self._replicate_physics = replicate_physics self._world_initialized = False self._ground_plane_prim_path = "/World/terrain" self._world = None self._world_scene = None self._world_physics_context = None self.omni_contact_sensors = {} self.contact_prims = contact_prims for robot_name in contact_prims: self.omni_contact_sensors[robot_name] = OmniContactSensors( name = robot_name, n_envs = self.num_envs, contact_prims = contact_prims, contact_offsets = contact_offsets, sensor_radii = sensor_radii, device = self.torch_device, dtype = self.torch_dtype, enable_debug=self._debug_enabled) # trigger __init__ of parent class BaseTask.__init__(self, name=name, offset=offset) self.xrdf_cmd_vals = [] # by default empty, needs to be overriden by # child class def update_jnt_imp_control_gains(self, robot_name: str, jnt_stiffness: float, jnt_damping: float, wheel_stiffness: float, wheel_damping: float, env_indxs: torch.Tensor = None): # updates joint imp. controller with new impedance values if self._debug_enabled: for_robots = "" if env_indxs is not None: if not isinstance(env_indxs, torch.Tensor): msg = "Provided env_indxs should be a torch tensor of indexes!" Journal.log(self.__class__.__name__, "update_jnt_imp_control_gains", msg, LogType.EXCEP, throw_when_excep = True) if self.using_gpu: if not env_indxs.device.type == "cuda": error = "Provided env_indxs should be on GPU!" Journal.log(self.__class__.__name__, "_step_jnt_imp_control", error, LogType.EXCEP, True) else: if not env_indxs.device.type == "cpu": error = "Provided env_indxs should be on CPU!" Journal.log(self.__class__.__name__, "_step_jnt_imp_control", error, LogType.EXCEP, True) for_robots = f"for robot {robot_name}, indexes: " + str(env_indxs.tolist()) if self._verbose: Journal.log(self.__class__.__name__, "update_jnt_imp_control_gains", f"updating joint impedances " + for_robots, LogType.STAT, throw_when_excep = True) # set jnt imp gains for the whole robot if env_indxs is None: gains_pos = torch.full((self.num_envs, \ self.jnt_imp_controllers[robot_name].n_dofs), jnt_stiffness, device = self.torch_device, dtype=self.torch_dtype) gains_vel = torch.full((self.num_envs, \ self.jnt_imp_controllers[robot_name].n_dofs), jnt_damping, device = self.torch_device, dtype=self.torch_dtype) else: gains_pos = torch.full((env_indxs.shape[0], \ self.jnt_imp_controllers[robot_name].n_dofs), jnt_stiffness, device = self.torch_device, dtype=self.torch_dtype) gains_vel = torch.full((env_indxs.shape[0], \ self.jnt_imp_controllers[robot_name].n_dofs), jnt_damping, device = self.torch_device, dtype=self.torch_dtype) self.jnt_imp_controllers[robot_name].set_gains( pos_gains = gains_pos, vel_gains = gains_vel, robot_indxs = env_indxs) # in case of wheels wheels_indxs = self.jnt_imp_controllers[robot_name].get_jnt_idxs_matching( name_pattern="wheel") if wheels_indxs is not None: if env_indxs is None: # wheels are velocity-controlled wheels_pos_gains = torch.full((self.num_envs, len(wheels_indxs)), wheel_stiffness, device = self.torch_device, dtype=self.torch_dtype) wheels_vel_gains = torch.full((self.num_envs, len(wheels_indxs)), wheel_damping, device = self.torch_device, dtype=self.torch_dtype) else: # wheels are velocity-controlled wheels_pos_gains = torch.full((env_indxs.shape[0], len(wheels_indxs)), wheel_stiffness, device = self.torch_device, dtype=self.torch_dtype) wheels_vel_gains = torch.full((env_indxs.shape[0], len(wheels_indxs)), wheel_damping, device = self.torch_device, dtype=self.torch_dtype) self.jnt_imp_controllers[robot_name].set_gains( pos_gains = wheels_pos_gains, vel_gains = wheels_vel_gains, jnt_indxs=wheels_indxs, robot_indxs = env_indxs) def update_root_offsets(self, robot_name: str, env_indxs: torch.Tensor = None): if self._debug_enabled: for_robots = "" if env_indxs is not None: if not isinstance(env_indxs, torch.Tensor): msg = "Provided env_indxs should be a torch tensor of indexes!" Journal.log(self.__class__.__name__, "update_root_offsets", msg, LogType.EXCEP, throw_when_excep = True) if self.using_gpu: if not env_indxs.device.type == "cuda": error = "Provided env_indxs should be on GPU!" Journal.log(self.__class__.__name__, "_step_jnt_imp_control", error, LogType.EXCEP, True) else: if not env_indxs.device.type == "cpu": error = "Provided env_indxs should be on CPU!" Journal.log(self.__class__.__name__, "_step_jnt_imp_control", error, LogType.EXCEP, True) for_robots = f"for robot {robot_name}, indexes: " + str(env_indxs.tolist()) if self._verbose: Journal.log(self.__class__.__name__, "update_root_offsets", f"updating root offsets " + for_robots, LogType.STAT, throw_when_excep = True) # only planar position used if env_indxs is None: self._root_pos_offsets[robot_name][:, 0:2] = self._root_p[robot_name][:, 0:2] self._root_q_offsets[robot_name][:, :] = self._root_q[robot_name] else: self._root_pos_offsets[robot_name][env_indxs, 0:2] = self._root_p[robot_name][env_indxs, 0:2] self._root_q_offsets[robot_name][env_indxs, :] = self._root_q[robot_name][env_indxs, :] def synch_default_root_states(self, robot_name: str = None, env_indxs: torch.Tensor = None): if self._debug_enabled: for_robots = "" if env_indxs is not None: if not isinstance(env_indxs, torch.Tensor): msg = "Provided env_indxs should be a torch tensor of indexes!" Journal.log(self.__class__.__name__, "synch_default_root_states", msg, LogType.EXCEP, throw_when_excep = True) if self.using_gpu: if not env_indxs.device.type == "cuda": error = "Provided env_indxs should be on GPU!" Journal.log(self.__class__.__name__, "_step_jnt_imp_control", error, LogType.EXCEP, True) else: if not env_indxs.device.type == "cpu": error = "Provided env_indxs should be on CPU!" Journal.log(self.__class__.__name__, "_step_jnt_imp_control", error, LogType.EXCEP, True) for_robots = f"for robot {robot_name}, indexes: " + str(env_indxs.tolist()) if self._verbose: Journal.log(self.__class__.__name__, "synch_default_root_states", f"updating default root states " + for_robots, LogType.STAT, throw_when_excep = True) if env_indxs is None: self._root_p_default[robot_name][:, :] = self._root_p[robot_name] self._root_q_default[robot_name][:, :] = self._root_q[robot_name] else: self._root_p_default[robot_name][env_indxs, :] = self._root_p[robot_name][env_indxs, :] self._root_q_default[robot_name][env_indxs, :] = self._root_q[robot_name][env_indxs, :] def post_initialization_steps(self): print("Performing post-initialization steps") self._world_initialized = True # used by other methods which nees to run # only when the world was initialized # populates robot info fields self._fill_robot_info_from_world() # initializes homing managers self._init_homing_managers() # initializes robot state data self._init_robots_state() # default robot state self._set_robots_default_jnt_config() self._set_robots_root_default_config() # initializes joint impedance controllers self._init_jnt_imp_control() # update solver options self._update_art_solver_options() self.reset() self._custom_post_init() self._get_solver_info() # get again solver option before printing everything self._print_envs_info() # debug prints def apply_collision_filters(self, physicscene_path: str, coll_root_path: str): self._cloner.filter_collisions(physicsscene_path = physicscene_path, collision_root_path = coll_root_path, prim_paths=self._envs_prim_paths, global_paths=[self._ground_plane_prim_path] # can collide with these prims ) def reset_jnt_imp_control(self, robot_name: str, env_indxs: torch.Tensor = None): if self._debug_enabled: for_robots = "" if env_indxs is not None: if not isinstance(env_indxs, torch.Tensor): Journal.log(self.__class__.__name__, "reset_jnt_imp_control", "Provided env_indxs should be a torch tensor of indexes!", LogType.EXCEP, throw_when_excep = True) if self.using_gpu: if not env_indxs.device.type == "cuda": error = "Provided env_indxs should be on GPU!" Journal.log(self.__class__.__name__, "_step_jnt_imp_control", error, LogType.EXCEP, True) else: if not env_indxs.device.type == "cpu": error = "Provided env_indxs should be on CPU!" Journal.log(self.__class__.__name__, "_step_jnt_imp_control", error, LogType.EXCEP, True) for_robots = f"for robot {robot_name}, indexes: " + str(env_indxs) if self._verbose: Journal.log(self.__class__.__name__, "reset_jnt_imp_control", f"resetting joint impedances " + for_robots, LogType.STAT, throw_when_excep = True) # resets all internal data, refs to defaults self.jnt_imp_controllers[robot_name].reset(robot_indxs = env_indxs) # restore current state if env_indxs is None: self.jnt_imp_controllers[robot_name].update_state(pos = self._jnts_q[robot_name][:, :], vel = self._jnts_v[robot_name][:, :], eff = None, robot_indxs = None) else: self.jnt_imp_controllers[robot_name].update_state(pos = self._jnts_q[robot_name][env_indxs, :], vel = self._jnts_v[robot_name][env_indxs, :], eff = None, robot_indxs = env_indxs) # restore default gains self.update_jnt_imp_control_gains(robot_name = robot_name, jnt_stiffness = self.default_jnt_stiffness, jnt_damping = self.default_jnt_damping, wheel_stiffness = self.default_wheel_stiffness, wheel_damping = self.default_wheel_damping, env_indxs = env_indxs) #restore jnt imp refs to homing if env_indxs is None: self.jnt_imp_controllers[robot_name].set_refs(pos_ref=self.homers[robot_name].get_homing()[:, :], robot_indxs = None) else: self.jnt_imp_controllers[robot_name].set_refs(pos_ref=self.homers[robot_name].get_homing()[env_indxs, :], robot_indxs = env_indxs) # actually applies reset commands to the articulation # self.jnt_imp_controllers[robot_name].apply_cmds() def set_world(self, world: World): if not isinstance(world, World): Journal.log(self.__class__.__name__, "configure_scene", "world should be an instance of omni.isaac.core.world.World!", LogType.EXCEP, throw_when_excep = True) self._world = world self._world_scene = self._world.scene self._world_physics_context = self._world.get_physics_context() def set_up_scene(self, scene: Scene): super().set_up_scene(scene) def configure_scene(self) -> None: # this is called automatically by the environment BEFORE # initializing the simulation if self._world is None: Journal.log(self.__class__.__name__, "configure_scene", "Did you call the set_world() method??", LogType.EXCEP, throw_when_excep = True) if not self.scene_setup_completed: for i in range(len(self.robot_names)): robot_name = self.robot_names[i] robot_pkg_name = self.robot_pkg_names[i] fix_base = self._fix_base[i] self_collide = self._self_collide[i] merge_fixed = self._merge_fixed[i] self._generate_rob_descriptions(robot_name=robot_name, robot_pkg_name=robot_pkg_name) self._import_urdf(robot_name, fix_base=fix_base, self_collide=self_collide, merge_fixed=merge_fixed) Journal.log(self.__class__.__name__, "set_up_scene", "cloning environments...", LogType.STAT, throw_when_excep = True) self._cloner.clone( source_prim_path=self._template_env_ns, prim_paths=self._envs_prim_paths, replicate_physics=self._replicate_physics, position_offsets = self._cloning_offset ) # we can clone the environment in which all the robos are Journal.log(self.__class__.__name__, "set_up_scene", "finishing scene setup...", LogType.STAT, throw_when_excep = True) for i in range(len(self.robot_names)): robot_name = self.robot_names[i] self._robots_art_views[robot_name] = ArticulationView(name = robot_name + "ArtView", prim_paths_expr = self._env_ns + "/env_.*"+ "/" + robot_name + "/base_link", reset_xform_properties=False) self._robots_articulations[robot_name] = self._world_scene.add(self._robots_art_views[robot_name]) # self._robots_geom_prim_views[robot_name] = GeometryPrimView(name = robot_name + "GeomView", # prim_paths_expr = self._env_ns + "/env*"+ "/" + robot_name, # # prepare_contact_sensors = True # ) # self._robots_geom_prim_views[robot_name].apply_collision_apis() # to be able to apply contact sensors if self.use_flat_ground: self._world_scene.add_default_ground_plane(z_position=0, name="terrain", prim_path= self._ground_plane_prim_path, static_friction=1.0, dynamic_friction=1.0, restitution=0.2) else: self.terrains = RlTerrains(get_current_stage()) self.terrains.get_obstacles_terrain(terrain_size=40, num_obs=100, max_height=0.4, min_size=0.5, max_size=5.0) # delete_prim(self._ground_plane_prim_path + "/SphereLight") # we remove the default spherical light # set default camera viewport position and target self._set_initial_camera_params() self.apply_collision_filters(self._world_physics_context.prim_path, "/World/collisions") # init contact sensors self._init_contact_sensors() # IMPORTANT: this has to be called # after calling the clone() method and initializing articulation views!!! self._world.reset() # reset world to make art views available self.post_initialization_steps() self.scene_setup_completed = True def post_reset(self): pass def reset(self, env_indxs: torch.Tensor = None, robot_names: List[str] =None): # we first reset all target articulations to their default state rob_names = robot_names if (robot_names is not None) else self.robot_names # resets the state of target robot and env to the defaults self.reset_state(env_indxs=env_indxs, robot_names=rob_names) # and jnt imp. controllers for i in range(len(rob_names)): self.reset_jnt_imp_control(robot_name=rob_names[i], env_indxs=env_indxs) def reset_state(self, env_indxs: torch.Tensor = None, robot_names: List[str] =None): rob_names = robot_names if (robot_names is not None) else self.robot_names if env_indxs is not None: if self._debug_enabled: if self.using_gpu: if not env_indxs.device.type == "cuda": error = "Provided env_indxs should be on GPU!" Journal.log(self.__class__.__name__, "_step_jnt_imp_control", error, LogType.EXCEP, True) else: if not env_indxs.device.type == "cpu": error = "Provided env_indxs should be on CPU!" Journal.log(self.__class__.__name__, "_step_jnt_imp_control", error, LogType.EXCEP, True) for i in range(len(rob_names)): robot_name = rob_names[i] # root q self._robots_art_views[robot_name].set_world_poses(positions = self._root_p_default[robot_name][env_indxs, :], orientations=self._root_q_default[robot_name][env_indxs, :], indices = env_indxs) # jnts q self._robots_art_views[robot_name].set_joint_positions(positions = self._jnts_q_default[robot_name][env_indxs, :], indices = env_indxs) # root v and omega self._robots_art_views[robot_name].set_joint_velocities(velocities = self._jnts_v_default[robot_name][env_indxs, :], indices = env_indxs) # jnts v concatenated_vel = torch.cat((self._root_v_default[robot_name][env_indxs, :], self._root_omega_default[robot_name][env_indxs, :]), dim=1) self._robots_art_views[robot_name].set_velocities(velocities = concatenated_vel, indices = env_indxs) # jnts eff self._robots_art_views[robot_name].set_joint_efforts(efforts = self._jnts_eff_default[robot_name][env_indxs, :], indices = env_indxs) else: for i in range(len(rob_names)): robot_name = rob_names[i] # root q self._robots_art_views[robot_name].set_world_poses(positions = self._root_p_default[robot_name][:, :], orientations=self._root_q_default[robot_name][:, :], indices = None) # jnts q self._robots_art_views[robot_name].set_joint_positions(positions = self._jnts_q_default[robot_name][:, :], indices = None) # root v and omega self._robots_art_views[robot_name].set_joint_velocities(velocities = self._jnts_v_default[robot_name][:, :], indices = None) # jnts v concatenated_vel = torch.cat((self._root_v_default[robot_name][:, :], self._root_omega_default[robot_name][:, :]), dim=1) self._robots_art_views[robot_name].set_velocities(velocities = concatenated_vel, indices = None) # jnts eff self._robots_art_views[robot_name].set_joint_efforts(efforts = self._jnts_eff_default[robot_name][:, :], indices = None) # we update the robots state self.get_states(env_indxs=env_indxs, robot_names=rob_names) def close(self): pass def root_pos_offsets(self, robot_name: str, env_idxs: torch.Tensor = None): if env_idxs is None: return self._root_pos_offsets[robot_name] else: return self._root_pos_offsets[robot_name][env_idxs, :] def root_q_offsets(self, robot_name: str, env_idxs: torch.Tensor = None): if env_idxs is None: return self._root_q_offsets[robot_name] else: return self._root_q_offsets[robot_name][env_idxs, :] def root_p(self, robot_name: str, env_idxs: torch.Tensor = None): if env_idxs is None: return self._root_p[robot_name] else: return self._root_p[robot_name][env_idxs, :] def root_p_rel(self, robot_name: str, env_idxs: torch.Tensor = None): rel_pos = torch.sub(self.root_p(robot_name=robot_name, env_idxs=env_idxs), self.root_pos_offsets(robot_name=robot_name, env_idxs=env_idxs)) return rel_pos def root_q(self, robot_name: str, env_idxs: torch.Tensor = None): if env_idxs is None: return self._root_q[robot_name] else: return self._root_q[robot_name][env_idxs, :] def root_q_rel(self, robot_name: str, env_idxs: torch.Tensor = None): rel_q = quaternion_difference(self.root_q_offsets(robot_name=robot_name, env_idxs=env_idxs), self.root_q(robot_name=robot_name, env_idxs=env_idxs)) return rel_q def root_v(self, robot_name: str, env_idxs: torch.Tensor = None): if env_idxs is None: return self._root_v[robot_name] else: return self._root_v[robot_name][env_idxs, :] def root_v_rel(self, robot_name: str, env_idxs: torch.Tensor = None): v_rel = rel_vel(offset_q0_q1=self.root_q_offsets(robot_name=robot_name, env_idxs=env_idxs), v0=self.root_v(robot_name=robot_name, env_idxs=env_idxs)) return v_rel def root_omega(self, robot_name: str, env_idxs: torch.Tensor = None): if env_idxs is None: return self._root_omega[robot_name] else: return self._root_omega[robot_name][env_idxs, :] def root_omega_rel(self, robot_name: str, env_idxs: torch.Tensor = None): omega_rel = rel_vel(offset_q0_q1=self.root_q_offsets(robot_name=robot_name, env_idxs=env_idxs), v0=self.root_omega(robot_name=robot_name, env_idxs=env_idxs)) return omega_rel def jnts_q(self, robot_name: str, env_idxs: torch.Tensor = None): if env_idxs is None: return self._jnts_q[robot_name] else: return self._jnts_q[robot_name][env_idxs, :] def jnts_v(self, robot_name: str, env_idxs: torch.Tensor = None): if env_idxs is None: return self._jnts_v[robot_name] else: return self._jnts_v[robot_name][env_idxs, :] def integration_dt(self): return self._integration_dt @abstractmethod def _xrdf_cmds(self) -> Dict: # this has to be implemented by the user depending on the arguments # the xacro description of the robot takes. The output is a list # of xacro commands. # Example implementation: # def _xrdf_cmds(): # cmds = {} # cmds{self.robot_names[0]} = [] # xrdf_cmd_vals = [True, True, True, False, False, True] # legs = "true" if xrdf_cmd_vals[0] else "false" # big_wheel = "true" if xrdf_cmd_vals[1] else "false" # upper_body ="true" if xrdf_cmd_vals[2] else "false" # velodyne = "true" if xrdf_cmd_vals[3] else "false" # realsense = "true" if xrdf_cmd_vals[4] else "false" # floating_joint = "true" if xrdf_cmd_vals[5] else "false" # horizon needs a floating joint # cmds.append("legs:=" + legs) # cmds.append("big_wheel:=" + big_wheel) # cmds.append("upper_body:=" + upper_body) # cmds.append("velodyne:=" + velodyne) # cmds.append("realsense:=" + realsense) # cmds.append("floating_joint:=" + floating_joint) # return cmds pass @abstractmethod def pre_physics_step(self, actions, robot_name: str) -> None: # apply actions to simulated robot # to be overriden by child class depending # on specific needs pass def _generate_srdf(self, robot_name: str, robot_pkg_name: str): # we generate the URDF where the description package is located import rospkg rospackage = rospkg.RosPack() descr_path = rospackage.get_path(robot_pkg_name + "_srdf") srdf_path = descr_path + "/srdf" xacro_name = robot_pkg_name xacro_path = srdf_path + "/" + xacro_name + ".srdf.xacro" self._srdf_paths[robot_name] = self._descr_dump_path + "/" + robot_name + ".srdf" if self._xrdf_cmds() is not None: cmds = self._xrdf_cmds()[robot_name] if cmds is None: xacro_cmd = ["xacro"] + [xacro_path] + ["-o"] + [self._srdf_paths[robot_name]] else: xacro_cmd = ["xacro"] + [xacro_path] + cmds + ["-o"] + [self._srdf_paths[robot_name]] if self._xrdf_cmds() is None: xacro_cmd = ["xacro"] + [xacro_path] + ["-o"] + [self._srdf_paths[robot_name]] import subprocess try: xacro_gen = subprocess.check_call(xacro_cmd) except: Journal.log(self.__class__.__name__, "_generate_urdf", "failed to generate " + robot_name + "\'S SRDF!!!", LogType.EXCEP, throw_when_excep = True) def _generate_urdf(self, robot_name: str, robot_pkg_name: str): # we generate the URDF where the description package is located import rospkg rospackage = rospkg.RosPack() descr_path = rospackage.get_path(robot_pkg_name + "_urdf") urdf_path = descr_path + "/urdf" xacro_name = robot_pkg_name xacro_path = urdf_path + "/" + xacro_name + ".urdf.xacro" self._urdf_paths[robot_name] = self._descr_dump_path + "/" + robot_name + ".urdf" if self._xrdf_cmds() is not None: cmds = self._xrdf_cmds()[robot_name] if cmds is None: xacro_cmd = ["xacro"] + [xacro_path] + ["-o"] + [self._urdf_paths[robot_name]] else: xacro_cmd = ["xacro"] + [xacro_path] + cmds + ["-o"] + [self._urdf_paths[robot_name]] if self._xrdf_cmds() is None: xacro_cmd = ["xacro"] + [xacro_path] + ["-o"] + [self._urdf_paths[robot_name]] import subprocess try: xacro_gen = subprocess.check_call(xacro_cmd) # we also generate an updated SRDF except: Journal.log(self.__class__.__name__, "_generate_urdf", "Failed to generate " + robot_name + "\'s URDF!!!", LogType.EXCEP, throw_when_excep = True) def _generate_rob_descriptions(self, robot_name: str, robot_pkg_name: str): self._descr_dump_path = "/tmp/" + f"{self.__class__.__name__}" Journal.log(self.__class__.__name__, "update_root_offsets", "generating URDF for robot "+ f"{robot_name}, of type {robot_pkg_name}...", LogType.STAT, throw_when_excep = True) self._generate_urdf(robot_name=robot_name, robot_pkg_name=robot_pkg_name) Journal.log(self.__class__.__name__, "update_root_offsets", "generating SRDF for robot "+ f"{robot_name}, of type {robot_pkg_name}...", LogType.STAT, throw_when_excep = True) # we also generate SRDF files, which are useful for control self._generate_srdf(robot_name=robot_name, robot_pkg_name=robot_pkg_name) def _import_urdf(self, robot_name: str, import_config: omni.importer.urdf._urdf.ImportConfig = _urdf.ImportConfig(), fix_base = False, self_collide = False, merge_fixed = True): Journal.log(self.__class__.__name__, "update_root_offsets", "importing robot URDF", LogType.STAT, throw_when_excep = True) _urdf.acquire_urdf_interface() # we overwrite some settings which are bound to be fixed import_config.merge_fixed_joints = merge_fixed # makes sim more stable # in case of fixed joints with light objects import_config.import_inertia_tensor = True # import_config.convex_decomp = False import_config.fix_base = fix_base import_config.self_collision = self_collide # import_config.distance_scale = 1 # import_config.make_default_prim = True # import_config.create_physics_scene = True # import_config.default_drive_strength = 1047.19751 # import_config.default_position_drive_damping = 52.35988 # import_config.default_drive_type = _urdf.UrdfJointTargetType.JOINT_DRIVE_POSITION # import URDF success, robot_prim_path_default = omni.kit.commands.execute( "URDFParseAndImportFile", urdf_path=self._urdf_paths[robot_name], import_config=import_config, ) robot_base_prim_path = self._template_env_ns + "/" + robot_name # moving default prim to base prim path for cloning move_prim(robot_prim_path_default, # from robot_base_prim_path) # to return success def _init_contact_sensors(self): for i in range(0, len(self.robot_names)): robot_name = self.robot_names[i] # creates base contact sensor (which is then cloned) self.omni_contact_sensors[robot_name].create_contact_sensors( self._world, self._env_ns ) def _init_robots_state(self): for i in range(0, len(self.robot_names)): robot_name = self.robot_names[i] pose = self._robots_art_views[robot_name].get_world_poses( clone = True) # tuple: (pos, quat) # root p (measured, previous, default) self._root_p[robot_name] = pose[0] self._root_p_prev[robot_name] = torch.clone(pose[0]) self._root_p_default[robot_name] = torch.clone(pose[0]) + self.distr_offset[robot_name] # root q (measured, previous, default) self._root_q[robot_name] = pose[1] # root orientation self._root_q_prev[robot_name] = torch.clone(pose[1]) self._root_q_default[robot_name] = torch.clone(pose[1]) # jnt q (measured, previous, default) self._jnts_q[robot_name] = self._robots_art_views[robot_name].get_joint_positions( clone = True) # joint positions self._jnts_q_prev[robot_name] = self._robots_art_views[robot_name].get_joint_positions( clone = True) self._jnts_q_default[robot_name] = self.homers[robot_name].get_homing(clone=True) # root v (measured, default) self._root_v[robot_name] = self._robots_art_views[robot_name].get_linear_velocities( clone = True) # root lin. velocity self._root_v_default[robot_name] = torch.full((self._root_v[robot_name].shape[0], self._root_v[robot_name].shape[1]), 0.0, dtype=self.torch_dtype, device=self.torch_device) # root omega (measured, default) self._root_omega[robot_name] = self._robots_art_views[robot_name].get_angular_velocities( clone = True) # root ang. velocity self._root_omega_default[robot_name] = torch.full((self._root_omega[robot_name].shape[0], self._root_omega[robot_name].shape[1]), 0.0, dtype=self.torch_dtype, device=self.torch_device) # joints v (measured, default) self._jnts_v[robot_name] = self._robots_art_views[robot_name].get_joint_velocities( clone = True) # joint velocities self._jnts_v_default[robot_name] = torch.full((self._jnts_v[robot_name].shape[0], self._jnts_v[robot_name].shape[1]), 0.0, dtype=self.torch_dtype, device=self.torch_device) self._jnts_eff_default[robot_name] = torch.full((self._jnts_v[robot_name].shape[0], self._jnts_v[robot_name].shape[1]), 0.0, dtype=self.torch_dtype, device=self.torch_device) self._root_pos_offsets[robot_name] = torch.zeros((self.num_envs, 3), device=self.torch_device) # reference position offses self._root_q_offsets[robot_name] = torch.zeros((self.num_envs, 4), device=self.torch_device) self._root_q_offsets[robot_name][:, 0] = 1.0 # init to valid identity quaternion self.update_root_offsets(robot_name) def _calc_robot_distrib(self): import math # we distribute robots in a single env. along the # circumference of a circle of given radius n_robots = len(self.robot_names) offset_baseangle = 2 * math.pi / n_robots for i in range(n_robots): offset_angle = offset_baseangle * (i + 1) robot_offset_wrt_center = torch.tensor([self.spawning_radius * math.cos(offset_angle), self.spawning_radius * math.sin(offset_angle), 0], device=self.torch_device, dtype=self.torch_dtype) # list with n references to the original tensor tensor_list = [robot_offset_wrt_center] * self.num_envs self.distr_offset[self.robot_names[i]] = torch.stack(tensor_list, dim=0) def _get_robots_state(self, env_indxs: torch.Tensor = None, robot_names: List[str] = None, dt: float = None, reset: bool = False): rob_names = robot_names if (robot_names is not None) else self.robot_names if env_indxs is not None: for i in range(0, len(rob_names)): robot_name = rob_names[i] pose = self._robots_art_views[robot_name].get_world_poses( clone = True, indices=env_indxs) # tuple: (pos, quat) self._root_p[robot_name][env_indxs, :] = pose[0] self._root_q[robot_name][env_indxs, :] = pose[1] # root orientation self._jnts_q[robot_name][env_indxs, :] = self._robots_art_views[robot_name].get_joint_positions( clone = True, indices=env_indxs) # joint positions if dt is None: # we get velocities from the simulation. This is not good since # these can actually represent artifacts which do not have physical meaning. # It's better to obtain them by differentiation to avoid issues with controllers, etc... self._root_v[robot_name][env_indxs, :] = self._robots_art_views[robot_name].get_linear_velocities( clone = True, indices=env_indxs) # root lin. velocity self._root_omega[robot_name][env_indxs, :] = self._robots_art_views[robot_name].get_angular_velocities( clone = True, indices=env_indxs) # root ang. velocity self._jnts_v[robot_name][env_indxs, :] = self._robots_art_views[robot_name].get_joint_velocities( clone = True, indices=env_indxs) # joint velocities else: # differentiate numerically if not reset: self._root_v[robot_name][env_indxs, :] = (self._root_p[robot_name][env_indxs, :] - \ self._root_p_prev[robot_name][env_indxs, :]) / dt self._root_omega[robot_name][env_indxs, :] = quat_to_omega(self._root_q[robot_name][env_indxs, :], self._root_q_prev[robot_name][env_indxs, :], dt) self._jnts_v[robot_name][env_indxs, :] = (self._jnts_q[robot_name][env_indxs, :] - \ self._jnts_q_prev[robot_name][env_indxs, :]) / dt else: # to avoid issues when differentiating numerically self._root_v[robot_name][env_indxs, :].zero_() self._root_omega[robot_name][env_indxs, :].zero_() self._jnts_v[robot_name][env_indxs, :].zero_() # update "previous" data for numerical differentiation self._root_p_prev[robot_name][env_indxs, :] = self._root_p[robot_name][env_indxs, :] self._root_q_prev[robot_name][env_indxs, :] = self._root_q[robot_name][env_indxs, :] self._jnts_q_prev[robot_name][env_indxs, :] = self._jnts_q[robot_name][env_indxs, :] else: # updating data for all environments for i in range(0, len(rob_names)): robot_name = rob_names[i] pose = self._robots_art_views[robot_name].get_world_poses( clone = True) # tuple: (pos, quat) self._root_p[robot_name][:, :] = pose[0] self._root_q[robot_name][:, :] = pose[1] # root orientation self._jnts_q[robot_name][:, :] = self._robots_art_views[robot_name].get_joint_positions( clone = True) # joint positions if dt is None: # we get velocities from the simulation. This is not good since # these can actually represent artifacts which do not have physical meaning. # It's better to obtain them by differentiation to avoid issues with controllers, etc... self._root_v[robot_name][:, :] = self._robots_art_views[robot_name].get_linear_velocities( clone = True) # root lin. velocity self._root_omega[robot_name][:, :] = self._robots_art_views[robot_name].get_angular_velocities( clone = True) # root ang. velocity self._jnts_v[robot_name][:, :] = self._robots_art_views[robot_name].get_joint_velocities( clone = True) # joint velocities else: # differentiate numerically if not reset: self._root_v[robot_name][:, :] = (self._root_p[robot_name][:, :] - \ self._root_p_prev[robot_name][:, :]) / dt self._root_omega[robot_name][:, :] = quat_to_omega(self._root_q[robot_name][:, :], self._root_q_prev[robot_name][:, :], dt) self._jnts_v[robot_name][:, :] = (self._jnts_q[robot_name][:, :] - \ self._jnts_q_prev[robot_name][:, :]) / dt # self._jnts_v[robot_name][:, :].zero_() else: # to avoid issues when differentiating numerically self._root_v[robot_name][:, :].zero_() self._root_omega[robot_name][:, :].zero_() self._jnts_v[robot_name][:, :].zero_() # update "previous" data for numerical differentiation self._root_p_prev[robot_name][:, :] = self._root_p[robot_name][:, :] self._root_q_prev[robot_name][:, :] = self._root_q[robot_name][:, :] self._jnts_q_prev[robot_name][:, :] = self._jnts_q[robot_name][:, :] def get_states(self, env_indxs: torch.Tensor = None, robot_names: List[str] = None): if self.use_diff_velocities: self._get_robots_state(dt = self.integration_dt(), env_indxs = env_indxs, robot_names = robot_names) # updates robot states # but velocities are obtained via num. differentiation else: self._get_robots_state(env_indxs = env_indxs, robot_names = robot_names) # velocities directly from simulator (can # introduce relevant artifacts, making them unrealistic) def _custom_post_init(self): # can be overridden by child class pass def _set_robots_default_jnt_config(self): # setting Isaac's internal defaults. Useful is resetting # whole scenes or views, but single env reset has to be implemented # manueally # we use the homing of the robots if (self._world_initialized): for i in range(0, len(self.robot_names)): robot_name = self.robot_names[i] homing = self.homers[robot_name].get_homing() self._robots_art_views[robot_name].set_joints_default_state(positions= homing, velocities = torch.zeros((homing.shape[0], homing.shape[1]), \ dtype=self.torch_dtype, device=self.torch_device), efforts = torch.zeros((homing.shape[0], homing.shape[1]), \ dtype=self.torch_dtype, device=self.torch_device)) else: Journal.log(self.__class__.__name__, "_set_robots_default_jnt_config", "Before calling __set_robots_default_jnt_config(), you need to reset the World" + \ " at least once and call post_initialization_steps()", LogType.EXCEP, throw_when_excep = True) def _set_robots_root_default_config(self): if (self._world_initialized): for i in range(0, len(self.robot_names)): robot_name = self.robot_names[i] self._robots_art_views[robot_name].set_default_state(positions = self._root_p_default[robot_name], orientations = self._root_q_default[robot_name]) else: Journal.log(self.__class__.__name__, "_generate_urdf", "Before calling _set_robots_root_default_config(), you need to reset the World" + \ " at least once and call post_initialization_steps()", LogType.EXCEP, throw_when_excep = True) return True def _get_solver_info(self): for i in range(0, len(self.robot_names)): robot_name = self.robot_names[i] self._solver_position_iteration_counts[robot_name] = self._robots_art_views[robot_name].get_solver_position_iteration_counts() self._solver_velocity_iteration_counts[robot_name] = self._robots_art_views[robot_name].get_solver_velocity_iteration_counts() self._solver_stabilization_threshs[robot_name] = self._robots_art_views[robot_name].get_stabilization_thresholds() def _update_art_solver_options(self): # sets new solver iteration options for specifc articulations self._get_solver_info() # gets current solver info for the articulations of the # environments, so that dictionaries are filled properly if (self._world_initialized): for i in range(0, len(self.robot_names)): robot_name = self.robot_names[i] # increase by a factor self._solver_position_iteration_counts[robot_name] = torch.full((self.num_envs,), self._solver_position_iteration_count) self._solver_velocity_iteration_counts[robot_name] = torch.full((self.num_envs,), self._solver_velocity_iteration_count) self._solver_stabilization_threshs[robot_name] = torch.full((self.num_envs,), self._solver_stabilization_thresh) self._robots_art_views[robot_name].set_solver_position_iteration_counts(self._solver_position_iteration_counts[robot_name]) self._robots_art_views[robot_name].set_solver_velocity_iteration_counts(self._solver_velocity_iteration_counts[robot_name]) self._robots_art_views[robot_name].set_stabilization_thresholds(self._solver_stabilization_threshs[robot_name]) self._get_solver_info() # gets again solver info for articulation, so that it's possible to debug if # the operation was successful else: Journal.log(self.__class__.__name__, "_set_robots_default_jnt_config", "Before calling update_art_solver_options(), you need to reset the World at least once!", LogType.EXCEP, throw_when_excep = True) def _print_envs_info(self): if (self._world_initialized): print("TASK INFO:") for i in range(0, len(self.robot_names)): robot_name = self.robot_names[i] task_info = f"[{robot_name}]" + "\n" + \ "bodies: " + str(self._robots_art_views[robot_name].body_names) + "\n" + \ "n. prims: " + str(self._robots_art_views[robot_name].count) + "\n" + \ "prims names: " + str(self._robots_art_views[robot_name].prim_paths) + "\n" + \ "n. bodies: " + str(self._robots_art_views[robot_name].num_bodies) + "\n" + \ "n. dofs: " + str(self._robots_art_views[robot_name].num_dof) + "\n" + \ "dof names: " + str(self._robots_art_views[robot_name].dof_names) + "\n" + \ "solver_position_iteration_counts: " + str(self._solver_position_iteration_counts[robot_name]) + "\n" + \ "solver_velocity_iteration_counts: " + str(self._solver_velocity_iteration_counts[robot_name]) + "\n" + \ "stabiliz. thresholds: " + str(self._solver_stabilization_threshs[robot_name]) # print("dof limits: " + str(self._robots_art_views[robot_name].get_dof_limits())) # print("effort modes: " + str(self._robots_art_views[robot_name].get_effort_modes())) # print("dof gains: " + str(self._robots_art_views[robot_name].get_gains())) # print("dof max efforts: " + str(self._robots_art_views[robot_name].get_max_efforts())) # print("dof gains: " + str(self._robots_art_views[robot_name].get_gains())) # print("physics handle valid: " + str(self._robots_art_views[robot_name].is_physics_handle_valid()) Journal.log(self.__class__.__name__, "_print_envs_info", task_info, LogType.STAT, throw_when_excep = True) else: Journal.log(self.__class__.__name__, "_set_robots_default_jnt_config", "Before calling __print_envs_info(), you need to reset the World at least once!", LogType.EXCEP, throw_when_excep = True) def _fill_robot_info_from_world(self): if self._world_initialized: for i in range(0, len(self.robot_names)): robot_name = self.robot_names[i] self.robot_bodynames[robot_name] = self._robots_art_views[robot_name].body_names self.robot_n_links[robot_name] = self._robots_art_views[robot_name].num_bodies self.robot_n_dofs[robot_name] = self._robots_art_views[robot_name].num_dof self.robot_dof_names[robot_name] = self._robots_art_views[robot_name].dof_names else: Journal.log(self.__class__.__name__, "_fill_robot_info_from_world", "Before calling _fill_robot_info_from_world(), you need to reset the World at least once!", LogType.EXCEP, throw_when_excep = True) def _init_homing_managers(self): if self._world_initialized: for i in range(0, len(self.robot_names)): robot_name = self.robot_names[i] self.homers[robot_name] = OmniRobotHomer(articulation=self._robots_art_views[robot_name], srdf_path=self._srdf_paths[robot_name], device=self.torch_device, dtype=self.torch_dtype) else: exception = "you should reset the World at least once and call the " + \ "post_initialization_steps() method before initializing the " + \ "homing manager." Journal.log(self.__class__.__name__, "_init_homing_managers", exception, LogType.EXCEP, throw_when_excep = True) def _init_jnt_imp_control(self): if self._world_initialized: for i in range(0, len(self.robot_names)): robot_name = self.robot_names[i] # creates impedance controller self.jnt_imp_controllers[robot_name] = OmniJntImpCntrl(articulation=self._robots_art_views[robot_name], default_pgain = self.default_jnt_stiffness, # defaults default_vgain = self.default_jnt_damping, override_art_controller=self._override_art_controller, filter_dt = None, filter_BW = 50, device= self.torch_device, dtype=self.torch_dtype, enable_safety=True, enable_profiling=self._debug_enabled, urdf_path=self._urdf_paths[robot_name], debug_checks = self._debug_enabled) self.reset_jnt_imp_control(robot_name) else: exception = "you should reset the World at least once and call the " + \ "post_initialization_steps() method before initializing the " + \ "joint impedance controller." Journal.log(self.__class__.__name__, "_init_homing_managers", exception, LogType.EXCEP, throw_when_excep = True) def _set_initial_camera_params(self, camera_position=[10, 10, 3], camera_target=[0, 0, 0]): set_camera_view(eye=camera_position, target=camera_target, camera_prim_path="/OmniverseKit_Persp")
68,642
Python
47.995717
142
0.49324
AndrePatri/OmniRoboGym/omni_robo_gym/tests/test_lunar_lander_stable_bs3.py
# Copyright (C) 2023 Andrea Patrizi (AndrePatri, andreapatrizi1b6e6@gmail.com) # # This file is part of OmniRoboGym and distributed under the General Public License version 2 license. # # OmniRoboGym is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # OmniRoboGym is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with OmniRoboGym. If not, see <http://www.gnu.org/licenses/>. # import gymnasium as gym from stable_baselines3 import DQN from stable_baselines3.common.evaluation import evaluate_policy # Create environment env = gym.make("LunarLander-v2", render_mode="rgb_array") # Instantiate the agent model = DQN("MlpPolicy", env, verbose=1) # Train the agent and display a progress bar model.learn(total_timesteps=int(2e5), progress_bar=True) # Save the agent model.save("dqn_lunar") del model # delete trained model to demonstrate loading # Load the trained agent # NOTE: if you have loading issue, you can pass `print_system_info=True` # to compare the system on which the model was trained vs the current one # model = DQN.load("dqn_lunar", env=env, print_system_info=True) model = DQN.load("dqn_lunar", env=env) # Evaluate the agent # NOTE: If you use wrappers with your environment that modify rewards, # this will be reflected here. To evaluate with original rewards, # wrap environment in a "Monitor" wrapper before other wrappers. mean_reward, std_reward = evaluate_policy(model, model.get_env(), n_eval_episodes=10) # Enjoy trained agent vec_env = model.get_env() obs = vec_env.reset() n_pred_iterations = 100000 for i in range(n_pred_iterations): action, _states = model.predict(obs, deterministic=True) obs, rewards, dones, info = vec_env.step(action) vec_env.render("human")
2,169
Python
38.454545
102
0.751498
AndrePatri/OmniRoboGym/omni_robo_gym/tests/create_terrain_demo.py
# Copyright (C) 2023 Andrea Patrizi (AndrePatri, andreapatrizi1b6e6@gmail.com) # # This file is part of OmniRoboGym and distributed under the General Public License version 2 license. # # OmniRoboGym is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # OmniRoboGym is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with OmniRoboGym. If not, see <http://www.gnu.org/licenses/>. # # Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os, sys SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(SCRIPT_DIR) import omni from omni.isaac.kit import SimulationApp import numpy as np simulation_app = SimulationApp({"headless": False}) from omni.isaac.core.tasks import BaseTask from omni.isaac.core import World from omni.isaac.core.objects import DynamicSphere from omni.isaac.core.utils.prims import define_prim from omni.isaac.core.utils.stage import get_current_stage from omni.isaac.core.materials import PreviewSurface from omni.isaac.cloner import GridCloner from pxr import UsdLux, UsdShade, Sdf from omni_robo_gym.utils.terrain_utils import * from omni_robo_gym.utils.terrains import RlTerrains class TerrainsTest(BaseTask): def __init__(self, name) -> None: BaseTask.__init__(self, name=name) self._device = "cpu" def set_up_scene(self, scene) -> None: self._stage = get_current_stage() distantLight = UsdLux.DistantLight.Define(self._stage, Sdf.Path("/World/DistantLight")) distantLight.CreateIntensityAttr(2000) self.terrains = RlTerrains(self._stage) self.terrains.get_obstacles_terrain( terrain_size = 40.0, num_obs = 200, max_height = 0.5, min_size = 0.5, max_size = 5.0,) super().set_up_scene(scene) return def post_reset(self): a = 1 def get_observations(self): pass def calculate_metrics(self) -> None: pass def is_done(self) -> None: pass if __name__ == "__main__": world = World( stage_units_in_meters=1.0, rendering_dt=1.0/60.0, backend="torch", device="cpu", ) terrain_creation_task = TerrainsTest(name="CustomTerrain", ) world.add_task(terrain_creation_task) world.reset() while simulation_app.is_running(): if world.is_playing(): if world.current_time_step_index == 0: world.reset(soft=True) world.step(render=True) else: world.step(render=True) simulation_app.close()
4,763
Python
33.773722
102
0.672475
AndrePatri/OmniRoboGym/omni_robo_gym/utils/contact_sensor.py
import torch import numpy as np from omni.isaac.sensor import ContactSensor from typing import List, Dict from omni.isaac.core.world import World from omni.isaac.core.prims import RigidPrimView, RigidContactView from SharsorIPCpp.PySharsorIPC import LogType from SharsorIPCpp.PySharsorIPC import Journal class OmniContactSensors: def __init__(self, name: str, # robot name for which contact sensors are to be created n_envs: int, # number of environments contact_prims: Dict[str, List] = None, contact_offsets: Dict[str, Dict[str, np.ndarray]] = None, sensor_radii: Dict[str, Dict[str, np.ndarray]] = None, device = "cuda", dtype = torch.float64, enable_debug: bool = False, filter_paths: List[str] = ["/World/terrain/GroundPlane/CollisionPlane"]): # contact sensors abstraction for a single robot # over multiple environments self._filter_paths = filter_paths self._enable_debug = enable_debug self.n_envs = n_envs self.device = device if self.device == "cuda": self.using_gpu = True else: self.using_gpu = False self.dtype = dtype self.name = name self.contact_radius_default = 0.003 # parses contact dictionaries and checks for issues self._parse_contact_dicts(self.name, contact_prims, contact_offsets, sensor_radii) self.n_sensors = len(self.contact_prims) self.in_contact = torch.full((n_envs, self.n_sensors), False, device = self.device, dtype=torch.bool) self.force_norm = torch.full((n_envs, self.n_sensors), -1.0, device = self.device, dtype=self.dtype) self.n_contacts = torch.full((n_envs, self.n_sensors), 0, device = self.device, dtype=torch.int) self.contact_sensors = [[None] * self.n_sensors] * n_envs # outer: environment, # inner: contact sensor, ordered as in contact_prims self.contact_geom_prim_views = [None] * self.n_sensors # self.contact_views = [None] * self.n_sensors def _parse_contact_dicts(self, name: str, contact_prims: Dict[str, List], contact_offsets: Dict[str, Dict[str, np.ndarray]], sensor_radii: Dict[str, Dict[str, np.ndarray]]): try: self.contact_prims = contact_prims[name] except: Journal.log(self.__class__.__name__, "_parse_contact_dicts", f"Could not find key {name} in contact_prims dictionary.", LogType.EXCEP, throw_when_excep = True) try: self.contact_offsets = contact_offsets[name] except: Journal.log(self.__class__.__name__, "_parse_contact_dicts", f"Could not find key {name} in contact_offsets dictionary.", LogType.EXCEP, throw_when_excep = True) try: self.sensor_radii = sensor_radii[name] except: Journal.log(self.__class__.__name__, "_parse_contact_dicts", f"Could not find key {name} in sensor_radii dictionary.", LogType.EXCEP, throw_when_excep = True) contact_offsets_ok = all(item in self.contact_offsets for item in self.contact_prims) sensor_radii_ok = all(item in self.sensor_radii for item in self.contact_prims) if not contact_offsets_ok: warning = f"Provided contact_offsets dictionary does not posses all the necessary keys. " + \ f"It should contain all of [{' '.join(self.contact_prims)}]. \n" + \ f"Resetting all offsets to zero..." Journal.log(self.__class__.__name__, "_parse_contact_dicts", warning, LogType.WARN, throw_when_excep = True) for i in range(0, len(self.contact_prims)): self.contact_offsets[self.contact_prims[i]] = np.array([0.0, 0.0, 0.0]) if not sensor_radii_ok: warning = f"Provided sensor_radii dictionary does not posses all the necessary keys. " + \ f"It should contain all of [{' '.join(self.contact_prims)}]. \n" + \ f"Resetting all radii to {self.contact_radius_default} ..." Journal.log(self.__class__.__name__, "_parse_contact_dicts", warning, LogType.WARN, throw_when_excep = True) for i in range(0, len(self.contact_prims)): self.sensor_radii[self.contact_prims[i]] = self.contact_radius_default def create_contact_sensors(self, world: World, envs_namespace: str): robot_name = self.name contact_link_names = self.contact_prims for sensor_idx in range(0, self.n_sensors): # we create views of the contact links for all envs if self.contact_geom_prim_views[sensor_idx] is None: self.contact_geom_prim_views[sensor_idx] = RigidPrimView(prim_paths_expr=envs_namespace + "/env_.*/" + robot_name + \ "/" + contact_link_names[sensor_idx], name= self.name + "RigidPrimView" + contact_link_names[sensor_idx], contact_filter_prim_paths_expr= self._filter_paths, prepare_contact_sensors=True, track_contact_forces = True, disable_stablization = False, reset_xform_properties=False, max_contact_count = self.n_envs ) world.scene.add(self.contact_geom_prim_views[sensor_idx]) # for env_idx in range(0, self.n_envs): # # env_idx = 0 # create contact sensors for base env only # for sensor_idx in range(0, self.n_sensors): # contact_link_prim_path = envs_namespace + f"/env_{env_idx}" + \ # "/" + robot_name + \ # "/" + contact_link_names[sensor_idx] # sensor_prim_path = contact_link_prim_path + \ # "/contact_sensor" # contact sensor prim path # print(f"[{self.__class__.__name__}]" + f"[{self.journal.status}]" + ": creating contact sensor at " + # f"{sensor_prim_path}...") # contact_sensor = ContactSensor( # prim_path=sensor_prim_path, # name=f"{robot_name}{env_idx}_{contact_link_names[sensor_idx]}_contact_sensor", # min_threshold=0, # max_threshold=10000000, # radius=self.sensor_radii[contact_link_names[sensor_idx]], # translation=self.contact_offsets[contact_link_names[sensor_idx]], # position=None # ) # self.contact_sensors[env_idx][sensor_idx] = world.scene.add(contact_sensor) # self.contact_sensors[env_idx][sensor_idx].add_raw_contact_data_to_frame() # print(f"[{self.__class__.__name__}]" + f"[{self.journal.status}]" + ": contact sensor at " + # f"{sensor_prim_path} created.") def get(self, dt: float, contact_link: str, env_indxs: torch.Tensor = None, clone = False): index = -1 try: index = self.contact_prims.index(contact_link) except: exception = f"[{self.__class__.__name__}]" + f"[{self.journal.exception}]" + \ f"could not find contact link {contact_link} in contact list {' '.join(self.contact_prims)}." Journal.log(self.__class__.__name__, "get", exception, LogType.EXCEP, throw_when_excep = True) if env_indxs is None: return self.contact_geom_prim_views[index].get_net_contact_forces(clone = clone, dt = dt).view(self.n_envs, 3) else: if self._enable_debug: if env_indxs is not None: if not isinstance(env_indxs, torch.Tensor): msg = "Provided env_indxs should be a torch tensor of indexes!" Journal.log(self.__class__.__name__, "get", msg, LogType.EXCEP, throw_when_excep = True) if not len(env_indxs.shape) == 1: msg = "Provided robot_indxs should be a 1D torch tensor!" Journal.log(self.__class__.__name__, "get", msg, LogType.EXCEP, throw_when_excep = True) if self.using_gpu: if not env_indxs.device.type == "cuda": error = "Provided env_indxs should be on GPU!" Journal.log(self.__class__.__name__, "_step_jnt_imp_control", error, LogType.EXCEP, True) else: if not env_indxs.device.type == "cpu": error = "Provided env_indxs should be on CPU!" Journal.log(self.__class__.__name__, "_step_jnt_imp_control", error, LogType.EXCEP, True) return self.contact_geom_prim_views[index].get_net_contact_forces(clone = clone, dt = dt).view(self.n_envs, 3)[env_indxs, :]
10,792
Python
43.415638
133
0.47424
AndrePatri/OmniRoboGym/omni_robo_gym/utils/math_utils.py
import torch import time import torch.nn.functional as F def normalize_quaternion(q): # Normalizes the quaternion return q / torch.norm(q, dim=-1, keepdim=True) def quaternion_difference(q1, q2): """ Compute the quaternion difference needed to rotate from q1 to q2 """ def quat_conjugate(q): # Computes the conjugate of a quaternion w, x, y, z = q.unbind(-1) return torch.stack([w, -x, -y, -z], dim=-1) q1_conj = quat_conjugate(q1) return quaternion_multiply(q2, q1_conj) def quaternion_multiply(q1, q2): """ Multiply two quaternions. """ w1, x1, y1, z1 = q1.unbind(-1) w2, x2, y2, z2 = q2.unbind(-1) return torch.stack([ w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2, w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2 ], dim=-1) def quaternion_to_angular_velocity(q_diff, dt): """ Convert a quaternion difference to an angular velocity vector. """ angle = 2 * torch.arccos(q_diff[..., 0].clamp(-1.0, 1.0)) # Clamping for numerical stability axis = q_diff[..., 1:] norm = axis.norm(dim=-1, keepdim=True) norm = torch.where(norm > 0, norm, torch.ones_like(norm)) axis = axis / norm angle = angle.unsqueeze(-1) # Add an extra dimension for broadcasting return (angle / dt) * axis def quat_to_omega(q0, q1, dt): """ Convert quaternion pairs to angular velocities """ if q0.shape != q1.shape: raise ValueError("Tensor shapes do not match in quat_to_omega.") # Normalize quaternions and compute differences q0_normalized = normalize_quaternion(q0) q1_normalized = normalize_quaternion(q1) q_diff = quaternion_difference(q0_normalized, q1_normalized) return quaternion_to_angular_velocity(q_diff, dt) def rel_vel(offset_q0_q1, v0): # Calculate relative linear velocity in frame q1 from linear velocity in frame q0 using quaternions. # Ensure the quaternion is normalized offset_q0_q1 = F.normalize(offset_q0_q1, p=2, dim=0) # Convert the linear velocity vector to a quaternion v0_q = torch.cat([torch.tensor([0]), v0]) # Rotate the linear velocity quaternion using the orientation offset quaternion rotated_velocity_quaternion = quaternion_multiply(offset_q0_q1, v0_q) offset_q0_q1_inverse = torch.cat([offset_q0_q1[0:1], -offset_q0_q1[1:]]) # Multiply by the conjugate of the orientation offset quaternion to obtain the result in frame f1 v1_q = quaternion_multiply(rotated_velocity_quaternion, offset_q0_q1_inverse) # Extract the linear velocity vector from the quaternion result v1 = v1_q[1:] return v1 # Example usage n_envs = 100 # Number of environments dt = 0.1 # Time step # Random example tensors for initial and final orientations q_initial = torch.randn(n_envs, 4) q_final = torch.randn(n_envs, 4) start_time = time.perf_counter() # Convert to angular velocities omega = quat_to_omega(q_initial, q_final, dt) end_time = time.perf_counter() elapsed_time = end_time - start_time print(f"Time taken to compute angular velocities: {elapsed_time:.6f} seconds")
3,149
Python
32.870967
104
0.668466
AndrePatri/OmniRoboGym/omni_robo_gym/utils/rt_factor.py
import time class RtFactor(): def __init__(self, dt_nom: float, window_size: int): self._it_counter = 0 self._dt_nom = dt_nom self._start_time = time.perf_counter() self._current_rt_factor = 0.0 self._window_size = window_size self._real_time = 0 self._nom_time = 0 def update(self): self._real_time = time.perf_counter() - self._start_time self._it_counter += 1 self._nom_time += self._dt_nom self._current_rt_factor = self._nom_time / self._real_time def reset_due(self): return (self._it_counter+1) % self._window_size == 0 def get_avrg_step_time(self): return self._real_time / self._window_size def get_dt_nom(self): return self._dt_nom def get_nom_time(self): return self._now_time def get(self): return self._current_rt_factor def reset(self): self._it_counter = 0 self._nom_time = 0 self._start_time = time.perf_counter()
1,096
Python
17.913793
66
0.530109
AndrePatri/OmniRoboGym/omni_robo_gym/utils/urdf_helpers.py
import xml.etree.ElementTree as ET class UrdfLimitsParser: def __init__(self, urdf_path, joint_names, backend = "numpy", device = "cpu"): self.urdf_path = urdf_path self.joint_names = joint_names self.limits_matrix = None self.backend = backend self.device = device if self.backend == "numpy" and \ self.device != "cpu": raise Exception("When using numpy backend, only cpu device is supported!") self.parse_urdf() def parse_urdf(self): tree = ET.parse(self.urdf_path) root = tree.getroot() num_joints = len(self.joint_names) self.limits_matrix = None self.inf = None if self.backend == "numpy": import numpy as np self.limits_matrix = np.full((num_joints, 6), np.nan) self.inf = np.inf elif self.backend == "torch": import torch self.limits_matrix = torch.full((num_joints, 6), torch.nan, device=self.device) self.inf = torch.inf else: raise Exception("Backend not supported") for joint_name in self.joint_names: joint_element = root.find(".//joint[@name='{}']".format(joint_name)) if joint_element is not None: limit_element = joint_element.find('limit') jnt_index = self.joint_names.index(joint_name) # position limits q_lower = float(limit_element.get('lower', - self.inf)) q_upper = float(limit_element.get('upper', self.inf)) # effort limits effort_limit = float(limit_element.get('effort', self.inf)) # vel limits velocity_limit = float(limit_element.get('velocity', self.inf)) self.limits_matrix[jnt_index, 0] = q_lower self.limits_matrix[jnt_index, 3] = q_upper self.limits_matrix[jnt_index, 1] = - abs(velocity_limit) self.limits_matrix[jnt_index, 4] = abs(velocity_limit) self.limits_matrix[jnt_index, 2] = - abs(effort_limit) self.limits_matrix[jnt_index, 5] = abs(effort_limit) def get_limits_matrix(self): return self.limits_matrix
2,425
Python
28.228915
91
0.524536
AndrePatri/OmniRoboGym/omni_robo_gym/utils/homing.py
# Copyright (C) 2023 Andrea Patrizi (AndrePatri, andreapatrizi1b6e6@gmail.com) # # This file is part of OmniRoboGym and distributed under the General Public License version 2 license. # # OmniRoboGym is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # OmniRoboGym is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with OmniRoboGym. If not, see <http://www.gnu.org/licenses/>. # from omni.isaac.core.articulations.articulation_view import ArticulationView import torch import xml.etree.ElementTree as ET from SharsorIPCpp.PySharsorIPC import LogType from SharsorIPCpp.PySharsorIPC import Journal class OmniRobotHomer: def __init__(self, articulation: ArticulationView, srdf_path: str, backend = "torch", device: torch.device = torch.device("cpu"), dtype = torch.float64): self.torch_dtype = dtype if not articulation.initialized: exception = f"the provided articulation is not initialized properly!" Journal.log(self.__class__.__name__, "__init__", exception, LogType.EXCEP, throw_when_excep = True) self._articulation = articulation self.srdf_path = srdf_path self._device = device self.num_robots = self._articulation.count self.n_dofs = self._articulation.num_dof self.jnts_names = self._articulation.dof_names self.joint_idx_map = {} for joint in range(0, self.n_dofs): self.joint_idx_map[self.jnts_names[joint]] = joint if (backend != "torch"): print(f"[{self.__class__.__name__}]" + f"[{self.journal.info}]" + ": forcing torch backend. Other backends are not yet supported.") self._backend = "torch" self._homing = torch.full((self.num_robots, self.n_dofs), 0.0, device = self._device, dtype=self.torch_dtype) # homing configuration # open srdf and parse the homing field with open(srdf_path, 'r') as file: self._srdf_content = file.read() try: self._srdf_root = ET.fromstring(self._srdf_content) # Now 'root' holds the root element of the XML tree. # You can navigate through the XML tree to extract the tags and their values. # Example: To find all elements with a specific tag, you can use: # elements = root.findall('.//your_tag_name') # Example: If you know the specific structure of your .SRDF file, you can extract # the data accordingly, for instance: # for child in root: # if child.tag == 'some_tag_name': # tag_value = child.text # # Do something with the tag value. # elif child.tag == 'another_tag_name': # # Handle another tag. except ET.ParseError as e: print(f"[{self.__class__.__name__}]" + f"[{self.journal.warning}]" + ": could not read SRDF properly!!") # Find all the 'joint' elements within 'group_state' with the name attribute and their values joints = self._srdf_root.findall(".//group_state[@name='home']/joint") self._homing_map = {} for joint in joints: joint_name = joint.attrib['name'] joint_value = joint.attrib['value'] self._homing_map[joint_name] = float(joint_value) self._assign2homing() def _assign2homing(self): for joint in list(self._homing_map.keys()): if joint in self.joint_idx_map: self._homing[:, self.joint_idx_map[joint]] = torch.full((self.num_robots, 1), self._homing_map[joint], device = self._device, dtype=self.torch_dtype).flatten() else: print(f"[{self.__class__.__name__}]" + f"[{self.journal.warning}]" + f"[{self._assign2homing.__name__}]" \ + ": joint " + f"{joint}" + " is not present in the articulation. It will be ignored.") def get_homing(self, clone: bool = False): if not clone: return self._homing else: return self._homing.clone()
5,070
Python
36.286764
144
0.554438
AndrePatri/OmniRoboGym/omni_robo_gym/utils/jnt_imp_cntrl.py
# Copyright (C) 2023 Andrea Patrizi (AndrePatri, andreapatrizi1b6e6@gmail.com) # # This file is part of OmniRoboGym and distributed under the General Public License version 2 license. # # OmniRoboGym is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # OmniRoboGym is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with OmniRoboGym. If not, see <http://www.gnu.org/licenses/>. # import torch from typing import List from enum import Enum from omni.isaac.core.articulations.articulation_view import ArticulationView from omni_robo_gym.utils.urdf_helpers import UrdfLimitsParser import time from SharsorIPCpp.PySharsorIPC import LogType from SharsorIPCpp.PySharsorIPC import Journal class FirstOrderFilter: # a class implementing a simple first order filter def __init__(self, dt: float, filter_BW: float = 0.1, rows: int = 1, cols: int = 1, device: torch.device = torch.device("cpu"), dtype = torch.double): self._torch_dtype = dtype self._torch_device = device self._dt = dt self._rows = rows self._cols = cols self._filter_BW = filter_BW import math self._gain = 2 * math.pi * self._filter_BW self.yk = torch.zeros((self._rows, self._cols), device = self._torch_device, dtype=self._torch_dtype) self.ykm1 = torch.zeros((self._rows, self._cols), device = self._torch_device, dtype=self._torch_dtype) self.refk = torch.zeros((self._rows, self._cols), device = self._torch_device, dtype=self._torch_dtype) self.refkm1 = torch.zeros((self._rows, self._cols), device = self._torch_device, dtype=self._torch_dtype) self._kh2 = self._gain * self._dt / 2.0 self._coeff_ref = self._kh2 * 1/ (1 + self._kh2) self._coeff_km1 = (1 - self._kh2) / (1 + self._kh2) def update(self, refk: torch.Tensor = None): if refk is not None: self.refk[:, :] = refk self.yk[:, :] = torch.add(torch.mul(self.ykm1, self._coeff_km1), torch.mul(torch.add(self.refk, self.refkm1), self._coeff_ref)) self.refkm1[:, :] = self.refk self.ykm1[:, :] = self.yk def reset(self, idxs: torch.Tensor = None): if idxs is not None: self.yk[:, :] = torch.zeros((self._rows, self._cols), device = self._torch_device, dtype=self._torch_dtype) self.ykm1[:, :] = torch.zeros((self._rows, self._cols), device = self._torch_device, dtype=self._torch_dtype) self.refk[:, :] = torch.zeros((self._rows, self._cols), device = self._torch_device, dtype=self._torch_dtype) self.refkm1[:, :] = torch.zeros((self._rows, self._cols), device = self._torch_device, dtype=self._torch_dtype) else: self.yk[idxs, :] = torch.zeros((idxs.shape[0], self._cols), device = self._torch_device, dtype=self._torch_dtype) self.ykm1[idxs, :] = torch.zeros((idxs.shape[0], self._cols), device = self._torch_device, dtype=self._torch_dtype) self.refk[idxs, :] = torch.zeros((idxs.shape[0], self._cols), device = self._torch_device, dtype=self._torch_dtype) self.refkm1[idxs, :] = torch.zeros((idxs.shape[0], self._cols), device = self._torch_device, dtype=self._torch_dtype) def get(self): return self.yk class JntSafety: def __init__(self, urdf_parser: UrdfLimitsParser): self.limits_parser = urdf_parser self.limit_matrix = self.limits_parser.get_limits_matrix() def apply(self, q_cmd=None, v_cmd=None, eff_cmd=None): if q_cmd is not None: self.saturate_tensor(q_cmd, position=True) if v_cmd is not None: self.saturate_tensor(v_cmd, velocity=True) if eff_cmd is not None: self.saturate_tensor(eff_cmd, effort=True) def has_nan(self, tensor): return torch.any(torch.isnan(tensor)) def saturate_tensor(self, tensor, position=False, velocity=False, effort=False): if self.has_nan(tensor): exception = f"Found nan elements in provided tensor!!" Journal.log(self.__class__.__name__, "saturate_tensor", exception, LogType.EXCEP, throw_when_excep = False) # Replace NaN values with infinity, so that we can clamp it tensor[:, :] = torch.nan_to_num(tensor, nan=torch.inf) if position: tensor[:, :] = torch.clamp(tensor[:, :], min=self.limit_matrix[:, 0], max=self.limit_matrix[:, 3]) elif velocity: tensor[:, :] = torch.clamp(tensor[:, :], min=self.limit_matrix[:, 1], max=self.limit_matrix[:, 4]) elif effort: tensor[:, :] = torch.clamp(tensor[:, :], min=self.limit_matrix[:, 2], max=self.limit_matrix[:, 5]) class OmniJntImpCntrl: class IndxState(Enum): NONE = -1 VALID = 1 INVALID = 0 def __init__(self, articulation: ArticulationView, default_pgain = 300.0, default_vgain = 30.0, backend = "torch", device: torch.device = torch.device("cpu"), filter_BW = 50.0, # [Hz] filter_dt = None, # should correspond to the dt between samples override_art_controller = False, init_on_creation = False, dtype = torch.double, enable_safety = True, urdf_path: str = None, enable_profiling: bool = False, debug_checks: bool = False): # [s] self._torch_dtype = dtype self._torch_device = device self.enable_profiling = enable_profiling self._debug_checks = debug_checks # debug data self.profiling_data = {} self.profiling_data["time_to_update_state"] = -1.0 self.profiling_data["time_to_set_refs"] = -1.0 self.profiling_data["time_to_apply_cmds"] = -1.0 self.start_time = None if self.enable_profiling: self.start_time = time.perf_counter() self.enable_safety = enable_safety self.limiter = None self.robot_limits = None self.urdf_path = urdf_path self.override_art_controller = override_art_controller # whether to override Isaac's internal joint # articulation PD controller or not self.init_art_on_creation = init_on_creation # init. articulation's gains and refs as soon as the controller # is created self.gains_initialized = False self.refs_initialized = False self._default_pgain = default_pgain self._default_vgain = default_vgain self._filter_BW = filter_BW self._filter_dt = filter_dt self._articulation_view = articulation # used to actually apply control # signals to the robot if not self._articulation_view.initialized: exception = f"the provided articulation_view is not initialized properly!" Journal.log(self.__class__.__name__, "__init__", exception, LogType.EXCEP, throw_when_excep = True) self._valid_signal_types = ["pos_ref", "vel_ref", "eff_ref", # references "pos", "vel", "eff", # measurements (necessary if overriding Isaac's art. controller) "pgain", "vgain"] self.num_robots = self._articulation_view.count self.n_dofs = self._articulation_view.num_dof self.jnts_names = self._articulation_view.dof_names if (backend != "torch"): warning = f"Only supported backend is torch!!!" Journal.log(self.__class__.__name__, "__init__", warning, LogType.WARN, throw_when_excep = True) self._backend = "torch" if self.enable_safety: if self.urdf_path is None: exception = "If enable_safety is set to True, a urdf_path should be provided too!" Journal.log(self.__class__.__name__, "__init__", exception, LogType.EXCEP, throw_when_excep = True) self.robot_limits = UrdfLimitsParser(urdf_path=self.urdf_path, joint_names=self.jnts_names, backend=self._backend, device=self._torch_device) self.limiter = JntSafety(urdf_parser=self.robot_limits) self._pos_err = None self._vel_err = None self._pos = None self._vel = None self._eff = None self._imp_eff = None self._filter_available = False if filter_dt is not None: self._filter_BW = filter_BW self._filter_dt = filter_dt self._pos_ref_filter = FirstOrderFilter(dt=self._filter_dt, filter_BW=self._filter_BW, rows=self.num_robots, cols=self.n_dofs, device=self._torch_device, dtype=self._torch_dtype) self._vel_ref_filter = FirstOrderFilter(dt=self._filter_dt, filter_BW=self._filter_BW, rows=self.num_robots, cols=self.n_dofs, device=self._torch_device, dtype=self._torch_dtype) self._eff_ref_filter = FirstOrderFilter(dt=self._filter_dt, filter_BW=self._filter_BW, rows=self.num_robots, cols=self.n_dofs, device=self._torch_device, dtype=self._torch_dtype) self._filter_available = True else: warning = f"No filter dt provided -> reference filter will not be used!" Journal.log(self.__class__.__name__, "__init__", warning, LogType.WARN, throw_when_excep = True) self.reset() # initialize data def update_state(self, pos: torch.Tensor = None, vel: torch.Tensor = None, eff: torch.Tensor = None, robot_indxs: torch.Tensor = None, jnt_indxs: torch.Tensor = None): if self.enable_profiling: self.start_time = time.perf_counter() selector = self._gen_selector(robot_indxs=robot_indxs, jnt_indxs=jnt_indxs) # only checks and throws # if debug_checks if pos is not None: self._validate_signal(signal = pos, selector = selector, name="pos") # does nothing if not debug_checks self._pos[selector] = pos if vel is not None: self._validate_signal(signal = vel, selector = selector, name="vel") self._vel[selector] = vel if eff is not None: self._validate_signal(signal = eff, selector = selector, name="eff") self._eff[selector] = eff if self.enable_profiling: self.profiling_data["time_to_update_state"] = \ time.perf_counter() - self.start_time def set_gains(self, pos_gains: torch.Tensor = None, vel_gains: torch.Tensor = None, robot_indxs: torch.Tensor = None, jnt_indxs: torch.Tensor = None): selector = self._gen_selector(robot_indxs=robot_indxs, jnt_indxs=jnt_indxs) # only checks and throws # if debug_checks if pos_gains is not None: self._validate_signal(signal = pos_gains, selector = selector, name="pos_gains") self._pos_gains[selector] = pos_gains if not self.override_art_controller: self._articulation_view.set_gains(kps = self._pos_gains) if vel_gains is not None: self._validate_signal(signal = vel_gains, selector = selector, name="vel_gains") self._vel_gains[selector] = vel_gains if not self.override_art_controller: self._articulation_view.set_gains(kds = self._vel_gains) def set_refs(self, eff_ref: torch.Tensor = None, pos_ref: torch.Tensor = None, vel_ref: torch.Tensor = None, robot_indxs: torch.Tensor = None, jnt_indxs: torch.Tensor = None): if self.enable_profiling: self.start_time = time.perf_counter() selector = self._gen_selector(robot_indxs=robot_indxs, jnt_indxs=jnt_indxs) # only checks and throws # if debug_checks if eff_ref is not None: self._validate_signal(signal = eff_ref, selector = selector, name="eff_ref") self._eff_ref[selector] = eff_ref if pos_ref is not None: self._validate_signal(signal = pos_ref, selector = selector, name="pos_ref") self._pos_ref[selector] = pos_ref if vel_ref is not None: self._validate_signal(signal = vel_ref, selector = selector, name="vel_ref") self._vel_ref[selector] = vel_ref if self.enable_profiling: self.profiling_data["time_to_set_refs"] = time.perf_counter() - self.start_time def apply_cmds(self, filter = False): # initialize gains and refs if not done previously if self.enable_profiling: self.start_time = time.perf_counter() if not self.gains_initialized: self._apply_init_gains_to_art() if not self.refs_initialized: self._apply_init_refs_to_art() if filter and self._filter_available: self._pos_ref_filter.update(self._pos_ref) self._vel_ref_filter.update(self._vel_ref) self._eff_ref_filter.update(self._eff_ref) # we first filter, then apply safety eff_ref_filt = self._eff_ref_filter.get() pos_ref_filt = self._pos_ref_filter.get() vel_ref_filt = self._vel_ref_filter.get() if self.limiter is not None: # saturating ref cmds self.limiter.apply(q_cmd=pos_ref_filt, v_cmd=vel_ref_filt, eff_cmd=eff_ref_filt) if not self.override_art_controller: # using omniverse's articulation PD controller self._articulation_view.set_joint_efforts(eff_ref_filt) self._articulation_view.set_joint_position_targets(pos_ref_filt) self._articulation_view.set_joint_velocity_targets(vel_ref_filt) else: # impedance torque computed explicitly self._pos_err = torch.sub(self._pos_ref_filter.get(), self._pos) self._vel_err = torch.sub(self._vel_ref_filter.get(), self._vel) self._imp_eff = torch.add(self._eff_ref_filter.get(), torch.add( torch.mul(self._pos_gains, self._pos_err), torch.mul(self._vel_gains, self._vel_err))) # torch.cuda.synchronize() # we also make the resulting imp eff safe if self.limiter is not None: self.limiter.apply(eff_cmd=eff_ref_filt) # apply only effort (comprehensive of all imp. terms) self._articulation_view.set_joint_efforts(self._imp_eff) else: # we first apply safety to reference joint cmds if self.limiter is not None: self.limiter.apply(q_cmd=self._pos_ref, v_cmd=self._vel_ref, eff_cmd=self._eff_ref) if not self.override_art_controller: # using omniverse's articulation PD controller self._articulation_view.set_joint_efforts(self._eff_ref) self._articulation_view.set_joint_position_targets(self._pos_ref) self._articulation_view.set_joint_velocity_targets(self._vel_ref) else: # impedance torque computed explicitly self._pos_err = torch.sub(self._pos_ref, self._pos) self._vel_err = torch.sub(self._vel_ref, self._vel) self._imp_eff = torch.add(self._eff_ref, torch.add( torch.mul(self._pos_gains, self._pos_err), torch.mul(self._vel_gains, self._vel_err))) # torch.cuda.synchronize() # we also make the resulting imp eff safe if self.limiter is not None: self.limiter.apply(eff_cmd=self._imp_eff) # apply only effort (comprehensive of all imp. terms) self._articulation_view.set_joint_efforts(self._imp_eff) if self.enable_profiling: self.profiling_data["time_to_apply_cmds"] = \ time.perf_counter() - self.start_time def get_jnt_names_matching(self, name_pattern: str): return [jnt for jnt in self.jnts_names if name_pattern in jnt] def get_jnt_idxs_matching(self, name_pattern: str): jnts_names = self.get_jnt_names_matching(name_pattern) jnt_idxs = [self.jnts_names.index(jnt) for jnt in jnts_names] if not len(jnt_idxs) == 0: return torch.tensor(jnt_idxs, dtype=torch.int64, device=self._torch_device) else: return None def pos_gains(self): return self._pos_gains def vel_gains(self): return self._vel_gains def eff_ref(self): return self._eff_ref def pos_ref(self): return self._pos_ref def vel_ref(self): return self._vel_ref def pos_err(self): return self._pos_err def vel_err(self): return self._vel_err def pos(self): return self._pos def vel(self): return self._vel def eff(self): return self._eff def imp_eff(self): return self._imp_eff def reset(self, robot_indxs: torch.Tensor = None): self.gains_initialized = False self.refs_initialized = False self._all_dofs_idxs = torch.tensor([i for i in range(0, self.n_dofs)], dtype=torch.int64, device=self._torch_device) self._all_robots_idxs = torch.tensor([i for i in range(0, self.num_robots)], dtype=torch.int64, device=self._torch_device) if robot_indxs is None: # reset all data # we assume diagonal joint impedance gain matrices, so we can save on memory and only store the diagonal self._pos_gains = torch.full((self.num_robots, self.n_dofs), self._default_pgain, device = self._torch_device, dtype=self._torch_dtype) self._vel_gains = torch.full((self.num_robots, self.n_dofs), self._default_vgain, device = self._torch_device, dtype=self._torch_dtype) self._eff_ref = torch.zeros((self.num_robots, self.n_dofs), device = self._torch_device, dtype=self._torch_dtype) self._pos_ref = torch.zeros((self.num_robots, self.n_dofs), device = self._torch_device, dtype=self._torch_dtype) self._vel_ref = torch.zeros((self.num_robots, self.n_dofs), device = self._torch_device, dtype=self._torch_dtype) self._pos_err = torch.zeros((self.num_robots, self.n_dofs), device = self._torch_device, dtype=self._torch_dtype) self._vel_err = torch.zeros((self.num_robots, self.n_dofs), device = self._torch_device, dtype=self._torch_dtype) self._pos = torch.zeros((self.num_robots, self.n_dofs), device = self._torch_device, dtype=self._torch_dtype) self._vel = torch.zeros((self.num_robots, self.n_dofs), device = self._torch_device, dtype=self._torch_dtype) self._eff = torch.zeros((self.num_robots, self.n_dofs), device = self._torch_device, dtype=self._torch_dtype) self._imp_eff = torch.zeros((self.num_robots, self.n_dofs), device = self._torch_device, dtype=self._torch_dtype) if self._filter_available: self._pos_ref_filter.reset() self._vel_ref_filter.reset() self._eff_ref_filter.reset() else: # only reset some robots if self._debug_checks: self._validate_selectors(robot_indxs=robot_indxs) # throws if checks not satisfied n_envs = robot_indxs.shape[0] # we assume diagonal joint impedance gain matrices, so we can save on memory and only store the diagonal self._pos_gains[robot_indxs, :] = torch.full((n_envs, self.n_dofs), self._default_pgain, device = self._torch_device, dtype=self._torch_dtype) self._vel_gains[robot_indxs, :] = torch.full((n_envs, self.n_dofs), self._default_vgain, device = self._torch_device, dtype=self._torch_dtype) self._eff_ref[robot_indxs, :] = 0 self._pos_ref[robot_indxs, :] = 0 self._vel_ref[robot_indxs, :] = 0 # if self.override_art_controller: # saving memory (these are not necessary if not overriding Isaac's art. controller) self._pos_err[robot_indxs, :] = torch.zeros((n_envs, self.n_dofs), device = self._torch_device, dtype=self._torch_dtype) self._vel_err[robot_indxs, :] = torch.zeros((n_envs, self.n_dofs), device = self._torch_device, dtype=self._torch_dtype) self._pos[robot_indxs, :] = torch.zeros((n_envs, self.n_dofs), device = self._torch_device, dtype=self._torch_dtype) self._vel[robot_indxs, :] = torch.zeros((n_envs, self.n_dofs), device = self._torch_device, dtype=self._torch_dtype) self._eff[robot_indxs, :] = torch.zeros((n_envs, self.n_dofs), device = self._torch_device, dtype=self._torch_dtype) self._imp_eff[robot_indxs, :] = torch.zeros((n_envs, self.n_dofs), device = self._torch_device, dtype=self._torch_dtype) if self._filter_available: self._pos_ref_filter.reset(idxs = robot_indxs) self._vel_ref_filter.reset(idxs = robot_indxs) self._eff_ref_filter.reset(idxs = robot_indxs) if self.init_art_on_creation: # will use updated gains/refs based on reset (non updated gains/refs will be the same) self._apply_init_gains_to_art() self._apply_init_refs_to_art() def _apply_init_gains_to_art(self): if not self.gains_initialized: if not self.override_art_controller: self._articulation_view.set_gains(kps = self._pos_gains, kds = self._vel_gains) else: # settings Isaac's PD controller gains to 0 no_gains = torch.zeros((self.num_robots, self.n_dofs), device = self._torch_device, dtype=self._torch_dtype) self._articulation_view.set_gains(kps = no_gains, kds = no_gains) self.gains_initialized = True def _apply_init_refs_to_art(self): if not self.refs_initialized: if not self.override_art_controller: self._articulation_view.set_joint_efforts(self._eff_ref) self._articulation_view.set_joint_position_targets(self._pos_ref) self._articulation_view.set_joint_velocity_targets(self._vel_ref) else: self._articulation_view.set_joint_efforts(self._eff_ref) self.refs_initialized = True def _validate_selectors(self, robot_indxs: torch.Tensor = None, jnt_indxs: torch.Tensor = None): if robot_indxs is not None: robot_indxs_shape = robot_indxs.shape if (not (len(robot_indxs_shape) == 1 and \ robot_indxs.dtype == torch.int64 and \ bool(torch.min(robot_indxs) >= 0) and \ bool(torch.max(robot_indxs) < self.num_robots)) and \ robot_indxs.device.type == self._torch_device.type): # sanity checks error = "Mismatch in provided selector \n" + \ "robot_indxs_shape -> " + f"{len(robot_indxs_shape)}" + " VS" + " expected -> " + f"{1}" + "\n" + \ "robot_indxs.dtype -> " + f"{robot_indxs.dtype}" + " VS" + " expected -> " + f"{torch.int64}" + "\n" + \ "torch.min(robot_indxs) >= 0) -> " + f"{bool(torch.min(robot_indxs) >= 0)}" + " VS" + f" {True}" + "\n" + \ "torch.max(robot_indxs) < self.n_dofs -> " + f"{torch.max(robot_indxs)}" + " VS" + f" {self.num_robots}\n" + \ "robot_indxs.device -> " + f"{robot_indxs.device.type}" + " VS" + " expected -> " + f"{self._torch_device.type}" + "\n" Journal.log(self.__class__.__name__, "_validate_selectors", error, LogType.EXCEP, throw_when_excep = True) if jnt_indxs is not None: jnt_indxs_shape = jnt_indxs.shape if (not (len(jnt_indxs_shape) == 1 and \ jnt_indxs.dtype == torch.int64 and \ bool(torch.min(jnt_indxs) >= 0) and \ bool(torch.max(jnt_indxs) < self.n_dofs)) and \ jnt_indxs.device.type == self._torch_device.type): # sanity checks error = "Mismatch in provided selector \n" + \ "jnt_indxs_shape -> " + f"{len(jnt_indxs_shape)}" + " VS" + " expected -> " + f"{1}" + "\n" + \ "jnt_indxs.dtype -> " + f"{jnt_indxs.dtype}" + " VS" + " expected -> " + f"{torch.int64}" + "\n" + \ "torch.min(jnt_indxs) >= 0) -> " + f"{bool(torch.min(jnt_indxs) >= 0)}" + " VS" + f" {True}" + "\n" + \ "torch.max(jnt_indxs) < self.n_dofs -> " + f"{torch.max(jnt_indxs)}" + " VS" + f" {self.num_robots}" + \ "robot_indxs.device -> " + f"{jnt_indxs.device.type}" + " VS" + " expected -> " + f"{self._torch_device.type}" + "\n" Journal.log(self.__class__.__name__, "_validate_selectors", error, LogType.EXCEP, throw_when_excep = True) def _validate_signal(self, signal: torch.Tensor, selector: torch.Tensor = None, name: str = "signal"): if self._debug_checks: signal_shape = signal.shape selector_shape = selector[0].shape if not (signal_shape[0] == selector_shape[0] and \ signal_shape[1] == selector_shape[1] and \ signal.device.type == self._torch_device.type and \ signal.dtype == self._torch_dtype): big_error = f"Mismatch in provided signal [{name}" + "] and/or selector \n" + \ "signal rows -> " + f"{signal_shape[0]}" + " VS" + " expected rows -> " + f"{selector_shape[0]}" + "\n" + \ "signal cols -> " + f"{signal_shape[1]}" + " VS" + " expected cols -> " + f"{selector_shape[1]}" + "\n" + \ "signal dtype -> " + f"{signal.dtype}" + " VS" + " expected -> " + f"{self._torch_dtype}" + "\n" + \ "signal device -> " + f"{signal.device.type}" + " VS" + " expected type -> " + f"{self._torch_device.type}" Journal.log(self.__class__.__name__, "_validate_signal", big_error, LogType.EXCEP, throw_when_excep = True) def _gen_selector(self, robot_indxs: torch.Tensor = None, jnt_indxs: torch.Tensor = None): if self._debug_checks: self._validate_selectors(robot_indxs=robot_indxs, jnt_indxs=jnt_indxs) # throws if not valid if robot_indxs is None: robot_indxs = self._all_robots_idxs if jnt_indxs is None: jnt_indxs = self._all_dofs_idxs return torch.meshgrid((robot_indxs, jnt_indxs), indexing="ij")
32,884
Python
40.157697
139
0.485282
AndrePatri/OmniRoboGym/omni_robo_gym/utils/terrains.py
# Copyright (C) 2023 Andrea Patrizi (AndrePatri, andreapatrizi1b6e6@gmail.com) # # This file is part of OmniRoboGym and distributed under the General Public License version 2 license. # # OmniRoboGym is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # OmniRoboGym is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with OmniRoboGym. If not, see <http://www.gnu.org/licenses/>. # import os, sys SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(SCRIPT_DIR) import numpy as np from omni_robo_gym.utils.terrain_utils import * from pxr import Usd class RlTerrains(): def __init__(self, stage: Usd.Stage): self._stage = stage def get_wave_terrain(self, terrain_size = 40, num_waves = 10, amplitude = 1, position = np.array([0.0, 0.0, 0.0])): # creates a terrain num_terrains = 1 terrain_width = terrain_size terrain_length = terrain_size horizontal_scale = 0.25 # [m] vertical_scale = 0.005 # [m] num_rows = int(terrain_width/horizontal_scale) num_cols = int(terrain_length/horizontal_scale) heightfield = np.zeros((num_terrains * num_rows, num_cols), dtype=np.int16) def new_sub_terrain(): return SubTerrain(width=num_rows, length=num_cols, vertical_scale=vertical_scale, horizontal_scale=horizontal_scale) heightfield[0:num_rows, :] = wave_terrain(new_sub_terrain(), num_waves=num_waves, amplitude=amplitude).height_field_raw vertices, triangles = convert_heightfield_to_trimesh(heightfield, horizontal_scale=horizontal_scale, vertical_scale=vertical_scale, slope_threshold=1.5) position = np.array([-terrain_width/2.0, terrain_length/2.0, 0]) + position orientation = np.array([0.70711, 0.0, 0.0, -0.70711]) add_terrain_to_stage(stage=self._stage, vertices=vertices, triangles=triangles, position=position, orientation=orientation) def get_sloped_terrain(self, terrain_size = 40, slope = -0.5, position = np.array([0.0, 0.0, 0.0])): # creates a terrain num_terrains = 1 terrain_width = terrain_size terrain_length = terrain_size horizontal_scale = 0.25 # [m] vertical_scale = 0.005 # [m] num_rows = int(terrain_width/horizontal_scale) num_cols = int(terrain_length/horizontal_scale) heightfield = np.zeros((num_terrains * num_rows, num_cols), dtype=np.int16) def new_sub_terrain(): return SubTerrain(width=num_rows, length=num_cols, vertical_scale=vertical_scale, horizontal_scale=horizontal_scale) heightfield[0:num_rows, :] = pyramid_sloped_terrain(new_sub_terrain(), slope=slope).height_field_raw vertices, triangles = convert_heightfield_to_trimesh(heightfield, horizontal_scale=horizontal_scale, vertical_scale=vertical_scale, slope_threshold=1.5) position = np.array([-terrain_width/2.0, terrain_length/2.0, 0]) + position orientation = np.array([0.70711, 0.0, 0.0, -0.70711]) add_terrain_to_stage(stage=self._stage, vertices=vertices, triangles=triangles, position=position, orientation=orientation) def get_stairs_terrain(self, terrain_size = 40, step_width = 0.75, step_height = -0.5, position = np.array([0.0, 0.0, 0.0])): # creates a terrain num_terrains = 1 terrain_width = terrain_size terrain_length = terrain_size horizontal_scale = 0.25 # [m] vertical_scale = 0.005 # [m] num_rows = int(terrain_width/horizontal_scale) num_cols = int(terrain_length/horizontal_scale) heightfield = np.zeros((num_terrains * num_rows, num_cols), dtype=np.int16) def new_sub_terrain(): return SubTerrain(width=num_rows, length=num_cols, vertical_scale=vertical_scale, horizontal_scale=horizontal_scale) heightfield[0:num_rows, :] = stairs_terrain(new_sub_terrain(), step_width=step_width, step_height=step_height).height_field_raw vertices, triangles = convert_heightfield_to_trimesh(heightfield, horizontal_scale=horizontal_scale, vertical_scale=vertical_scale, slope_threshold=1.5) position = np.array([-terrain_width/2.0, terrain_length/2.0, 0]) + position orientation = np.array([0.70711, 0.0, 0.0, -0.70711]) add_terrain_to_stage(stage=self._stage, vertices=vertices, triangles=triangles, position=position, orientation=orientation) def get_random_terrain(self, terrain_size = 40, min_height = -0.2, max_height = 0.2, step = 0.2, downsampled_scale=0.5, position = np.array([0.0, 0.0, 0.0])): # creates a terrain num_terrains = 1 terrain_width = terrain_size terrain_length = terrain_size horizontal_scale = 0.25 # [m] vertical_scale = 0.005 # [m] num_rows = int(terrain_width/horizontal_scale) num_cols = int(terrain_length/horizontal_scale) heightfield = np.zeros((num_terrains * num_rows, num_cols), dtype=np.int16) def new_sub_terrain(): return SubTerrain(width=num_rows, length=num_cols, vertical_scale=vertical_scale, horizontal_scale=horizontal_scale) heightfield[0:num_rows, :] = random_uniform_terrain(new_sub_terrain(), min_height=min_height, max_height=max_height, step=step, downsampled_scale=downsampled_scale).height_field_raw vertices, triangles = convert_heightfield_to_trimesh(heightfield, horizontal_scale=horizontal_scale, vertical_scale=vertical_scale, slope_threshold=1.5) position = np.array([-terrain_width/2.0, terrain_length/2.0, 0]) + position orientation = np.array([0.70711, 0.0, 0.0, -0.70711]) add_terrain_to_stage(stage=self._stage, vertices=vertices, triangles=triangles, position=position, orientation=orientation) def get_obstacles_terrain(self, terrain_size = 40.0, num_obs = 50, max_height = 0.5, min_size = 0.5, max_size = 5.0, position = np.array([0.0, 0.0, 0.0])): # create all available terrain types num_terains = 1 terrain_width = terrain_size terrain_length = terrain_size horizontal_scale = 0.25 # [m] vertical_scale = 0.005 # [m] num_rows = int(terrain_width/horizontal_scale) num_cols = int(terrain_length/horizontal_scale) heightfield = np.zeros((num_terains*num_rows, num_cols), dtype=np.int16) def new_sub_terrain(): return SubTerrain(width=num_rows, length=num_cols, vertical_scale=vertical_scale, horizontal_scale=horizontal_scale) heightfield[0:num_rows, :] = discrete_obstacles_terrain(new_sub_terrain(), max_height=max_height, min_size=min_size, max_size=max_size, num_rects=num_obs).height_field_raw vertices, triangles = convert_heightfield_to_trimesh(heightfield, horizontal_scale=horizontal_scale, vertical_scale=vertical_scale, slope_threshold=1.5) position = np.array([-terrain_width/2.0, terrain_length/2.0, 0]) + position orientation = np.array([0.70711, 0.0, 0.0, -0.70711]) add_terrain_to_stage(stage=self._stage, vertices=vertices, triangles=triangles, position=position, orientation=orientation) def post_reset(self): a = 1 def get_observations(self): pass def calculate_metrics(self) -> None: pass def is_done(self) -> None: pass
9,922
Python
36.730038
160
0.528926
AndrePatri/OmniRoboGym/docs/grid_cloner_bugfix/grid_cloner.py
# Copyright (c) 2022-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 typing import List, Union import numpy as np import omni.usd import torch from omni.isaac.cloner import Cloner from pxr import Gf, UsdGeom class GridCloner(Cloner): """ This is a specialized Cloner class that will automatically generate clones in a grid fashion. """ def __init__(self, spacing: float, num_per_row: int = -1): """ Args: spacing (float): Spacing between clones. num_per_row (int): Number of clones to place in a row. Defaults to sqrt(num_clones). """ self._spacing = spacing self._num_per_row = num_per_row Cloner.__init__(self) def clone( self, source_prim_path: str, prim_paths: List[str], position_offsets: np.ndarray = None, orientation_offsets: np.ndarray = None, replicate_physics: bool = False, base_env_path: str = None, root_path: str = None, copy_from_source: bool = False ): """ Creates clones in a grid fashion. Positions of clones are computed automatically. Args: source_prim_path (str): Path of source object. prim_paths (List[str]): List of destination paths. position_offsets (np.ndarray): Positions to be applied as local translations on top of computed clone position. Defaults to None, no offset will be applied. orientation_offsets (np.ndarray): Orientations to be applied as local rotations for each clone. Defaults to None, no offset will be applied. replicate_physics (bool): Uses omni.physics replication. This will replicate physics properties directly for paths beginning with root_path and skip physics parsing for anything under the base_env_path. base_env_path (str): Path to namespace for all environments. Required if replicate_physics=True and define_base_env() not called. root_path (str): Prefix path for each environment. Required if replicate_physics=True and generate_paths() not called. copy_from_source: (bool): Setting this to False will inherit all clones from the source prim; any changes made to the source prim will be reflected in the clones. Setting this to True will make copies of the source prim when creating new clones; changes to the source prim will not be reflected in clones. Defaults to False. Note that setting this to True will take longer to execute. Returns: positions (List): Computed positions of all clones. """ num_clones = len(prim_paths) self._num_per_row = int(np.sqrt(num_clones)) if self._num_per_row == -1 else self._num_per_row num_rows = np.ceil(num_clones / self._num_per_row) num_cols = np.ceil(num_clones / num_rows) row_offset = 0.5 * self._spacing * (num_rows - 1) col_offset = 0.5 * self._spacing * (num_cols - 1) stage = omni.usd.get_context().get_stage() positions = [] orientations = [] for i in range(num_clones): # compute transform row = i // num_cols col = i % num_cols x = row_offset - row * self._spacing y = col * self._spacing - col_offset up_axis = UsdGeom.GetStageUpAxis(stage) position = [x, y, 0] if up_axis == UsdGeom.Tokens.z else [x, 0, y] orientation = Gf.Quatd.GetIdentity() if position_offsets is not None: translation = position_offsets[i] + position else: translation = position if orientation_offsets is not None: orientation = ( Gf.Quatd(orientation_offsets[i][0].item(), Gf.Vec3d(orientation_offsets[i][1:].tolist())) * orientation ) else: orientation = [ orientation.GetReal(), orientation.GetImaginary()[0], orientation.GetImaginary()[1], orientation.GetImaginary()[2], ] positions.append(translation) orientations.append(orientation) super().clone( source_prim_path=source_prim_path, prim_paths=prim_paths, positions=positions, orientations=orientations, replicate_physics=replicate_physics, base_env_path=base_env_path, root_path=root_path, copy_from_source=copy_from_source, ) return positions
5,073
Python
40.590164
246
0.606742
AndrePatri/OmniRoboGym/docs/contact_sensor_bugfix/contact_sensor.py
# Copyright (c) 2021-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 simulation_app = SimulationApp({"headless": False}) import argparse import sys import carb import numpy as np from omni.isaac.core import World from omni.isaac.core.articulations import Articulation from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage from omni.isaac.sensor import ContactSensor from omni.isaac.cloner import GridCloner import omni.isaac.core.utils.prims as prim_utils parser = argparse.ArgumentParser() parser.add_argument("--test", default=False, action="store_true", help="Run in test mode") args, unknown = parser.parse_known_args() assets_root_path = get_assets_root_path() if assets_root_path is None: carb.log_error("Could not find Isaac Sim assets folder") simulation_app.close() sys.exit() my_world = World(stage_units_in_meters=1.0) my_world.scene.add_default_ground_plane() asset_path = assets_root_path + "/Isaac/Robots/Ant/ant.usd" add_reference_to_stage(usd_path=asset_path, prim_path="/World/envs/env_0/Ant") ant = my_world.scene.add(Articulation(prim_path="/World/envs/env_0/Ant/torso", name="ant", translation=np.array([0, 0, 1.5]))) ant_foot_prim_names = ["right_back_foot", "left_back_foot", "front_right_foot", "front_left_foot"] translations = np.array( [[0.38202, -0.40354, -0.0887], [-0.4, -0.40354, -0.0887], [-0.4, 0.4, -0.0887], [0.4, 0.4, -0.0887]] ) # moving def prim # move_prim(robot_prim_path_default, # from # robot_base_prim_path) # to num_envs = 3 env_ns = "/World/envs" env_spacing = 15 # [m] template_env_ns = env_ns + "/env_0" cloner = GridCloner(spacing=env_spacing) cloner.define_base_env(env_ns) envs_prim_paths = cloner.generate_paths(env_ns + "/env", num_envs) cloner.clone( source_prim_path=template_env_ns, prim_paths=envs_prim_paths, replicate_physics=True, position_offsets = None ) ant_sensors = [] for i in range(4): ant_sensors.append( my_world.scene.add( ContactSensor( prim_path="/World/envs/env_0/Ant/" + ant_foot_prim_names[i] + "/contact_sensor", name="ant_contact_sensor_{}".format(i), min_threshold=0, max_threshold=10000000, radius=0.1, translation=translations[i], ) ) ) ant_sensors[0].add_raw_contact_data_to_frame() ant_sensors2 = [] for i in range(4): ant_sensors2.append( my_world.scene.add( ContactSensor( prim_path="/World/envs/env_1/Ant/" + ant_foot_prim_names[i] + "/contact_sensor", name="ant_contact_sensor2_{}".format(i), min_threshold=0, max_threshold=10000000, radius=0.1, translation=translations[i], ) ) ) ant_sensors2[0].add_raw_contact_data_to_frame() my_world.reset() while simulation_app.is_running(): my_world.step(render=True) if my_world.is_playing(): print(ant_sensors2[0].get_current_frame()) if my_world.current_time_step_index == 0: my_world.reset() simulation_app.close()
3,638
Python
30.370689
126
0.657779
AndrePatri/OmniRoboGym/docs/sim_substepping_reset_issue/test_substepping_when_reset.py
# Copyright (c) 2021-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. # import numpy as np import torch def get_device(sim_params): if "sim_device" in sim_params: device = sim_params["sim_device"] else: device = "cpu" physics_device_id = carb.settings.get_settings().get_as_int("/physics/cudaDevice") gpu_id = 0 if physics_device_id < 0 else physics_device_id if sim_params and "use_gpu_pipeline" in sim_params: # GPU pipeline must use GPU simulation if sim_params["use_gpu_pipeline"]: device = "cuda:" + str(gpu_id) elif sim_params and "use_gpu" in sim_params: if sim_params["use_gpu"]: device = "cuda:" + str(gpu_id) return device def sim_parameters(): # simulation parameters sim_params = {} # device settings sim_params["use_gpu_pipeline"] = True # disabling gpu pipeline is necessary to be able # to retrieve some quantities from the simulator which, otherwise, would have random values sim_params["use_gpu"] = True # does this actually do anything? if sim_params["use_gpu_pipeline"]: sim_params["device"] = "cuda" else: sim_params["device"] = "cpu" device = sim_params["device"] # sim_params["dt"] = 1.0/100.0 # physics_dt? sim_params["physics_dt"] = 1.0/400.0 # physics_dt? sim_params["rendering_dt"] = sim_params["physics_dt"] sim_params["substeps"] = 1 # number of physics steps to be taken for for each rendering step sim_params["gravity"] = np.array([0.0, 0.0, -9.81]) sim_params["enable_scene_query_support"] = False sim_params["use_fabric"] = True # Enable/disable reading of physics buffers directly. Default is True. sim_params["replicate_physics"] = True # sim_params["worker_thread_count"] = 4 sim_params["solver_type"] = 1 # 0: PGS, 1:TGS, defaults to TGS. PGS faster but TGS more stable sim_params["enable_stabilization"] = True # sim_params["bounce_threshold_velocity"] = 0.2 # sim_params["friction_offset_threshold"] = 0.04 # sim_params["friction_correlation_distance"] = 0.025 # sim_params["enable_sleeping"] = True # Per-actor settings ( can override in actor_options ) sim_params["solver_position_iteration_count"] = 4 # defaults to 4 sim_params["solver_velocity_iteration_count"] = 1 # defaults to 1 sim_params["sleep_threshold"] = 0.0 # Mass-normalized kinetic energy threshold below which an actor may go to sleep. # Allowed range [0, max_float). sim_params["stabilization_threshold"] = 1e-5 # Per-body settings ( can override in actor_options ) # sim_params["enable_gyroscopic_forces"] = True # sim_params["density"] = 1000 # density to be used for bodies that do not specify mass or density # sim_params["max_depenetration_velocity"] = 100.0 # sim_params["solver_velocity_iteration_count"] = 1 # GPU buffers settings # sim_params["gpu_max_rigid_contact_count"] = 512 * 1024 # sim_params["gpu_max_rigid_patch_count"] = 80 * 1024 # sim_params["gpu_found_lost_pairs_capacity"] = 1024 # sim_params["gpu_found_lost_aggregate_pairs_capacity"] = 1024 # sim_params["gpu_total_aggregate_pairs_capacity"] = 1024 # sim_params["gpu_max_soft_body_contacts"] = 1024 * 1024 # sim_params["gpu_max_particle_contacts"] = 1024 * 1024 # sim_params["gpu_heap_capacity"] = 64 * 1024 * 1024 # sim_params["gpu_temp_buffer_capacity"] = 16 * 1024 * 1024 # sim_params["gpu_max_num_partitions"] = 8 return sim_params def reset_state(art_view, idxs: torch.Tensor): # root q art_view.set_world_poses(positions = root_p_default[idxs, :], orientations=root_q_default[idxs, :], indices = idxs) # jnts q art_view.set_joint_positions(positions = jnts_q_default[idxs, :], indices = idxs) # root v and omega art_view.set_joint_velocities(velocities = jnts_v_default[idxs, :], indices = idxs) # jnts v concatenated_vel = torch.cat((root_v_default[idxs, :], root_omega_default[idxs, :]), dim=1) art_view.set_velocities(velocities = concatenated_vel, indices = idxs) # jnts eff art_view.set_joint_efforts(efforts = jnts_eff_default[idxs, :], indices = idxs) def get_robot_state( art_view): pose = art_view.get_world_poses( clone = True) # tuple: (pos, quat) # root p (measured, previous, default) root_p = pose[0] # root q (measured, previous, default) root_q = pose[1] # root orientation # jnt q (measured, previous, default) jnts_q = art_view.get_joint_positions( clone = True) # joint positions # root v (measured, default) root_v= art_view.get_linear_velocities( clone = True) # root lin. velocity # root omega (measured, default) root_omega = art_view.get_angular_velocities( clone = True) # root ang. velocity # joints v (measured, default) jnts_v = art_view.get_joint_velocities( clone = True) # joint velocities jnts_eff = art_view.get_measured_joint_efforts(clone = True) return root_p, root_q, jnts_q, root_v, root_omega, jnts_v, jnts_eff from omni.isaac.kit import SimulationApp import carb import os experience = f'{os.environ["EXP_PATH"]}/omni.isaac.sim.python.omnirobogym.headless.kit' sim_params = sim_parameters() num_envs = 2 headless = True simulation_app = SimulationApp({"headless": headless, "physics_gpu": 0}, experience=experience) from omni.isaac.core import World from omni.isaac.core.articulations import ArticulationView from omni.importer.urdf import _urdf # urdf import config import_config = _urdf.ImportConfig() import_config.merge_fixed_joints = True import_config.import_inertia_tensor = True import_config.fix_base = False import_config.self_collision = False my_world = World(stage_units_in_meters=1.0, physics_dt=sim_params["physics_dt"], rendering_dt=sim_params["rendering_dt"], backend="torch", device=str(get_device(sim_params=sim_params)), physics_prim_path="/physicsScene", set_defaults = False, sim_params=sim_params) # create initial robot import omni.isaac.core.utils.prims as prim_utils # create GridCloner instance env_ns = "/World/envs" template_env_ns = env_ns + "/env" # a single env. may contain multiple robots base_env = template_env_ns + "_0" base_robot_path = base_env + "/panda" # get path to resource from omni.isaac.core.utils.extensions import get_extension_path_from_name extension_path = get_extension_path_from_name("omni.importer.urdf") # import URDF at default prim path import omni.kit success, robot_prim_path_default = omni.kit.commands.execute( "URDFParseAndImportFile", urdf_path=extension_path + "/data/urdf/robots/franka_description/robots/panda_arm.urdf", import_config=import_config, ) # moving default prim to base prim path (for potential cloning) from omni.isaac.core.utils.prims import move_prim prim_utils.define_prim(base_env) move_prim(robot_prim_path_default, # from base_robot_path) # to # cloning from omni.isaac.cloner import GridCloner cloner = GridCloner(spacing=6) _envs_prim_paths = cloner.generate_paths(template_env_ns, num_envs) position_offsets = np.array([[0.0, 0.0, 0.6]] * num_envs) cloner.clone( source_prim_path=base_env, prim_paths=_envs_prim_paths, base_env_path=base_env, position_offsets=position_offsets, replicate_physics=True ) # Prim paths structure: # World/envs/env_0/panda/panda_link0/... # this only in 2023.1.0 art_view = ArticulationView(name = "Panda" + "ArtView", prim_paths_expr = env_ns + "/env_.*"+ "/panda/panda_link0", reset_xform_properties=False # required as per doc. when cloning ) # moreover, robots are not cloned at different locations my_world.scene.add(art_view) ground_plane_prim_path = "/World/terrain" my_world.scene.add_default_ground_plane(z_position=0, name="terrain", prim_path= ground_plane_prim_path, static_friction=0.5, dynamic_friction=0.5, restitution=0.8) cloner.filter_collisions(physicsscene_path = my_world.get_physics_context().prim_path, collision_root_path = "/World/collisions", prim_paths=_envs_prim_paths, global_paths=[ground_plane_prim_path] # can collide with these prims ) my_world.reset() # init default state from measurements root_p, root_q, jnts_q, root_v, \ root_omega, jnts_v, jnts_eff = get_robot_state(art_view) root_p_default = torch.clone(root_p) root_q_default = torch.clone(root_q) jnts_q_default = torch.clone(jnts_q) jnts_v_default = torch.clone(jnts_v) root_omega_default = torch.clone(root_omega) root_v_default = torch.clone(root_v) jnts_eff_default = torch.clone(jnts_eff).zero_() # default values root_p_default[:, 0] = 0 root_p_default[:, 1] = 0 root_p_default[:, 2] = 0.5 root_q_default[:, 0] = 0.0 root_q_default[:, 1] = 0.0 root_q_default[:, 2] = 0.0 root_q_default[:, 3] = 1.0 jnts_q_default[:, :] = 1.0 jnts_v_default[:, :] = 0.0 root_omega_default[:, :] = 0.0 root_v_default[:, :] = 0.0 no_gains = torch.zeros((num_envs, jnts_eff_default.shape[1]), device = get_device(sim_params), dtype=torch.float32) art_view.set_gains(kps = no_gains, kds = no_gains) print("Extension path: " + str(extension_path)) print("Prim paths: " + str(art_view.prim_paths)) reset_ever_n_steps = 100 just_reset = False for i in range(0, 1000): if ((i + 1) % reset_ever_n_steps) == 0: print("resetting to default") reset_state(art_view, torch.tensor([0], dtype=torch.int)) just_reset = True my_world.step() # retrieve state root_p, root_q, jnts_q, root_v, \ root_omega, jnts_v, jnts_eff = get_robot_state(art_view) # if just_reset: # check we hace reset correcty print("measured") print(jnts_q) print("default") print(jnts_q_default) simulation_app.close()
11,081
Python
34.06962
120
0.624222
abizovnuralem/go2_omniverse/terrain_cfg.py
# Copyright (c) 2024, RoboVerse community # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from terrain_generator_cfg import TerrainGeneratorCfg import omni.isaac.orbit.terrains as terrain_gen ROUGH_TERRAINS_CFG = TerrainGeneratorCfg( size=(8.0, 8.0), border_width=0.0, num_rows=1, num_cols=2, horizontal_scale=0.1, vertical_scale=0.005, slope_threshold=0.75, use_cache=False, sub_terrains={ "pyramid_stairs": terrain_gen.MeshPyramidStairsTerrainCfg( proportion=0.2, step_height_range=(0.05, 0.23), step_width=0.3, platform_width=3.0, border_width=1.0, holes=False, ), "pyramid_stairs_inv": terrain_gen.MeshInvertedPyramidStairsTerrainCfg( proportion=0.2, step_height_range=(0.05, 0.23), step_width=0.3, platform_width=3.0, border_width=1.0, holes=False, ), }, )
2,217
Python
38.607142
80
0.700947
abizovnuralem/go2_omniverse/agent_cfg.py
# Copyright (c) 2024, RoboVerse community # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. unitree_go2_agent_cfg = { 'seed': 42, 'device': 'cuda', 'num_steps_per_env': 24, 'max_iterations': 15000, 'empirical_normalization': False, 'policy': { 'class_name': 'ActorCritic', 'init_noise_std': 1.0, 'actor_hidden_dims': [512, 256, 128], 'critic_hidden_dims': [512, 256, 128], 'activation': 'elu' }, 'algorithm': { 'class_name': 'PPO', 'value_loss_coef': 1.0, 'use_clipped_value_loss': True, 'clip_param': 0.2, 'entropy_coef': 0.01, 'num_learning_epochs': 5, 'num_mini_batches': 4, 'learning_rate': 0.001, 'schedule': 'adaptive', 'gamma': 0.99, 'lam': 0.95, 'desired_kl': 0.01, 'max_grad_norm': 1.0 }, 'save_interval': 50, 'experiment_name': 'unitree_go2_rough', 'run_name': '', 'logger': 'tensorboard', 'neptune_project': 'orbit', 'wandb_project': 'orbit', 'resume': False, 'load_run': '.*', 'load_checkpoint': 'model_.*.pt' }
2,562
Python
40.338709
80
0.613193
abizovnuralem/go2_omniverse/main.py
# Copyright (c) 2024, RoboVerse community # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Script to play a checkpoint if an RL agent from RSL-RL.""" from __future__ import annotations """Launch Isaac Sim Simulator first.""" import argparse from omni.isaac.orbit.app import AppLauncher # local imports import cli_args # isort: skip # add argparse arguments parser = argparse.ArgumentParser(description="Train an RL agent with RSL-RL.") parser.add_argument("--cpu", action="store_true", default=False, help="Use CPU pipeline.") parser.add_argument( "--disable_fabric", action="store_true", default=False, help="Disable fabric and use USD I/O operations." ) parser.add_argument("--num_envs", type=int, default=1, help="Number of environments to simulate.") parser.add_argument("--task", type=str, default="Isaac-Velocity-Rough-Unitree-Go2-v0", help="Name of the task.") parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment") # append RSL-RL cli arguments cli_args.add_rsl_rl_args(parser) # append AppLauncher cli args AppLauncher.add_app_launcher_args(parser) args_cli = parser.parse_args() # launch omniverse app app_launcher = AppLauncher(args_cli) simulation_app = app_launcher.app import omni ext_manager = omni.kit.app.get_app().get_extension_manager() ext_manager.set_extension_enabled_immediate("omni.isaac.ros2_bridge", True) """Rest everything follows.""" import os import math import gymnasium as gym import torch import carb import usdrt.Sdf from omni.isaac.orbit_tasks.utils import get_checkpoint_path from omni.isaac.orbit_tasks.utils.wrappers.rsl_rl import ( RslRlOnPolicyRunnerCfg, RslRlVecEnvWrapper ) from omni.isaac.orbit.utils import configclass from omni.isaac.orbit_assets.unitree import UNITREE_GO2_CFG from omni.isaac.orbit.envs import RLTaskEnvCfg import omni.isaac.orbit.sim as sim_utils from omni.isaac.orbit.assets import ArticulationCfg, AssetBaseCfg from omni.isaac.orbit.managers import CurriculumTermCfg as CurrTerm from omni.isaac.orbit.managers import EventTermCfg as EventTerm from omni.isaac.orbit.managers import ObservationGroupCfg as ObsGroup from omni.isaac.orbit.managers import ObservationTermCfg as ObsTerm from omni.isaac.orbit.managers import RewardTermCfg as RewTerm from omni.isaac.orbit.managers import SceneEntityCfg from omni.isaac.orbit.managers import TerminationTermCfg as DoneTerm from omni.isaac.orbit.scene import InteractiveSceneCfg from omni.isaac.orbit.sensors import ContactSensorCfg, RayCasterCfg, patterns, CameraCfg from omni.isaac.orbit.terrains import TerrainImporterCfg from omni.isaac.orbit.utils import configclass from omni.isaac.orbit.utils.noise import AdditiveUniformNoiseCfg as Unoise import omni.isaac.orbit_tasks.locomotion.velocity.mdp as mdp import omni.appwindow # Contains handle to keyboard from rsl_rl.runners import OnPolicyRunner from typing import Literal from dataclasses import MISSING from omnigraph import create_front_cam_omnigraph from agent_cfg import unitree_go2_agent_cfg from terrain_cfg import ROUGH_TERRAINS_CFG base_command = [0, 0, 0] @configclass class MySceneCfg(InteractiveSceneCfg): """Configuration for the terrain scene with a legged robot.""" # ground terrain terrain = TerrainImporterCfg( prim_path="/World/ground", terrain_type="generator", terrain_generator=ROUGH_TERRAINS_CFG, max_init_terrain_level=5, collision_group=-1, physics_material=sim_utils.RigidBodyMaterialCfg( friction_combine_mode="multiply", restitution_combine_mode="multiply", static_friction=1.0, dynamic_friction=1.0, ), visual_material=sim_utils.MdlFileCfg( mdl_path="{NVIDIA_NUCLEUS_DIR}/Materials/Base/Architecture/Shingles_01.mdl", project_uvw=True, ), debug_vis=False, ) # robots robot: ArticulationCfg = MISSING # sensors camera = CameraCfg( prim_path="{ENV_REGEX_NS}/Robot/base/front_cam", update_period=0.1, height=480, width=640, data_types=["rgb", "distance_to_image_plane"], spawn=sim_utils.PinholeCameraCfg( focal_length=24.0, focus_distance=400.0, horizontal_aperture=20.955, clipping_range=(0.1, 1.0e5) ), offset=CameraCfg.OffsetCfg(pos=(0.510, 0.0, 0.015), rot=(0.5, -0.5, 0.5, -0.5), convention="ros"), ) height_scanner = RayCasterCfg( prim_path="{ENV_REGEX_NS}/Robot/base", offset=RayCasterCfg.OffsetCfg(pos=(0.0, 0.0, 20.0)), attach_yaw_only=True, pattern_cfg=patterns.GridPatternCfg(resolution=0.1, size=[1.6, 1.0]), debug_vis=False, mesh_prim_paths=["/World/ground"], ) contact_forces = ContactSensorCfg(prim_path="{ENV_REGEX_NS}/Robot/.*", history_length=3, track_air_time=True) # lights light = AssetBaseCfg( prim_path="/World/light", spawn=sim_utils.DistantLightCfg(color=(0.75, 0.75, 0.75), intensity=3000.0), ) sky_light = AssetBaseCfg( prim_path="/World/skyLight", spawn=sim_utils.DomeLightCfg(color=(0.13, 0.13, 0.13), intensity=1000.0), ) def constant_commands(env: RLTaskEnvCfg) -> torch.Tensor: global base_command """The generated command from the command generator.""" return torch.tensor([base_command], device=env.device).repeat(env.num_envs, 1) @configclass class ObservationsCfg: """Observation specifications for the MDP.""" @configclass class PolicyCfg(ObsGroup): """Observations for policy group.""" # observation terms (order preserved) base_lin_vel = ObsTerm(func=mdp.base_lin_vel) base_ang_vel = ObsTerm(func=mdp.base_ang_vel) projected_gravity = ObsTerm( func=mdp.projected_gravity, noise=Unoise(n_min=-0.05, n_max=0.05), ) velocity_commands = ObsTerm(func=constant_commands) joint_pos = ObsTerm(func=mdp.joint_pos_rel) joint_vel = ObsTerm(func=mdp.joint_vel_rel) actions = ObsTerm(func=mdp.last_action) height_scan = ObsTerm( func=mdp.height_scan, params={"sensor_cfg": SceneEntityCfg("height_scanner")}, clip=(-1.0, 1.0), ) def __post_init__(self): self.enable_corruption = True self.concatenate_terms = True # observation groups policy: PolicyCfg = PolicyCfg() @configclass class ActionsCfg: """Action specifications for the MDP.""" joint_pos = mdp.JointPositionActionCfg(asset_name="robot", joint_names=[".*"], scale=0.5, use_default_offset=True) @configclass class CommandsCfg: """Command specifications for the MDP.""" base_velocity = mdp.UniformVelocityCommandCfg( asset_name="robot", resampling_time_range=(0.0, 0.0), rel_standing_envs=0.02, rel_heading_envs=1.0, heading_command=True, heading_control_stiffness=0.5, debug_vis=True, ranges=mdp.UniformVelocityCommandCfg.Ranges( lin_vel_x=(0.0, 0.0), lin_vel_y=(0.0, 0.0), ang_vel_z=(0.0, 0.0), heading=(0, 0) ), ) @configclass class RewardsCfg: """Reward terms for the MDP.""" # -- task track_lin_vel_xy_exp = RewTerm( func=mdp.track_lin_vel_xy_exp, weight=1.0, params={"command_name": "base_velocity", "std": math.sqrt(0.25)} ) track_ang_vel_z_exp = RewTerm( func=mdp.track_ang_vel_z_exp, weight=0.5, params={"command_name": "base_velocity", "std": math.sqrt(0.25)} ) # -- penalties lin_vel_z_l2 = RewTerm(func=mdp.lin_vel_z_l2, weight=-2.0) ang_vel_xy_l2 = RewTerm(func=mdp.ang_vel_xy_l2, weight=-0.05) dof_torques_l2 = RewTerm(func=mdp.joint_torques_l2, weight=-1.0e-5) dof_acc_l2 = RewTerm(func=mdp.joint_acc_l2, weight=-2.5e-7) action_rate_l2 = RewTerm(func=mdp.action_rate_l2, weight=-0.01) feet_air_time = RewTerm( func=mdp.feet_air_time, weight=0.125, params={ "sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*FOOT"), "command_name": "base_velocity", "threshold": 0.5, }, ) undesired_contacts = RewTerm( func=mdp.undesired_contacts, weight=-1.0, params={"sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*THIGH"), "threshold": 1.0}, ) # -- optional penalties flat_orientation_l2 = RewTerm(func=mdp.flat_orientation_l2, weight=0.0) dof_pos_limits = RewTerm(func=mdp.joint_pos_limits, weight=0.0) @configclass class TerminationsCfg: """Termination terms for the MDP.""" time_out = DoneTerm(func=mdp.time_out, time_out=True) base_contact = DoneTerm( func=mdp.illegal_contact, params={"sensor_cfg": SceneEntityCfg("contact_forces", body_names="base"), "threshold": 1.0}, ) @configclass class EventCfg: """Configuration for events.""" # startup physics_material = EventTerm( func=mdp.randomize_rigid_body_material, mode="startup", params={ "asset_cfg": SceneEntityCfg("robot", body_names=".*"), "static_friction_range": (0.8, 0.8), "dynamic_friction_range": (0.6, 0.6), "restitution_range": (0.0, 0.0), "num_buckets": 64, }, ) @configclass class CurriculumCfg: """Curriculum terms for the MDP.""" terrain_levels = CurrTerm(func=mdp.terrain_levels_vel) @configclass class ViewerCfg: """Configuration of the scene viewport camera.""" eye: tuple[float, float, float] = (7.5, 7.5, 7.5) lookat: tuple[float, float, float] = (0.0, 0.0, 0.0) cam_prim_path: str = "/OmniverseKit_Persp" resolution: tuple[int, int] = (1920, 1080) origin_type: Literal["world", "env", "asset_root"] = "world" env_index: int = 0 asset_name: str | None = None @configclass class LocomotionVelocityRoughEnvCfg(RLTaskEnvCfg): """Configuration for the locomotion velocity-tracking environment.""" # Scene settings scene: MySceneCfg = MySceneCfg(num_envs=4096, env_spacing=2.5) viewer: ViewerCfg = ViewerCfg() # Basic settings observations: ObservationsCfg = ObservationsCfg() actions: ActionsCfg = ActionsCfg() commands: CommandsCfg = CommandsCfg() # MDP settings rewards: RewardsCfg = RewardsCfg() terminations: TerminationsCfg = TerminationsCfg() events: EventCfg = EventCfg() curriculum: CurriculumCfg = CurriculumCfg() def __post_init__(self): """Post initialization.""" # general settings self.decimation = 4 self.episode_length_s = 20.0 # simulation settings self.sim.dt = 0.005 self.sim.disable_contact_processing = True self.sim.physics_material = self.scene.terrain.physics_material # update sensor update periods # we tick all the sensors based on the smallest update period (physics update period) if self.scene.height_scanner is not None: self.scene.height_scanner.update_period = self.decimation * self.sim.dt if self.scene.contact_forces is not None: self.scene.contact_forces.update_period = self.sim.dt # check if terrain levels curriculum is enabled - if so, enable curriculum for terrain generator # this generates terrains with increasing difficulty and is useful for training if getattr(self.curriculum, "terrain_levels", None) is not None: if self.scene.terrain.terrain_generator is not None: self.scene.terrain.terrain_generator.curriculum = True else: if self.scene.terrain.terrain_generator is not None: self.scene.terrain.terrain_generator.curriculum = False @configclass class UnitreeGo2RoughEnvCfg(LocomotionVelocityRoughEnvCfg): def __post_init__(self): # post init of parent super().__post_init__() self.scene.robot = UNITREE_GO2_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") self.scene.height_scanner.prim_path = "{ENV_REGEX_NS}/Robot/base" # reduce action scale self.actions.joint_pos.scale = 0.25 # rewards self.rewards.feet_air_time.params["sensor_cfg"].body_names = ".*_foot" self.rewards.feet_air_time.weight = 0.01 self.rewards.undesired_contacts = None self.rewards.dof_torques_l2.weight = -0.0002 self.rewards.track_lin_vel_xy_exp.weight = 1.5 self.rewards.track_ang_vel_z_exp.weight = 0.75 self.rewards.dof_acc_l2.weight = -2.5e-7 # terminations self.terminations.base_contact.params["sensor_cfg"].body_names = "base" #create ros2 camera stream omnigraph create_front_cam_omnigraph() def sub_keyboard_event(event, *args, **kwargs) -> bool: global base_command if event.type == carb.input.KeyboardEventType.KEY_PRESS: if event.input.name == 'W': base_command = [1, 0, 0] if event.input.name == 'S': base_command = [-1, 0, 0] if event.input.name == 'A': base_command = [0, 1, 0] if event.input.name == 'D': base_command = [0, -1, 0] if event.input.name == 'Q': base_command = [0, 0, 1] if event.input.name == 'E': base_command = [0, 0, -1] elif event.type == carb.input.KeyboardEventType.KEY_RELEASE: base_command = [0, 0, 0] return True def main(): # acquire input interface _input = carb.input.acquire_input_interface() _appwindow = omni.appwindow.get_default_app_window() _keyboard = _appwindow.get_keyboard() _sub_keyboard = _input.subscribe_to_keyboard_events(_keyboard, sub_keyboard_event) """Play with RSL-RL agent.""" # parse configuration env_cfg = UnitreeGo2RoughEnvCfg() env_cfg.scene.num_envs = 1 agent_cfg: RslRlOnPolicyRunnerCfg = unitree_go2_agent_cfg # create isaac environment env = gym.make(args_cli.task, cfg=env_cfg) # wrap around environment for rsl-rl env = RslRlVecEnvWrapper(env) # specify directory for logging experiments log_root_path = os.path.join("logs", "rsl_rl", agent_cfg["experiment_name"]) log_root_path = os.path.abspath(log_root_path) print(f"[INFO] Loading experiment from directory: {log_root_path}") resume_path = get_checkpoint_path(log_root_path, agent_cfg["load_run"], agent_cfg["load_checkpoint"]) print(f"[INFO]: Loading model checkpoint from: {resume_path}") # load previously trained model ppo_runner = OnPolicyRunner(env, agent_cfg, log_dir=None, device=agent_cfg["device"]) ppo_runner.load(resume_path) print(f"[INFO]: Loading model checkpoint from: {resume_path}") # obtain the trained policy for inference policy = ppo_runner.get_inference_policy(device=env.unwrapped.device) # reset environment obs, _ = env.get_observations() # simulate environment while simulation_app.is_running(): # run everything in inference mode with torch.inference_mode(): # agent stepping actions = policy(obs) # env stepping obs, _, _, _ = env.step(actions) # close the simulator env.close() if __name__ == "__main__": # run the main function main() # close sim app simulation_app.close()
16,627
Python
34.529914
118
0.669333
abizovnuralem/go2_omniverse/omnigraph.py
# Copyright (c) 2024, RoboVerse community # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import omni import omni.graph.core as og def create_front_cam_omnigraph(): """Define the OmniGraph for the Isaac Sim environment.""" keys = og.Controller.Keys graph_path = "/ROS_" + "front_cam" (camera_graph, _, _, _) = og.Controller.edit( { "graph_path": graph_path, "evaluator_name": "execution", "pipeline_stage": og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION, }, { keys.CREATE_NODES: [ ("OnPlaybackTick", "omni.graph.action.OnPlaybackTick"), ("IsaacCreateRenderProduct", "omni.isaac.core_nodes.IsaacCreateRenderProduct"), ("ROS2CameraHelper", "omni.isaac.ros2_bridge.ROS2CameraHelper"), ], keys.SET_VALUES: [ ("IsaacCreateRenderProduct.inputs:cameraPrim", "/World/envs/env_0/Robot/base/front_cam"), ("IsaacCreateRenderProduct.inputs:enabled", True), ("ROS2CameraHelper.inputs:type", "rgb"), ("ROS2CameraHelper.inputs:topicName", "unitree_go2/front_cam/rgb"), ("ROS2CameraHelper.inputs:frameId", "unitree_go2"), ], keys.CONNECT: [ ("OnPlaybackTick.outputs:tick", "IsaacCreateRenderProduct.inputs:execIn"), ("IsaacCreateRenderProduct.outputs:execOut", "ROS2CameraHelper.inputs:execIn"), ("IsaacCreateRenderProduct.outputs:renderProductPath", "ROS2CameraHelper.inputs:renderProductPath"), ], }, )
2,912
Python
45.238095
116
0.67239
An-u-rag/synthetic-visual-dataset-generation/main.py
import numpy as np import os import json import os # class_name_to_id_mapping = {"Cow": 0, # "Chicken": 1, # "Sheep": 2, # "Goat": 3, # "Pig": 4} class_name_to_id_mapping = {"cow_1": 0, "cow_2": 1, "cow_3": 2, "cow_4": 3, "cow_5": 4, "pig_clean": 5, "pig_dirty": 6 } # Convert the info dict to the required yolo format and write it to disk def convert_to_yolov5(info_dict, image_file, name_file): print_buffer = [] print(info_dict) data = np.load(info_dict) # image_file = Image.open(image_file) image_w, image_h = image_file.size class_id = {} with open(name_file, 'r') as info_name: data_name = json.load(info_name) # print(data_name) for k, v in data_name.items(): class_id[k] = class_name_to_id_mapping[v["class"]] # for values in data_name.values(): # # print(values) # class_id[values["class"]] = class_name_to_id_mapping[values["class"]] # class_id[class_name_to_id_mapping[values["class"]]] = values["class"] # class_id.append(class_name_to_id_mapping[values["class"]]) # class_id = class_name_to_id_mapping[values["name"]] # print(class_id) # counter = 0 # For each bounding box for b in data: # Transform the bbox co-ordinates as per the format required by YOLO v5 b_center_x = (b[1] + b[3]) / 2 b_center_y = (b[2] + b[4]) / 2 b_width = (b[3] - b[1]) b_height = (b[4] - b[2]) # Normalise the co-ordinates by the dimensions of the image b_center_x /= image_w b_center_y /= image_h b_width /= image_w b_height /= image_h # print(counter) print(class_id) # Write the bbox details to the file print(class_id.get(str(b[0]))) print_buffer.append( "{} {:.3f} {:.3f} {:.3f} {:.3f}".format(class_id.get(str(b[0])), b_center_x, b_center_y, b_width, b_height)) # counter += 1 # print(print_buffer) # Name of the file which we have to save path_pic = "C:/Users/xyche/Downloads/dataset" save_file_name = os.path.join(path_pic, info_dict.replace("bounding_box_2d_tight_", "rgb_").replace("npy", "txt")) # Save the annotation to disk print("\n".join(print_buffer), file=open(save_file_name, "w")) import os from PIL import Image # Convert and save the annotations # path_label = "/content/RenderProduct_Replicator/bounding_box_2d_loose" path_pic = "C:/Users/xyche/Downloads/dataset" datanames = os.listdir(path_pic) for i in datanames: if os.path.splitext(i)[1] == '.npy': # np.load("../"+info_dict) # info_dict = open(os.path.join(path_pic,i), "rb") info_dict = os.path.join(path_pic, i) image_file = i.replace("bounding_box_2d_tight_", "rgb_").replace("npy", "png") # os.listdir(path_pic) image_file = Image.open(os.path.join(path_pic, image_file)) info_name = i.replace("bounding_box_2d_tight_", "bounding_box_2d_tight_labels_").replace("npy", "json") name_file = os.path.join(path_pic, info_name) convert_to_yolov5(info_dict, image_file, name_file) # print(os.listdir(path_pic)) annotations = [os.path.join(path_pic, x) for x in os.listdir(path_pic) if x[-3:] == "txt" and x != 'metadata.txt'] # print(len(annotations)) from sklearn.model_selection import train_test_split # Read images and annotations images = [os.path.join(path_pic, x) for x in os.listdir(path_pic) if x[-3:] == "png"] # print(len(images)) # datanames = os.listdir(path_pic) annotations = [os.path.join(path_pic, x) for x in os.listdir(path_pic) if x[-3:] == "txt" and x != 'metadata.txt'] # print(len(annotations)) images.sort() annotations.sort() # for i in annotations: # update_annotations = i.replace("bounding_box_2d_loose_", "rgb_").replace("txt", "png") # if update_annotations not in images: # print(update_annotations) # Split the dataset into train-valid-test splits train_images, val_images, train_annotations, val_annotations = train_test_split(images, annotations, test_size=0.2, random_state=1) val_images, test_images, val_annotations, test_annotations = train_test_split(val_images, val_annotations, test_size=0.5, random_state=1) path1 = 'C:/Users/xyche/Downloads/dataset' os.mkdir(path1 + '/images') os.mkdir(path1 + '/labels') file_name = ['/train', '/val', '/test'] path2 = 'C:/Users/xyche/Downloads/dataset/images' for name in file_name: os.mkdir(path2 + name) path3 = 'C:/Users/xyche/Downloads/dataset/labels' for name in file_name: os.mkdir(path3 + name) import shutil # Utility function to move images def move_files_to_folder(list_of_files, destination_folder): for f in list_of_files: shutil.copy(f, destination_folder) # Move the splits into their folders move_files_to_folder(train_images, 'C:/Users/xyche/Downloads/dataset/images/train/') move_files_to_folder(val_images, 'C:/Users/xyche/Downloads/dataset/images/val/') move_files_to_folder(test_images, 'C:/Users/xyche/Downloads/dataset/images/test/') move_files_to_folder(train_annotations, 'C:/Users/xyche/Downloads/dataset/labels/train/') move_files_to_folder(val_annotations, 'C:/Users/xyche/Downloads/dataset/labels/val/') move_files_to_folder(test_annotations, 'C:/Users/xyche/Downloads/dataset/labels/test/') import yaml desired_caps = { 'train': 'C:/Users/xyche/Downloads/dataset/images/train/', 'val': 'C:/Users/xyche/Downloads/dataset/images/val/', 'test': 'C:/Users/xyche/Downloads/dataset/images/test/', # number of classes 'nc': 7, # class names #'names': ['Sam', 'Lucy', 'Ross', 'Mary', 'Elon', 'Alex', 'Max'] 'names': ['0', '1', '2', '3', '4', '5', '6'] } curpath = 'C:/Users/xyche/Downloads/dataset' yamlpath = os.path.join(curpath, "./dataset.yaml") with open(yamlpath, "w", encoding="utf-8") as f: yaml.dump(desired_caps, f)
6,421
Python
37.22619
120
0.583242
An-u-rag/synthetic-visual-dataset-generation/fiftyone.py
import fiftyone as fo name = "my-dataset" dataset_dir = "C:/Users/xyche/Downloads/dataset" # Create the dataset dataset = fo.Dataset.from_dir( dataset_dir=dataset_dir, dataset_type=fo.types.YOLOv5Dataset, name=name, ) # View summary info about the dataset print(dataset) # Print the first few samples in the dataset print(dataset.head()) session = fo.launch_app(dataset)
387
Python
19.421052
48
0.73385
An-u-rag/synthetic-visual-dataset-generation/ReplicatorScripts/Replicator_RandomizeCows_Basic.py
import io import json import time import asyncio from typing import List import omni.kit import omni.usd import omni.replicator.core as rep import numpy as np from omni.replicator.core import AnnotatorRegistry, BackendDispatch, Writer, WriterRegistry, orchestrator from omni.syntheticdata.scripts.SyntheticData import SyntheticData camera_positions = [(1720, -1220, 200), (3300, -1220, 200), (3300, -3500, 200), (1720, -3500, 200)] # Attach Render Product with rep.new_layer(): camera = rep.create.camera() render_product = rep.create.render_product(camera, (1280, 1280)) # Randomizer Function def randomize_cows(): cows = rep.get.prims(semantics=[('class', 'cow')]) with cows: rep.modify.visibility(rep.distribution.choice([True, False])) return cows.node rep.randomizer.register(randomize_cows) # Trigger to call randomizer with rep.trigger.on_frame(num_frames=10): with camera: rep.modify.pose(position=rep.distribution.choice( camera_positions), look_at=(2500, -2300, 0)) rep.randomizer.randomize_cows() # Initialize and attach Writer to store result writer = rep.WriterRegistry.get('CowWriter') writer.initialize(output_dir='C:/Users/anura/Desktop/IndoorRanch_ReplicatorOutputs/Run4', rgb=True, bounding_box_2d_tight=True) writer.attach([render_product])
1,376
Python
22.741379
105
0.713663
An-u-rag/synthetic-visual-dataset-generation/ReplicatorScripts/Replicator_RandomizeSimple.py
import io import json import time import asyncio from typing import List import omni.kit import omni.usd import omni.replicator.core as rep import csv import numpy as np from omni.replicator.core import AnnotatorRegistry, BackendDispatch, Writer, WriterRegistry, orchestrator from omni.syntheticdata.scripts.SyntheticData import SyntheticData class CowWriter(Writer): def __init__( self, output_dir: str, semantic_types: List[str] = None, rgb: bool = True, bounding_box_2d_loose: bool = False, image_output_format: str = "png", ): self._output_dir = output_dir self._backend = BackendDispatch({"paths": {"out_dir": output_dir}}) self._frame_id = 0 self._sequence_id = 0 self._image_output_format = image_output_format self._output_data_format = {} self.annotators = [] if semantic_types is None: semantic_types = ["class"] # RGB if rgb: self.annotators.append(AnnotatorRegistry.get_annotator("rgb")) if bounding_box_2d_loose: self.annotators.append( AnnotatorRegistry.get_annotator("bounding_box_2d_loose", init_params={ "semanticTypes": semantic_types}) ) def write(self, data: dict): sequence_id = "" for trigger_name, call_count in data["trigger_outputs"].items(): if "on_time" in trigger_name: sequence_id = f"{call_count}_{sequence_id}" if sequence_id != self._sequence_id: self._frame_id = 0 self._sequence_id = sequence_id for annotator in data.keys(): annotator_split = annotator.split("-") render_product_path = "" multi_render_prod = 0 if len(annotator_split) > 1: multi_render_prod = 1 render_product_name = annotator_split[-1] render_product_path = f"{render_product_name}/" if annotator.startswith("rgb"): if multi_render_prod: render_product_path += "rgb/" self._write_rgb(data, render_product_path, annotator) if annotator.startswith("bounding_box_2d_loose"): if multi_render_prod: render_product_path += "bounding_box_2d_loose/" self._write_bounding_box_data( data, "2d_loose", render_product_path, annotator) self._frame_id += 1 def _write_rgb(self, data: dict, render_product_path: str, annotator: str): file_path = f"{render_product_path}rgb_{self._sequence_id}{self._frame_id:0}.{self._image_output_format}" self._backend.write_image(file_path, data[annotator]) def _write_bounding_box_data(self, data: dict, bbox_type: str, render_product_path: str, annotator: str): bbox_data_all = data[annotator]["data"] id_to_labels = data[annotator]["info"]["idToLabels"] prim_paths = data[annotator]["info"]["primPaths"] target_coco_bbox_data = [] count = 0 print(bbox_data_all) labels_file_path = f"{render_product_path}rgb_{self._sequence_id}{self._frame_id:0}.txt" for bbox_data in bbox_data_all: target_bbox_data = {'x_min': bbox_data['x_min'], 'y_min': bbox_data['y_min'], 'x_max': bbox_data['x_max'], 'y_max': bbox_data['y_max']} width = int( abs(target_bbox_data["x_max"] - target_bbox_data["x_min"])) height = int( abs(target_bbox_data["y_max"] - target_bbox_data["y_min"])) semantic_label = data[annotator]["info"]["idToLabels"].get(bbox_data["semanticId"]) coco_bbox_data = [] coco_bbox_data.append(semantic_label) coco_bbox_data.append(str((float(target_bbox_data["x_min"]) + float(target_bbox_data["x_max"]))/2)) coco_bbox_data.append(str((float(target_bbox_data["y_min"]) + float(target_bbox_data["y_max"]))/2)) coco_bbox_data.append(str(width)) coco_bbox_data.append(str(height)) target_coco_bbox_data.append(coco_bbox_data) count += 1 buf = io.StringIO() writer = csv.writer(buf, delimiter = " ") writer.writerows(target_coco_bbox_data) self._backend.write_blob(labels_file_path, bytes(buf.getvalue(), "utf-8")) rep.WriterRegistry.register(CowWriter) camera_positions = [(-1100, 1480, -900), (-1100, 3355, -900), (2815, 3410, -800), (2815, 1380, -800)] # Attach Render Product with rep.new_layer(): camera = rep.create.camera() render_product = rep.create.render_product(camera, (1280, 1280)) # Randomizer Function def randomize_pigsdirty(): pigs = rep.get.prims(semantics=[('class', 'pig_dirty')]) with pigs: rep.modify.visibility(rep.distribution.choice([True, False])) return pigs.node rep.randomizer.register(randomize_pigsdirty) def randomize_pigsclean(): pigs = rep.get.prims(semantics=[('class', 'pig_clean')]) with pigs: rep.modify.visibility(rep.distribution.choice([True, False])) return pigs.node rep.randomizer.register(randomize_pigsclean) def randomize_cows2(): cows = rep.get.prims(semantics=[('class', 'cow_2')]) with cows: rep.modify.visibility(rep.distribution.choice([True, False])) return cows.node rep.randomizer.register(randomize_cows2) def randomize_cows3(): cows = rep.get.prims(semantics=[('class', 'cow_3')]) with cows: rep.modify.visibility(rep.distribution.choice([True, False])) return cows.node rep.randomizer.register(randomize_cows3) def randomize_cows4(): cows = rep.get.prims(semantics=[('class', 'cow_4')]) with cows: rep.modify.visibility(rep.distribution.choice([True, False])) return cows.node rep.randomizer.register(randomize_cows4) def randomize_environment(): envs = ["omniverse://localhost/NVIDIA/Assets/Skies/Clear/noon_grass_4k.hdr", "omniverse://localhost/NVIDIA/Assets/Skies/Night/moonlit_golf_4k.hdr", "omniverse://localhost/NVIDIA/Assets/Skies/Storm/approaching_storm_4k.hdr"] lights = rep.create.light( light_type = "Dome", position = (2500, -2300, 0), intensity = rep.distribution.choice([1., 10., 100., 1000.]), texture = rep.distribution.choice(envs) ) return lights.node rep.randomizer.register(randomize_environment) # Trigger to call randomizer with rep.trigger.on_frame(num_frames=3000): with camera: rep.modify.pose(position=rep.distribution.choice( camera_positions), look_at=(790, 2475, -1178)) rep.randomizer.randomize_environment() rep.randomizer.randomize_pigsdirty() rep.randomizer.randomize_pigsclean() rep.randomizer.randomize_cows2() rep.randomizer.randomize_cows3() rep.randomizer.randomize_cows4() writer = rep.WriterRegistry.get('BasicWriter') writer.initialize(output_dir='C:/Users/anura/Desktop/IndoorRanch_ReplicatorOutputs/SanjRun1', rgb=True, bounding_box_2d_tight=True, bounding_box_2d_loose=True, semantic_segmentation=True, bounding_box_3d=True) writer.attach([render_product])
7,338
Python
34.8
134
0.615018
An-u-rag/synthetic-visual-dataset-generation/ReplicatorScripts/Replicator_RandomizeCows.py
import io import json import time import asyncio from typing import List import omni.kit import omni.usd import omni.replicator.core as rep import numpy as np from omni.replicator.core import AnnotatorRegistry, BackendDispatch, Writer, WriterRegistry, orchestrator from omni.syntheticdata.scripts.SyntheticData import SyntheticData class CowWriter(Writer): def __init__( self, output_dir: str, semantic_types: List[str] = None, rgb: bool = True, bounding_box_2d_tight: bool = False, bounding_box_2d_loose: bool = False, semantic_segmentation: bool = False, instance_id_segmentation: bool = False, instance_segmentation: bool = False, distance_to_camera: bool = False, bounding_box_3d: bool = False, image_output_format: str = "png", ): self._output_dir = output_dir self._backend = BackendDispatch({"paths": {"out_dir": output_dir}}) self._frame_id = 0 self._sequence_id = 0 self._image_output_format = image_output_format self._output_data_format = {} self.annotators = [] if semantic_types is None: semantic_types = ["class"] # RGB if rgb: self.annotators.append(AnnotatorRegistry.get_annotator("rgb")) # Bounding Box 2D if bounding_box_2d_tight: self.annotators.append( AnnotatorRegistry.get_annotator("bounding_box_2d_tight", init_params={ "semanticTypes": semantic_types}) ) if bounding_box_2d_loose: self.annotators.append( AnnotatorRegistry.get_annotator("bounding_box_2d_loose", init_params={ "semanticTypes": semantic_types}) ) # Semantic Segmentation if semantic_segmentation: self.annotators.append( AnnotatorRegistry.get_annotator( "semantic_segmentation", init_params={"semanticTypes": semantic_types}, ) ) # Instance Segmentation if instance_id_segmentation: self.annotators.append( AnnotatorRegistry.get_annotator( "instance_id_segmentation", init_params={} ) ) # Instance Segmentation if instance_segmentation: self.annotators.append( AnnotatorRegistry.get_annotator( "instance_segmentation", init_params={"semanticTypes": semantic_types}, ) ) # Depth if distance_to_camera: self.annotators.append( AnnotatorRegistry.get_annotator("distance_to_camera")) # Bounding Box 3D if bounding_box_3d: self.annotators.append( AnnotatorRegistry.get_annotator("bounding_box_3d", init_params={ "semanticTypes": semantic_types}) ) def write(self, data: dict): sequence_id = "" for trigger_name, call_count in data["trigger_outputs"].items(): if "on_time" in trigger_name: sequence_id = f"{call_count}_{sequence_id}" if sequence_id != self._sequence_id: self._frame_id = 0 self._sequence_id = sequence_id for annotator in data.keys(): annotator_split = annotator.split("-") render_product_path = "" multi_render_prod = 0 if len(annotator_split) > 1: multi_render_prod = 1 render_product_name = annotator_split[-1] render_product_path = f"{render_product_name}/" if annotator.startswith("rgb"): if multi_render_prod: render_product_path += "rgb/" self._write_rgb(data, render_product_path, annotator) if annotator.startswith("distance_to_camera"): if multi_render_prod: render_product_path += "distance_to_camera/" self._write_distance_to_camera( data, render_product_path, annotator) if annotator.startswith("semantic_segmentation"): if multi_render_prod: render_product_path += "semantic_segmentation/" self._write_semantic_segmentation( data, render_product_path, annotator) if annotator.startswith("instance_id_segmentation"): if multi_render_prod: render_product_path += "instance_id_segmentation/" self._write_instance_id_segmentation( data, render_product_path, annotator) if annotator.startswith("instance_segmentation"): if multi_render_prod: render_product_path += "instance_segmentation/" self._write_instance_segmentation( data, render_product_path, annotator) if annotator.startswith("bounding_box_3d"): if multi_render_prod: render_product_path += "bounding_box_3d/" self._write_bounding_box_data( data, "3d", render_product_path, annotator) if annotator.startswith("bounding_box_2d_loose"): if multi_render_prod: render_product_path += "bounding_box_2d_loose/" self._write_bounding_box_data( data, "2d_loose", render_product_path, annotator) if annotator.startswith("bounding_box_2d_tight"): if multi_render_prod: render_product_path += "bounding_box_2d_tight/" self._write_bounding_box_data( data, "2d_tight", render_product_path, annotator) self._frame_id += 1 def _write_rgb(self, data: dict, render_product_path: str, annotator: str): file_path = f"{render_product_path}rgb_{self._sequence_id}{self._frame_id:0}.{self._image_output_format}" self._backend.write_image(file_path, data[annotator]) def _write_distance_to_camera(self, data: dict, render_product_path: str, annotator: str): dist_to_cam_data = data[annotator] file_path = ( f"{render_product_path}distance_to_camera_{self._sequence_id}{self._frame_id:0}.npy" ) buf = io.BytesIO() np.save(buf, dist_to_cam_data) self._backend.write_blob(file_path, buf.getvalue()) def _write_semantic_segmentation(self, data: dict, render_product_path: str, annotator: str): semantic_seg_data = data[annotator]["data"] height, width = semantic_seg_data.shape[:2] file_path = ( f"{render_product_path}semantic_segmentation_{self._sequence_id}{self._frame_id:0}.png" ) if self.colorize_semantic_segmentation: semantic_seg_data = semantic_seg_data.view( np.uint8).reshape(height, width, -1) self._backend.write_image(file_path, semantic_seg_data) else: semantic_seg_data = semantic_seg_data.view( np.uint32).reshape(height, width) self._backend.write_image(file_path, semantic_seg_data) id_to_labels = data[annotator]["info"]["idToLabels"] file_path = f"{render_product_path}semantic_segmentation_labels_{self._sequence_id}{self._frame_id:0}.json" buf = io.BytesIO() buf.write(json.dumps( {str(k): v for k, v in id_to_labels.items()}).encode()) self._backend.write_blob(file_path, buf.getvalue()) def _write_instance_id_segmentation(self, data: dict, render_product_path: str, annotator: str): instance_seg_data = data[annotator]["data"] height, width = instance_seg_data.shape[:2] file_path = f"{render_product_path}instance_id_segmentation_{self._sequence_id}{self._frame_id:0}.png" if self.colorize_instance_id_segmentation: instance_seg_data = instance_seg_data.view( np.uint8).reshape(height, width, -1) self._backend.write_image(file_path, instance_seg_data) else: instance_seg_data = instance_seg_data.view( np.uint32).reshape(height, width) self._backend.write_image(file_path, instance_seg_data) id_to_labels = data[annotator]["info"]["idToLabels"] file_path = f"{render_product_path}instance_id_segmentation_mapping_{self._sequence_id}{self._frame_id:0}.json" buf = io.BytesIO() buf.write(json.dumps( {str(k): v for k, v in id_to_labels.items()}).encode()) self._backend.write_blob(file_path, buf.getvalue()) def _write_instance_segmentation(self, data: dict, render_product_path: str, annotator: str): instance_seg_data = data[annotator]["data"] height, width = instance_seg_data.shape[:2] file_path = ( f"{render_product_path}instance_segmentation_{self._sequence_id}{self._frame_id:0}.png" ) if self.colorize_instance_segmentation: instance_seg_data = instance_seg_data.view( np.uint8).reshape(height, width, -1) self._backend.write_image(file_path, instance_seg_data) else: instance_seg_data = instance_seg_data.view( np.uint32).reshape(height, width) self._backend.write_image(file_path, instance_seg_data) id_to_labels = data[annotator]["info"]["idToLabels"] file_path = f"{render_product_path}instance_segmentation_mapping_{self._sequence_id}{self._frame_id:0}.json" buf = io.BytesIO() buf.write(json.dumps( {str(k): v for k, v in id_to_labels.items()}).encode()) self._backend.write_blob(file_path, buf.getvalue()) id_to_semantics = data[annotator]["info"]["idToSemantics"] file_path = f"{render_product_path}instance_segmentation_semantics_mapping_{self._sequence_id}{self._frame_id:0}.json" buf = io.BytesIO() buf.write(json.dumps( {str(k): v for k, v in id_to_semantics.items()}).encode()) self._backend.write_blob(file_path, buf.getvalue()) def _write_bounding_box_data(self, data: dict, bbox_type: str, render_product_path: str, annotator: str): bbox_data_all = data[annotator]["data"] print(bbox_data_all) id_to_labels = data[annotator]["info"]["idToLabels"] prim_paths = data[annotator]["info"]["primPaths"] file_path = f"{render_product_path}bounding_box_{bbox_type}_{self._sequence_id}{self._frame_id:0}.npy" buf = io.BytesIO() np.save(buf, bbox_data_all) self._backend.write_blob(file_path, buf.getvalue()) labels_file_path = f"{render_product_path}bounding_box_{bbox_type}_labels_{self._sequence_id}{self._frame_id:0}.json" buf = io.BytesIO() buf.write(json.dumps(id_to_labels).encode()) self._backend.write_blob(labels_file_path, buf.getvalue()) labels_file_path = f"{render_product_path}bounding_box_{bbox_type}_prim_paths_{self._sequence_id}{self._frame_id:0}.json" buf = io.BytesIO() buf.write(json.dumps(prim_paths).encode()) self._backend.write_blob(labels_file_path, buf.getvalue()) target_coco_bbox_data = [] count = 0 for bbox_data in bbox_data_all: target_bbox_data = {'x_min': bbox_data['x_min'], 'y_min': bbox_data['y_min'], 'x_max': bbox_data['x_max'], 'y_max': bbox_data['y_max']} width = int( abs(target_bbox_data["x_max"] - target_bbox_data["x_min"])) height = int( abs(target_bbox_data["y_max"] - target_bbox_data["y_min"])) if width != 2147483647 and height != 2147483647: # filepath = f"rgb_{self._frame_id}.{self._image_output_format}" # self._backend.write_image(filepath, data["rgb"]) bbox_filepath = f"bbox_{self._frame_id}.txt" coco_bbox_data = { "name": prim_paths[count], "x_min": int(target_bbox_data["x_min"]), "y_min": int(target_bbox_data["y_min"]), "x_max": int(target_bbox_data["x_max"]), "y_max": int(target_bbox_data["y_max"]), "width": width, "height": height} target_coco_bbox_data.append(coco_bbox_data) count += 1 buf = io.BytesIO() buf.write(json.dumps(target_coco_bbox_data).encode()) self._backend.write_blob(bbox_filepath, buf.getvalue()) rep.WriterRegistry.register(CowWriter) camera_positions = [(1720, -1220, 200), (3300, -1220, 200), (3300, -3500, 200), (1720, -3500, 200)] # Attach Render Product with rep.new_layer(): camera = rep.create.camera() render_product = rep.create.render_product(camera, (1280, 1280)) # Randomizer Function def randomize_cows1(): cows = rep.get.prims(semantics=[('class', 'cow_1')]) with cows: rep.modify.visibility(rep.distribution.choice([True, False])) return cows.node rep.randomizer.register(randomize_cows1) def randomize_cows2(): cows = rep.get.prims(semantics=[('class', 'cow_2')]) with cows: rep.modify.visibility(rep.distribution.choice([True, False])) return cows.node rep.randomizer.register(randomize_cows2) def randomize_cows3(): cows = rep.get.prims(semantics=[('class', 'cow_3')]) with cows: rep.modify.visibility(rep.distribution.choice([True, False])) return cows.node rep.randomizer.register(randomize_cows3) def randomize_cows4(): cows = rep.get.prims(semantics=[('class', 'cow_4')]) with cows: rep.modify.visibility(rep.distribution.choice([True, False])) return cows.node rep.randomizer.register(randomize_cows4) def randomize_environment(): envs = ["omniverse://localhost/NVIDIA/Assets/Skies/Clear/noon_grass_4k.hdr", "omniverse://localhost/NVIDIA/Assets/Skies/Night/moonlit_golf_4k.hdr", "omniverse://localhost/NVIDIA/Assets/Skies/Storm/approaching_storm_4k.hdr"] lights = rep.create.light( light_type = "Dome", position = (2500, -2300, 0), intensity = rep.distribution.choice([1., 10., 100., 1000.]), texture = rep.distribution.choice(envs) ) return lights.node rep.randomizer.register(randomize_environment) # Trigger to call randomizer with rep.trigger.on_frame(num_frames=10): with camera: rep.modify.pose(position=rep.distribution.choice( camera_positions), look_at=(2500, -2300, 0)) rep.randomizer.randomize_environment() rep.randomizer.randomize_cows1() rep.randomizer.randomize_cows2() rep.randomizer.randomize_cows3() rep.randomizer.randomize_cows4() writer = rep.WriterRegistry.get('BasicWriter') writer.initialize(output_dir='C:/Users/anura/Desktop/IndoorRanch_ReplicatorOutputs/NewRun1', rgb=True, bounding_box_2d_tight=True) writer.attach([render_product])
15,455
Python
35.8
129
0.581171
An-u-rag/synthetic-visual-dataset-generation/ReplicatorScripts/CowWriter_COCO.py
import io import json import time import asyncio from typing import List import omni.kit import omni.usd import omni.replicator.core as rep import numpy as np from omni.replicator.core import AnnotatorRegistry, BackendDispatch, Writer, WriterRegistry, orchestrator from omni.syntheticdata.scripts.SyntheticData import SyntheticData class CowWriter(Writer): def __init__( self, output_dir: str, semantic_types: List[str] = None, rgb: bool = True, bounding_box_2d_tight: bool = False, bounding_box_2d_loose: bool = False, semantic_segmentation: bool = False, instance_id_segmentation: bool = False, instance_segmentation: bool = False, distance_to_camera: bool = False, bounding_box_3d: bool = False, image_output_format: str = "png", ): self._output_dir = output_dir self._backend = BackendDispatch({"paths": {"out_dir": output_dir}}) self._frame_id = 0 self._sequence_id = 0 self._image_output_format = image_output_format self._output_data_format = {} self.annotators = [] if semantic_types is None: semantic_types = ["class"] # RGB if rgb: self.annotators.append(AnnotatorRegistry.get_annotator("rgb")) # Bounding Box 2D if bounding_box_2d_tight: self.annotators.append( AnnotatorRegistry.get_annotator("bounding_box_2d_tight", init_params={ "semanticTypes": semantic_types}) ) if bounding_box_2d_loose: self.annotators.append( AnnotatorRegistry.get_annotator("bounding_box_2d_loose", init_params={ "semanticTypes": semantic_types}) ) # Semantic Segmentation if semantic_segmentation: self.annotators.append( AnnotatorRegistry.get_annotator( "semantic_segmentation", init_params={"semanticTypes": semantic_types}, ) ) # Instance Segmentation if instance_id_segmentation: self.annotators.append( AnnotatorRegistry.get_annotator( "instance_id_segmentation", init_params={} ) ) # Instance Segmentation if instance_segmentation: self.annotators.append( AnnotatorRegistry.get_annotator( "instance_segmentation", init_params={"semanticTypes": semantic_types}, ) ) # Depth if distance_to_camera: self.annotators.append( AnnotatorRegistry.get_annotator("distance_to_camera")) # Bounding Box 3D if bounding_box_3d: self.annotators.append( AnnotatorRegistry.get_annotator("bounding_box_3d", init_params={ "semanticTypes": semantic_types}) ) def write(self, data: dict): sequence_id = "" for trigger_name, call_count in data["trigger_outputs"].items(): if "on_time" in trigger_name: sequence_id = f"{call_count}_{sequence_id}" if sequence_id != self._sequence_id: self._frame_id = 0 self._sequence_id = sequence_id for annotator in data.keys(): annotator_split = annotator.split("-") render_product_path = "" multi_render_prod = 0 if len(annotator_split) > 1: multi_render_prod = 1 render_product_name = annotator_split[-1] render_product_path = f"{render_product_name}/" if annotator.startswith("rgb"): if multi_render_prod: render_product_path += "rgb/" self._write_rgb(data, render_product_path, annotator) if annotator.startswith("distance_to_camera"): if multi_render_prod: render_product_path += "distance_to_camera/" self._write_distance_to_camera( data, render_product_path, annotator) if annotator.startswith("semantic_segmentation"): if multi_render_prod: render_product_path += "semantic_segmentation/" self._write_semantic_segmentation( data, render_product_path, annotator) if annotator.startswith("instance_id_segmentation"): if multi_render_prod: render_product_path += "instance_id_segmentation/" self._write_instance_id_segmentation( data, render_product_path, annotator) if annotator.startswith("instance_segmentation"): if multi_render_prod: render_product_path += "instance_segmentation/" self._write_instance_segmentation( data, render_product_path, annotator) if annotator.startswith("bounding_box_3d"): if multi_render_prod: render_product_path += "bounding_box_3d/" self._write_bounding_box_data( data, "3d", render_product_path, annotator) if annotator.startswith("bounding_box_2d_loose"): if multi_render_prod: render_product_path += "bounding_box_2d_loose/" self._write_bounding_box_data( data, "2d_loose", render_product_path, annotator) if annotator.startswith("bounding_box_2d_tight"): if multi_render_prod: render_product_path += "bounding_box_2d_tight/" self._write_bounding_box_data( data, "2d_tight", render_product_path, annotator) self._frame_id += 1 def _write_rgb(self, data: dict, render_product_path: str, annotator: str): file_path = f"{render_product_path}rgb_{self._sequence_id}{self._frame_id:0}.{self._image_output_format}" self._backend.write_image(file_path, data[annotator]) def _write_distance_to_camera(self, data: dict, render_product_path: str, annotator: str): dist_to_cam_data = data[annotator] file_path = ( f"{render_product_path}distance_to_camera_{self._sequence_id}{self._frame_id:0}.npy" ) buf = io.BytesIO() np.save(buf, dist_to_cam_data) self._backend.write_blob(file_path, buf.getvalue()) def _write_semantic_segmentation(self, data: dict, render_product_path: str, annotator: str): semantic_seg_data = data[annotator]["data"] height, width = semantic_seg_data.shape[:2] file_path = ( f"{render_product_path}semantic_segmentation_{self._sequence_id}{self._frame_id:0}.png" ) if self.colorize_semantic_segmentation: semantic_seg_data = semantic_seg_data.view( np.uint8).reshape(height, width, -1) self._backend.write_image(file_path, semantic_seg_data) else: semantic_seg_data = semantic_seg_data.view( np.uint32).reshape(height, width) self._backend.write_image(file_path, semantic_seg_data) id_to_labels = data[annotator]["info"]["idToLabels"] file_path = f"{render_product_path}semantic_segmentation_labels_{self._sequence_id}{self._frame_id:0}.json" buf = io.BytesIO() buf.write(json.dumps( {str(k): v for k, v in id_to_labels.items()}).encode()) self._backend.write_blob(file_path, buf.getvalue()) def _write_instance_id_segmentation(self, data: dict, render_product_path: str, annotator: str): instance_seg_data = data[annotator]["data"] height, width = instance_seg_data.shape[:2] file_path = f"{render_product_path}instance_id_segmentation_{self._sequence_id}{self._frame_id:0}.png" if self.colorize_instance_id_segmentation: instance_seg_data = instance_seg_data.view( np.uint8).reshape(height, width, -1) self._backend.write_image(file_path, instance_seg_data) else: instance_seg_data = instance_seg_data.view( np.uint32).reshape(height, width) self._backend.write_image(file_path, instance_seg_data) id_to_labels = data[annotator]["info"]["idToLabels"] file_path = f"{render_product_path}instance_id_segmentation_mapping_{self._sequence_id}{self._frame_id:0}.json" buf = io.BytesIO() buf.write(json.dumps( {str(k): v for k, v in id_to_labels.items()}).encode()) self._backend.write_blob(file_path, buf.getvalue()) def _write_instance_segmentation(self, data: dict, render_product_path: str, annotator: str): instance_seg_data = data[annotator]["data"] height, width = instance_seg_data.shape[:2] file_path = ( f"{render_product_path}instance_segmentation_{self._sequence_id}{self._frame_id:0}.png" ) if self.colorize_instance_segmentation: instance_seg_data = instance_seg_data.view( np.uint8).reshape(height, width, -1) self._backend.write_image(file_path, instance_seg_data) else: instance_seg_data = instance_seg_data.view( np.uint32).reshape(height, width) self._backend.write_image(file_path, instance_seg_data) id_to_labels = data[annotator]["info"]["idToLabels"] file_path = f"{render_product_path}instance_segmentation_mapping_{self._sequence_id}{self._frame_id:0}.json" buf = io.BytesIO() buf.write(json.dumps( {str(k): v for k, v in id_to_labels.items()}).encode()) self._backend.write_blob(file_path, buf.getvalue()) id_to_semantics = data[annotator]["info"]["idToSemantics"] file_path = f"{render_product_path}instance_segmentation_semantics_mapping_{self._sequence_id}{self._frame_id:0}.json" buf = io.BytesIO() buf.write(json.dumps( {str(k): v for k, v in id_to_semantics.items()}).encode()) self._backend.write_blob(file_path, buf.getvalue()) def _write_bounding_box_data(self, data: dict, bbox_type: str, render_product_path: str, annotator: str): bbox_data_all = data[annotator]["data"] print(bbox_data_all) id_to_labels = data[annotator]["info"]["idToLabels"] prim_paths = data[annotator]["info"]["primPaths"] file_path = f"{render_product_path}bounding_box_{bbox_type}_{self._sequence_id}{self._frame_id:0}.npy" buf = io.BytesIO() np.save(buf, bbox_data_all) self._backend.write_blob(file_path, buf.getvalue()) labels_file_path = f"{render_product_path}bounding_box_{bbox_type}_labels_{self._sequence_id}{self._frame_id:0}.json" buf = io.BytesIO() buf.write(json.dumps(id_to_labels).encode()) self._backend.write_blob(labels_file_path, buf.getvalue()) labels_file_path = f"{render_product_path}bounding_box_{bbox_type}_prim_paths_{self._sequence_id}{self._frame_id:0}.json" buf = io.BytesIO() buf.write(json.dumps(prim_paths).encode()) self._backend.write_blob(labels_file_path, buf.getvalue()) target_coco_bbox_data = [] count = 0 for bbox_data in bbox_data_all: target_bbox_data = {'x_min': bbox_data['x_min'], 'y_min': bbox_data['y_min'], 'x_max': bbox_data['x_max'], 'y_max': bbox_data['y_max']} width = int( abs(target_bbox_data["x_max"] - target_bbox_data["x_min"])) height = int( abs(target_bbox_data["y_max"] - target_bbox_data["y_min"])) if width != 2147483647 and height != 2147483647: bbox_filepath = f"bbox_{self._frame_id}.json" coco_bbox_data = { "name": prim_paths[count], "x_min": int(target_bbox_data["x_min"]), "y_min": int(target_bbox_data["y_min"]), "x_max": int(target_bbox_data["x_max"]), "y_max": int(target_bbox_data["y_max"]), "width": width, "height": height} target_coco_bbox_data.append(coco_bbox_data) count += 1 buf = io.BytesIO() buf.write(json.dumps(target_coco_bbox_data).encode()) self._backend.write_blob(bbox_filepath, buf.getvalue()) rep.WriterRegistry.register(CowWriter)
12,859
Python
41.442244
129
0.565674
CesiumGS/cesium-omniverse/copy-python-path-for-vs.py
from os import getcwd from os.path import exists import json from textwrap import indent from jsmin import jsmin # # Note: This requires JSMin to be installed since the vscode workspace files have Comments in them. # You can install JSMin by just installing it globally via pip. # # Also Note: You may need to run Visual Studio and open a Python file before running this script. # cwd_path = getcwd() root_path = f"{cwd_path}/extern/nvidia/app" vs_code_workspace_file_path = f"{cwd_path}/.vscode/cesium-omniverse-windows.code-workspace" vs_python_settings_file_path = f"{cwd_path}/.vs/PythonSettings.json" if not exists(root_path): print(f"Could not find {root_path}") exit(1) if not exists(vs_code_workspace_file_path): print(f"Could not find {vs_code_workspace_file_path}") exit(1) if not exists(vs_python_settings_file_path): print(f"Could not find {vs_python_settings_file_path}") exit(1) print(f"Using root path: {root_path}") print(f"Using vs code workspace file: {vs_code_workspace_file_path}") print(f"Using vs PythonSettings file: {vs_python_settings_file_path}") with open(vs_code_workspace_file_path) as fh: m = jsmin(fh.read()) vs_code_workspace_file = json.loads(m) def process_paths(path): return path.replace("${workspaceFolder}", cwd_path).replace("/", "\\") extra_paths = list(map(process_paths, vs_code_workspace_file["settings"]["python.analysis.extraPaths"])) with open(vs_python_settings_file_path, 'r') as fh: vs_python_settings = json.load(fh) vs_python_settings["SearchPaths"] = extra_paths # The read and write handles are split because we want to truncate the old file. with open(vs_python_settings_file_path, 'w') as fh: json.dump(vs_python_settings, fh, indent=2) print(f"Wrote to {vs_python_settings_file_path}")
1,800
Python
32.981131
104
0.725556
CesiumGS/cesium-omniverse/exts/cesium.powertools/cesium/powertools/extension.py
from functools import partial import asyncio from typing import Optional, List import logging import omni.ext import omni.ui as ui import omni.kit.ui from .powertools_window import CesiumPowertoolsWindow from cesium.omniverse.utils import wait_n_frames, dock_window_async from cesium.omniverse.install import WheelInfo, WheelInstaller class CesiumPowertoolsExtension(omni.ext.IExt): def __init__(self): super().__init__() self._logger = logging.getLogger(__name__) self._powertools_window: Optional[CesiumPowertoolsWindow] = None self._install_py_dependencies() def on_startup(self): self._logger.info("Starting Cesium Power Tools...") self._setup_menus() self._show_and_dock_startup_windows() def on_shutdown(self): self._destroy_powertools_window() def _setup_menus(self): ui.Workspace.set_show_window_fn( CesiumPowertoolsWindow.WINDOW_NAME, partial(self._show_powertools_window, None) ) editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: editor_menu.add_item( CesiumPowertoolsWindow.MENU_PATH, self._show_powertools_window, toggle=True, value=True ) def _show_and_dock_startup_windows(self): ui.Workspace.show_window(CesiumPowertoolsWindow.WINDOW_NAME) asyncio.ensure_future(dock_window_async(self._powertools_window, target="Property")) def _destroy_powertools_window(self): if self._powertools_window is not None: self._powertools_window.destroy() self._powertools_window = None async def _destroy_window_async(self, path): # Wait one frame, this is due to the one frame defer in Window::_moveToMainOSWindow() await wait_n_frames(1) if path is CesiumPowertoolsWindow.MENU_PATH: self._destroy_powertools_window() def _visibility_changed_fn(self, path, visible): editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: editor_menu.set_value(path, visible) if not visible: asyncio.ensure_future(self._destroy_window_async(path)) def _show_powertools_window(self, _menu, value): if value: self._powertools_window = CesiumPowertoolsWindow(width=300, height=400) self._powertools_window.set_visibility_changed_fn( partial(self._visibility_changed_fn, CesiumPowertoolsWindow.MENU_PATH) ) elif self._powertools_window is not None: self._powertools_window.visible = False def _install_py_dependencies(self): vendor_wheels: List[WheelInfo] = [ WheelInfo( module="pyproj", windows_whl="pyproj-3.6.0-cp310-cp310-win_amd64.whl", linux_x64_whl="pyproj-3.6.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", linux_aarch_whl="pyproj-3.6.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", ) ] for w in vendor_wheels: installer = WheelInstaller(w, extension_module="cesium.powertools") if not installer.install(): self._logger.error(f"Could not install wheel for {w.module}")
3,271
Python
34.565217
108
0.646897
CesiumGS/cesium-omniverse/exts/cesium.powertools/cesium/powertools/__init__.py
from .extension import * # noqa: F401 F403
44
Python
21.499989
43
0.704545
CesiumGS/cesium-omniverse/exts/cesium.powertools/cesium/powertools/powertools_window.py
import logging import omni.ui as ui from typing import Callable, Optional, List from cesium.omniverse.ui import CesiumOmniverseDebugWindow from .georefhelper.georef_helper_window import CesiumGeorefHelperWindow from .utils import ( extend_far_plane, save_carb_settings, save_fabric_stage, set_sunstudy_from_georef, ) import os from functools import partial from .benchmarking.load_timer_window import CesiumLoadTimerWindow powertools_extension_location = os.path.join(os.path.dirname(__file__), "../../") class PowertoolsAction: def __init__(self, title: str, action: Callable): self._title = title self._action = action self._button: Optional[ui.Button] = None def destroy(self): if self._button is not None: self._button.destroy() self._button = None def button(self): if self._button is None: self._button = ui.Button(self._title, height=0, clicked_fn=self._action) return self._button class CesiumPowertoolsWindow(ui.Window): WINDOW_NAME = "Cesium Power Tools" MENU_PATH = f"Window/Cesium/{WINDOW_NAME}" def __init__(self, **kwargs): super().__init__(CesiumPowertoolsWindow.WINDOW_NAME, **kwargs) self._logger = logging.getLogger(__name__) # You do not necessarily need to create an action function in this window class. If you have a function # in another window or class, you can absolutely call that instead from here. self._actions: List[PowertoolsAction] = [ PowertoolsAction("Open Cesium Debugging Window", CesiumOmniverseDebugWindow.show_window), PowertoolsAction("Open Cesium Georeference Helper Window", CesiumGeorefHelperWindow.create_window), PowertoolsAction("Open Cesium Load Timer Window", CesiumLoadTimerWindow.create_window), PowertoolsAction("Extend Far Plane", extend_far_plane), PowertoolsAction("Save Carb Settings", partial(save_carb_settings, powertools_extension_location)), PowertoolsAction("Save Fabric Stage", partial(save_fabric_stage, powertools_extension_location)), PowertoolsAction("Set Sun Study from Georef", set_sunstudy_from_georef), ] self.frame.set_build_fn(self._build_fn) def destroy(self) -> None: for action in self._actions: action.destroy() self._actions.clear() super().destroy() def _build_fn(self): with ui.ScrollingFrame(): with ui.VStack(spacing=4): for action in self._actions: action.button()
2,623
Python
35.444444
111
0.666794
CesiumGS/cesium-omniverse/exts/cesium.powertools/cesium/powertools/benchmarking/load_timer_window.py
import logging import omni.ui as ui import carb.events import omni.kit.app as app from typing import List from cesium.omniverse.ui.models.space_delimited_number_model import SpaceDelimitedNumberModel from cesium.omniverse.utils.cesium_interface import CesiumInterfaceManager from datetime import datetime from cesium.omniverse.usdUtils import get_tileset_paths class CesiumLoadTimerWindow(ui.Window): WINDOW_NAME = "Cesium Load Timer" _logger: logging.Logger _last_tiles_loading_worker = 0 def __init__(self, **kwargs): super().__init__(CesiumLoadTimerWindow.WINDOW_NAME, **kwargs) self._logger = logging.getLogger(__name__) self._timer_active = False self._tiles_loading_worker_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._load_time_seconds_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._past_results_model: ui.SimpleStringModel = ui.SimpleStringModel("") self._subscriptions: List[carb.events.ISubscription] = [] self._setup_subscriptions() # Set the function that is called to build widgets when the window is visible self.frame.set_build_fn(self._build_fn) self.set_visibility_changed_fn(self._visibility_changed_fn) def destroy(self): self._remove_subscriptions() super().destroy() def __del__(self): self.destroy() def _visibility_changed_fn(self, visible): if not visible: self._remove_subscriptions() def _setup_subscriptions(self): update_stream = app.get_app().get_update_event_stream() self._subscriptions.append( update_stream.create_subscription_to_pop(self._on_update_frame, name="on_update_frame") ) def _remove_subscriptions(self): for subscription in self._subscriptions: subscription.unsubscribe() self._subscriptions.clear() def _on_update_frame(self, _e: carb.events.IEvent): if not self.visible or not self._timer_active: return with CesiumInterfaceManager() as interface: render_statistics = interface.get_render_statistics() # Loading worker count has changed from last frame, so update the timer if render_statistics.tiles_loading_worker != self._last_tiles_loading_worker: # Register a new end-time and calculate the total elapsed time in seconds self._end_time = datetime.now() time_elapsed = self._end_time - self._start_time self._load_time_seconds_model.set_value(time_elapsed.total_seconds()) # If 30 sucessive frames with zero tiles loading occurs, we assume loading has finished if render_statistics.tiles_loading_worker == 0: self._zero_counter += 1 if self._zero_counter >= 30: self._end_load_timer() # Cancel the timer after 30 successful 0 tile frames else: self._zero_counter = 0 # Store the number of tile workers for use in the next update cycle self._last_tiles_loading_worker = render_statistics.tiles_loading_worker self._tiles_loading_worker_model.set_value(render_statistics.tiles_loading_worker) def _start_load_timer(self): self._start_time = datetime.now() self._end_time = datetime.now() self._timer_active = True self._zero_counter = 0 with CesiumInterfaceManager() as interface: tileset_paths = get_tileset_paths() for tileset_path in tileset_paths: interface.reload_tileset(tileset_path) def _end_load_timer(self): self._timer_active = False result_str = f"{self._load_time_seconds_model}\n" + self._past_results_model.get_value_as_string() self._past_results_model.set_value(result_str) @staticmethod def create_window(): return CesiumLoadTimerWindow(width=300, height=370) def _build_fn(self): """Builds out the UI""" with ui.VStack(spacing=4): ui.Label( "This tool records the amount of time taken to reload all tilesets in the stage", word_wrap=True, ) def reload_all_tilesets(): self._start_load_timer() ui.Button("Reload all Tilesets", height=20, clicked_fn=reload_all_tilesets) ui.Label( "The timer automatically completes when no tiles are queued to load for 30 successive frames", word_wrap=True, ) for label, model in [ ("Tiles loading (worker)", self._tiles_loading_worker_model), ("Load time (s)", self._load_time_seconds_model), ]: with ui.HStack(height=0): ui.Label(label, height=0) ui.StringField(model=model, height=0, read_only=True) ui.Label("Past results:", height=0) ui.StringField(model=self._past_results_model, multiline=True, height=150)
5,135
Python
36.764706
110
0.627653
CesiumGS/cesium-omniverse/exts/cesium.powertools/cesium/powertools/georefhelper/georef_helper_window.py
import logging import omni.ui as ui import omni.usd from .proj import epsg_to_ecef, epsg_to_wgs84, get_crs_name_from_epsg import math from cesium.omniverse.utils.custom_fields import string_field_with_label, int_field_with_label, float_field_with_label from pxr import Sdf class CesiumGeorefHelperWindow(ui.Window): WINDOW_NAME = "Cesium Georeference Helper" _logger: logging.Logger def __init__(self, **kwargs): super().__init__(CesiumGeorefHelperWindow.WINDOW_NAME, **kwargs) self._logger = logging.getLogger(__name__) # Set the function that is called to build widgets when the window is visible self.frame.set_build_fn(self._build_fn) def destroy(self): # It will destroy all the children super().destroy() def __del__(self): self.destroy() @staticmethod def create_window(): return CesiumGeorefHelperWindow(width=250, height=600) def _convert_coordinates(self): # Get the CRS and check if it is valid, adjust UI values accordingly crs = get_crs_name_from_epsg(self._epsg_model.get_value_as_int()) if crs is None: self._epsg_name_model.set_value("Invalid EPSG Code") self._wgs84_latitude_model.set_value(math.nan) self._wgs84_longitude_model.set_value(math.nan) self._wgs84_height_model.set_value(math.nan) self._ecef_x_model.set_value(math.nan) self._ecef_y_model.set_value(math.nan) self._ecef_z_model.set_value(math.nan) return self._epsg_name_model.set_value(crs) # Convert coords to WGS84 and set in UI wgs84_coords = epsg_to_wgs84( self._epsg_model.as_string, self._easting_model.as_float, self._northing_model.as_float, self._elevation_model.as_float, ) self._wgs84_latitude_model.set_value(wgs84_coords[0]) self._wgs84_longitude_model.set_value(wgs84_coords[1]) self._wgs84_height_model.set_value(wgs84_coords[2]) # Convert coords to ECEF and set in UI ecef_coords = epsg_to_ecef( self._epsg_model.as_string, self._easting_model.as_float, self._northing_model.as_float, self._elevation_model.as_float, ) self._ecef_x_model.set_value(ecef_coords[0]) self._ecef_y_model.set_value(ecef_coords[1]) self._ecef_z_model.set_value(ecef_coords[2]) def _set_georeference_prim(self): if math.isnan(self._wgs84_latitude_model.get_value_as_float()): self._logger.warning("Cannot set CesiumGeoreference to NaN") return stage = omni.usd.get_context().get_stage() cesium_prim = stage.GetPrimAtPath("/CesiumGeoreference") cesium_prim.GetAttribute("cesium:georeferenceOrigin:latitude").Set( self._wgs84_latitude_model.get_value_as_float() ) cesium_prim.GetAttribute("cesium:georeferenceOrigin:longitude").Set( self._wgs84_longitude_model.get_value_as_float() ) cesium_prim.GetAttribute("cesium:georeferenceOrigin:height").Set( self._wgs84_height_model.get_value_as_float() ) @staticmethod def set_georef_from_environment(): stage = omni.usd.get_context().get_stage() environment_prim = stage.GetPrimAtPath("/Environment") cesium_prim = stage.GetPrimAtPath("/CesiumGeoreference") lat_attr = environment_prim.GetAttribute("location:latitude") long_attr = environment_prim.GetAttribute("location:longitude") if lat_attr and long_attr: cesium_prim.GetAttribute("cesium:georeferenceOrigin:latitude").Set(lat_attr.Get()) cesium_prim.GetAttribute("cesium:georeferenceOrigin:longitude").Set(long_attr.Get()) cesium_prim.GetAttribute("cesium:georeferenceOrigin:height").Set(0.0) else: logger = logging.getLogger(__name__) logger.warning( "Cannot set CesiumGeoreference as environment prim does not have latitude or longitude attributes" ) @staticmethod def set_georef_from_anchor(): logger = logging.getLogger(__name__) stage = omni.usd.get_context().get_stage() cesium_prim = stage.GetPrimAtPath("/CesiumGeoreference") if not cesium_prim.IsValid(): logger.error("No CesiumGeoreference found") return selection = omni.usd.get_context().get_selection().get_selected_prim_paths() for prim_path in selection: prim = stage.GetPrimAtPath(prim_path) latitude = prim.GetAttribute("cesium:anchor:latitude").Get() longitude = prim.GetAttribute("cesium:anchor:longitude").Get() height = prim.GetAttribute("cesium:anchor:height").Get() if latitude is not None and longitude is not None and height is not None: cesium_prim.GetAttribute("cesium:georeferenceOrigin:latitude").Set(latitude) cesium_prim.GetAttribute("cesium:georeferenceOrigin:longitude").Set(longitude) cesium_prim.GetAttribute("cesium:georeferenceOrigin:height").Set(height) return logger.error("Please select a prim with a globe anchor") def _build_fn(self): """Builds out the UI buttons and their handlers.""" with ui.VStack(spacing=4): label_style = {"Label": {"font_size": 16}} ui.Label( "Enter coordinates in any EPSG CRS to convert them to ECEF and WGS84", word_wrap=True, style=label_style, ) ui.Spacer(height=10) ui.Label("Your Project Details:", style=label_style) # TODO: Precision issues to resolve def on_coordinate_update(event): self._convert_coordinates() # Define the SimpleValueModels for the UI self._epsg_model = ui.SimpleIntModel(28356) self._epsg_name_model = ui.SimpleStringModel("") self._easting_model = ui.SimpleFloatModel(503000.0) self._northing_model = ui.SimpleFloatModel(6950000.0) self._elevation_model = ui.SimpleFloatModel(0.0) # Add the value changed callbacks self._epsg_model.add_value_changed_fn(on_coordinate_update) self._easting_model.add_value_changed_fn(on_coordinate_update) self._northing_model.add_value_changed_fn(on_coordinate_update) self._elevation_model.add_value_changed_fn(on_coordinate_update) # TODO: Make EPSG an autocomplete field int_field_with_label("EPSG Code", model=self._epsg_model) string_field_with_label("EPSG Name", model=self._epsg_name_model, enabled=False) float_field_with_label("Easting / X", model=self._easting_model) float_field_with_label("Northing / Y", model=self._northing_model) float_field_with_label("Elevation / Z", model=self._elevation_model) ui.Spacer(height=10) # TODO: It would be nice to be able to copy these fields, or potentially have two way editing ui.Label("WGS84 Results:", style=label_style) self._wgs84_latitude_model = ui.SimpleFloatModel(0.0) self._wgs84_longitude_model = ui.SimpleFloatModel(0.0) self._wgs84_height_model = ui.SimpleFloatModel(0.0) float_field_with_label("Latitude", model=self._wgs84_latitude_model, enabled=False) float_field_with_label("Longitude", model=self._wgs84_longitude_model, enabled=False) float_field_with_label("Elevation", model=self._wgs84_height_model, enabled=False) ui.Spacer(height=10) ui.Label("ECEF Results:", style=label_style) self._ecef_x_model = ui.SimpleFloatModel(0.0) self._ecef_y_model = ui.SimpleFloatModel(0.0) self._ecef_z_model = ui.SimpleFloatModel(0.0) float_field_with_label("X", model=self._ecef_x_model, enabled=False) float_field_with_label("Y", model=self._ecef_y_model, enabled=False) float_field_with_label("Z", model=self._ecef_z_model, enabled=False) ui.Button("Set Georeference from EPSG", height=20, clicked_fn=self._set_georeference_prim) ui.Button( "Set Georeference from Environment Prim", height=20, clicked_fn=self.set_georef_from_environment ) ui.Button("Set Georef from Selected Anchor", height=20, clicked_fn=self.set_georef_from_anchor) # Do the first conversion self._convert_coordinates()
8,726
Python
41.15942
118
0.628467
CesiumGS/cesium-omniverse/exts/cesium.powertools/cesium/powertools/georefhelper/proj.py
ECEF_EPSG = 4978 WGS84_EPSG = 4979 def get_crs_name_from_epsg(epsg_code): import pyproj try: return pyproj.crs.CRS.from_epsg(epsg_code).name except pyproj.exceptions.CRSError: return None def epsg_to_epsg(from_epsg, to_epsg, x, y, z): import pyproj from_crs = pyproj.crs.CRS.from_epsg(from_epsg) to_crs = pyproj.crs.CRS.from_epsg(to_epsg) # Define the from and to coordinate systems transformer = pyproj.Transformer.from_crs(from_crs, to_crs) # Convert ECEF coordinates to longitude, latitude, and height lat, lon, height = transformer.transform(x, y, z) return lat, lon, height def epsg_to_wgs84(from_epsg, x, y, z): return epsg_to_epsg(from_epsg, WGS84_EPSG, x, y, z) def epsg_to_ecef(from_epsg, x, y, z): return epsg_to_epsg(from_epsg, ECEF_EPSG, x, y, z) def ecef_to_wgs84(x, y, z): return epsg_to_epsg(ECEF_EPSG, WGS84_EPSG, x, y, z) def wgs84_to_ecef(x, y, z): return epsg_to_epsg(WGS84_EPSG, ECEF_EPSG, x, y, z)
1,012
Python
22.558139
65
0.658103
CesiumGS/cesium-omniverse/exts/cesium.powertools/cesium/powertools/utils/__init__.py
from .utils import * # noqa: F401 F403
40
Python
19.49999
39
0.675
CesiumGS/cesium-omniverse/exts/cesium.powertools/cesium/powertools/utils/utils.py
import logging import omni.usd from omni.kit.viewport.utility import get_active_viewport from pxr import Gf, UsdGeom, Sdf import json import carb.settings import os from cesium.omniverse.utils.cesium_interface import CesiumInterfaceManager from asyncio import ensure_future # Modified version of ScopedEdit in _build_viewport_cameras in omni.kit.widget.viewport class ScopedEdit: def __init__(self, stage): self.__stage = stage edit_target = stage.GetEditTarget() edit_layer = edit_target.GetLayer() self.__edit_layer = stage.GetSessionLayer() self.__was_editable = self.__edit_layer.permissionToEdit if not self.__was_editable: self.__edit_layer.SetPermissionToEdit(True) if self.__edit_layer != edit_layer: stage.SetEditTarget(self.__edit_layer) self.__edit_target = edit_target else: self.__edit_target = None def __del__(self): if self.__edit_layer and not self.__was_editable: self.__edit_layer.SetPermissionToEdit(False) self.__edit_layer = None if self.__edit_target: self.__stage.SetEditTarget(self.__edit_target) self.__edit_target = None def extend_far_plane(): stage = omni.usd.get_context().get_stage() viewport = get_active_viewport() camera_path = viewport.get_active_camera() camera = UsdGeom.Camera.Get(stage, camera_path) assert camera.GetPrim().IsValid() scoped_edit = ScopedEdit(stage) # noqa: F841 camera.GetClippingRangeAttr().Set(Gf.Vec2f(1.0, 10000000000.0)) def save_carb_settings(powertools_extension_location: str): carb_settings_path = os.path.join(powertools_extension_location, "carb_settings.txt") with open(carb_settings_path, "w") as fh: fh.write(json.dumps(carb.settings.get_settings().get("/"), indent=2)) def save_fabric_stage(powertools_extension_location: str): with CesiumInterfaceManager() as interface: fabric_stage_path = os.path.join(powertools_extension_location, "fabric_stage.txt") with open(fabric_stage_path, "w") as fh: fh.write(interface.print_fabric_stage()) # Helper function to search for an attribute on a prim, or create it if not present def get_or_create_attribute(prim, name, type): attribute = prim.GetAttribute(name) if not attribute: attribute = prim.CreateAttribute(name, type) return attribute def set_sunstudy_from_georef(): stage = omni.usd.get_context().get_stage() environment_prim = stage.GetPrimAtPath("/Environment") cesium_prim = stage.GetPrimAtPath("/CesiumGeoreference") lat_attr = get_or_create_attribute(environment_prim, "location:latitude", Sdf.ValueTypeNames.Float) lat_attr.Set(cesium_prim.GetAttribute("cesium:georeferenceOrigin:latitude").Get()) long_attr = get_or_create_attribute(environment_prim, "location:longitude", Sdf.ValueTypeNames.Float) long_attr.Set(cesium_prim.GetAttribute("cesium:georeferenceOrigin:longitude").Get()) north_attr = get_or_create_attribute(environment_prim, "location:north_orientation", Sdf.ValueTypeNames.Float) north_attr.Set(90.0) # Always set to 90, otherwise the sun is at the wrong angle
3,243
Python
37.164705
114
0.69411
CesiumGS/cesium-omniverse/exts/cesium.usd.plugins/cesium/usd/__init__.py
from .plugins import * # noqa: F401 F403
42
Python
20.49999
41
0.690476
CesiumGS/cesium-omniverse/exts/cesium.usd.plugins/cesium/usd/plugins/__init__.py
import os # noqa: F401 from pxr import Plug pluginsRoot = os.path.join(os.path.dirname(__file__), "../../../plugins") cesiumUsdSchemasPath = pluginsRoot + "/CesiumUsdSchemas/resources" Plug.Registry().RegisterPlugins(cesiumUsdSchemasPath) plugin = Plug.Registry().GetPluginWithName("CesiumUsdSchemas") if plugin: plugin.Load() else: print("Cannot find plugin")
372
Python
27.692306
73
0.739247
CesiumGS/cesium-omniverse/exts/cesium.usd.plugins/cesium/usd/plugins/CesiumUsdSchemas/__init__.py
from . import _CesiumUsdSchemas from pxr import Tf Tf.PrepareModule(_CesiumUsdSchemas, locals()) del Tf try: import __DOC __DOC.Execute(locals()) del __DOC except Exception: try: import __tmpDoc __tmpDoc.Execute(locals()) del __tmpDoc except Exception: pass
314
Python
14.749999
45
0.617834
CesiumGS/cesium-omniverse/exts/cesium.omniverse.cpp.tests/cesium/omniverse/cpp/tests/extension.py
import os import omni.ext import omni.usd import omni.kit.ui import omni.kit.app from .bindings import acquire_cesium_omniverse_tests_interface, release_cesium_omniverse_tests_interface class CesiumOmniverseCppTestsExtension(omni.ext.IExt): def __init__(self): super().__init__() self.tests_set_up = False self.frames_since_stage_opened = 0 self.frame_count_delta = 0 self.frames_between_setup_and_tests = 15 def on_startup(self): print("Starting Cesium Tests Extension...") global tests_interface tests_interface = acquire_cesium_omniverse_tests_interface() tests_interface.on_startup(os.path.join(os.path.dirname(__file__), "../../../../../cesium.omniverse")) update_stream = omni.kit.app.get_app().get_update_event_stream() # To ensure the tests only run after the stage has been opened, we # attach a handler to an event that occurs every frame. That handler # checks if the stage has opened, runs once, then detaches itself self._run_once_sub = update_stream.create_subscription_to_pop( self.run_once_after_stage_opens, name="Run once after stage opens" ) print("Started Cesium Tests Extension.") def run_once_after_stage_opens(self, _): # wait until the USD stage is fully set up if omni.usd.get_context().get_stage_state() == omni.usd.StageState.OPENED: # set up tests on one frame, then run the tests on the next frame # note we can't use wait_n_frames here as this is a subscribed function # so it cannot be async if not self.tests_set_up: self.tests_set_up = True print("Beginning Cesium Tests Extension tests") stageId = omni.usd.get_context().get_stage_id() tests_interface.set_up_tests(stageId) self.frame_count_delta = 1 elif self.frames_since_stage_opened >= self.frames_between_setup_and_tests: # unsubscribe so there's no way the next frame triggers another run self._run_once_sub.unsubscribe() tests_interface.run_all_tests() print("Cesium Tests Extension tests complete") self.frames_since_stage_opened += self.frame_count_delta def on_shutdown(self): print("Stopping Cesium Tests Extension...") tests_interface.on_shutdown() release_cesium_omniverse_tests_interface(tests_interface) print("Stopped Cesium Tests Extension.")
2,571
Python
41.163934
110
0.639051
CesiumGS/cesium-omniverse/exts/cesium.omniverse.cpp.tests/cesium/omniverse/cpp/tests/bindings/__init__.py
from .CesiumOmniverseCppTestsPythonBindings import * # noqa: F401 F403
72
Python
35.499982
71
0.819444
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/extension.py
from .bindings import acquire_cesium_omniverse_interface, release_cesium_omniverse_interface, Viewport from .ui.add_menu_controller import CesiumAddMenuController from .install import perform_vendor_install from .utils import wait_n_frames, dock_window_async, perform_action_after_n_frames_async from .usdUtils import ( add_tileset_ion, add_raster_overlay_ion, add_cartographic_polygon, get_or_create_cesium_data, get_or_create_cesium_georeference, ) from .ui.asset_window import CesiumOmniverseAssetWindow from .ui.debug_window import CesiumOmniverseDebugWindow from .ui.main_window import CesiumOmniverseMainWindow from .ui.settings_window import CesiumOmniverseSettingsWindow from .ui.credits_viewport_frame import CesiumCreditsViewportFrame from .ui.fabric_modal import CesiumFabricModal from .models import AssetToAdd, RasterOverlayToAdd from .ui import CesiumAttributesWidgetController import asyncio from functools import partial import logging import carb.events import carb.settings as omni_settings import omni.ext import omni.kit.app as omni_app import omni.kit.ui import omni.kit.pipapi from omni.kit.viewport.window import get_viewport_window_instances import omni.ui as ui import omni.usd import os from typing import List, Optional, Callable from .ui.credits_viewport_controller import CreditsViewportController from cesium.usd.plugins.CesiumUsdSchemas import Data as CesiumData, IonServer as CesiumIonServer from omni.kit.capture.viewport import CaptureExtension CESIUM_DATA_PRIM_PATH = "/Cesium" cesium_extension_location = os.path.join(os.path.dirname(__file__), "../../") class CesiumOmniverseExtension(omni.ext.IExt): @staticmethod def _set_menu(path, value): # Set the menu to create this window on and off editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: editor_menu.set_value(path, value) def __init__(self) -> None: super().__init__() self._main_window: Optional[CesiumOmniverseMainWindow] = None self._asset_window: Optional[CesiumOmniverseAssetWindow] = None self._debug_window: Optional[CesiumOmniverseDebugWindow] = None self._settings_window: Optional[CesiumOmniverseSettingsWindow] = None self._credits_viewport_frames: List[CesiumCreditsViewportFrame] = [] self._on_stage_subscription: Optional[carb.events.ISubscription] = None self._on_update_subscription: Optional[carb.events.ISubscription] = None self._show_asset_window_subscription: Optional[carb.events.ISubscription] = None self._token_set_subscription: Optional[carb.events.ISubscription] = None self._add_ion_asset_subscription: Optional[carb.events.ISubscription] = None self._add_blank_asset_subscription: Optional[carb.events.ISubscription] = None self._add_raster_overlay_subscription: Optional[carb.events.ISubscription] = None self._add_cartographic_polygon_subscription: Optional[carb.events.ISubscription] = None self._assets_to_add_after_token_set: List[AssetToAdd] = [] self._raster_overlay_to_add_after_token_set: List[RasterOverlayToAdd] = [] self._adding_assets = False self._attributes_widget_controller: Optional[CesiumAttributesWidgetController] = None self._credits_viewport_controller: Optional[CreditsViewportController] = None self._add_menu_controller: Optional[CesiumAddMenuController] = None self._logger: logging.Logger = logging.getLogger(__name__) self._menus = [] self._num_credits_viewport_frames: int = 0 self._capture_instance = None perform_vendor_install() def on_startup(self): # The ability to show up the window if the system requires it. We use it in QuickLayout. ui.Workspace.set_show_window_fn(CesiumOmniverseMainWindow.WINDOW_NAME, partial(self.show_main_window, None)) ui.Workspace.set_show_window_fn( CesiumOmniverseAssetWindow.WINDOW_NAME, partial(self.show_assets_window, None) ) ui.Workspace.set_show_window_fn(CesiumOmniverseDebugWindow.WINDOW_NAME, partial(self.show_debug_window, None)) ui.Workspace.set_show_window_fn( CesiumOmniverseSettingsWindow.WINDOW_NAME, partial(self.show_settings_window, None) ) settings = omni_settings.get_settings() show_on_startup = settings.get_as_bool("/exts/cesium.omniverse/showOnStartup") self._add_to_menu(CesiumOmniverseMainWindow.MENU_PATH, self.show_main_window, show_on_startup) self._add_to_menu(CesiumOmniverseAssetWindow.MENU_PATH, self.show_assets_window, False) self._add_to_menu(CesiumOmniverseDebugWindow.MENU_PATH, self.show_debug_window, False) self._add_to_menu(CesiumOmniverseSettingsWindow.MENU_PATH, self.show_settings_window, False) self._logger.info("CesiumOmniverse startup") # Acquire the Cesium Omniverse interface. global _cesium_omniverse_interface _cesium_omniverse_interface = acquire_cesium_omniverse_interface() _cesium_omniverse_interface.on_startup(cesium_extension_location) settings.set("/rtx/hydra/TBNFrameMode", 1) # Allow material graph to find cesium mdl exports mdl_custom_paths_name = "materialConfig/searchPaths/custom" mdl_user_allow_list_name = "materialConfig/materialGraph/userAllowList" mdl_renderer_custom_paths_name = "/renderer/mdl/searchPaths/custom" cesium_mdl_search_path = os.path.join(cesium_extension_location, "mdl") cesium_mdl_name = "cesium.mdl" mdl_custom_paths = settings.get(mdl_custom_paths_name) or [] mdl_user_allow_list = settings.get(mdl_user_allow_list_name) or [] mdl_custom_paths.append(cesium_mdl_search_path) mdl_user_allow_list.append(cesium_mdl_name) mdl_renderer_custom_paths = settings.get_as_string(mdl_renderer_custom_paths_name) mdl_renderer_custom_paths_sep = "" if mdl_renderer_custom_paths == "" else ";" mdl_renderer_custom_paths = mdl_renderer_custom_paths + mdl_renderer_custom_paths_sep + cesium_mdl_search_path settings.set_string_array(mdl_custom_paths_name, mdl_custom_paths) settings.set_string_array(mdl_user_allow_list_name, mdl_user_allow_list) settings.set_string(mdl_renderer_custom_paths_name, mdl_renderer_custom_paths) # Show the window. It will call `self.show_window` if show_on_startup: asyncio.ensure_future(perform_action_after_n_frames_async(15, CesiumOmniverseExtension._open_window)) self._credits_viewport_controller = CreditsViewportController(_cesium_omniverse_interface) self._add_menu_controller = CesiumAddMenuController(_cesium_omniverse_interface) # Subscribe to stage event stream usd_context = omni.usd.get_context() if usd_context.get_stage_state() == omni.usd.StageState.OPENED: _cesium_omniverse_interface.on_stage_change(usd_context.get_stage_id()) self._on_stage_subscription = usd_context.get_stage_event_stream().create_subscription_to_pop( self._on_stage_event, name="cesium.omniverse.ON_STAGE_EVENT" ) self._on_update_subscription = ( omni_app.get_app() .get_update_event_stream() .create_subscription_to_pop(self._on_update_frame, name="cesium.omniverse.extension.ON_UPDATE_FRAME") ) bus = omni_app.get_app().get_message_bus_event_stream() show_asset_window_event = carb.events.type_from_string("cesium.omniverse.SHOW_ASSET_WINDOW") self._show_asset_window_subscription = bus.create_subscription_to_pop_by_type( show_asset_window_event, self._on_show_asset_window_event ) token_set_event = carb.events.type_from_string("cesium.omniverse.SET_DEFAULT_TOKEN_SUCCESS") self._token_set_subscription = bus.create_subscription_to_pop_by_type(token_set_event, self._on_token_set) add_ion_asset_event = carb.events.type_from_string("cesium.omniverse.ADD_ION_ASSET") self._add_ion_asset_subscription = bus.create_subscription_to_pop_by_type( add_ion_asset_event, self._on_add_ion_asset_event ) add_blank_asset_event = carb.events.type_from_string("cesium.omniverse.ADD_BLANK_ASSET") self._add_blank_asset_subscription = bus.create_subscription_to_pop_by_type( add_blank_asset_event, self._on_add_blank_asset_event ) add_cartographic_polygon_event = carb.events.type_from_string("cesium.omniverse.ADD_CARTOGRAPHIC_POLYGON") self._add_cartographic_polygon_subscription = bus.create_subscription_to_pop_by_type( add_cartographic_polygon_event, self._on_add_cartographic_polygon_event ) add_raster_overlay_event = carb.events.type_from_string("cesium.omniverse.ADD_RASTER_OVERLAY") self._add_raster_overlay_subscription = bus.create_subscription_to_pop_by_type( add_raster_overlay_event, self._on_add_raster_overlay_to_tileset ) self._capture_instance = CaptureExtension.get_instance() def on_shutdown(self): self._menus.clear() if self._main_window is not None: self._main_window.destroy() self._main_window = None if self._asset_window is not None: self._asset_window.destroy() self._asset_window = None if self._debug_window is not None: self._debug_window.destroy() self._debug_window = None if self._settings_window is not None: self._settings_window.destroy() self._settings_window = None if self._credits_viewport_controller is not None: self._credits_viewport_controller.destroy() self._credits_viewport_controller = None # Deregister the function that shows the window from omni.ui ui.Workspace.set_show_window_fn(CesiumOmniverseMainWindow.WINDOW_NAME, None) ui.Workspace.set_show_window_fn(CesiumOmniverseAssetWindow.WINDOW_NAME, None) ui.Workspace.set_show_window_fn(CesiumOmniverseDebugWindow.WINDOW_NAME, None) ui.Workspace.set_show_window_fn(CesiumOmniverseSettingsWindow.WINDOW_NAME, None) if self._on_stage_subscription is not None: self._on_stage_subscription.unsubscribe() self._on_stage_subscription = None if self._on_update_subscription is not None: self._on_update_subscription.unsubscribe() self._on_update_subscription = None if self._token_set_subscription is not None: self._token_set_subscription.unsubscribe() self._token_set_subscription = None if self._add_ion_asset_subscription is not None: self._add_ion_asset_subscription.unsubscribe() self._add_ion_asset_subscription = None if self._add_blank_asset_subscription is not None: self._add_blank_asset_subscription.unsubscribe() self._add_blank_asset_subscription = None if self._add_raster_overlay_subscription is not None: self._add_raster_overlay_subscription.unsubscribe() self._add_raster_overlay_subscription = None if self._add_cartographic_polygon_subscription is not None: self._add_cartographic_polygon_subscription.unsubscribe() self._add_cartographic_polygon_subscription = None if self._show_asset_window_subscription is not None: self._show_asset_window_subscription.unsubscribe() self._show_asset_window_subscription = None if self._attributes_widget_controller is not None: self._attributes_widget_controller.destroy() self._attributes_widget_controller = None if self._add_menu_controller is not None: self._add_menu_controller.destroy() self._add_menu_controller = None self._capture_instance = None self._destroy_credits_viewport_frames() self._logger.info("CesiumOmniverse shutdown") # Release the Cesium Omniverse interface. _cesium_omniverse_interface.on_shutdown() release_cesium_omniverse_interface(_cesium_omniverse_interface) def _on_update_frame(self, _): if omni.usd.get_context().get_stage_state() != omni.usd.StageState.OPENED: return viewports = [] for instance in get_viewport_window_instances(): viewport_api = instance.viewport_api viewport = Viewport() viewport.viewMatrix = viewport_api.view viewport.projMatrix = viewport_api.projection viewport.width = float(viewport_api.resolution[0]) viewport.height = float(viewport_api.resolution[1]) viewports.append(viewport) if len(viewports) != self._num_credits_viewport_frames: self._setup_credits_viewport_frames() self._num_credits_viewport_frames = len(viewports) wait_for_loading_tiles = ( self._capture_instance.progress.capture_status == omni.kit.capture.viewport.CaptureStatus.CAPTURING ) _cesium_omniverse_interface.on_update_frame(viewports, wait_for_loading_tiles) def _on_stage_event(self, event): if _cesium_omniverse_interface is None: return if event.type == int(omni.usd.StageEventType.OPENED): _cesium_omniverse_interface.on_stage_change(omni.usd.get_context().get_stage_id()) self._attributes_widget_controller = CesiumAttributesWidgetController(_cesium_omniverse_interface) # Show Fabric modal if Fabric is disabled. fabric_enabled = omni_settings.get_settings().get_as_bool("/app/useFabricSceneDelegate") if not fabric_enabled: asyncio.ensure_future(perform_action_after_n_frames_async(15, CesiumOmniverseExtension._open_modal)) get_or_create_cesium_data() get_or_create_cesium_georeference() self._setup_ion_server_prims() elif event.type == int(omni.usd.StageEventType.CLOSED): _cesium_omniverse_interface.on_stage_change(0) if self._attributes_widget_controller is not None: self._attributes_widget_controller.destroy() self._attributes_widget_controller = None def _on_show_asset_window_event(self, _): self.do_show_assets_window() def _on_token_set(self, _: carb.events.IEvent): if self._adding_assets: return self._adding_assets = True for asset in self._assets_to_add_after_token_set: self._add_ion_assets(asset) self._assets_to_add_after_token_set.clear() for raster_overlay in self._raster_overlay_to_add_after_token_set: self._add_raster_overlay_to_tileset(raster_overlay) self._raster_overlay_to_add_after_token_set.clear() self._adding_assets = False def _on_add_ion_asset_event(self, event: carb.events.IEvent): asset_to_add = AssetToAdd.from_event(event) self._add_ion_assets(asset_to_add) def _on_add_blank_asset_event(self, event: carb.events.IEvent): asset_to_add = AssetToAdd.from_event(event) self._add_ion_assets(asset_to_add, skip_ion_checks=True) def _on_add_cartographic_polygon_event(self, event: carb.events.IEvent): self._add_cartographic_polygon_assets() def _add_ion_assets(self, asset_to_add: Optional[AssetToAdd], skip_ion_checks=False): if asset_to_add is None: self._logger.warning("Insufficient information to add asset.") return if not skip_ion_checks: session = _cesium_omniverse_interface.get_session() if not session.is_connected(): self._logger.warning("Must be logged in to add ion asset.") return if not _cesium_omniverse_interface.is_default_token_set(): bus = omni_app.get_app().get_message_bus_event_stream() show_token_window_event = carb.events.type_from_string("cesium.omniverse.SHOW_TOKEN_WINDOW") bus.push(show_token_window_event) self._assets_to_add_after_token_set.append(asset_to_add) return if asset_to_add.raster_overlay_name is not None and asset_to_add.raster_overlay_ion_asset_id is not None: tileset_path = add_tileset_ion(asset_to_add.tileset_name, asset_to_add.tileset_ion_asset_id) add_raster_overlay_ion( tileset_path, asset_to_add.raster_overlay_name, asset_to_add.raster_overlay_ion_asset_id ) else: tileset_path = add_tileset_ion(asset_to_add.tileset_name, asset_to_add.tileset_ion_asset_id) if tileset_path == "": self._logger.warning("Error adding tileset and raster overlay to stage") def _add_cartographic_polygon_assets(self): add_cartographic_polygon() def _on_add_raster_overlay_to_tileset(self, event: carb.events.IEvent): raster_overlay_to_add = RasterOverlayToAdd.from_event(event) if raster_overlay_to_add is None: self._logger.warning("Insufficient information to add raster overlay.") self._add_raster_overlay_to_tileset(raster_overlay_to_add) def _add_raster_overlay_to_tileset(self, raster_overlay_to_add: RasterOverlayToAdd): session = _cesium_omniverse_interface.get_session() if not session.is_connected(): self._logger.warning("Must be logged in to add ion asset.") return if not _cesium_omniverse_interface.is_default_token_set(): bus = omni_app.get_app().get_message_bus_event_stream() show_token_window_event = carb.events.type_from_string("cesium.omniverse.SHOW_TOKEN_WINDOW") bus.push(show_token_window_event) self._raster_overlay_to_add_after_token_set.append(raster_overlay_to_add) return add_raster_overlay_ion( raster_overlay_to_add.tileset_path, raster_overlay_to_add.raster_overlay_name, raster_overlay_to_add.raster_overlay_ion_asset_id, ) _cesium_omniverse_interface.reload_tileset(raster_overlay_to_add.tileset_path) def _add_to_menu(self, path, callback: Callable[[bool], None], show_on_startup): editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: self._menus.append(editor_menu.add_item(path, callback, toggle=True, value=show_on_startup)) async def _destroy_window_async(self, path): # Wait one frame, this is due to the one frame defer in Window::_moveToMainOSWindow() await wait_n_frames(1) if path is CesiumOmniverseMainWindow.MENU_PATH: if self._main_window is not None: self._main_window.destroy() self._main_window = None elif path is CesiumOmniverseAssetWindow.MENU_PATH: if self._asset_window is not None: self._asset_window.destroy() self._asset_window = None elif path is CesiumOmniverseDebugWindow.MENU_PATH: if self._debug_window is not None: self._debug_window.destroy() self._debug_window = None elif path is CesiumOmniverseSettingsWindow.MENU_PATH: if self._settings_window is not None: self._settings_window.destroy() self._settings_window = None def _visibility_changed_fn(self, path, visible): # Called when the user pressed "X" self._set_menu(path, visible) if not visible: # Destroy the window, since we are creating new window in show_window asyncio.ensure_future(self._destroy_window_async(path)) def show_main_window(self, _menu, value): if _cesium_omniverse_interface is None: logging.error("Cesium Omniverse Interface is not set.") return if value: self._main_window = CesiumOmniverseMainWindow(_cesium_omniverse_interface, width=300, height=400) self._main_window.set_visibility_changed_fn( partial(self._visibility_changed_fn, CesiumOmniverseMainWindow.MENU_PATH) ) asyncio.ensure_future(dock_window_async(self._main_window)) elif self._main_window is not None: self._main_window.visible = False def do_show_assets_window(self): if self._asset_window: self._asset_window.focus() return self._asset_window = CesiumOmniverseAssetWindow(_cesium_omniverse_interface, width=700, height=300) self._asset_window.set_visibility_changed_fn( partial(self._visibility_changed_fn, CesiumOmniverseAssetWindow.MENU_PATH) ) asyncio.ensure_future(dock_window_async(self._asset_window, "Content")) def show_assets_window(self, _menu, value): if _cesium_omniverse_interface is None: logging.error("Cesium Omniverse Interface is not set.") return if value: self.do_show_assets_window() elif self._asset_window is not None: self._asset_window.visible = False def show_debug_window(self, _menu, value): if _cesium_omniverse_interface is None: logging.error("Cesium Omniverse Interface is not set.") return if value: self._debug_window = CesiumOmniverseDebugWindow( _cesium_omniverse_interface, CesiumOmniverseDebugWindow.WINDOW_NAME, width=300, height=365 ) self._debug_window.set_visibility_changed_fn( partial(self._visibility_changed_fn, CesiumOmniverseDebugWindow.MENU_PATH) ) asyncio.ensure_future(dock_window_async(self._debug_window)) elif self._debug_window is not None: self._debug_window.visible = False def show_settings_window(self, _menu, value): if _cesium_omniverse_interface is None: logging.error("Cesium Omniverse Interface is not set.") return if value: self._settings_window = CesiumOmniverseSettingsWindow( _cesium_omniverse_interface, CesiumOmniverseSettingsWindow.WINDOW_NAME, width=300, height=365 ) self._settings_window.set_visibility_changed_fn( partial(self._visibility_changed_fn, CesiumOmniverseSettingsWindow.MENU_PATH) ) asyncio.ensure_future(dock_window_async(self._settings_window)) elif self._settings_window is not None: self._settings_window.visible = False def _setup_credits_viewport_frames(self): self._destroy_credits_viewport_frames() self._credits_viewport_frames = [ CesiumCreditsViewportFrame(_cesium_omniverse_interface, i) for i in get_viewport_window_instances() ] if self._credits_viewport_controller is not None: self._credits_viewport_controller.broadcast_credits() def _destroy_credits_viewport_frames(self): for credits_viewport_frame in self._credits_viewport_frames: credits_viewport_frame.destroy() self._credits_viewport_frames.clear() @staticmethod def _open_window(): ui.Workspace.show_window(CesiumOmniverseMainWindow.WINDOW_NAME) @staticmethod def _open_modal(): CesiumFabricModal() def _setup_ion_server_prims(self): # TODO: Move a lot of this to usdUtils.py stage = omni.usd.get_context().get_stage() server_prims: List[CesiumIonServer] = [x for x in stage.Traverse() if x.IsA(CesiumIonServer)] if len(server_prims) < 1: # If we have no ion server prims, lets add a default one for the official ion servers. path = "/CesiumServers/IonOfficial" prim: CesiumIonServer = CesiumIonServer.Define(stage, path) prim.GetDisplayNameAttr().Set("ion.cesium.com") prim.GetIonServerUrlAttr().Set("https://ion.cesium.com/") prim.GetIonServerApiUrlAttr().Set("https://api.cesium.com/") prim.GetIonServerApplicationIdAttr().Set(413) data_prim: CesiumData = CesiumData.Get(stage, CESIUM_DATA_PRIM_PATH) data_prim.GetSelectedIonServerRel().AddTarget(path)
24,467
Python
44.227357
118
0.666285
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/__init__.py
from .extension import * # noqa: F401 F403 F405 from .utils import * # noqa: F401 F403 F405 from .usdUtils import * # noqa: F401 F403 F405 from .ui import * # noqa: F401 F403 F405
184
Python
35.999993
48
0.695652
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/usdUtils/usdUtils.py
import omni.usd import re from pxr import Sdf from typing import List, Optional from pxr import UsdGeom from cesium.usd.plugins.CesiumUsdSchemas import ( Data as CesiumData, Tileset as CesiumTileset, IonRasterOverlay as CesiumIonRasterOverlay, Georeference as CesiumGeoreference, GlobeAnchorAPI as CesiumGlobeAnchorAPI, Tokens as CesiumTokens, ) CESIUM_DATA_PRIM_PATH = "/Cesium" CESIUM_GEOREFERENCE_PRIM_PATH = "/CesiumGeoreference" def get_safe_name(name: str) -> str: return re.sub("[\\W]+", "_", name) def get_or_create_cesium_data() -> CesiumData: stage = omni.usd.get_context().get_stage() path = CESIUM_DATA_PRIM_PATH prim = stage.GetPrimAtPath(path) if prim.IsValid(): return CesiumData.Get(stage, path) return CesiumData.Define(stage, path) def get_or_create_cesium_georeference() -> CesiumGeoreference: stage = omni.usd.get_context().get_stage() georeference_paths = get_georeference_paths() if len(georeference_paths) < 1: return CesiumGeoreference.Define(stage, CESIUM_GEOREFERENCE_PRIM_PATH) return CesiumGeoreference.Get(stage, georeference_paths[0]) def add_tileset_ion(name: str, asset_id: int, token: str = "") -> str: stage = omni.usd.get_context().get_stage() safe_name = get_safe_name(name) if not safe_name.startswith("/"): safe_name = "/" + safe_name # get_stage_next_free_path will increment the path name if there is a collision tileset_path = omni.usd.get_stage_next_free_path(stage, safe_name, False) tileset = CesiumTileset.Define(stage, tileset_path) tileset.GetIonAssetIdAttr().Set(asset_id) tileset.GetIonAccessTokenAttr().Set(token) tileset.GetSourceTypeAttr().Set(CesiumTokens.ion) georeference = get_or_create_cesium_georeference() georeference_path = georeference.GetPath().pathString tileset.GetGeoreferenceBindingRel().AddTarget(georeference_path) server_prim_path = get_path_to_current_ion_server() if server_prim_path != "": tileset.GetIonServerBindingRel().AddTarget(server_prim_path) return tileset_path def add_raster_overlay_ion(tileset_path: str, name: str, asset_id: int, token: str = "") -> str: stage = omni.usd.get_context().get_stage() safe_name = get_safe_name(name) raster_overlay_path = Sdf.Path(tileset_path).AppendPath(safe_name).pathString # get_stage_next_free_path will increment the path name if there is a collision raster_overlay_path = omni.usd.get_stage_next_free_path(stage, raster_overlay_path, False) raster_overlay = CesiumIonRasterOverlay.Define(stage, raster_overlay_path) tileset_prim = CesiumTileset.Get(stage, tileset_path) tileset_prim.GetRasterOverlayBindingRel().AddTarget(raster_overlay_path) raster_overlay.GetIonAssetIdAttr().Set(asset_id) raster_overlay.GetIonAccessTokenAttr().Set(token) server_prim_path = get_path_to_current_ion_server() if server_prim_path != "": raster_overlay.GetIonServerBindingRel().AddTarget(server_prim_path) return raster_overlay_path def add_cartographic_polygon() -> str: stage = omni.usd.get_context().get_stage() name = "cartographic_polygon" cartographic_polygon_path = Sdf.Path("/CesiumCartographicPolygons").AppendPath(name).pathString cartographic_polygon_path = omni.usd.get_stage_next_free_path(stage, cartographic_polygon_path, False) basis_curves = UsdGeom.BasisCurves.Define(stage, cartographic_polygon_path) basis_curves.GetTypeAttr().Set("linear") basis_curves.GetWrapAttr().Set("periodic") # Set curve to have 10m edge lengths curve_size = 10 / UsdGeom.GetStageMetersPerUnit(stage) basis_curves.GetPointsAttr().Set( [ (-curve_size, 0, -curve_size), (-curve_size, 0, curve_size), (curve_size, 0, curve_size), (curve_size, 0, -curve_size), ] ) basis_curves.GetCurveVertexCountsAttr().Set([4]) # Set curve to a 0.5m width curve_width = 0.5 / UsdGeom.GetStageMetersPerUnit(stage) basis_curves.GetWidthsAttr().Set([curve_width, curve_width, curve_width, curve_width]) add_globe_anchor_to_prim(cartographic_polygon_path) return cartographic_polygon_path def is_tileset(path: str) -> bool: stage = omni.usd.get_context().get_stage() prim = stage.GetPrimAtPath(path) return prim.IsA(CesiumTileset) def remove_tileset(path: str) -> None: stage = omni.usd.get_context().get_stage() stage.RemovePrim(path) def get_path_to_current_ion_server() -> Optional[str]: data = get_or_create_cesium_data() rel = data.GetSelectedIonServerRel() targets = rel.GetForwardedTargets() if len(targets) < 1: return None return targets[0].pathString def set_path_to_current_ion_server(path: str) -> None: data = get_or_create_cesium_data() rel = data.GetSelectedIonServerRel() # This check helps avoid sending unnecessary USD notifications # See https://github.com/CesiumGS/cesium-omniverse/issues/640 if get_path_to_current_ion_server() != path: rel.SetTargets([path]) def get_tileset_paths() -> List[str]: stage = omni.usd.get_context().get_stage() paths = [x.GetPath().pathString for x in stage.Traverse() if x.IsA(CesiumTileset)] return paths def get_georeference_paths() -> List[str]: stage = omni.usd.get_context().get_stage() paths = [x.GetPath().pathString for x in stage.Traverse() if x.IsA(CesiumGeoreference)] return paths def add_globe_anchor_to_prim(path: str) -> CesiumGlobeAnchorAPI: stage = omni.usd.get_context().get_stage() prim = stage.GetPrimAtPath(path) georeference_path = get_or_create_cesium_georeference().GetPath().pathString globe_anchor = CesiumGlobeAnchorAPI.Apply(prim) globe_anchor.GetGeoreferenceBindingRel().AddTarget(georeference_path) return globe_anchor
5,914
Python
30.972973
106
0.701048
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/usdUtils/__init__.py
from .usdUtils import * # noqa: F401 F403
43
Python
20.99999
42
0.697674
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/install/wheel_installer.py
from dataclasses import dataclass import logging from pathlib import Path import platform import omni.kit.app as app import omni.kit.pipapi from ..utils.utils import str_is_empty_or_none @dataclass class WheelInfo: """ Data class containing the module and wheel file names for each platform. """ module: str windows_whl: str linux_x64_whl: str linux_aarch_whl: str class WheelInstaller: """ Class for installing wheel files bundled with the extension. """ def __init__(self, info: WheelInfo, extension_module="cesium.omniverse"): """ Creates a new instance of a wheel installer for installing a python package. :param info: A WheelInfo data class containing the information for wheel installation. :param extension_module: The full module for the extension, if a different extension is using this class. :raises ValueError: If any arguments are null or empty strings. """ self._logger = logging.getLogger(__name__) if ( str_is_empty_or_none(info.windows_whl) or str_is_empty_or_none(info.linux_x64_whl) or str_is_empty_or_none(info.linux_aarch_whl) ): raise ValueError(f"One or more wheels is missing for {info.module}.") self._info = info manager = app.get_app().get_extension_manager() ext_id = manager.get_extension_id_by_module(extension_module) self._vendor_directory_path = Path(manager.get_extension_path(ext_id)).joinpath("vendor") def install(self) -> bool: """ Installs the correct wheel for the current platform. :return: ``True`` if the installation was successful. """ if platform.system() == "Windows": return self._perform_install(self._info.windows_whl) else: machine = platform.machine() if machine.startswith("arm") or machine.startswith("aarch"): return self._perform_install(self._info.linux_aarch_whl) return self._perform_install(self._info.linux_x64_whl) def _perform_install(self, wheel_file_name: str) -> bool: """ Performs the actual installation of the wheel file. :param wheel_file_name: The file name of the wheel to install. :return: ``True`` if the installation was successful. """ path = self._vendor_directory_path.joinpath(wheel_file_name) return omni.kit.pipapi.install( package=str(path), module=self._info.module, use_online_index=False, ignore_cache=True, ignore_import_check=False, )
2,682
Python
30.940476
113
0.631991
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/install/vendor_install.py
import logging from typing import List from .wheel_installer import WheelInfo, WheelInstaller def perform_vendor_install(): logger = logging.getLogger(__name__) # Only vendor wheels for the main Cesium Omniverse extension should be placed here. # This action needs to be mirrored for each extension. vendor_wheels: List[WheelInfo] = [ WheelInfo( module="lxml", windows_whl="lxml-4.9.2-cp310-cp310-win_amd64.whl", linux_x64_whl=( "lxml-4.9.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl" ), linux_aarch_whl=( "lxml-4.9.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_24_aarch64.whl" ), ) ] for w in vendor_wheels: installer = WheelInstaller(w) if not installer.install(): logger.error(f"Could not install wheel for {w.module}")
964
Python
32.275861
112
0.623444
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/install/__init__.py
from .wheel_installer import WheelInfo, WheelInstaller # noqa: F401 F403 from .vendor_install import perform_vendor_install # noqa: F401 F403
144
Python
47.333318
73
0.791667
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/asset_details_widget.py
from typing import Optional import carb.events import omni.kit.app as app import omni.ui as ui import omni.usd as usd from ..bindings import ICesiumOmniverseInterface from .models import IonAssetItem from ..models import AssetToAdd, RasterOverlayToAdd from .styles import CesiumOmniverseUiStyles from ..usdUtils import is_tileset, get_tileset_paths class CesiumAssetDetailsWidget(ui.ScrollingFrame): def __init__( self, cesium_omniverse_interface: ICesiumOmniverseInterface, asset: Optional[IonAssetItem] = None, **kwargs ): super().__init__(**kwargs) self._cesium_omniverse_interface = cesium_omniverse_interface self.style = CesiumOmniverseUiStyles.asset_detail_frame self._name = asset.name.as_string if asset else "" self._id = asset.id.as_int if asset else 0 self._description = asset.description.as_string if asset else "" self._attribution = asset.attribution.as_string if asset else "" self._asset_type = asset.type.as_string if asset else "" self._name_label: Optional[ui.Label] = None self._id_label: Optional[ui.Label] = None self._description_label: Optional[ui.Label] = None self._attribution_label: Optional[ui.Label] = None self.set_build_fn(self._build_fn) def __del__(self): self.destroy() def destroy(self) -> None: if self._name_label is not None: self._name_label.destroy() if self._id_label is not None: self._id_label.destroy() if self._description_label is not None: self._description_label.destroy() if self._attribution_label is not None: self._attribution_label.destroy() def update_selection(self, asset: Optional[IonAssetItem]): self._name = asset.name.as_string if asset else "" self._id = asset.id.as_int if asset else 0 self._description = asset.description.as_string if asset else "" self._attribution = asset.attribution.as_string if asset else "" self._asset_type = asset.type.as_string if asset else "" self.rebuild() def _should_be_visible(self): return self._name != "" or self._id != 0 or self._description != "" or self._attribution != "" def _add_overlay_with_tileset(self): asset_to_add = AssetToAdd("Cesium World Terrain", 1, self._name, self._id) add_asset_event = carb.events.type_from_string("cesium.omniverse.ADD_ION_ASSET") app.get_app().get_message_bus_event_stream().push(add_asset_event, payload=asset_to_add.to_dict()) def _add_tileset_button_clicked(self): asset_to_add = AssetToAdd(self._name, self._id) add_asset_event = carb.events.type_from_string("cesium.omniverse.ADD_ION_ASSET") app.get_app().get_message_bus_event_stream().push(add_asset_event, payload=asset_to_add.to_dict()) def _add_raster_overlay_button_clicked(self): context = usd.get_context() selection = context.get_selection().get_selected_prim_paths() tileset_path: Optional[str] = None if len(selection) > 0 and is_tileset(context.get_stage().GetPrimAtPath(selection[0])): tileset_path = selection[0] if tileset_path is None: all_tileset_paths = get_tileset_paths() if len(all_tileset_paths) > 0: tileset_path = all_tileset_paths[0] else: self._add_overlay_with_tileset() return raster_overlay_to_add = RasterOverlayToAdd(tileset_path, self._id, self._name) add_raster_overlay_event = carb.events.type_from_string("cesium.omniverse.ADD_RASTER_OVERLAY") app.get_app().get_message_bus_event_stream().push( add_raster_overlay_event, payload=raster_overlay_to_add.to_dict() ) def _build_fn(self): with self: if self._should_be_visible(): with ui.VStack(spacing=20): with ui.VStack(spacing=5): ui.Label( self._name, style=CesiumOmniverseUiStyles.asset_detail_name_label, height=0, word_wrap=True, ) ui.Label( f"(ID: {self._id})", style=CesiumOmniverseUiStyles.asset_detail_id_label, height=0, word_wrap=True, ) with ui.HStack(spacing=0, height=0): ui.Spacer(height=0) if self._asset_type == "3DTILES" or self._asset_type == "TERRAIN": ui.Button( "Add to Stage", width=0, height=0, style=CesiumOmniverseUiStyles.blue_button_style, clicked_fn=self._add_tileset_button_clicked, ) elif self._asset_type == "RASTER_OVERLAY": ui.Button( "Use as Terrain Tileset Base Layer", width=0, height=0, style=CesiumOmniverseUiStyles.blue_button_style, clicked_fn=self._add_raster_overlay_button_clicked, ) else: # Skipping adding a button for things we cannot add for now. pass ui.Spacer(height=0) with ui.VStack(spacing=5): ui.Label("Description", style=CesiumOmniverseUiStyles.asset_detail_header_label, height=0) ui.Label(self._description, word_wrap=True, alignment=ui.Alignment.TOP, height=0) with ui.VStack(spacing=5): ui.Label("Attribution", style=CesiumOmniverseUiStyles.asset_detail_header_label, height=0) ui.Label(self._attribution, word_wrap=True, alignment=ui.Alignment.TOP, height=0) else: ui.Spacer()
6,333
Python
42.682758
115
0.552503
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/debug_window.py
import logging from typing import Optional import omni.ui as ui from .statistics_widget import CesiumOmniverseStatisticsWidget from ..bindings import ICesiumOmniverseInterface from ..usdUtils import remove_tileset, get_tileset_paths class CesiumOmniverseDebugWindow(ui.Window): WINDOW_NAME = "Cesium Debugging" MENU_PATH = f"Window/Cesium/{WINDOW_NAME}" _logger: logging.Logger _cesium_omniverse_interface: Optional[ICesiumOmniverseInterface] = None def __init__(self, cesium_omniverse_interface: ICesiumOmniverseInterface, title: str, **kwargs): super().__init__(title, **kwargs) self._logger = logging.getLogger(__name__) self._cesium_omniverse_interface = cesium_omniverse_interface self._statistics_widget: Optional[CesiumOmniverseStatisticsWidget] = None # Set the function that is called to build widgets when the window is visible self.frame.set_build_fn(self._build_fn) def destroy(self): if self._statistics_widget is not None: self._statistics_widget.destroy() self._statistics_widget = None # It will destroy all the children super().destroy() def __del__(self): self.destroy() @staticmethod def show_window(): ui.Workspace.show_window(CesiumOmniverseDebugWindow.WINDOW_NAME) def _build_fn(self): """Builds out the UI buttons and their handlers.""" def remove_all_tilesets(): """Removes all tilesets from the stage.""" tileset_paths = get_tileset_paths() for tileset_path in tileset_paths: remove_tileset(tileset_path) def reload_all_tilesets(): """Reloads all tilesets.""" tileset_paths = get_tileset_paths() for tileset_path in tileset_paths: self._cesium_omniverse_interface.reload_tileset(tileset_path) with ui.VStack(spacing=10): with ui.VStack(): ui.Button("Remove all Tilesets", height=20, clicked_fn=remove_all_tilesets) ui.Button("Reload all Tilesets", height=20, clicked_fn=reload_all_tilesets) self._statistics_widget = CesiumOmniverseStatisticsWidget(self._cesium_omniverse_interface)
2,270
Python
33.938461
103
0.659912
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/uri_image.py
import urllib.request from io import BytesIO from PIL import Image import omni.ui as ui class CesiumUriImage: """A wrapper around an ui.ImageProvider that provides a clean way to load images from URIs or base64 encoded data strings.""" def __init__(self, src: str, padding=0, height=None, **kwargs): style_type = kwargs.pop("style_type_name_override", self.__class__.__name__) name = kwargs.pop("name", "") with ui.ZStack(height=0, width=0): # This is copied from uri_image.py since we seem to blow the stack if we nest any deeper when rendering. data = urllib.request.urlopen(src).read() img_data = BytesIO(data) image = Image.open(img_data) if image.mode != "RGBA": image = image.convert("RGBA") pixels = list(image.getdata()) provider = ui.ByteImageProvider() provider.set_bytes_data(pixels, [image.size[0], image.size[1]]) if height is None: width = image.size[0] height = image.size[1] else: # If the user is explicitely setting the height of the image, we need to calc an appropriate width width = image.size[0] * (height / image.size[1]) # Add padding for all sides height += padding * 2 width += padding * 2 self._image = ui.ImageWithProvider( provider, width=width, height=height, fill_policy=ui.IwpFillPolicy.IWP_PRESERVE_ASPECT_FIT, style={"alignment": ui.Alignment.CENTER, "margin": padding}, style_type_name_override=style_type, name=name, ) def get_image(self): return self._image
1,823
Python
36.224489
117
0.563357
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/styles.py
from omni.ui import Alignment, color as cl, Direction class CesiumOmniverseUiStyles: intro_label_style = { "font_size": 16, } troubleshooter_header_style = { "font_size": 18, } attribution_header_style = { "font_size": 18, } quick_add_section_label = { "font_size": 20, "margin": 5, } quick_add_button = {"Button.Label": {"font_size": 16}} blue_button_style = { "Button": { "background_color": cl("#4BA1CA"), "padding": 12, }, "Button.Label": { "color": cl("#FFF"), "font_size": 16, }, "Button:hovered": { "background_color": cl("#3C81A2"), }, "Button:pressed": {"background_color": cl("#2D6179")}, } top_bar_button_style = { "Button": {"padding": 10.0, "stack_direction": Direction.TOP_TO_BOTTOM}, "Button.Image": { "alignment": Alignment.CENTER, }, "Button.Label": {"alignment": Alignment.CENTER_BOTTOM}, "Button.Image:disabled": {"color": cl("#808080")}, "Button.Label:disabled": {"color": cl("#808080")}, } asset_detail_frame = {"ScrollingFrame": {"background_color": cl("#1F2123"), "padding": 10}} asset_detail_name_label = {"font_size": 22} asset_detail_header_label = {"font_size": 18} asset_detail_id_label = {"font_size": 14} asset_detail_content_label = {"font_size": 16}
1,483
Python
24.586206
95
0.527984
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/credits_parser.py
import logging import omni.ui as ui import webbrowser from dataclasses import dataclass from functools import partial from typing import Optional, List, Tuple from .uri_image import CesiumUriImage from .image_button import CesiumImageButton @dataclass class ParsedCredit: text: Optional[str] = None image_uri: Optional[str] = None link: Optional[str] = None class CesiumCreditsParser: """Takes in a credits array and outputs the elements necessary to show the credits. Should be embedded in a VStack or HStack.""" def _parse_element(self, element, link: Optional[str] = None) -> List[ParsedCredit]: results = [] tag = element.tag if tag == "html" or tag == "body": for child in element.iterchildren(): results.extend(self._parse_element(child, link)) elif tag == "a": # TODO: We probably need to do some sanitization of the href. link = element.attrib["href"] text = "".join(element.itertext()) if text != "": results.append(ParsedCredit(text=text, link=link)) for child in element.iterchildren(): results.extend(self._parse_element(child, link)) elif tag == "img": src = element.attrib["src"] if link is None: results.append(ParsedCredit(image_uri=src)) else: results.append(ParsedCredit(image_uri=src, link=link)) elif tag == "span" or tag == "div": for child in element.iterchildren(): results.extend(self._parse_element(child, link)) # Sometimes divs or spans have text. text = "".join(element.itertext()) if text: results.append(ParsedCredit(text=text)) else: text = "".join(element.itertext()) if link is None: results.append(ParsedCredit(text=text)) else: results.append(ParsedCredit(text=text, link=link)) return results def _parse_credits( self, asset_credits: List[Tuple[str, bool]], should_show_on_screen: bool, perform_fallback=False ) -> List[ParsedCredit]: results = [] try: from lxml import etree parser = etree.HTMLParser() for credit, show_on_screen in asset_credits: if credit == "" or show_on_screen is not should_show_on_screen: continue if credit[0] == "<": try: doc = etree.fromstring(credit, parser) results.extend(self._parse_element(doc)) continue except etree.XMLSyntaxError as err: self._logger.info(err) results.append(ParsedCredit(text=credit)) except Exception as e: self._logger.debug(e) if perform_fallback: self._logger.warning("Performing credits fallback.") for credit, _ in asset_credits: results.append(ParsedCredit(text=credit)) return results @staticmethod def _button_clicked(link: str): webbrowser.open_new_tab(link) def _build_ui_elements(self, parsed_credits: List[ParsedCredit], label_alignment: ui.Alignment): for parsed_credit in parsed_credits: # VStack + Spacer pushes our content to the bottom of the Stack to account for varying heights with ui.VStack(spacing=0, width=0): ui.Spacer() if parsed_credit.image_uri is not None: if parsed_credit.link is not None: CesiumImageButton( src=parsed_credit.image_uri, padding=4, height=28, clicked_fn=partial(self._button_clicked, parsed_credit.link), ) else: CesiumUriImage(src=parsed_credit.image_uri, padding=4, height=28) elif parsed_credit.text is not None: if parsed_credit.link is not None: ui.Button( parsed_credit.text, clicked_fn=partial(self._button_clicked, parsed_credit.link), height=0, width=0, ) else: ui.Label(parsed_credit.text, height=0, word_wrap=True, alignment=label_alignment) def _build_ui(self, parsed_credits: List[ParsedCredit], combine_labels: bool, label_alignment: ui.Alignment): if combine_labels: label_strings = [] other_credits = [] for credit in parsed_credits: if credit.text is not None and credit.link is None: label_strings.append(credit.text) else: other_credits.append(credit) label_strings_combined = " - ".join(label_strings) # Add the label even if the string is empty. The label will expand to fill the parent HStack # which acts like a spacer that right-aligns the image and button elements. Eventually we # should find a different solution here. # VStack + Spacer pushes our content to the bottom of the Stack to account for varying heights with ui.VStack(spacing=0): ui.Spacer() ui.Label(label_strings_combined, height=0, word_wrap=True, alignment=label_alignment) self._build_ui_elements(other_credits, label_alignment) else: self._build_ui_elements(parsed_credits, label_alignment) # There is a builtin name called credits, which is why this argument is called asset_credits. def __init__( self, asset_credits: List[Tuple[str, bool]], should_show_on_screen: bool, perform_fallback=False, combine_labels=False, label_alignment=ui.Alignment.LEFT, ): self._logger = logging.getLogger(__name__) parsed_credits = self._parse_credits(asset_credits, should_show_on_screen, perform_fallback) self._build_ui(parsed_credits, combine_labels, label_alignment)
6,390
Python
38.450617
113
0.56025
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/quick_add_widget.py
import logging import carb.events import omni.kit.app as app import omni.ui as ui import omni.usd from typing import List, Optional from ..bindings import ICesiumOmniverseInterface from ..models import AssetToAdd from .styles import CesiumOmniverseUiStyles from cesium.usd.plugins.CesiumUsdSchemas import IonServer as CesiumIonServer LABEL_HEIGHT = 24 BUTTON_HEIGHT = 40 class CesiumOmniverseQuickAddWidget(ui.Frame): def __init__(self, cesium_omniverse_interface: ICesiumOmniverseInterface, **kwargs): self._logger = logging.getLogger(__name__) self._cesium_omniverse_interface = cesium_omniverse_interface self._ion_quick_add_frame: Optional[ui.Frame] = None self._subscriptions: List[carb.events.ISubscription] = [] self._setup_subscriptions() super().__init__(build_fn=self._build_ui, **kwargs) def destroy(self) -> None: for subscription in self._subscriptions: subscription.unsubscribe() self._subscriptions.clear() def _setup_subscriptions(self): update_stream = app.get_app().get_update_event_stream() self._subscriptions.append( update_stream.create_subscription_to_pop(self._on_update_frame, name="on_update_frame") ) def _on_update_frame(self, _: carb.events.IEvent): if self._ion_quick_add_frame is None: return if omni.usd.get_context().get_stage_state() != omni.usd.StageState.OPENED: return session = self._cesium_omniverse_interface.get_session() if session is not None: stage = omni.usd.get_context().get_stage() current_server_path = self._cesium_omniverse_interface.get_server_path() current_server = CesiumIonServer.Get(stage, current_server_path) current_server_url = current_server.GetIonServerUrlAttr().Get() # Temporary workaround to only show quick add assets for official ion server # until quick add route is implemented self._ion_quick_add_frame.visible = ( session.is_connected() and current_server_url == "https://ion.cesium.com/" ) @staticmethod def _add_blank_button_clicked(): asset_to_add = AssetToAdd("Cesium Tileset", 0) add_blank_asset_event = carb.events.type_from_string("cesium.omniverse.ADD_BLANK_ASSET") app.get_app().get_message_bus_event_stream().push(add_blank_asset_event, payload=asset_to_add.to_dict()) @staticmethod def _add_cartographic_polygon_button_clicked(): add_cartographic_polygon_event = carb.events.type_from_string("cesium.omniverse.ADD_CARTOGRAPHIC_POLYGON") app.get_app().get_message_bus_event_stream().push(add_cartographic_polygon_event, payload={}) def _photorealistic_tiles_button_clicked(self): self._add_ion_assets(AssetToAdd("Google Photorealistic 3D Tiles", 2275207)) def _cwt_bing_maps_button_clicked(self): self._add_ion_assets(AssetToAdd("Cesium World Terrain", 1, "Bing Maps Aerial imagery", 2)) def _cwt_bing_maps_labels_button_clicked(self): self._add_ion_assets(AssetToAdd("Cesium World Terrain", 1, "Bing Maps Aerial with Labels imagery", 3)) def _cwt_bing_maps_roads_button_clicked(self): self._add_ion_assets(AssetToAdd("Cesium World Terrain", 1, "Bing Maps Road imagery", 4)) def _cwt_sentinel_button_clicked(self): self._add_ion_assets(AssetToAdd("Cesium World Terrain", 1, "Sentinel-2 imagery", 3954)) def _cesium_osm_buildings_clicked(self): self._add_ion_assets(AssetToAdd("Cesium OSM Buildings", 96188)) @staticmethod def _add_ion_assets(asset_to_add: AssetToAdd): add_asset_event = carb.events.type_from_string("cesium.omniverse.ADD_ION_ASSET") app.get_app().get_message_bus_event_stream().push(add_asset_event, payload=asset_to_add.to_dict()) def _build_ui(self): with self: with ui.VStack(spacing=10): with ui.VStack(spacing=5): ui.Label( "Quick Add Basic Assets", style=CesiumOmniverseUiStyles.quick_add_section_label, height=LABEL_HEIGHT, ) ui.Button( "Blank 3D Tiles Tileset", style=CesiumOmniverseUiStyles.quick_add_button, clicked_fn=self._add_blank_button_clicked, height=BUTTON_HEIGHT, ) ui.Button( "Cesium Cartographic Polygon", style=CesiumOmniverseUiStyles.quick_add_button, clicked_fn=self._add_cartographic_polygon_button_clicked, height=BUTTON_HEIGHT, ) self._ion_quick_add_frame = ui.Frame(visible=False, height=0) with self._ion_quick_add_frame: with ui.VStack(spacing=5): ui.Label( "Quick Add Cesium ion Assets", style=CesiumOmniverseUiStyles.quick_add_section_label, height=LABEL_HEIGHT, ) ui.Button( "Google Photorealistic 3D Tiles", style=CesiumOmniverseUiStyles.quick_add_button, height=BUTTON_HEIGHT, clicked_fn=self._photorealistic_tiles_button_clicked, ) ui.Button( "Cesium World Terrain + Bing Maps Aerial imagery", style=CesiumOmniverseUiStyles.quick_add_button, height=BUTTON_HEIGHT, clicked_fn=self._cwt_bing_maps_button_clicked, ) ui.Button( "Cesium World Terrain + Bing Maps with Labels imagery", style=CesiumOmniverseUiStyles.quick_add_button, height=BUTTON_HEIGHT, clicked_fn=self._cwt_bing_maps_labels_button_clicked, ) ui.Button( "Cesium World Terrain + Bing Maps Road imagery", style=CesiumOmniverseUiStyles.quick_add_button, height=BUTTON_HEIGHT, clicked_fn=self._cwt_bing_maps_roads_button_clicked, ) ui.Button( "Cesium World Terrain + Sentinel-2 imagery", style=CesiumOmniverseUiStyles.quick_add_button, height=BUTTON_HEIGHT, clicked_fn=self._cwt_sentinel_button_clicked, ) ui.Button( "Cesium OSM Buildings", style=CesiumOmniverseUiStyles.quick_add_button, height=BUTTON_HEIGHT, clicked_fn=self._cesium_osm_buildings_clicked, )
7,293
Python
44.874214
114
0.56232
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/troubleshooter_window.py
import logging import carb.events import omni.kit.app as app import omni.ui as ui import webbrowser from typing import List, Optional from ..bindings import ICesiumOmniverseInterface from .pass_fail_widget import CesiumPassFailWidget from .styles import CesiumOmniverseUiStyles class CesiumTroubleshooterWindow(ui.Window): WINDOW_BASE_NAME = "Token Troubleshooting" def __init__( self, cesium_omniverse_interface: ICesiumOmniverseInterface, name: str, tileset_path: str, tileset_ion_asset_id: int, raster_overlay_ion_asset_id: int, message: str, **kwargs, ): window_name = f"{CesiumTroubleshooterWindow.WINDOW_BASE_NAME} - {name}" super().__init__(window_name, **kwargs) self._cesium_omniverse_interface = cesium_omniverse_interface self._logger = logging.getLogger(__name__) self._name = name self._tileset_path = tileset_path self._tileset_ion_asset_id = tileset_ion_asset_id self.raster_overlay_ion_asset_id = raster_overlay_ion_asset_id ion_id = raster_overlay_ion_asset_id if raster_overlay_ion_asset_id > 0 else tileset_ion_asset_id self._message = ( f"{name} tried to access Cesium ion for asset id {ion_id}, but it didn't work, probably " + "due to a problem with the access token. This panel will help you fix it!" ) self.height = 400 self.width = 700 self.padding_x = 12 self.padding_y = 12 self._token_details_event_type = carb.events.type_from_string("cesium.omniverse.TOKEN_DETAILS_READY") self._asset_details_event_type = carb.events.type_from_string("cesium.omniverse.ASSET_DETAILS_READY") self._default_token_stack: Optional[ui.VStack] = None self._default_token_is_valid_widget: Optional[CesiumPassFailWidget] = None self._default_token_has_access_widget: Optional[CesiumPassFailWidget] = None self._default_token_associated_to_account_widget: Optional[CesiumPassFailWidget] = None self._asset_token_stack: Optional[ui.VStack] = None self._asset_token_is_valid_widget: Optional[CesiumPassFailWidget] = None self._asset_token_has_access_widget: Optional[CesiumPassFailWidget] = None self._asset_token_associated_to_account_widget: Optional[CesiumPassFailWidget] = None self._asset_on_account_widget: Optional[CesiumPassFailWidget] = None self._subscriptions: List[carb.events.ISubscription] = [] self._setup_subscriptions() if raster_overlay_ion_asset_id > 0: self._cesium_omniverse_interface.update_troubleshooting_details( tileset_path, tileset_ion_asset_id, raster_overlay_ion_asset_id, self._token_details_event_type, self._asset_details_event_type, ) else: self._cesium_omniverse_interface.update_troubleshooting_details( tileset_path, tileset_ion_asset_id, self._token_details_event_type, self._asset_details_event_type ) self.frame.set_build_fn(self._build_ui) def __del__(self): self.destroy() def destroy(self): for subscription in self._subscriptions: subscription.unsubscribe() self._subscriptions = None def _setup_subscriptions(self): bus = app.get_app().get_message_bus_event_stream() self._subscriptions.append( bus.create_subscription_to_pop_by_type( self._token_details_event_type, self._on_token_details_ready, name="cesium.omniverse.TOKEN_DETAILS_READY", ) ) self._subscriptions.append( bus.create_subscription_to_pop_by_type( self._asset_details_event_type, self._on_asset_details_ready, name="cesium.omniverse.ASSET_DETAILS_READY", ) ) def _on_token_details_ready(self, _e: carb.events.IEvent): self._logger.info("Received token details event.") default_token_details = self._cesium_omniverse_interface.get_default_token_troubleshooting_details() if self._default_token_stack is not None: self._default_token_stack.visible = default_token_details.show_details if self._default_token_is_valid_widget is not None: self._default_token_is_valid_widget.passed = default_token_details.is_valid if self._default_token_has_access_widget is not None: self._default_token_has_access_widget.passed = default_token_details.allows_access_to_asset if self._default_token_associated_to_account_widget is not None: self._default_token_associated_to_account_widget.passed = ( default_token_details.associated_with_user_account ) asset_token_details = self._cesium_omniverse_interface.get_asset_token_troubleshooting_details() if self._asset_token_stack is not None: self._asset_token_stack.visible = asset_token_details.show_details if self._asset_token_is_valid_widget is not None: self._asset_token_is_valid_widget.passed = asset_token_details.is_valid if self._asset_token_has_access_widget is not None: self._asset_token_has_access_widget.passed = asset_token_details.allows_access_to_asset if self._asset_token_associated_to_account_widget is not None: self._asset_token_associated_to_account_widget.passed = asset_token_details.associated_with_user_account def _on_asset_details_ready(self, _e: carb.events.IEvent): asset_details = self._cesium_omniverse_interface.get_asset_troubleshooting_details() if self._asset_on_account_widget is not None: self._asset_on_account_widget.passed = asset_details.asset_exists_in_user_account @staticmethod def _on_open_ion_button_clicked(): webbrowser.open("https://ion.cesium.com") def _build_ui(self): with ui.VStack(spacing=10): ui.Label(self._message, height=54, word_wrap=True) with ui.VGrid(spacing=10, column_count=2): self._asset_token_stack = ui.VStack(spacing=5, visible=False) with self._asset_token_stack: ui.Label( f"{self._name}'s Access Token", height=16, style=CesiumOmniverseUiStyles.troubleshooter_header_style, ) with ui.HStack(height=16, spacing=10): self._asset_token_is_valid_widget = CesiumPassFailWidget() ui.Label("Is a valid Cesium ion Token") with ui.HStack(height=16, spacing=10): self._asset_token_has_access_widget = CesiumPassFailWidget() ui.Label("Allows access to this asset") with ui.HStack(height=16, spacing=10): self._asset_token_associated_to_account_widget = CesiumPassFailWidget() ui.Label("Is associated with your user account") self._default_token_stack = ui.VStack(spacing=5, visible=False) with self._default_token_stack: ui.Label( "Project Default Access Token", height=16, style=CesiumOmniverseUiStyles.troubleshooter_header_style, ) with ui.HStack(height=16, spacing=10): self._default_token_is_valid_widget = CesiumPassFailWidget() ui.Label("Is a valid Cesium ion Token") with ui.HStack(height=16, spacing=10): self._default_token_has_access_widget = CesiumPassFailWidget() ui.Label("Allows access to this asset") with ui.HStack(height=16, spacing=10): self._default_token_associated_to_account_widget = CesiumPassFailWidget() ui.Label("Is associated with your user account") with ui.VStack(spacing=5): ui.Label("Asset", height=16, style=CesiumOmniverseUiStyles.troubleshooter_header_style) with ui.HStack(height=16, spacing=10): self._asset_on_account_widget = CesiumPassFailWidget() ui.Label("Asset ID exists in your user account") ui.Spacer() ui.Button( "Open Cesium ion on the Web", alignment=ui.Alignment.CENTER, height=36, style=CesiumOmniverseUiStyles.blue_button_style, clicked_fn=self._on_open_ion_button_clicked, )
8,910
Python
43.778894
116
0.609091
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/sign_in_widget.py
import logging import carb.events import omni.kit.app as app import omni.ui as ui import omni.kit.clipboard as clipboard import webbrowser from pathlib import Path from typing import List, Optional from ..bindings import ICesiumOmniverseInterface from .styles import CesiumOmniverseUiStyles class CesiumOmniverseSignInWidget(ui.Frame): def __init__(self, cesium_omniverse_interface: ICesiumOmniverseInterface, **kwargs): manager = app.get_app().get_extension_manager() ext_id = manager.get_extension_id_by_module("cesium.omniverse") self._logger = logging.getLogger(__name__) self._images_path = Path(manager.get_extension_path(ext_id)).joinpath("images") self._cesium_omniverse_interface = cesium_omniverse_interface self._connect_button: Optional[ui.Button] = None self._waiting_message_frame: Optional[ui.Frame] = None self._authorize_url_field: Optional[ui.StringField] = None self._subscriptions: List[carb.events.ISubscription] = [] self._setup_subscriptions() super().__init__(build_fn=self._build_ui, **kwargs) def destroy(self): for subscription in self._subscriptions: subscription.unsubscribe() self._subscriptions.clear() def _setup_subscriptions(self): update_stream = app.get_app().get_update_event_stream() self._subscriptions.append( update_stream.create_subscription_to_pop(self._on_update_frame, name="on_update_frame") ) def _on_update_frame(self, _e: carb.events.IEvent): if not self.visible: return session = self._cesium_omniverse_interface.get_session() if session is not None and self._waiting_message_frame is not None: self._waiting_message_frame.visible = session.is_connecting() if session.is_connecting(): authorize_url = session.get_authorize_url() if self._authorize_url_field.model.get_value_as_string() != authorize_url: self._authorize_url_field.model.set_value(authorize_url) webbrowser.open(authorize_url) def _build_ui(self): with self: with ui.VStack(alignment=ui.Alignment.CENTER_TOP, spacing=ui.Length(20, ui.UnitType.PIXEL)): ui.Spacer(height=0) ui.Image( f"{self._images_path}/placeholder_logo.png", alignment=ui.Alignment.CENTER, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, height=140, ) with ui.HStack(height=0): ui.Spacer() ui.Label( "Access global high-resolution 3D content, including photogrammetry, " "terrain, imagery, and buildings. Bring your own data for tiling, hosting, " "and streaming to Omniverse.", alignment=ui.Alignment.CENTER, style=CesiumOmniverseUiStyles.intro_label_style, width=ui.Length(80, ui.UnitType.PERCENT), word_wrap=True, ) ui.Spacer() with ui.HStack(height=0): ui.Spacer() self._connect_button = ui.Button( "Connect to Cesium ion", alignment=ui.Alignment.CENTER, height=ui.Length(36, ui.UnitType.PIXEL), width=ui.Length(180, ui.UnitType.PIXEL), style=CesiumOmniverseUiStyles.blue_button_style, clicked_fn=self._connect_button_clicked, ) ui.Spacer() self._waiting_message_frame = ui.Frame(visible=False, height=0) with self._waiting_message_frame: with ui.VStack(spacing=10): ui.Label("Waiting for you to sign into Cesium ion with your web browser...") ui.Button("Open web browser again", clicked_fn=self._open_web_browser_again_clicked) ui.Label("Or copy the URL below into your web browser.") with ui.HStack(): self._authorize_url_field = ui.StringField(read_only=True) self._authorize_url_field.model.set_value("https://cesium.com") ui.Button("Copy to Clipboard", clicked_fn=self._copy_to_clipboard_clicked) ui.Spacer(height=10) def _connect_button_clicked(self) -> None: self._cesium_omniverse_interface.connect_to_ion() def _open_web_browser_again_clicked(self) -> None: webbrowser.open(self._authorize_url_field.model.get_value_as_string()) def _copy_to_clipboard_clicked(self) -> None: if self._authorize_url_field is not None: clipboard.copy(self._authorize_url_field.model.get_value_as_string())
5,049
Python
44.909091
108
0.579719
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/main_window.py
from ..bindings import ICesiumOmniverseInterface, CesiumIonSession import logging import carb.events import omni.kit.app as app import omni.ui as ui import webbrowser from pathlib import Path from typing import List, Optional from .quick_add_widget import CesiumOmniverseQuickAddWidget from .sign_in_widget import CesiumOmniverseSignInWidget from .profile_widget import CesiumOmniverseProfileWidget from .token_window import CesiumOmniverseTokenWindow from .troubleshooter_window import CesiumTroubleshooterWindow from .asset_window import CesiumOmniverseAssetWindow from .styles import CesiumOmniverseUiStyles HELP_URL = "https://community.cesium.com/c/cesium-for-omniverse" LEARN_URL = "https://cesium.com/learn/omniverse/" UPLOAD_URL = "https://ion.cesium.com/addasset" class CesiumOmniverseMainWindow(ui.Window): """ The main window for working with Cesium for Omniverse. Docked in the same area as "Stage". """ WINDOW_NAME = "Cesium" MENU_PATH = f"Window/Cesium/{WINDOW_NAME}" def __init__(self, cesium_omniverse_interface: ICesiumOmniverseInterface, **kwargs): super().__init__(CesiumOmniverseMainWindow.WINDOW_NAME, **kwargs) manager = app.get_app().get_extension_manager() ext_id = manager.get_extension_id_by_module("cesium.omniverse") self._cesium_omniverse_interface = cesium_omniverse_interface self._logger = logging.getLogger(__name__) self._icon_path = Path(manager.get_extension_path(ext_id)).joinpath("images") # Buttons aren't created until the build function is called. self._add_button: Optional[ui.Button] = None self._upload_button: Optional[ui.Button] = None self._token_button: Optional[ui.Button] = None self._learn_button: Optional[ui.Button] = None self._help_button: Optional[ui.Button] = None self._sign_out_button: Optional[ui.Button] = None self._quick_add_widget: Optional[CesiumOmniverseQuickAddWidget] = None self._sign_in_widget: Optional[CesiumOmniverseSignInWidget] = None self._profile_widget: Optional[CesiumOmniverseProfileWidget] = None self._troubleshooter_window: Optional[CesiumTroubleshooterWindow] = None self._asset_window: Optional[CesiumOmniverseAssetWindow] = None self._subscriptions: List[carb.events.ISubscription] = [] self._setup_subscriptions() self.frame.set_build_fn(self._build_fn) def destroy(self) -> None: for subscription in self._subscriptions: subscription.unsubscribe() if self._sign_in_widget is not None: self._sign_in_widget.destroy() self._sign_in_widget = None if self._profile_widget is not None: self._profile_widget.destroy() self._profile_widget = None if self._quick_add_widget is not None: self._quick_add_widget.destroy() self._quick_add_widget = None if self._troubleshooter_window is not None: self._troubleshooter_window.destroy() self._troubleshooter_window = None super().destroy() def __del__(self): self.destroy() def _setup_subscriptions(self): update_stream = app.get_app().get_update_event_stream() bus = app.get_app().get_message_bus_event_stream() self._subscriptions.append( update_stream.create_subscription_to_pop(self._on_update_frame, name="on_update_frame") ) assets_updated_event = carb.events.type_from_string("cesium.omniverse.ASSETS_UPDATED") self._subscriptions.append( bus.create_subscription_to_pop_by_type( assets_updated_event, self._on_assets_updated, name="assets_updated" ) ) connection_updated_event = carb.events.type_from_string("cesium.omniverse.CONNECTION_UPDATED") self._subscriptions.append( bus.create_subscription_to_pop_by_type( connection_updated_event, self._on_connection_updated, name="connection_updated" ) ) profile_updated_event = carb.events.type_from_string("cesium.omniverse.PROFILE_UPDATED") self._subscriptions.append( bus.create_subscription_to_pop_by_type( profile_updated_event, self._on_profile_updated, name="profile_updated" ) ) tokens_updated_event = carb.events.type_from_string("cesium.omniverse.TOKENS_UPDATED") self._subscriptions.append( bus.create_subscription_to_pop_by_type( tokens_updated_event, self._on_tokens_updated, name="tokens_updated" ) ) show_token_window_event = carb.events.type_from_string("cesium.omniverse.SHOW_TOKEN_WINDOW") self._subscriptions.append( bus.create_subscription_to_pop_by_type( show_token_window_event, self._on_show_token_window, name="cesium.omniverse.SHOW_TOKEN_WINDOW" ) ) show_troubleshooter_event = carb.events.type_from_string("cesium.omniverse.SHOW_TROUBLESHOOTER") self._subscriptions.append( bus.create_subscription_to_pop_by_type( show_troubleshooter_event, self._on_show_troubleshooter_window, name="cesium.omniverse.SHOW_TROUBLESHOOTER", ) ) def _on_update_frame(self, _e: carb.events.IEvent): session: CesiumIonSession = self._cesium_omniverse_interface.get_session() if session is not None and self._sign_in_widget is not None: # Since this goes across the pybind barrier, just grab it once. is_connected = session.is_connected() self._sign_in_widget.visible = not is_connected self._set_top_bar_button_status(is_connected) def _on_assets_updated(self, _e: carb.events.IEvent): self._logger.info("Received ion Assets updated event.") def _on_connection_updated(self, _e: carb.events.IEvent): self._logger.info("Received ion Connection updated event.") def _on_profile_updated(self, _e: carb.events.IEvent): self._logger.info("Received ion Profile updated event.") def _on_tokens_updated(self, _e: carb.events.IEvent): self._logger.info("Received ion Tokens updated event.") def _on_show_token_window(self, _e: carb.events.IEvent): self._show_token_window() def _on_show_troubleshooter_window(self, _e: carb.events.IEvent): tileset_path = _e.payload["tilesetPath"] tileset_ion_asset_id = _e.payload["tilesetIonAssetId"] raster_overlay_ion_asset_id = _e.payload["rasterOverlayIonAssetId"] message = _e.payload["message"] name = _e.payload["rasterOverlayName"] if _e.payload["rasterOverlayName"] else _e.payload["tilesetName"] if self._troubleshooter_window: self._troubleshooter_window.destroy() self._troubleshooter_window = None self._troubleshooter_window = CesiumTroubleshooterWindow( self._cesium_omniverse_interface, name, tileset_path, tileset_ion_asset_id, raster_overlay_ion_asset_id, message, ) def _set_top_bar_button_status(self, enabled: bool): self._add_button.enabled = enabled self._upload_button.enabled = enabled self._sign_out_button.enabled = enabled def _build_fn(self): """Builds all UI components.""" with ui.VStack(spacing=0): button_style = CesiumOmniverseUiStyles.top_bar_button_style self._profile_widget = CesiumOmniverseProfileWidget(self._cesium_omniverse_interface, height=20) with ui.HStack(height=ui.Length(80, ui.UnitType.PIXEL)): self._add_button = ui.Button( "Add", image_url=f"{self._icon_path}/FontAwesome/plus-solid.png", style=button_style, clicked_fn=self._add_button_clicked, enabled=False, ) self._upload_button = ui.Button( "Upload", image_url=f"{self._icon_path}/FontAwesome/cloud-upload-alt-solid.png", style=button_style, clicked_fn=self._upload_button_clicked, enabled=False, ) self._token_button = ui.Button( "Token", image_url=f"{self._icon_path}/FontAwesome/key-solid.png", style=button_style, clicked_fn=self._token_button_clicked, ) self._learn_button = ui.Button( "Learn", image_url=f"{self._icon_path}/FontAwesome/book-reader-solid.png", style=button_style, clicked_fn=self._learn_button_clicked, ) self._help_button = ui.Button( "Help", image_url=f"{self._icon_path}/FontAwesome/hands-helping-solid.png", style=button_style, clicked_fn=self._help_button_clicked, ) self._sign_out_button = ui.Button( "Sign Out", image_url=f"{self._icon_path}/FontAwesome/sign-out-alt-solid.png", # style=button_style, style=button_style, clicked_fn=self._sign_out_button_clicked, enabled=False, ) with ui.ScrollingFrame(): with ui.VStack(spacing=0): self._quick_add_widget = CesiumOmniverseQuickAddWidget(self._cesium_omniverse_interface) self._sign_in_widget = CesiumOmniverseSignInWidget( self._cesium_omniverse_interface, visible=False ) def _add_button_clicked(self) -> None: if not self._add_button or not self._add_button.enabled: return show_asset_window_event = carb.events.type_from_string("cesium.omniverse.SHOW_ASSET_WINDOW") app.get_app().get_message_bus_event_stream().push(show_asset_window_event) def _upload_button_clicked(self) -> None: if not self._upload_button or not self._upload_button.enabled: return webbrowser.open_new_tab(UPLOAD_URL) def _token_button_clicked(self) -> None: if not self._token_button: return self._show_token_window() def _learn_button_clicked(self) -> None: if not self._learn_button: return webbrowser.open_new_tab(LEARN_URL) def _help_button_clicked(self) -> None: if not self._help_button: return webbrowser.open_new_tab(HELP_URL) def _sign_out_button_clicked(self) -> None: if not self._sign_out_button or not self._sign_out_button.enabled: return session = self._cesium_omniverse_interface.get_session() if session is not None: session.disconnect() self._set_top_bar_button_status(False) def _show_token_window(self): self._cesium_omniverse_interface.get_session().refresh_tokens() CesiumOmniverseTokenWindow(self._cesium_omniverse_interface)
11,391
Python
38.97193
112
0.61452
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/settings_window.py
import logging import carb.settings from typing import Optional import omni.ui as ui from ..bindings import ICesiumOmniverseInterface from cesium.omniverse.utils.custom_fields import int_field_with_label class CesiumOmniverseSettingsWindow(ui.Window): WINDOW_NAME = "Cesium Settings" MENU_PATH = f"Window/Cesium/{WINDOW_NAME}" _logger: logging.Logger _cesium_omniverse_interface: Optional[ICesiumOmniverseInterface] = None def __init__(self, cesium_omniverse_interface: ICesiumOmniverseInterface, title: str, **kwargs): super().__init__(title, **kwargs) self._logger = logging.getLogger(__name__) self._cesium_omniverse_interface = cesium_omniverse_interface self._cache_items_setting = "/persistent/exts/cesium.omniverse/maxCacheItems" # Set the function that is called to build widgets when the window is visible self.frame.set_build_fn(self._build_fn) def destroy(self): # It will destroy all the children super().destroy() def __del__(self): self.destroy() @staticmethod def show_window(): ui.Workspace.show_window(CesiumOmniverseSettingsWindow.WINDOW_NAME) def _build_fn(self): """Builds out the UI buttons and their handlers.""" def set_cache_parameters(): newval = self._cache_items_model.get_value_as_int() carb.settings.get_settings().set(self._cache_items_setting, newval) def clear_cache(): self._cesium_omniverse_interface.clear_accessor_cache() with ui.VStack(spacing=4): cache_items = carb.settings.get_settings().get(self._cache_items_setting) self._cache_items_model = ui.SimpleIntModel(cache_items) int_field_with_label("Maximum cache items", model=self._cache_items_model) ui.Button("Set cache parameters (requires restart)", height=20, clicked_fn=set_cache_parameters) ui.Button("Clear cache", height=20, clicked_fn=clear_cache)
2,009
Python
36.924528
108
0.678447
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/credits_viewport_frame.py
import logging import carb.events import omni.kit.app as app import omni.ui as ui from typing import List, Optional, Tuple from ..bindings import ICesiumOmniverseInterface from .credits_parser import CesiumCreditsParser from .credits_window import CesiumOmniverseCreditsWindow import json from .events import EVENT_CREDITS_CHANGED class CesiumCreditsViewportFrame: def __init__(self, cesium_omniverse_interface: ICesiumOmniverseInterface, instance): self._logger = logging.getLogger(__name__) self._cesium_omniverse_interface = cesium_omniverse_interface self._credits_viewport_frame = instance.get_frame("cesium.omniverse.viewport.ION_CREDITS") self._credits_window: Optional[CesiumOmniverseCreditsWindow] = None self._data_attribution_button: Optional[ui.Button] = None self._on_credits_changed_event = EVENT_CREDITS_CHANGED self._subscriptions: List[carb.events.ISubscription] = [] self._setup_subscriptions() self._credits: List[Tuple[str, bool]] = [] self._new_credits: List[Tuple[str, bool]] = [] self._build_fn() def getFrame(self): return self._credits_viewport_frame def __del__(self): self.destroy() def destroy(self): for subscription in self._subscriptions: subscription.unsubscribe() self._subscriptions.clear() if self._credits_window is not None: self._credits_window.destroy() self._credits_window = None def _setup_subscriptions(self): update_stream = app.get_app().get_update_event_stream() self._subscriptions.append( update_stream.create_subscription_to_pop( self._on_update_frame, name="cesium.omniverse.viewport.ON_UPDATE_FRAME" ) ) message_bus = app.get_app().get_message_bus_event_stream() self._subscriptions.append( message_bus.create_subscription_to_pop_by_type(EVENT_CREDITS_CHANGED, self._on_credits_changed) ) def _on_update_frame(self, _e: carb.events.IEvent): if self._data_attribution_button is None: return if self._new_credits != self._credits: self._credits.clear() self._credits.extend(self._new_credits) self._build_fn() has_offscreen_credits = False for _, show_on_screen in self._new_credits: if not show_on_screen: has_offscreen_credits = True if has_offscreen_credits != self._data_attribution_button.visible: if has_offscreen_credits: self._logger.info("Show Data Attribution") else: self._logger.info("Hide Data Attribution") self._data_attribution_button.visible = has_offscreen_credits def _on_data_attribution_button_clicked(self): self._credits_window = CesiumOmniverseCreditsWindow(self._cesium_omniverse_interface, self._credits) def _build_fn(self): with self._credits_viewport_frame: with ui.VStack(): ui.Spacer() with ui.HStack(height=0): # Prevent credits from overlapping the axis display ui.Spacer(width=100) with ui.HStack(height=0, spacing=4): CesiumCreditsParser( self._credits, should_show_on_screen=True, combine_labels=True, label_alignment=ui.Alignment.RIGHT, ) # VStack + Spacer pushes our content to the bottom of the Stack to account for varying heights with ui.VStack(spacing=0, width=0): ui.Spacer() self._data_attribution_button = ui.Button( "Data Attribution", visible=False, width=0, height=0, clicked_fn=self._on_data_attribution_button_clicked, ) def _on_credits_changed(self, _e: carb.events.IEvent): credits_json = _e.payload["credits"] credits = json.loads(credits_json) if credits is not None: self._new_credits = credits
4,373
Python
36.706896
114
0.586783
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/__init__.py
from .styles import CesiumOmniverseUiStyles # noqa: F401 from .quick_add_widget import CesiumOmniverseQuickAddWidget # noqa: F401 from .sign_in_widget import CesiumOmniverseSignInWidget # noqa: F401 from .profile_widget import CesiumOmniverseProfileWidget # noqa: F401 from .token_window import CesiumOmniverseTokenWindow # noqa: F401 from .main_window import CesiumOmniverseMainWindow # noqa: F401 from .asset_window import CesiumOmniverseAssetWindow # noqa: F401 from .debug_window import CesiumOmniverseDebugWindow # noqa: F401 from .attributes_widget_controller import CesiumAttributesWidgetController # noqa: F401 from .fabric_modal import CesiumFabricModal # noqa: F401 from .credits_window import CesiumOmniverseCreditsWindow # noqa: F401 from .credits_viewport_frame import CesiumCreditsViewportFrame # noqa: F401 from .credits_parser import CesiumCreditsParser # noqa: F401 from .search_field_widget import CesiumSearchFieldWidget # noqa: F401 from .statistics_widget import CesiumOmniverseStatisticsWidget # noqa: F401 from .models import * # noqa: F401 F403 from .credits_viewport_controller import CreditsViewportController # noqa: F401 from .add_menu_controller import CesiumAddMenuController # noqa: F401
1,237
Python
64.157891
88
0.819725
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/search_field_widget.py
from typing import Callable, List, Optional import carb.events import omni.ui as ui from omni.ui import color as cl class CesiumSearchFieldWidget(ui.Frame): def __init__( self, callback_fn: Callable[[ui.AbstractValueModel], None], default_value="", font_size=14, **kwargs ): self._callback_fn = callback_fn self._search_value = ui.SimpleStringModel(default_value) self._font_size = font_size self._clear_button_stack: Optional[ui.Stack] = None self._subscriptions: List[carb.Subscription] = [] self._setup_subscriptions() super().__init__(build_fn=self._build_fn, **kwargs) def destroy(self): super().destroy() @property def search_value(self) -> str: return self._search_value.get_value_as_string() @search_value.setter def search_value(self, value: str): self._search_value.set_value(value) self._set_clear_button_visibility() def _update_visibility(self, _e): self._set_clear_button_visibility() def _setup_subscriptions(self): self._subscriptions.append(self._search_value.subscribe_value_changed_fn(self._callback_fn)) self._subscriptions.append(self._search_value.subscribe_value_changed_fn(self._update_visibility)) def _on_clear_click(self): self._search_value.set_value("") self._set_clear_button_visibility() def _set_clear_button_visibility(self): self._clear_button_stack.visible = self._search_value.as_string != "" def _build_fn(self): with self: with ui.ZStack(height=0): ui.Rectangle(style={"background_color": cl("#1F2123"), "border_radius": 3}) with ui.HStack(alignment=ui.Alignment.CENTER): image_size = self._font_size * 2 ui.Image( "resources/glyphs/menu_search.svg", width=image_size, height=image_size, style={"margin": 4}, ) with ui.VStack(): ui.Spacer() ui.StringField( model=self._search_value, height=self._font_size, style={"font_size": self._font_size} ) ui.Spacer() self._clear_button_stack = ui.VStack(width=0, visible=False) with self._clear_button_stack: ui.Spacer() ui.Button( image_url="resources/icons/Close.png", width=0, height=0, image_width=self._font_size, image_height=self._font_size, style={"margin": 4, "background_color": cl("#1F2123")}, clicked_fn=self._on_clear_click, opaque_for_mouse_events=True, ) ui.Spacer()
3,077
Python
37.962025
114
0.521287
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/credits_window.py
import logging import omni.kit.app as app import omni.ui as ui from pathlib import Path from typing import List, Tuple from .credits_parser import CesiumCreditsParser from ..bindings import ICesiumOmniverseInterface from .styles import CesiumOmniverseUiStyles class CesiumOmniverseCreditsWindow(ui.Window): WINDOW_NAME = "Data Attribution" # There is a builtin name called credits, which is why this argument is called asset_credits. def __init__( self, cesium_omniverse_interface: ICesiumOmniverseInterface, asset_credits: List[Tuple[str, bool]], **kwargs ): super().__init__(CesiumOmniverseCreditsWindow.WINDOW_NAME, **kwargs) manager = app.get_app().get_extension_manager() ext_id = manager.get_extension_id_by_module("cesium.omniverse") self._cesium_omniverse_interface = cesium_omniverse_interface self._logger = logging.getLogger(__name__) self._images_path = Path(manager.get_extension_path(ext_id)).joinpath("images") self.height = 500 self.width = 400 self.padding_x = 12 self.padding_y = 12 self._credits = asset_credits self.frame.set_build_fn(self._build_ui) def __del__(self): self.destroy() def destroy(self): super().destroy() def _build_ui(self): with ui.VStack(spacing=5): ui.Label("Data Provided By:", height=0, style=CesiumOmniverseUiStyles.attribution_header_style) CesiumCreditsParser(self._credits, should_show_on_screen=False, perform_fallback=True)
1,566
Python
31.645833
116
0.683269
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/pass_fail_widget.py
from pathlib import Path import carb.events import omni.kit.app as app import omni.ui as ui from typing import List class CesiumPassFailWidget(ui.Frame): def __init__(self, passed=False, **kwargs): self._passed_model = ui.SimpleBoolModel(passed) manager = app.get_app().get_extension_manager() ext_id = manager.get_extension_id_by_module("cesium.omniverse") self._icon_path = Path(manager.get_extension_path(ext_id)).joinpath("images") self._subscriptions: List[carb.Subscription] = [] self._setup_subscriptions() super().__init__(build_fn=self._build_ui, **kwargs) def __del__(self): self.destroy() def destroy(self): for subscription in self._subscriptions: subscription.unsubscribe() self._subscriptions.clear() @property def passed(self) -> bool: return self._passed_model.get_value_as_bool() @passed.setter def passed(self, value: bool): self._passed_model.set_value(value) def _setup_subscriptions(self): self._subscriptions.append(self._passed_model.subscribe_value_changed_fn(lambda _e: self.rebuild())) def _build_ui(self): with self: with ui.VStack(width=16, height=16): path_root = f"{self._icon_path}/FontAwesome" icon = ( f"{path_root}/check-solid.svg" if self._passed_model.get_value_as_bool() else f"{path_root}/times-solid.svg" ) ui.Image( icon, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, alignment=ui.Alignment.CENTER_BOTTOM, width=16, height=16, )
1,794
Python
30.491228
108
0.572464
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/events.py
from carb.events import type_from_string # Event base path. Do not use directly outside of events.py _EVENT_BASE = "cesium.omniverse.event" # Signals the credits have changed. Currently, this only triggers when the displayed # credits are changed. It is possible for the credit payload that shows under # the "Data Attribution" button to change, but this event will not fire for that. EVENT_CREDITS_CHANGED = type_from_string(f"{_EVENT_BASE}.viewport.CREDITS_CHANGED")
471
Python
46.199995
84
0.779193
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/attributes_widget_controller.py
import logging import omni.kit.window.property from .attributes import ( CesiumDataSchemaAttributesWidget, CesiumGeoreferenceSchemaAttributesWidget, CesiumTilesetAttributesWidget, CesiumGlobeAnchorAttributesWidget, CesiumIonServerAttributesWidget, CesiumIonRasterOverlayAttributesWidget, CesiumPolygonRasterOverlayAttributesWidget, CesiumTileMapServiceRasterOverlayAttributesWidget, CesiumWebMapServiceRasterOverlayAttributesWidget, CesiumWebMapTileServiceRasterOverlayAttributesWidget, ) from ..bindings import ICesiumOmniverseInterface class CesiumAttributesWidgetController: """ This is designed as a helpful function for separating out the registration and unregistration of Cesium's attributes widgets. """ def __init__(self, _cesium_omniverse_interface: ICesiumOmniverseInterface): self._cesium_omniverse_interface = _cesium_omniverse_interface self._logger = logging.getLogger(__name__) self._register_data_attributes_widget() self._register_georeference_attributes_widget() self._register_tileset_attributes_widget() self._register_global_anchor_attributes_widget() self._register_ion_server_attributes_widget() self._register_ion_raster_overlay_attributes_widget() self._register_polygon_raster_overlay_attributes_widget() self._register_tile_map_service_raster_overlay_attributes_widget() self._register_web_map_service_raster_overlay_attributes_widget() self._register_web_map_tile_service_raster_overlay_attributes_widget() def destroy(self): self._unregister_data_attributes_widget() self._unregister_georeference_attributes_widget() self._unregister_tileset_attributes_widget() self._unregister_global_anchor_attributes_widget() self._unregister_ion_server_attributes_widget() self._unregister_ion_raster_overlay_attributes_widget() self._unregister_polygon_raster_overlay_attributes_widget() self._unregister_tile_map_service_raster_overlay_attributes_widget() self._unregister_web_map_service_raster_overlay_attributes_widget() self._unregister_web_map_tile_service_raster_overlay_attributes_widget() @staticmethod def _register_data_attributes_widget(): window = omni.kit.window.property.get_window() if window is not None: window.register_widget("prim", "cesiumData", CesiumDataSchemaAttributesWidget()) @staticmethod def _unregister_data_attributes_widget(): window = omni.kit.window.property.get_window() if window is not None: window.unregister_widget("prim", "cesiumData") @staticmethod def _register_georeference_attributes_widget(): window = omni.kit.window.property.get_window() if window is not None: window.register_widget("prim", "cesiumGeoreference", CesiumGeoreferenceSchemaAttributesWidget()) @staticmethod def _unregister_georeference_attributes_widget(): window = omni.kit.window.property.get_window() if window is not None: window.unregister_widget("prim", "cesiumGeoreference") def _register_tileset_attributes_widget(self): window = omni.kit.window.property.get_window() if window is not None: window.register_widget( "prim", "cesiumTileset", CesiumTilesetAttributesWidget(self._cesium_omniverse_interface) ) @staticmethod def _unregister_tileset_attributes_widget(): window = omni.kit.window.property.get_window() if window is not None: window.unregister_widget("prim", "cesiumTileset") @staticmethod def _register_ion_raster_overlay_attributes_widget(): window = omni.kit.window.property.get_window() if window is not None: window.register_widget("prim", "cesiumIonRasterOverlay", CesiumIonRasterOverlayAttributesWidget()) @staticmethod def _unregister_ion_raster_overlay_attributes_widget(): window = omni.kit.window.property.get_window() if window is not None: window.unregister_widget("prim", "cesiumIonRasterOverlay") @staticmethod def _register_polygon_raster_overlay_attributes_widget(): window = omni.kit.window.property.get_window() if window is not None: window.register_widget("prim", "cesiumPolygonRasterOverlay", CesiumPolygonRasterOverlayAttributesWidget()) @staticmethod def _unregister_polygon_raster_overlay_attributes_widget(): window = omni.kit.window.property.get_window() if window is not None: window.unregister_widget("prim", "cesiumPolygonRasterOverlay") @staticmethod def _register_web_map_service_raster_overlay_attributes_widget(): window = omni.kit.window.property.get_window() if window is not None: window.register_widget( "prim", "cesiumWebMapServiceRasterOverlay", CesiumWebMapServiceRasterOverlayAttributesWidget() ) @staticmethod def _register_tile_map_service_raster_overlay_attributes_widget(): window = omni.kit.window.property.get_window() if window is not None: window.register_widget( "prim", "cesiumTileMapServiceRasterOverlay", CesiumTileMapServiceRasterOverlayAttributesWidget() ) @staticmethod def _register_web_map_tile_service_raster_overlay_attributes_widget(): window = omni.kit.window.property.get_window() if window is not None: window.register_widget( "prim", "cesiumWebMapTileServiceRasterOverlay", CesiumWebMapTileServiceRasterOverlayAttributesWidget() ) @staticmethod def _unregister_web_map_service_raster_overlay_attributes_widget(): window = omni.kit.window.property.get_window() if window is not None: window.unregister_widget("prim", "cesiumWebMapServiceRasterOverlay") @staticmethod def _unregister_tile_map_service_raster_overlay_attributes_widget(): window = omni.kit.window.property.get_window() if window is not None: window.unregister_widget("prim", "cesiumTileMapServiceRasterOverlay") @staticmethod def _unregister_web_map_tile_service_raster_overlay_attributes_widget(): window = omni.kit.window.property.get_window() if window is not None: window.unregister_widget("prim", "cesiumWebMapTileServiceRasterOverlay") def _register_global_anchor_attributes_widget(self): window = omni.kit.window.property.get_window() if window is not None: window.register_widget( "prim", "cesiumGlobeAnchorAPI", CesiumGlobeAnchorAttributesWidget(self._cesium_omniverse_interface) ) @staticmethod def _unregister_global_anchor_attributes_widget(): window = omni.kit.window.property.get_window() if window is not None: window.unregister_widget("prim", "cesiumGlobalAnchorAPI") def _register_ion_server_attributes_widget(self): window = omni.kit.window.property.get_window() if window is not None: window.register_widget( "prim", "cesiumIonServer", CesiumIonServerAttributesWidget(self._cesium_omniverse_interface) ) @staticmethod def _unregister_ion_server_attributes_widget(): window = omni.kit.window.property.get_window() if window is not None: window.unregister_widget("prim", "cesiumIonServer")
7,625
Python
41.603352
118
0.694164
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/statistics_widget.py
import logging import carb.events import omni.kit.app as app import omni.ui as ui from typing import List from ..bindings import ICesiumOmniverseInterface from .models.space_delimited_number_model import SpaceDelimitedNumberModel from .models.human_readable_bytes_model import HumanReadableBytesModel MATERIALS_CAPACITY_TEXT = "Materials capacity" MATERIALS_LOADED_TEXT = "Materials loaded" GEOMETRIES_CAPACITY_TEXT = "Geometries capacity" GEOMETRIES_LOADED_TEXT = "Geometries loaded" GEOMETRIES_RENDERED_TEXT = "Geometries rendered" TRIANGLES_LOADED_TEXT = "Triangles loaded" TRIANGLES_RENDERED_TEXT = "Triangles rendered" TILESET_CACHED_BYTES_TEXT = "Tileset cached bytes" TILESET_CACHED_BYTES_HUMAN_READABLE_TEXT = "Tileset cached bytes (Human-readable)" TILES_VISITED_TEXT = "Tiles visited" CULLED_TILES_VISITED_TEXT = "Culled tiles visited" TILES_RENDERED_TEXT = "Tiles rendered" TILES_CULLED_TEXT = "Tiles culled" MAX_DEPTH_VISITED_TEXT = "Max depth visited" TILES_LOADING_WORKER_TEXT = "Tiles loading (worker)" TILES_LOADING_MAIN_TEXT = "Tiles loading (main)" TILES_LOADED_TEXT = "Tiles loaded" class CesiumOmniverseStatisticsWidget(ui.Frame): """ Widget that displays statistics about the scene. """ def __init__(self, cesium_omniverse_interface: ICesiumOmniverseInterface, **kwargs): super().__init__(build_fn=self._build_fn, **kwargs) self._logger = logging.getLogger(__name__) self._cesium_omniverse_interface = cesium_omniverse_interface self._materials_capacity_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._materials_loaded_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._geometries_capacity_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._geometries_loaded_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._geometries_rendered_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._triangles_loaded_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._triangles_rendered_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._tileset_cached_bytes_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._tileset_cached_bytes_human_readable_model: HumanReadableBytesModel = HumanReadableBytesModel(0) self._tiles_visited_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._culled_tiles_visited_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._tiles_rendered_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._tiles_culled_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._max_depth_visited_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._tiles_loading_worker_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._tiles_loading_main_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._tiles_loaded_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._subscriptions: List[carb.events.ISubscription] = [] self._setup_subscriptions() def __del__(self): self.destroy() def destroy(self): for subscription in self._subscriptions: subscription.unsubscribe() self._subscriptions.clear() super().destroy() def _setup_subscriptions(self): update_stream = app.get_app().get_update_event_stream() self._subscriptions.append( update_stream.create_subscription_to_pop(self._on_update_frame, name="on_update_frame") ) def _on_update_frame(self, _e: carb.events.IEvent): if not self.visible: return render_statistics = self._cesium_omniverse_interface.get_render_statistics() self._materials_capacity_model.set_value(render_statistics.materials_capacity) self._materials_loaded_model.set_value(render_statistics.materials_loaded) self._geometries_capacity_model.set_value(render_statistics.geometries_capacity) self._geometries_loaded_model.set_value(render_statistics.geometries_loaded) self._geometries_rendered_model.set_value(render_statistics.geometries_rendered) self._triangles_loaded_model.set_value(render_statistics.triangles_loaded) self._triangles_rendered_model.set_value(render_statistics.triangles_rendered) self._tileset_cached_bytes_model.set_value(render_statistics.tileset_cached_bytes) self._tileset_cached_bytes_human_readable_model.set_value(render_statistics.tileset_cached_bytes) self._tiles_visited_model.set_value(render_statistics.tiles_visited) self._culled_tiles_visited_model.set_value(render_statistics.culled_tiles_visited) self._tiles_rendered_model.set_value(render_statistics.tiles_rendered) self._tiles_culled_model.set_value(render_statistics.tiles_culled) self._max_depth_visited_model.set_value(render_statistics.max_depth_visited) self._tiles_loading_worker_model.set_value(render_statistics.tiles_loading_worker) self._tiles_loading_main_model.set_value(render_statistics.tiles_loading_main) self._tiles_loaded_model.set_value(render_statistics.tiles_loaded) def _build_fn(self): """Builds all UI components.""" with ui.VStack(spacing=4): with ui.HStack(height=16): ui.Label("Statistics", height=0) ui.Spacer() for label, model in [ (MATERIALS_CAPACITY_TEXT, self._materials_capacity_model), (MATERIALS_LOADED_TEXT, self._materials_loaded_model), (GEOMETRIES_CAPACITY_TEXT, self._geometries_capacity_model), (GEOMETRIES_LOADED_TEXT, self._geometries_loaded_model), (GEOMETRIES_RENDERED_TEXT, self._geometries_rendered_model), (TRIANGLES_LOADED_TEXT, self._triangles_loaded_model), (TRIANGLES_RENDERED_TEXT, self._triangles_rendered_model), (TILESET_CACHED_BYTES_TEXT, self._tileset_cached_bytes_model), (TILESET_CACHED_BYTES_HUMAN_READABLE_TEXT, self._tileset_cached_bytes_human_readable_model), (TILES_VISITED_TEXT, self._tiles_visited_model), (CULLED_TILES_VISITED_TEXT, self._culled_tiles_visited_model), (TILES_RENDERED_TEXT, self._tiles_rendered_model), (TILES_CULLED_TEXT, self._tiles_culled_model), (MAX_DEPTH_VISITED_TEXT, self._max_depth_visited_model), (TILES_LOADING_WORKER_TEXT, self._tiles_loading_worker_model), (TILES_LOADING_MAIN_TEXT, self._tiles_loading_main_model), (TILES_LOADED_TEXT, self._tiles_loaded_model), ]: with ui.HStack(height=0): ui.Label(label, height=0) ui.StringField(model=model, height=0, read_only=True)
7,064
Python
52.931297
109
0.708097
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/token_window.py
import logging import carb.events import omni.kit.app as app import omni.ui as ui import omni.usd from pathlib import Path from enum import Enum from typing import List, Optional from ..bindings import ICesiumOmniverseInterface, Token from .styles import CesiumOmniverseUiStyles from cesium.usd.plugins.CesiumUsdSchemas import IonServer as CesiumIonServer from ..usdUtils import get_path_to_current_ion_server SELECT_TOKEN_TEXT = ( "Cesium for Omniverse embeds a Cesium ion token in your stage in order to allow it " "to access the assets you add. Select the Cesium ion token to use." ) CREATE_NEW_LABEL_TEXT = "Create a new token" USE_EXISTING_LABEL_TEXT = "Use an existing token" SPECIFY_TOKEN_LABEL_TEXT = "Specify a token" CREATE_NEW_FIELD_LABEL_TEXT = "Name" USE_EXISTING_FIELD_LABEL_TEXT = "Token" SPECIFY_TOKEN_FIELD_LABEL_TEXT = "Token" SELECT_BUTTON_TEXT = "Use as Project Default Token" DEFAULT_TOKEN_PLACEHOLDER_BASE = "{0} (Created by Cesium For Omniverse)" OUTER_SPACING = 10 CHECKBOX_WIDTH = 20 INNER_HEIGHT = 20 FIELD_SPACING = 8 FIELD_LABEL_WIDTH = 40 class TokenOptionEnum(Enum): CREATE_NEW = 1 USE_EXISTING = 2 SPECIFY_TOKEN = 3 class UseExistingComboItem(ui.AbstractItem): def __init__(self, token: Token): super().__init__() self.id = ui.SimpleStringModel(token.id) self.name = ui.SimpleStringModel(token.name) self.token = ui.SimpleStringModel(token.token) def __str__(self): return f"{self.id.get_value_as_string()}:{self.name.get_value_as_string()}:{self.token.get_value_as_string()}" class UseExistingComboModel(ui.AbstractItemModel): def __init__(self, item_list): super().__init__() self._logger = logging.getLogger(__name__) self._current_index = ui.SimpleIntModel(0) self._current_index.add_value_changed_fn(lambda index_model: self._item_changed(None)) self._items = [UseExistingComboItem(text) for text in item_list] def replace_all_items(self, items: List[str]): self._items.clear() self._items = [UseExistingComboItem(text) for text in items] self._current_index.set_value(0) self._item_changed(None) def append_child_item(self, parent_item: ui.AbstractItem, model: str): self._items.append(UseExistingComboItem(model)) self._item_changed(None) def get_item_children(self, item=None): return self._items def get_item_value_model(self, item: UseExistingComboItem = None, column_id: int = 0): if item is None: return self._current_index return item.name def get_current_selection(self): if len(self._items) < 1: return None return self._items[self._current_index.get_value_as_int()] class CesiumOmniverseTokenWindow(ui.Window): WINDOW_NAME = "Select Cesium ion Token" def __init__(self, cesium_omniverse_interface: ICesiumOmniverseInterface, **kwargs): super().__init__(CesiumOmniverseTokenWindow.WINDOW_NAME, **kwargs) self._cesium_omniverse_interface = cesium_omniverse_interface self._logger = logging.getLogger(__name__) self.height = 400 self.width = 600 self.padding_x = 12 self.padding_y = 12 session = self._cesium_omniverse_interface.get_session() self._is_connected: bool = session.is_connected() if self._is_connected: self._selected_option = TokenOptionEnum.CREATE_NEW else: self._selected_option = TokenOptionEnum.SPECIFY_TOKEN self._create_new_radio_button_model = ui.SimpleBoolModel(self._is_connected) self._create_new_radio_button_model.add_value_changed_fn( lambda m: self._radio_button_changed(m, TokenOptionEnum.CREATE_NEW) ) self._use_existing_radio_button_model = ui.SimpleBoolModel(False) self._use_existing_radio_button_model.add_value_changed_fn( lambda m: self._radio_button_changed(m, TokenOptionEnum.USE_EXISTING) ) self._specify_token_radio_button_model = ui.SimpleBoolModel(not self._is_connected) self._specify_token_radio_button_model.add_value_changed_fn( lambda m: self._radio_button_changed(m, TokenOptionEnum.SPECIFY_TOKEN) ) self._use_existing_combo_box: Optional[ui.ComboBox] = None stage = omni.usd.get_context().get_stage() root_identifier = stage.GetRootLayer().identifier # In the event that the stage has been saved and the root layer identifier is a file path then we want to # grab just the final bit of that. if not root_identifier.startswith("anon:"): try: root_identifier = Path(root_identifier).name except NotImplementedError as e: self._logger.warning( f"Unknown stage identifier type. Passed {root_identifier} to Path. Exception: {e}" ) self._create_new_field_model = ui.SimpleStringModel(DEFAULT_TOKEN_PLACEHOLDER_BASE.format(root_identifier)) self._use_existing_combo_model = UseExistingComboModel([]) server_prim_path = get_path_to_current_ion_server() server_prim = CesiumIonServer.Get(stage, server_prim_path) if server_prim.GetPrim().IsValid(): current_token = server_prim.GetProjectDefaultIonAccessTokenAttr().Get() self._specify_token_field_model = ui.SimpleStringModel(current_token if current_token is not None else "") else: self._specify_token_field_model = ui.SimpleStringModel() self._reload_next_frame = False # _handle_select_result is different from most subscriptions. We delete it when we are done, so it is separate # from the subscriptions array. self._handle_select_result_sub: Optional[carb.events.ISubscription] = None self._subscriptions: List[carb.events.ISubscription] = [] self._setup_subscriptions() self.frame.set_build_fn(self._build_ui) def __del__(self): self.destroy() def destroy(self): for subscription in self._subscriptions: subscription.unsubscribe() self._subscriptions.clear() if self._handle_select_result_sub is not None: self._handle_select_result_sub.unsubscribe() self._handle_select_result_sub = None super().destroy() def _setup_subscriptions(self): update_stream = app.get_app().get_update_event_stream() self._subscriptions.append( update_stream.create_subscription_to_pop(self._on_update_frame, name="on_update_frame") ) def _on_update_frame(self, _e: carb.events.IEvent): session = self._cesium_omniverse_interface.get_session() if self._reload_next_frame and session.is_token_list_loaded(): token_list = session.get_tokens() self._use_existing_combo_model.replace_all_items(token_list) if self._use_existing_combo_box: self._use_existing_combo_box.enabled = True self._reload_next_frame = False elif session.is_loading_token_list(): if self._use_existing_combo_box: self._use_existing_combo_box.enabled = False self._reload_next_frame = True def _select_button_clicked(self): bus = app.get_app().get_message_bus_event_stream() completed_event = carb.events.type_from_string("cesium.omniverse.SET_DEFAULT_PROJECT_TOKEN_COMPLETE") self._handle_select_result_sub = bus.create_subscription_to_pop_by_type( completed_event, self._handle_select_result, name="cesium.omniverse.HANDLE_SELECT_TOKEN_RESULT" ) if self._selected_option is TokenOptionEnum.CREATE_NEW: self._create_token() elif self._selected_option is TokenOptionEnum.USE_EXISTING: self._use_existing_token() elif self._selected_option is TokenOptionEnum.SPECIFY_TOKEN: self._specify_token() def _handle_select_result(self, _e: carb.events.IEvent): # We probably need to put some better error handling here in the future. result = self._cesium_omniverse_interface.get_set_default_token_result() if result.code != 0: self._logger.warning(f"Error when trying to set token: {result.message}") bus = app.get_app().get_message_bus_event_stream() success_event = carb.events.type_from_string("cesium.omniverse.SET_DEFAULT_TOKEN_SUCCESS") bus.push(success_event) self.visible = False self.destroy() def _create_token(self): name = self._create_new_field_model.get_value_as_string().strip() if name != "": self._cesium_omniverse_interface.create_token(name) def _use_existing_token(self): token = self._use_existing_combo_model.get_current_selection() if token is not None: self._cesium_omniverse_interface.select_token( token.id.get_value_as_string(), token.token.get_value_as_string() ) def _specify_token(self): token = self._specify_token_field_model.get_value_as_string().strip() if token != "": self._cesium_omniverse_interface.specify_token(token) def _radio_button_changed(self, model, selected: TokenOptionEnum): if not model.get_value_as_bool(): self._reselect_if_none_selected(selected) return self._selected_option = selected if self._selected_option is TokenOptionEnum.CREATE_NEW: self._create_new_radio_button_model.set_value(True) self._use_existing_radio_button_model.set_value(False) self._specify_token_radio_button_model.set_value(False) elif self._selected_option is TokenOptionEnum.USE_EXISTING: self._create_new_radio_button_model.set_value(False) self._use_existing_radio_button_model.set_value(True) self._specify_token_radio_button_model.set_value(False) elif self._selected_option is TokenOptionEnum.SPECIFY_TOKEN: self._create_new_radio_button_model.set_value(False) self._use_existing_radio_button_model.set_value(False) self._specify_token_radio_button_model.set_value(True) def _reselect_if_none_selected(self, selected): """ Reselect the checkbox in our "radio buttons" if none are selected. This is necessary because Omniverse has us using checkboxes to make a radio button rather than a proper radio button. """ if ( not self._create_new_radio_button_model.get_value_as_bool() and not self._use_existing_radio_button_model.get_value_as_bool() and not self._specify_token_radio_button_model.get_value_as_bool() ): if selected is TokenOptionEnum.CREATE_NEW: self._create_new_radio_button_model.set_value(True) elif selected is TokenOptionEnum.USE_EXISTING: self._use_existing_radio_button_model.set_value(True) elif selected is TokenOptionEnum.SPECIFY_TOKEN: self._specify_token_radio_button_model.set_value(True) @staticmethod def _build_field( label_text: str, field_label_text: str, checkbox_model: ui.SimpleBoolModel, string_field_model: ui.SimpleStringModel, visible=True, ): with ui.HStack(spacing=OUTER_SPACING, visible=visible): ui.CheckBox(checkbox_model, width=CHECKBOX_WIDTH) with ui.VStack(height=INNER_HEIGHT, spacing=FIELD_SPACING): ui.Label(label_text) with ui.HStack(): ui.Label(field_label_text, width=FIELD_LABEL_WIDTH) ui.StringField(string_field_model) def _build_ui(self): with ui.VStack(spacing=10): ui.Label(SELECT_TOKEN_TEXT, height=40, word_wrap=True) self._build_field( CREATE_NEW_LABEL_TEXT, CREATE_NEW_FIELD_LABEL_TEXT, self._create_new_radio_button_model, self._create_new_field_model, self._is_connected, ) with ui.HStack(spacing=OUTER_SPACING, visible=self._is_connected): ui.CheckBox(self._use_existing_radio_button_model, width=CHECKBOX_WIDTH) with ui.VStack(height=20, spacing=FIELD_SPACING): ui.Label(USE_EXISTING_LABEL_TEXT) with ui.HStack(): ui.Label(USE_EXISTING_FIELD_LABEL_TEXT, width=FIELD_LABEL_WIDTH) self._use_existing_combo_box = ui.ComboBox(self._use_existing_combo_model) self._build_field( SPECIFY_TOKEN_LABEL_TEXT, SPECIFY_TOKEN_FIELD_LABEL_TEXT, self._specify_token_radio_button_model, self._specify_token_field_model, ) ui.Button( SELECT_BUTTON_TEXT, alignment=ui.Alignment.CENTER, height=36, style=CesiumOmniverseUiStyles.blue_button_style, clicked_fn=self._select_button_clicked, )
13,286
Python
40.009259
118
0.638717
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/profile_widget.py
import omni.usd import logging import carb.events import omni.kit.app as app import omni.ui as ui from typing import List, Optional from ..bindings import ICesiumOmniverseInterface, CesiumIonSession from enum import Enum from cesium.usd.plugins.CesiumUsdSchemas import IonServer as CesiumIonServer from ..usdUtils import set_path_to_current_ion_server class SessionState(Enum): NOT_CONNECTED = 1 LOADING = 2 CONNECTED = 3 def get_session_state(session: CesiumIonSession) -> SessionState: if session.is_profile_loaded(): return SessionState.CONNECTED elif session.is_loading_profile(): return SessionState.LOADING else: return SessionState.NOT_CONNECTED def get_profile_id(session: CesiumIonSession) -> Optional[int]: if session.is_profile_loaded(): profile = session.get_profile() return profile.id return None class SessionComboItem(ui.AbstractItem): def __init__(self, session: CesiumIonSession, server: CesiumIonServer): super().__init__() session_state = get_session_state(session) prefix = "" suffix = "" if session_state == SessionState.NOT_CONNECTED: suffix += " (not connected)" elif session_state == SessionState.LOADING: suffix += " (loading profile...)" elif session_state == SessionState.CONNECTED: prefix += session.get_profile().username prefix += " @ " # Get the display name from the server prim. If that's empty, use the prim path. server_name = server.GetDisplayNameAttr().Get() if server_name == "": server_name = server.GetPath() self.text = ui.SimpleStringModel(f"{prefix}{server_name}{suffix}") self.server = server class SessionComboModel(ui.AbstractItemModel): def __init__(self): super().__init__() self._logger = logging.getLogger(__name__) self._current_index = ui.SimpleIntModel(0) self._current_index.add_value_changed_fn(lambda index_model: self._item_changed(None)) self._items = [] def replace_all_items( self, sessions: List[CesiumIonSession], servers: List[CesiumIonServer], current_server: CesiumIonServer ): self._items.clear() self._items = [SessionComboItem(session, server) for session, server in zip(sessions, servers)] current_index = 0 for index, server in enumerate(servers): if server.GetPath() == current_server.GetPath(): current_index = index break self._current_index.set_value(current_index) self._item_changed(None) def get_item_children(self, item=None): return self._items def get_item_value_model(self, item: SessionComboItem = None, column_id: int = 0): if item is None: return self._current_index return item.text def get_current_selection(self): if len(self._items) < 1: return None return self._items[self._current_index.get_value_as_int()] class CesiumOmniverseProfileWidget(ui.Frame): def __init__(self, cesium_omniverse_interface: ICesiumOmniverseInterface, **kwargs): self._logger = logging.getLogger(__name__) self._cesium_omniverse_interface = cesium_omniverse_interface self._profile_ids: List[int] = [] self._session_states: List[SessionState] = [] self._server_paths: List[str] = [] self._server_names: List[str] = [] self._sessions_combo_box: Optional[ui.ComboBox] = None self._sessions_combo_model = SessionComboModel() self._sessions_combo_model.add_item_changed_fn(self._on_item_changed) self._subscriptions: List[carb.events.ISubscription] = [] self._setup_subscriptions() super().__init__(build_fn=self._build_ui, **kwargs) def destroy(self) -> None: for subscription in self._subscriptions: subscription.unsubscribe() self._subscriptions.clear() def _setup_subscriptions(self): update_stream = app.get_app().get_update_event_stream() self._subscriptions.append( update_stream.create_subscription_to_pop(self._on_update_frame, name="on_update_frame") ) def _on_item_changed(self, item_model, item): item = self._sessions_combo_model.get_current_selection() if item is not None: server_path = item.server.GetPath() set_path_to_current_ion_server(server_path) def _on_update_frame(self, _e: carb.events.IEvent): if omni.usd.get_context().get_stage_state() != omni.usd.StageState.OPENED: return stage = omni.usd.get_context().get_stage() sessions = self._cesium_omniverse_interface.get_sessions() server_paths = self._cesium_omniverse_interface.get_server_paths() servers = [CesiumIonServer.Get(stage, server_path) for server_path in server_paths] server_names = [server.GetDisplayNameAttr().Get() for server in servers] current_server_path = self._cesium_omniverse_interface.get_server_path() current_server = CesiumIonServer.Get(stage, current_server_path) profile_ids = [] session_states = [] for session in sessions: profile_id = get_profile_id(session) session_state = get_session_state(session) if session.is_connected() and not session.is_profile_loaded(): session.refresh_profile() profile_ids.append(profile_id) session_states.append(session_state) if ( profile_ids != self._profile_ids or session_states != self._session_states or server_paths != self._server_paths or server_names != self._server_names ): self._logger.info("Rebuilding profile widget") self._profile_ids = profile_ids self._session_states = session_states self._server_paths = server_paths self._server_names = server_names self._sessions_combo_model.replace_all_items(sessions, servers, current_server) self.rebuild() def _build_ui(self): self._sessions_combo_box = ui.ComboBox(self._sessions_combo_model)
6,315
Python
33.703297
111
0.634363
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/add_menu_controller.py
from functools import partial import logging import omni.kit.context_menu from omni.kit.property.usd import PrimPathWidget, PrimSelectionPayload from omni.kit.window.property import get_window as get_property_window import omni.usd from pxr import Sdf, Tf, UsdGeom from cesium.usd.plugins.CesiumUsdSchemas import ( Tileset as CesiumTileset, PolygonRasterOverlay as CesiumPolygonRasterOverlay, IonRasterOverlay as CesiumIonRasterOverlay, WebMapServiceRasterOverlay as CesiumWebMapServiceRasterOverlay, TileMapServiceRasterOverlay as CesiumTileMapServiceRasterOverlay, WebMapTileServiceRasterOverlay as CesiumWebMapTileServiceRasterOverlay, ) from ..usdUtils import add_globe_anchor_to_prim from ..bindings import ICesiumOmniverseInterface class CesiumAddMenuController: def __init__(self, cesium_omniverse_interface: ICesiumOmniverseInterface): self._logger = logging.getLogger(__name__) self._cesium_omniverse_interface = cesium_omniverse_interface context_menu = omni.kit.context_menu.get_instance() if context_menu is None: self._logger.error("Cannot add Cesium options to Add menu when context_menu is disabled.") return self._items_added = [ PrimPathWidget.add_button_menu_entry( "Cesium/Globe Anchor", show_fn=partial(self._show_add_globe_anchor, context_menu=context_menu, usd_type=UsdGeom.Xformable), onclick_fn=self._add_globe_anchor_api, ), PrimPathWidget.add_button_menu_entry( "Cesium/Ion Raster Overlay", show_fn=partial(self._show_add_raster_overlay, context_menu=context_menu, usd_type=CesiumTileset), onclick_fn=self._add_ion_raster_overlay, ), PrimPathWidget.add_button_menu_entry( "Cesium/Polygon Raster Overlay", show_fn=partial(self._show_add_raster_overlay, context_menu=context_menu, usd_type=CesiumTileset), onclick_fn=self._add_polygon_raster_overlay, ), PrimPathWidget.add_button_menu_entry( "Cesium/Web Map Service Raster Overlay", show_fn=partial(self._show_add_raster_overlay, context_menu=context_menu, usd_type=CesiumTileset), onclick_fn=self._add_web_map_service_raster_overlay, ), PrimPathWidget.add_button_menu_entry( "Cesium/Tile Map Service Raster Overlay", show_fn=partial(self._show_add_raster_overlay, context_menu=context_menu, usd_type=CesiumTileset), onclick_fn=self._add_tile_map_service_raster_overlay, ), PrimPathWidget.add_button_menu_entry( "Cesium/Web Map Tile Service Raster Overlay", show_fn=partial(self._show_add_raster_overlay, context_menu=context_menu, usd_type=CesiumTileset), onclick_fn=self._add_web_map_tile_service_raster_overlay, ), ] def destroy(self): for item in self._items_added: PrimPathWidget.remove_button_menu_entry(item) self._items_added.clear() def _add_globe_anchor_api(self, payload: PrimSelectionPayload): for path in payload: add_globe_anchor_to_prim(path) get_property_window().request_rebuild() def _add_ion_raster_overlay(self, payload: PrimSelectionPayload): stage = omni.usd.get_context().get_stage() for path in payload: child_path = Sdf.Path(path).AppendPath("ion_raster_overlay") ion_raster_overlay_path: str = omni.usd.get_stage_next_free_path(stage, child_path, False) CesiumIonRasterOverlay.Define(stage, ion_raster_overlay_path) tileset_prim = CesiumTileset.Get(stage, path) tileset_prim.GetRasterOverlayBindingRel().AddTarget(ion_raster_overlay_path) get_property_window().request_rebuild() def _add_polygon_raster_overlay(self, payload: PrimSelectionPayload): stage = omni.usd.get_context().get_stage() for path in payload: child_path = Sdf.Path(path).AppendPath("polygon_raster_overlay") polygon_raster_overlay_path: str = omni.usd.get_stage_next_free_path(stage, child_path, False) CesiumPolygonRasterOverlay.Define(stage, polygon_raster_overlay_path) tileset_prim = CesiumTileset.Get(stage, path) tileset_prim.GetRasterOverlayBindingRel().AddTarget(polygon_raster_overlay_path) get_property_window().request_rebuild() def _add_web_map_service_raster_overlay(self, payload: PrimSelectionPayload): stage = omni.usd.get_context().get_stage() for path in payload: child_path = Sdf.Path(path).AppendPath("web_map_service_raster_overlay") raster_overlay_path: str = omni.usd.get_stage_next_free_path(stage, child_path, False) CesiumWebMapServiceRasterOverlay.Define(stage, raster_overlay_path) tileset_prim = CesiumTileset.Get(stage, path) tileset_prim.GetRasterOverlayBindingRel().AddTarget(raster_overlay_path) get_property_window().request_rebuild() def _add_tile_map_service_raster_overlay(self, payload: PrimSelectionPayload): stage = omni.usd.get_context().get_stage() for path in payload: child_path = Sdf.Path(path).AppendPath("tile_map_service_raster_overlay") raster_overlay_path: str = omni.usd.get_stage_next_free_path(stage, child_path, False) CesiumTileMapServiceRasterOverlay.Define(stage, raster_overlay_path) tileset_prim = CesiumTileset.Get(stage, path) tileset_prim.GetRasterOverlayBindingRel().AddTarget(raster_overlay_path) get_property_window().request_rebuild() def _add_web_map_tile_service_raster_overlay(self, payload: PrimSelectionPayload): stage = omni.usd.get_context().get_stage() for path in payload: child_path = Sdf.Path(path).AppendPath("web_map_tile_service_raster_overlay") raster_overlay_path: str = omni.usd.get_stage_next_free_path(stage, child_path, False) CesiumWebMapTileServiceRasterOverlay.Define(stage, raster_overlay_path) tileset_prim = CesiumTileset.Get(stage, path) tileset_prim.GetRasterOverlayBindingRel().AddTarget(raster_overlay_path) get_property_window().request_rebuild() @staticmethod def _show_add_globe_anchor(objects: dict, context_menu: omni.kit.context_menu, usd_type: Tf.Type) -> bool: return context_menu.prim_is_type(objects, type=usd_type) @staticmethod def _show_add_raster_overlay(objects: dict, context_menu: omni.kit.context_menu, usd_type: Tf.Type) -> bool: return context_menu.prim_is_type(objects, type=usd_type)
6,877
Python
51.907692
116
0.671514
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/image_button.py
import urllib.request from io import BytesIO from PIL import Image import omni.ui as ui class CesiumImageButton: """A button with an image from a URL or base64 encoded string. Based off of Nvidia's ButtonWithProvider sample.""" def __init__(self, src: str, button_type=ui.Button, padding=0, height=None, **kwargs): style_type = kwargs.pop("style_type_name_override", self.__class__.__name__) name = kwargs.pop("name", "") with ui.ZStack(height=0, width=0): # This is copied from uri_image.py since we seem to blow the stack if we nest any deeper when rendering. data = urllib.request.urlopen(src).read() img_data = BytesIO(data) image = Image.open(img_data) if image.mode != "RGBA": image = image.convert("RGBA") pixels = list(image.getdata()) provider = ui.ByteImageProvider() provider.set_bytes_data(pixels, [image.size[0], image.size[1]]) if height is None: width = image.size[0] height = image.size[1] else: # If the user is explicitely setting the height of the button, we need to calc an appropriate width width = image.size[0] * (height / image.size[1]) # Add padding for all sides height += padding * 2 width += padding * 2 # The styles here are very specific to this stuff so they shouldn't be included # in the CesiumOmniverseUiStyles class. self._button = button_type( text=" ", # Workaround Buttons without text do not expand vertically style_type_name_override=style_type, name=name, width=width, height=height, style={ "border_radius": 6, "background_color": ui.color.transparent, "color": ui.color.transparent, ":hovered": {"background_color": ui.color("#9E9E9E")}, }, **kwargs, ) self._image = ui.ImageWithProvider( provider, width=width, height=height, fill_policy=ui.IwpFillPolicy.IWP_PRESERVE_ASPECT_FIT, style={"alignment": ui.Alignment.CENTER, "margin": padding}, style_type_name_override=style_type, name=name, ) def get_image(self): return self._image def __getattr__(self, attr): return getattr(self._button, attr) def __setattr__(self, attr, value): if attr == "_image" or attr == "_button": super().__setattr__(attr, value) else: self._button.__setattr__(attr, value)
2,834
Python
37.31081
118
0.538109
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/credits_viewport_controller.py
from .credits_parser import CesiumCreditsParser, ParsedCredit from typing import List, Optional, Tuple import logging import carb.events import omni.kit.app as app from ..bindings import ICesiumOmniverseInterface import omni.ui as ui import omni.kit.app import json from carb.events import IEventStream from .events import EVENT_CREDITS_CHANGED class CreditsViewportController: def __init__(self, cesium_omniverse_interface: ICesiumOmniverseInterface): self._cesium_omniverse_interface = cesium_omniverse_interface self._logger: Optional[logging.Logger] = logging.getLogger(__name__) self._parsed_credits: List[ParsedCredit] = [] self._credits: List[Tuple[str, bool]] = [] self._subscriptions: List[carb.events.ISubscription] = [] self._setup_update_subscription() self._message_bus: IEventStream = omni.kit.app.get_app().get_message_bus_event_stream() self._EVENT_CREDITS_CHANGED: int = EVENT_CREDITS_CHANGED def __del__(self): self.destroy() def destroy(self): for subscription in self._subscriptions: subscription.unsubscribe() self._subscriptions.clear() def _setup_update_subscription(self): update_stream = app.get_app().get_update_event_stream() self._subscriptions.append( update_stream.create_subscription_to_pop( self._on_update_frame, name="cesium.omniverse.viewport.ON_UPDATE_FRAME" ) ) def _on_update_frame(self, _e: carb.events.IEvent): if self._cesium_omniverse_interface is None: return new_credits = self._cesium_omniverse_interface.get_credits() # cheap test if new_credits != self._credits: self._credits.clear() self._credits.extend(new_credits) # deep test credits_parser = CesiumCreditsParser( new_credits, should_show_on_screen=True, combine_labels=True, label_alignment=ui.Alignment.RIGHT, ) new_parsed_credits = credits_parser._parse_credits(new_credits, True, False) if new_parsed_credits != self._parsed_credits: self._parsed_credits = new_parsed_credits self.broadcast_credits() self._cesium_omniverse_interface.credits_start_next_frame() def broadcast_credits(self): my_payload = json.dumps(self._credits) self._message_bus.push(self._EVENT_CREDITS_CHANGED, payload={"credits": my_payload})
2,567
Python
36.217391
95
0.64589
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/fabric_modal.py
import carb.settings import omni.ui as ui import omni.kit.window.file class CesiumFabricModal(ui.Window): def __init__(self): window_flags = ui.WINDOW_FLAGS_NO_RESIZE window_flags |= ui.WINDOW_FLAGS_NO_SCROLLBAR window_flags |= ui.WINDOW_FLAGS_MODAL window_flags |= ui.WINDOW_FLAGS_NO_CLOSE window_flags |= ui.WINDOW_FLAGS_NO_COLLAPSE super().__init__("Enable Fabric", height=200, width=300, flags=window_flags) self.frame.set_build_fn(self._build_fn) def _on_yes_click(self): carb.settings.get_settings().set_bool("/app/useFabricSceneDelegate", True) carb.settings.get_settings().set_bool("/app/usdrt/scene_delegate/enableProxyCubes", False) carb.settings.get_settings().set_bool("/app/usdrt/scene_delegate/geometryStreaming/enabled", False) carb.settings.get_settings().set_bool("/omnihydra/parallelHydraSprimSync", False) omni.kit.window.file.new() self.visible = False def _on_no_click(self): self.visible = False def _build_fn(self): with ui.VStack(height=0, spacing=10): ui.Label( "The Omniverse Fabric Scene Delegate is currently disabled. Cesium for Omniverse requires the " "Fabric Scene Delegate to be enabled to function.", word_wrap=True, ) ui.Label("Would you like to enable the Fabric Scene Delegate and create a new stage?", word_wrap=True) ui.Button("Yes", clicked_fn=self._on_yes_click) ui.Button("No", clicked_fn=self._on_no_click)
1,601
Python
40.076922
114
0.643348
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/asset_window.py
import logging from typing import cast, List, Optional import carb.events import omni.kit.app as app import omni.ui as ui from .asset_details_widget import CesiumAssetDetailsWidget from .search_field_widget import CesiumSearchFieldWidget from .models import IonAssets, IonAssetItem, IonAssetDelegate from .styles import CesiumOmniverseUiStyles from ..bindings import ICesiumOmniverseInterface class CesiumOmniverseAssetWindow(ui.Window): """ The asset list window for Cesium for Omniverse. Docked in the same area as "Assets". """ WINDOW_NAME = "Cesium Assets" MENU_PATH = f"Window/Cesium/{WINDOW_NAME}" def __init__(self, cesium_omniverse_interface: ICesiumOmniverseInterface, **kwargs): super().__init__(CesiumOmniverseAssetWindow.WINDOW_NAME, **kwargs) self._cesium_omniverse_interface = cesium_omniverse_interface self._logger = logging.getLogger(__name__) self._assets = IonAssets() self._assets_delegate = IonAssetDelegate() self._refresh_button: Optional[ui.Button] = None self._asset_tree_view: Optional[ui.TreeView] = None self._asset_details_widget: Optional[CesiumAssetDetailsWidget] = None self._search_field_widget: Optional[CesiumSearchFieldWidget] = None self._subscriptions: List[carb.events.ISubscription] = [] self._setup_subscriptions() self.frame.set_build_fn(self._build_fn) self._refresh_list() self.focus() def __del__(self): self.destroy() def destroy(self): if self._refresh_button is not None: self._refresh_button.destroy() self._refresh_button = None if self._asset_tree_view is not None: self._asset_tree_view.destroy() self._asset_tree_view = None if self._asset_details_widget is not None: self._asset_details_widget.destroy() self._asset_details_widget = None if self._search_field_widget is not None: self._search_field_widget.destroy() self._search_field_widget = None for subscription in self._subscriptions: subscription.unsubscribe() self._subscriptions.clear() super().destroy() def _setup_subscriptions(self): bus = app.get_app().get_message_bus_event_stream() assets_updated_event = carb.events.type_from_string("cesium.omniverse.ASSETS_UPDATED") self._subscriptions.append( bus.create_subscription_to_pop_by_type( assets_updated_event, self._on_assets_updated, name="cesium.omniverse.asset_window.assets_updated" ) ) def _refresh_list(self): session = self._cesium_omniverse_interface.get_session() if session is not None: self._logger.info("Cesium ion Assets refreshing.") session.refresh_assets() if self._search_field_widget is not None: self._search_field_widget.search_value = "" def _on_assets_updated(self, _e: carb.events.IEvent): session = self._cesium_omniverse_interface.get_session() if session is not None: self._logger.info("Cesium ion Assets refreshed.") self._assets.replace_items( [ IonAssetItem( item.asset_id, item.name, item.description, item.attribution, item.asset_type, item.date_added ) for item in session.get_assets().items ] ) def _refresh_button_clicked(self): self._refresh_list() self._selection_changed([]) def _selection_changed(self, items: List[ui.AbstractItem]): if len(items) > 0: item = cast(IonAssetItem, items.pop()) else: item = None self._asset_details_widget.update_selection(item) def _search_value_changed(self, _e): if self._search_field_widget is None: return self._assets.filter_items(self._search_field_widget.search_value) def _build_fn(self): """Builds all UI components.""" with ui.VStack(spacing=5): with ui.HStack(height=30): self._refresh_button = ui.Button( "Refresh", alignment=ui.Alignment.CENTER, width=80, style=CesiumOmniverseUiStyles.blue_button_style, clicked_fn=self._refresh_button_clicked, ) ui.Spacer() with ui.VStack(width=0): ui.Spacer() self._search_field_widget = CesiumSearchFieldWidget( self._search_value_changed, width=320, height=32 ) with ui.HStack(spacing=5): with ui.ScrollingFrame( style_type_name_override="TreeView", style={"Field": {"background_color": 0xFF000000}}, width=ui.Length(2, ui.UnitType.FRACTION), ): self._asset_tree_view = ui.TreeView( self._assets, delegate=self._assets_delegate, root_visible=False, header_visible=True, style={"TreeView.Item": {"margin": 4}}, ) self._asset_tree_view.set_selection_changed_fn(self._selection_changed) self._asset_details_widget = CesiumAssetDetailsWidget( self._cesium_omniverse_interface, width=ui.Length(1, ui.UnitType.FRACTION) )
5,691
Python
35.72258
118
0.582499
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/attributes/web_map_tile_service_raster_overlay_attributes_widget.py
import logging import omni.kit.window.property import omni.usd import omni.ui from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty from omni.kit.property.usd.usd_property_widget import SchemaPropertiesWidget from cesium.usd.plugins.CesiumUsdSchemas import ( WebMapTileServiceRasterOverlay as CesiumWebMapTileServiceRasterOverlay, ) from .cesium_properties_widget_builder import build_slider, build_common_raster_overlay_properties class CesiumWebMapTileServiceRasterOverlayAttributesWidget(SchemaPropertiesWidget): def __init__(self): super().__init__( "Cesium Web Map Service Raster Overlay Settings", CesiumWebMapTileServiceRasterOverlay, include_inherited=True, ) self._logger = logging.getLogger(__name__) self._stage = omni.usd.get_context().get_stage() def clean(self): super().clean() def _on_usd_changed(self, notice, stage): window = omni.kit.window.property.get_window() window.request_rebuild() def _customize_props_layout(self, props): frame = CustomLayoutFrame(hide_extra=True) prim_path = self._payload.get_paths()[0] webMapTileServiceRasterOverlay = CesiumWebMapTileServiceRasterOverlay.Get(self._stage, prim_path) specify_zoom_levels = webMapTileServiceRasterOverlay.GetSpecifyZoomLevelsAttr().Get() specify_tile_matrix_set_labels = webMapTileServiceRasterOverlay.GetSpecifyTileMatrixSetLabelsAttr().Get() specify_tiling_scheme = webMapTileServiceRasterOverlay.GetSpecifyTilingSchemeAttr().Get() with frame: with CustomLayoutGroup("WMTS Settings"): CustomLayoutProperty("cesium:url") CustomLayoutProperty("cesium:layer") CustomLayoutProperty("cesium:style") CustomLayoutProperty("cesium:format") with CustomLayoutGroup("Tiling Matrix Set Settings", collapsed=False): CustomLayoutProperty("cesium:tileMatrixSetId") CustomLayoutProperty("cesium:specifyTileMatrixSetLabels") if specify_tile_matrix_set_labels: CustomLayoutProperty("cesium:tileMatrixSetLabels") else: CustomLayoutProperty("cesium:tileMatrixSetLabelPrefix") CustomLayoutProperty("cesium:useWebMercatorProjection") with CustomLayoutGroup("Tiling Scheme Settings", collapsed=False): CustomLayoutProperty("cesium:specifyTilingScheme") if specify_tiling_scheme: CustomLayoutProperty("cesium:rootTilesX") CustomLayoutProperty("cesium:rootTilesY") CustomLayoutProperty("cesium:west") CustomLayoutProperty("cesium:east") CustomLayoutProperty("cesium:south") CustomLayoutProperty("cesium:north") with CustomLayoutGroup("Zoom Settings", collapsed=False): CustomLayoutProperty("cesium:specifyZoomLevels") if specify_zoom_levels: CustomLayoutProperty( "cesium:minimumZoomLevel", build_fn=build_slider( 0, 30, type="int", constrain={"attr": "cesium:maximumZoomLevel", "type": "maximum"} ), ) CustomLayoutProperty( "cesium:maximumZoomLevel", build_fn=build_slider( 0, 30, type="int", constrain={"attr": "cesium:minimumZoomLevel", "type": "minimum"} ), ) build_common_raster_overlay_properties() return frame.apply(props) def reset(self): if self._listener: self._listener.Revoke() self._listener = None super().reset()
4,112
Python
45.738636
115
0.606031
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/attributes/web_map_service_raster_overlay_attributes_widget.py
import logging from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty from omni.kit.property.usd.usd_property_widget import SchemaPropertiesWidget from cesium.usd.plugins.CesiumUsdSchemas import ( WebMapServiceRasterOverlay as CesiumWebMapServiceRasterOverlay, ) from .cesium_properties_widget_builder import build_slider, build_common_raster_overlay_properties class CesiumWebMapServiceRasterOverlayAttributesWidget(SchemaPropertiesWidget): def __init__(self): super().__init__( "Cesium Web Map Service Raster Overlay Settings", CesiumWebMapServiceRasterOverlay, include_inherited=True ) self._logger = logging.getLogger(__name__) def clean(self): super().clean() def _customize_props_layout(self, props): frame = CustomLayoutFrame(hide_extra=True) with frame: with CustomLayoutGroup("Base URL"): CustomLayoutProperty("cesium:baseUrl") with CustomLayoutGroup("Layers"): CustomLayoutProperty("cesium:layers") with CustomLayoutGroup("Tile Size"): CustomLayoutProperty("cesium:tileWidth", build_fn=build_slider(64, 2048, type="int")) CustomLayoutProperty("cesium:tileHeight", build_fn=build_slider(64, 2048, type="int")) with CustomLayoutGroup("Zoom Settings"): CustomLayoutProperty( "cesium:minimumLevel", build_fn=build_slider( 0, 30, type="int", constrain={"attr": "cesium:maximumLevel", "type": "maximum"} ), ) CustomLayoutProperty( "cesium:maximumLevel", build_fn=build_slider( 0, 30, type="int", constrain={"attr": "cesium:minimumLevel", "type": "minimum"} ), ) build_common_raster_overlay_properties() return frame.apply(props)
2,039
Python
41.499999
118
0.621383
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/attributes/cesium_properties_widget_builder.py
from typing import List import omni.ui as ui from pxr import Sdf from functools import partial from omni.kit.property.usd.custom_layout_helper import CustomLayoutGroup, CustomLayoutProperty def update_range(stage, prim_paths, constrain, attr_name): min_val = max_val = None for path in prim_paths: prim = stage.GetPrimAtPath(path) attr = prim.GetAttribute(constrain["attr"]) if prim else None if prim and attr: if constrain["type"] == "minimum": min_val = attr.Get() else: max_val = attr.Get() break for path in prim_paths: prim = stage.GetPrimAtPath(path) attr = prim.GetAttribute(attr_name) if prim else None if prim and attr: val = attr.Get() if min_val: val = max(min_val, val) elif max_val: val = min(max_val, val) attr.Set(val) break def _build_slider( stage, attr_name, metadata, property_type, prim_paths: List[Sdf.Path], type="float", additional_label_kwargs={}, additional_widget_kwargs={}, ): from omni.kit.window.property.templates import HORIZONTAL_SPACING from omni.kit.property.usd.usd_attribute_model import UsdAttributeModel from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidgetBuilder if not attr_name or not property_type: return with ui.HStack(spacing=HORIZONTAL_SPACING): model_kwargs = UsdPropertiesWidgetBuilder.get_attr_value_range_kwargs(metadata) model = UsdAttributeModel( stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata, **model_kwargs, ) UsdPropertiesWidgetBuilder.create_label(attr_name, metadata, additional_label_kwargs) widget_kwargs = {"model": model} widget_kwargs.update(UsdPropertiesWidgetBuilder.get_attr_value_soft_range_kwargs(metadata)) if additional_widget_kwargs: widget_kwargs.update(additional_widget_kwargs) with ui.ZStack(): if type == "float": value_widget = UsdPropertiesWidgetBuilder.create_drag_or_slider( ui.FloatDrag, ui.FloatSlider, **widget_kwargs ) else: value_widget = UsdPropertiesWidgetBuilder.create_drag_or_slider( ui.IntDrag, ui.IntSlider, **widget_kwargs ) mixed_overlay = UsdPropertiesWidgetBuilder.create_mixed_text_overlay() UsdPropertiesWidgetBuilder.create_control_state( value_widget=value_widget, mixed_overlay=mixed_overlay, **widget_kwargs ) if len(additional_widget_kwargs["constrain"]) == 2: callback = partial(update_range, stage, prim_paths, additional_widget_kwargs["constrain"], attr_name) model.add_value_changed_fn(lambda m: callback()) return model def build_slider(min_value, max_value, type="float", constrain={}): if type not in ["int", "float"]: raise ValueError("'type' must be 'int' or 'float'") if len(constrain) not in [0, 2]: raise ValueError("'constrain' must be empty or a {'attr': ___, 'type': ___} dictionary") if constrain[1] not in ["minimum", "maximum"]: raise ValueError("constrain['type'] must be 'minimum' or 'maximum'") def custom_slider(stage, attr_name, metadata, property_type, prim_paths, *args, **kwargs): additional_widget_kwargs = {"min": min_value, "max": max_value, "constrain": constrain} additional_widget_kwargs.update(kwargs) return _build_slider( stage, attr_name, metadata, property_type, prim_paths, additional_widget_kwargs=additional_widget_kwargs, type=type, ) return custom_slider def build_common_raster_overlay_properties(add_overlay_render_method=False): with CustomLayoutGroup("Rendering"): CustomLayoutProperty("cesium:alpha", build_fn=build_slider(0, 1)) if add_overlay_render_method: CustomLayoutProperty("cesium:overlayRenderMethod") CustomLayoutProperty("cesium:maximumScreenSpaceError") CustomLayoutProperty("cesium:maximumTextureSize") CustomLayoutProperty("cesium:maximumSimultaneousTileLoads") CustomLayoutProperty("cesium:subTileCacheBytes") CustomLayoutProperty("cesium:showCreditsOnScreen")
4,541
Python
36.53719
113
0.632019
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/attributes/ion_raster_overlay_attributes_widget.py
import logging from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty from omni.kit.property.usd.usd_property_widget import SchemaPropertiesWidget from cesium.usd.plugins.CesiumUsdSchemas import ( IonRasterOverlay as CesiumIonRasterOverlay, IonServer as CesiumIonServer, ) from .cesium_properties_widget_builder import build_common_raster_overlay_properties class CesiumIonRasterOverlayAttributesWidget(SchemaPropertiesWidget): def __init__(self): super().__init__("Cesium Ion Raster Overlay Settings", CesiumIonRasterOverlay, include_inherited=True) self._logger = logging.getLogger(__name__) def clean(self): super().clean() def _customize_props_layout(self, props): frame = CustomLayoutFrame(hide_extra=True) with frame: with CustomLayoutGroup("Source"): CustomLayoutProperty("cesium:ionAssetId") CustomLayoutProperty("cesium:ionAccessToken") CustomLayoutProperty("cesium:ionServerBinding") build_common_raster_overlay_properties(add_overlay_render_method=True) return frame.apply(props) def _filter_props_to_build(self, props): filtered_props = super()._filter_props_to_build(props) filtered_props.extend(prop for prop in props if prop.GetName() == "cesium:ionServerBinding") return filtered_props def get_additional_kwargs(self, ui_attr): if ui_attr.prop_name == "cesium:ionServerBinding": return None, {"target_picker_filter_type_list": [CesiumIonServer], "targets_limit": 1} return None, {"targets_limit": 0}
1,685
Python
39.142856
113
0.706825
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/attributes/__init__.py
from .data_attributes_widget import CesiumDataSchemaAttributesWidget # noqa: F401 from .georeference_attributes_widget import CesiumGeoreferenceSchemaAttributesWidget # noqa :F401 from .tileset_attributes_widget import CesiumTilesetAttributesWidget # noqa: F401 from .globe_anchor_attributes_widget import CesiumGlobeAnchorAttributesWidget # noqa: F401 from .ion_server_attributes_widget import CesiumIonServerAttributesWidget # noqa: F401 from .ion_raster_overlay_attributes_widget import CesiumIonRasterOverlayAttributesWidget # noqa: F401 from .polygon_raster_overlay_attributes_widget import CesiumPolygonRasterOverlayAttributesWidget # noqa: F401 from .tile_map_service_raster_overlay_attributes_widget import ( # noqa: F401 CesiumTileMapServiceRasterOverlayAttributesWidget, ) from .web_map_service_raster_overlay_attributes_widget import ( # noqa: F401 CesiumWebMapServiceRasterOverlayAttributesWidget, ) from .web_map_tile_service_raster_overlay_attributes_widget import ( # noqa: F401 CesiumWebMapTileServiceRasterOverlayAttributesWidget, )
1,072
Python
62.117643
110
0.835821
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/attributes/ion_server_attributes_widget.py
import logging from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty from omni.kit.property.usd.usd_property_widget import SchemaPropertiesWidget from ...bindings import ICesiumOmniverseInterface from cesium.usd.plugins.CesiumUsdSchemas import IonServer as CesiumIonServer class CesiumIonServerAttributesWidget(SchemaPropertiesWidget): def __init__(self, _cesium_omniverse_interface: ICesiumOmniverseInterface): super().__init__("Cesium ion Server Settings", CesiumIonServer, include_inherited=False) self._logger = logging.getLogger(__name__) self._cesium_omniverse_interface = _cesium_omniverse_interface def clean(self): super().clean() def _customize_props_layout(self, props): frame = CustomLayoutFrame(hide_extra=True) with frame: with CustomLayoutGroup("ion Server"): CustomLayoutProperty("cesium:displayName") CustomLayoutProperty("cesium:ionServerUrl") CustomLayoutProperty("cesium:ionServerApiUrl") CustomLayoutProperty("cesium:ionServerApplicationId") with CustomLayoutGroup("Project Default Token"): CustomLayoutProperty("cesium:projectDefaultIonAccessToken") CustomLayoutProperty("cesium:projectDefaultIonAccessTokenId") return frame.apply(props)
1,416
Python
41.939393
113
0.721751
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/attributes/globe_anchor_attributes_widget.py
import logging from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty from omni.kit.property.usd.usd_property_widget import SchemaPropertiesWidget from ...bindings import ICesiumOmniverseInterface from cesium.usd.plugins.CesiumUsdSchemas import ( GlobeAnchorAPI as CesiumGlobeAnchorAPI, Georeference as CesiumGeoreference, ) class CesiumGlobeAnchorAttributesWidget(SchemaPropertiesWidget): def __init__(self, _cesium_omniverse_interface: ICesiumOmniverseInterface): super().__init__("Cesium Globe Anchor", CesiumGlobeAnchorAPI, include_inherited=False) self._logger = logging.getLogger(__name__) self._cesium_omniverse_interface = _cesium_omniverse_interface def clean(self): super().clean() def _customize_props_layout(self, props): frame = CustomLayoutFrame(hide_extra=True) with frame: with CustomLayoutGroup("Options"): CustomLayoutProperty("cesium:anchor:adjustOrientationForGlobeWhenMoving") CustomLayoutProperty("cesium:anchor:detectTransformChanges") CustomLayoutProperty("cesium:anchor:georeferenceBinding") with CustomLayoutGroup("Global Positioning"): CustomLayoutProperty("cesium:anchor:latitude") CustomLayoutProperty("cesium:anchor:longitude") CustomLayoutProperty("cesium:anchor:height") with CustomLayoutGroup("Advanced Positioning", collapsed=True): CustomLayoutProperty("cesium:anchor:position") return frame.apply(props) def _filter_props_to_build(self, props): filtered_props = super()._filter_props_to_build(props) filtered_props.extend(prop for prop in props if prop.GetName() == "cesium:anchor:georeferenceBinding") return filtered_props def get_additional_kwargs(self, ui_attr): if ui_attr.prop_name == "cesium:anchor:georeferenceBinding": return None, {"target_picker_filter_type_list": [CesiumGeoreference], "targets_limit": 1} return None, {"targets_limit": 0}
2,142
Python
42.734693
113
0.705415
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/attributes/data_attributes_widget.py
import logging from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty from omni.kit.property.usd.usd_property_widget import SchemaPropertiesWidget from cesium.usd.plugins.CesiumUsdSchemas import Data as CesiumData class CesiumDataSchemaAttributesWidget(SchemaPropertiesWidget): def __init__(self): super().__init__("Cesium Settings", CesiumData, include_inherited=False) self._logger = logging.getLogger(__name__) def clean(self): super().clean() def _customize_props_layout(self, props): frame = CustomLayoutFrame(hide_extra=True) with frame: with CustomLayoutGroup("Debug Options", collapsed=True): CustomLayoutProperty("cesium:debug:disableMaterials") CustomLayoutProperty("cesium:debug:disableTextures") CustomLayoutProperty("cesium:debug:disableGeometryPool") CustomLayoutProperty("cesium:debug:disableMaterialPool") CustomLayoutProperty("cesium:debug:disableTexturePool") CustomLayoutProperty("cesium:debug:geometryPoolInitialCapacity") CustomLayoutProperty("cesium:debug:materialPoolInitialCapacity") CustomLayoutProperty("cesium:debug:texturePoolInitialCapacity") CustomLayoutProperty("cesium:debug:randomColors") CustomLayoutProperty("cesium:debug:disableGeoreferencing") return frame.apply(props)
1,505
Python
44.636362
113
0.70897
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/attributes/georeference_attributes_widget.py
import logging from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty from omni.kit.property.usd.usd_property_widget import SchemaPropertiesWidget from cesium.usd.plugins.CesiumUsdSchemas import Georeference as CesiumGeoreference class CesiumGeoreferenceSchemaAttributesWidget(SchemaPropertiesWidget): def __init__(self): super().__init__("Cesium Georeference", CesiumGeoreference, include_inherited=False) self._logger = logging.getLogger(__name__) def clean(self): super().clean() def _customize_props_layout(self, props): frame = CustomLayoutFrame(hide_extra=True) with frame: with CustomLayoutGroup("Georeference Origin Point Coordinates"): CustomLayoutProperty("cesium:georeferenceOrigin:latitude", "Latitude") CustomLayoutProperty("cesium:georeferenceOrigin:longitude", "Longitude") CustomLayoutProperty("cesium:georeferenceOrigin:height", "Height") return frame.apply(props)
1,068
Python
40.115383
113
0.730337
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/attributes/tile_map_service_raster_overlay_attributes_widget.py
import logging import omni.usd import omni.ui import omni.kit.window.property from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty from omni.kit.property.usd.usd_property_widget import SchemaPropertiesWidget from cesium.usd.plugins.CesiumUsdSchemas import ( TileMapServiceRasterOverlay as CesiumTileMapServiceRasterOverlay, ) from .cesium_properties_widget_builder import build_slider, build_common_raster_overlay_properties from pxr import Usd, Tf class CesiumTileMapServiceRasterOverlayAttributesWidget(SchemaPropertiesWidget): def __init__(self): super().__init__( "Cesium Tile Map Service Raster Overlay Settings", CesiumTileMapServiceRasterOverlay, include_inherited=True, ) self._logger = logging.getLogger(__name__) self._listener = None self._props = None self._stage = omni.usd.get_context().get_stage() def clean(self): super().clean() def _on_usd_changed(self, notice, stage): window = omni.kit.window.property.get_window() window.request_rebuild() def _customize_props_layout(self, props): if not self._listener: self._listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._on_usd_changed, self._stage) frame = CustomLayoutFrame(hide_extra=True) prim_path = self._payload.get_paths()[0] tileMapServiceRasterOverlay = CesiumTileMapServiceRasterOverlay.Get(self._stage, prim_path) specify_zoom_levels = tileMapServiceRasterOverlay.GetSpecifyZoomLevelsAttr().Get() with frame: with CustomLayoutGroup("URL"): CustomLayoutProperty("cesium:url") with CustomLayoutGroup("Zoom Settings"): CustomLayoutProperty( "cesium:specifyZoomLevels", ) if specify_zoom_levels: CustomLayoutProperty( "cesium:minimumZoomLevel", build_fn=build_slider( 0, 30, type="int", constrain={"attr": "cesium:maximumZoomLevel", "type": "maximum"} ), ) CustomLayoutProperty( "cesium:maximumZoomLevel", build_fn=build_slider( 0, 30, type="int", constrain={"attr": "cesium:minimumZoomLevel", "type": "minimum"} ), ) build_common_raster_overlay_properties() return frame.apply(props) def reset(self): if self._listener: self._listener.Revoke() self._listener = None super().reset()
2,777
Python
36.54054
113
0.60569
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/attributes/tileset_attributes_widget.py
import logging from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty from omni.kit.property.usd.usd_property_widget import SchemaPropertiesWidget import omni.ui as ui from ...bindings import ICesiumOmniverseInterface from cesium.usd.plugins.CesiumUsdSchemas import ( Tileset as CesiumTileset, IonServer as CesiumIonServer, Georeference as CesiumGeoreference, RasterOverlay as CesiumRasterOverlay, ) class CesiumTilesetAttributesWidget(SchemaPropertiesWidget): def __init__(self, _cesium_omniverse_interface: ICesiumOmniverseInterface): super().__init__("Cesium Tileset Settings", CesiumTileset, include_inherited=False) self._logger = logging.getLogger(__name__) self._cesium_omniverse_interface = _cesium_omniverse_interface def clean(self): super().clean() def on_refresh_button_clicked(self): tileset_path = self._payload[0] self._cesium_omniverse_interface.reload_tileset(tileset_path.pathString) def _customize_props_layout(self, props): frame = CustomLayoutFrame(hide_extra=True) with frame: ui.Button("Refresh Tileset", clicked_fn=self.on_refresh_button_clicked) with CustomLayoutGroup("Credit Display"): CustomLayoutProperty("cesium:showCreditsOnScreen") with CustomLayoutGroup("Source"): CustomLayoutProperty("cesium:sourceType") CustomLayoutProperty("cesium:ionAssetId") CustomLayoutProperty("cesium:ionAccessToken") CustomLayoutProperty("cesium:ionServerBinding") CustomLayoutProperty("cesium:url") with CustomLayoutGroup("Raster Overlays"): CustomLayoutProperty("cesium:rasterOverlayBinding") with CustomLayoutGroup("Level of Detail"): CustomLayoutProperty("cesium:maximumScreenSpaceError") with CustomLayoutGroup("Tile Loading"): CustomLayoutProperty("cesium:preloadAncestors") CustomLayoutProperty("cesium:preloadSiblings") CustomLayoutProperty("cesium:forbidHoles") CustomLayoutProperty("cesium:maximumSimultaneousTileLoads") CustomLayoutProperty("cesium:maximumCachedBytes") CustomLayoutProperty("cesium:loadingDescendantLimit") CustomLayoutProperty("cesium:mainThreadLoadingTimeLimit") with CustomLayoutGroup("Tile Culling"): CustomLayoutProperty("cesium:enableFrustumCulling") CustomLayoutProperty("cesium:enableFogCulling") CustomLayoutProperty("cesium:enforceCulledScreenSpaceError") CustomLayoutProperty("cesium:culledScreenSpaceError") with CustomLayoutGroup("Rendering"): CustomLayoutProperty("cesium:suspendUpdate") CustomLayoutProperty("cesium:smoothNormals") with CustomLayoutGroup("Georeference"): CustomLayoutProperty("cesium:georeferenceBinding") return frame.apply(props) def _filter_props_to_build(self, props): filtered_props = super()._filter_props_to_build(props) filtered_props.extend( prop for prop in props if prop.GetName() == "cesium:ionServerBinding" or prop.GetName() == "cesium:georeferenceBinding" or prop.GetName() == "cesium:rasterOverlayBinding" ) return filtered_props def get_additional_kwargs(self, ui_attr): if ui_attr.prop_name == "cesium:ionServerBinding": return None, {"target_picker_filter_type_list": [CesiumIonServer], "targets_limit": 1} elif ui_attr.prop_name == "cesium:georeferenceBinding": return None, {"target_picker_filter_type_list": [CesiumGeoreference], "targets_limit": 1} elif ui_attr.prop_name == "cesium:rasterOverlayBinding": return None, {"target_picker_filter_type_list": [CesiumRasterOverlay]} return None, {"targets_limit": 0}
4,108
Python
46.229885
113
0.672833
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/attributes/polygon_raster_overlay_attributes_widget.py
import logging from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty from omni.kit.property.usd.usd_property_widget import SchemaPropertiesWidget from cesium.usd.plugins.CesiumUsdSchemas import ( PolygonRasterOverlay as CesiumPolygonRasterOverlay, ) from pxr import UsdGeom from .cesium_properties_widget_builder import build_common_raster_overlay_properties class CesiumPolygonRasterOverlayAttributesWidget(SchemaPropertiesWidget): def __init__(self): super().__init__("Cesium Polygon Raster Overlay Settings", CesiumPolygonRasterOverlay, include_inherited=True) self._logger = logging.getLogger(__name__) def clean(self): super().clean() def _customize_props_layout(self, props): frame = CustomLayoutFrame(hide_extra=True) with frame: with CustomLayoutGroup("Cartographic Polygons"): CustomLayoutProperty("cesium:cartographicPolygonBinding") with CustomLayoutGroup("Invert Selection"): CustomLayoutProperty("cesium:invertSelection") build_common_raster_overlay_properties() return frame.apply(props) def _filter_props_to_build(self, props): filtered_props = super()._filter_props_to_build(props) filtered_props.extend(prop for prop in props if prop.GetName() == "cesium:cartographicPolygonBinding") return filtered_props def get_additional_kwargs(self, ui_attr): if ui_attr.prop_name == "cesium:cartographicPolygonBinding": return None, {"target_picker_filter_type_list": [UsdGeom.BasisCurves]} return None, {"targets_limit": 0}
1,693
Python
39.333332
118
0.71707
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/models/__init__.py
from .date_model import DateModel # noqa: F401 from .asset_window_models import IonAssets, IonAssetItem, IonAssetDelegate # noqa: F401 from .space_delimited_number_model import SpaceDelimitedNumberModel # noqa: F401 from .human_readable_bytes_model import HumanReadableBytesModel # noqa: F401
297
Python
58.599988
88
0.808081
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/models/asset_window_models.py
from typing import List import omni.ui as ui from .date_model import DateModel class IonAssetItem(ui.AbstractItem): """Represents an ion Asset.""" def __init__( self, asset_id: int, name: str, description: str, attribution: str, asset_type: str, date_added: str ): super().__init__() self.id = ui.SimpleIntModel(asset_id) self.name = ui.SimpleStringModel(name) self.description = ui.SimpleStringModel(description) self.attribution = ui.SimpleStringModel(attribution) self.type = ui.SimpleStringModel(asset_type) self.dateAdded = DateModel(date_added) def __repr__(self): return f"{self.name.as_string} (ID: {self.id.as_int})" class IonAssets(ui.AbstractItemModel): """Represents a list of ion assets for the asset window.""" def __init__(self, items=None, filter_value=""): super().__init__() if items is None: items = [] self._items: List[IonAssetItem] = items self._visible_items: List[IonAssetItem] = [] self._current_filter = filter_value self.filter_items(filter_value) def replace_items(self, items: List[IonAssetItem]): self._items.clear() self._items.extend(items) self.filter_items(self._current_filter) def filter_items(self, filter_value: str): self._current_filter = filter_value if filter_value == "": self._visible_items = self._items.copy() else: self._visible_items = [ item for item in self._items if filter_value.lower() in item.name.as_string.lower() ] self._item_changed(None) def get_item_children(self, item: IonAssetItem = None) -> List[IonAssetItem]: if item is not None: return [] return self._visible_items def get_item_value_model_count(self, item: IonAssetItem = None) -> int: """The number of columns""" return 3 def get_item_value_model(self, item: IonAssetItem = None, column_id: int = 0) -> ui.AbstractValueModel: """Returns the value model for the specific column.""" if item is None: item = self._visible_items[0] # When we are finally on Python 3.10 with Omniverse, we should change this to a switch. return item.name if column_id == 0 else item.type if column_id == 1 else item.dateAdded class IonAssetDelegate(ui.AbstractItemDelegate): def build_header(self, column_id: int = 0) -> None: with ui.ZStack(height=20): if column_id == 0: ui.Label("Name") elif column_id == 1: ui.Label("Type") else: ui.Label("Date Added") def build_branch( self, model: ui.AbstractItemModel, item: ui.AbstractItem = None, column_id: int = 0, level: int = 0, expanded: bool = False, ) -> None: # We don't use this because we don't have a hierarchy, but we need to at least stub it out. pass def build_widget( self, model: IonAssets, item: IonAssetItem = None, column_id: int = 0, level: int = 0, expanded: bool = False ) -> None: with ui.ZStack(height=20): value_model = model.get_item_value_model(item, column_id) ui.Label(value_model.as_string)
3,372
Python
32.396039
117
0.596085
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/models/human_readable_bytes_model.py
import omni.ui as ui class HumanReadableBytesModel(ui.AbstractValueModel): """Takes an integer containing bytes and outputs a human-readable string.""" def __init__(self, value: int): super().__init__() self._value = value def __str__(self): return self.get_value_as_string() def set_value(self, value: int): self._value = value self._value_changed() def get_value_as_bool(self) -> bool: raise NotImplementedError def get_value_as_int(self) -> int: return self._value def get_value_as_float(self) -> float: return float(self._value) def get_value_as_string(self) -> str: value = self._value for unit in ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB"]: if abs(value) < 1024: return f"{value:3.2f} {unit}" value /= 1024 return f"{value:.2f}YiB"
919
Python
26.058823
80
0.563656
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/models/date_model.py
from datetime import datetime import omni.ui as ui class DateModel(ui.AbstractValueModel): """Takes an RFC 3339 formatted timestamp and produces a date value.""" def __init__(self, value: str): super().__init__() self._value = datetime.strptime(value[0:19], "%Y-%m-%dT%H:%M:%S") def get_value_as_string(self) -> str: return self._value.strftime("%Y-%m-%d")
397
Python
27.428569
74
0.627204
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/models/space_delimited_number_model.py
import math import omni.ui as ui class SpaceDelimitedNumberModel(ui.AbstractValueModel): """Divides large numbers into delimited groups for readability.""" def __init__(self, value: float): super().__init__() self._value = value def __str__(self): return self.get_value_as_string() def set_value(self, value: float) -> None: self._value = value self._value_changed() def get_value_as_bool(self) -> bool: raise NotImplementedError def get_value_as_int(self) -> int: return math.trunc(self._value) def get_value_as_float(self) -> float: return self._value def get_value_as_string(self) -> str: # Replacing the comma with spaces because NIST did a lot of research and recommends it. # https://physics.nist.gov/cuu/pdf/sp811.pdf#10.5.3 return f"{self._value:,}".replace(",", " ")
907
Python
27.374999
95
0.618523
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/models/tests/date_model_test.py
import omni.kit.test from cesium.omniverse.ui.models.date_model import DateModel class Test(omni.kit.test.AsyncTestCase): async def setUp(self): pass async def tearDown(self): pass async def test_date_model(self): input_value = "2016-10-17T22:04:30.353Z" expected_output = "2016-10-17" date_model = DateModel(input_value) self.assertEqual(date_model.as_string, expected_output)
443
Python
23.666665
63
0.668172
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/models/tests/__init__.py
from .date_model_test import * # noqa: F401 F403
50
Python
24.499988
49
0.7
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/tests/pass_fail_widget_test.py
import omni.ui as ui from omni.ui.tests.test_base import OmniUiTest from cesium.omniverse.tests.utils import get_golden_img_dir, wait_for_update from cesium.omniverse.ui.pass_fail_widget import CesiumPassFailWidget class PassFailWidgetTest(OmniUiTest): async def setUp(self): await super().setUp() self._golden_image_dir = get_golden_img_dir() async def tearDown(self): await super().tearDown() async def test_pass_fail_widget_passed(self): window = await self.create_test_window() with window.frame: with ui.VStack(height=0): widget = CesiumPassFailWidget(True) self.assertIsNotNone(widget) self.assertTrue(widget.passed) await wait_for_update() await self.finalize_test( golden_img_dir=self._golden_image_dir, golden_img_name="test_pass_fail_widget_passed.png" ) widget.destroy() async def test_pass_fail_widget_failed(self): window = await self.create_test_window() with window.frame: with ui.VStack(height=0): widget = CesiumPassFailWidget(False) self.assertIsNotNone(widget) self.assertFalse(widget.passed) await wait_for_update() await self.finalize_test( golden_img_dir=self._golden_image_dir, golden_img_name="test_pass_fail_widget_failed.png" ) widget.destroy() async def test_pass_fail_widget_updated(self): window = await self.create_test_window() with window.frame: with ui.VStack(height=0): widget = CesiumPassFailWidget(False) self.assertIsNotNone(widget) self.assertFalse(widget.passed) await wait_for_update() widget.passed = True await wait_for_update() self.assertTrue(widget.passed) await self.finalize_test( golden_img_dir=self._golden_image_dir, golden_img_name="test_pass_fail_widget_changed.png" ) widget.destroy()
2,090
Python
27.256756
102
0.61866
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/tests/__init__.py
from .pass_fail_widget_test import PassFailWidgetTest # noqa: F401
68
Python
33.499983
67
0.794118
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/bindings/__init__.py
from .CesiumOmniversePythonBindings import * # noqa: F401 F403
64
Python
31.499984
63
0.796875
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/models/raster_overlay_to_add.py
from __future__ import annotations from typing import Optional import carb.events class RasterOverlayToAdd: def __init__(self, tileset_path: str, raster_overlay_ion_asset_id: int, raster_overlay_name: str): self.tileset_path = tileset_path self.raster_overlay_ion_asset_id = raster_overlay_ion_asset_id self.raster_overlay_name = raster_overlay_name def to_dict(self) -> dict: return { "tileset_path": self.tileset_path, "raster_overlay_ion_asset_id": self.raster_overlay_ion_asset_id, "raster_overlay_name": self.raster_overlay_name, } @staticmethod def from_event(event: carb.events.IEvent) -> Optional[RasterOverlayToAdd]: if event.payload is None or len(event.payload) == 0: return None return RasterOverlayToAdd( event.payload["tileset_path"], event.payload["raster_overlay_ion_asset_id"], event.payload["raster_overlay_name"], )
1,004
Python
33.655171
102
0.639442
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/models/__init__.py
from .asset_to_add import AssetToAdd # noqa: F401 from .raster_overlay_to_add import RasterOverlayToAdd # noqa: F401
119
Python
38.999987
67
0.773109
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/models/asset_to_add.py
from __future__ import annotations from typing import Optional import carb.events class AssetToAdd: def __init__( self, tileset_name: str, tileset_ion_asset_id: int, raster_overlay_name: Optional[str] = None, raster_overlay_ion_asset_id: Optional[int] = None, ): self.tileset_name = tileset_name self.tileset_ion_asset_id = tileset_ion_asset_id self.raster_overlay_name = raster_overlay_name self.raster_overlay_ion_asset_id = raster_overlay_ion_asset_id def to_dict(self) -> dict: return { "tileset_name": self.tileset_name, "tileset_ion_asset_id": self.tileset_ion_asset_id, "raster_overlay_name": self.raster_overlay_name, "raster_overlay_ion_asset_id": self.raster_overlay_ion_asset_id, } @staticmethod def from_event(event: carb.events.IEvent) -> Optional[AssetToAdd]: if event.payload is None or len(event.payload) == 0: return None return AssetToAdd( event.payload["tileset_name"], event.payload["tileset_ion_asset_id"], event.payload["raster_overlay_name"], event.payload["raster_overlay_ion_asset_id"], )
1,259
Python
32.157894
76
0.609214