file_path
stringlengths
21
224
content
stringlengths
0
80.8M
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)
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)
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})
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)
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) )
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()
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)
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")
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}
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, )
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)
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}
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)
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)
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()
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}
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}
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
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)
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"
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")
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(",", " ")
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)
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/models/tests/__init__.py
from .date_model_test import * # noqa: F401 F403
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()
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/tests/__init__.py
from .pass_fail_widget_test import PassFailWidgetTest # noqa: F401
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/bindings/__init__.py
from .CesiumOmniversePythonBindings import * # noqa: F401 F403
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/bindings/CesiumOmniversePythonBindings.pyi
from typing import Any, List, Tuple from typing import overload class Asset: def __init__(self, *args, **kwargs) -> None: ... @property def asset_id(self) -> int: ... @property def asset_type(self) -> str: ... @property def attribution(self) -> str: ... @property def bytes(self) -> int: ... @property def date_added(self) -> str: ... @property def description(self) -> str: ... @property def name(self) -> str: ... @property def percent_complete(self) -> int: ... @property def status(self) -> str: ... class AssetTroubleshootingDetails: def __init__(self, *args, **kwargs) -> None: ... @property def asset_exists_in_user_account(self) -> bool: ... @property def asset_id(self) -> int: ... class Assets: def __init__(self, *args, **kwargs) -> None: ... @property def items(self) -> Any: ... @property def link(self) -> str: ... class CesiumIonSession: def __init__(self, *args, **kwargs) -> None: ... def disconnect(self) -> None: ... def get_assets(self, *args, **kwargs) -> Any: ... def get_authorize_url(self) -> str: ... def get_connection(self, *args, **kwargs) -> Any: ... def get_profile(self, *args, **kwargs) -> Any: ... def get_tokens(self, *args, **kwargs) -> Any: ... def is_asset_list_loaded(self) -> bool: ... def is_connected(self) -> bool: ... def is_connecting(self) -> bool: ... def is_loading_asset_list(self) -> bool: ... def is_loading_profile(self) -> bool: ... def is_loading_token_list(self) -> bool: ... def is_profile_loaded(self) -> bool: ... def is_resuming(self) -> bool: ... def is_token_list_loaded(self) -> bool: ... def refresh_assets(self) -> None: ... def refresh_profile(self) -> None: ... def refresh_tokens(self) -> None: ... class Connection: def __init__(self, *args, **kwargs) -> None: ... def get_access_token(self) -> str: ... def get_api_uri(self) -> str: ... class ICesiumOmniverseInterface: def __init__(self, *args, **kwargs) -> None: ... def clear_accessor_cache(self) -> None: ... def connect_to_ion(self) -> None: ... def create_token(self, arg0: str) -> None: ... def credits_available(self) -> bool: ... def credits_start_next_frame(self) -> None: ... def get_asset_token_troubleshooting_details(self, *args, **kwargs) -> Any: ... def get_asset_troubleshooting_details(self, *args, **kwargs) -> Any: ... def get_credits(self) -> List[Tuple[str, bool]]: ... def get_default_token_troubleshooting_details(self, *args, **kwargs) -> Any: ... def get_render_statistics(self, *args, **kwargs) -> Any: ... def get_server_path(self) -> str: ... def get_server_paths(self) -> List[str]: ... def get_session(self, *args, **kwargs) -> Any: ... def get_sessions(self, *args, **kwargs) -> Any: ... def get_set_default_token_result(self, *args, **kwargs) -> Any: ... def is_default_token_set(self) -> bool: ... def is_tracing_enabled(self) -> bool: ... def on_shutdown(self) -> None: ... def on_stage_change(self, arg0: int) -> None: ... def on_startup(self, arg0: str) -> None: ... def on_update_frame(self, arg0: List[ViewportPythonBinding], arg1: bool) -> None: ... def print_fabric_stage(self) -> str: ... def reload_tileset(self, arg0: str) -> None: ... def select_token(self, arg0: str, arg1: str) -> None: ... def specify_token(self, arg0: str) -> None: ... @overload def update_troubleshooting_details(self, arg0: str, arg1: int, arg2: int, arg3: int) -> None: ... @overload def update_troubleshooting_details(self, arg0: str, arg1: int, arg2: int, arg3: int, arg4: int) -> None: ... class Profile: def __init__(self, *args, **kwargs) -> None: ... @property def id(self) -> int: ... @property def username(self) -> str: ... class RenderStatistics: def __init__(self, *args, **kwargs) -> None: ... @property def culled_tiles_visited(self) -> int: ... @property def geometries_capacity(self) -> int: ... @property def geometries_loaded(self) -> int: ... @property def geometries_rendered(self) -> int: ... @property def materials_capacity(self) -> int: ... @property def materials_loaded(self) -> int: ... @property def max_depth_visited(self) -> int: ... @property def tiles_culled(self) -> int: ... @property def tiles_loaded(self) -> int: ... @property def tiles_loading_main(self) -> int: ... @property def tiles_loading_worker(self) -> int: ... @property def tiles_rendered(self) -> int: ... @property def tiles_visited(self) -> int: ... @property def tileset_cached_bytes(self) -> int: ... @property def triangles_loaded(self) -> int: ... @property def triangles_rendered(self) -> int: ... class SetDefaultTokenResult: def __init__(self, *args, **kwargs) -> None: ... @property def code(self) -> int: ... @property def message(self) -> str: ... class Token: def __init__(self, *args, **kwargs) -> None: ... @property def id(self) -> str: ... @property def is_default(self) -> bool: ... @property def name(self) -> str: ... @property def token(self) -> str: ... class TokenTroubleshootingDetails: def __init__(self, *args, **kwargs) -> None: ... @property def allows_access_to_asset(self) -> bool: ... @property def associated_with_user_account(self) -> bool: ... @property def is_valid(self) -> bool: ... @property def show_details(self) -> bool: ... @property def token(self) -> Token: ... class Viewport: height: float projMatrix: Matrix4d viewMatrix: Matrix4d width: float def __init__(self) -> None: ... def acquire_cesium_omniverse_interface( plugin_name: str = ..., library_path: str = ... ) -> ICesiumOmniverseInterface: ... def release_cesium_omniverse_interface(arg0: ICesiumOmniverseInterface) -> None: ...
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"], )
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
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"], )
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/models/tests/raster_overlay_to_add_test.py
import carb.events import omni.kit.test from unittest.mock import MagicMock from cesium.omniverse.models.raster_overlay_to_add import RasterOverlayToAdd TILESET_PATH = "/fake/tileset/path" RASTER_OVERLAY_NAME = "fake_raster_overlay_name" RASTER_OVERLAY_ION_ASSET_ID = 2 PAYLOAD_DICT = { "tileset_path": TILESET_PATH, "raster_overlay_name": RASTER_OVERLAY_NAME, "raster_overlay_ion_asset_id": RASTER_OVERLAY_ION_ASSET_ID, } class RasterOverlayToAddTest(omni.kit.test.AsyncTestCase): async def setUp(self): pass async def tearDown(self): pass async def test_convert_raster_overlay_to_add_to_dict(self): raster_overlay_to_add = RasterOverlayToAdd( tileset_path=TILESET_PATH, raster_overlay_ion_asset_id=RASTER_OVERLAY_ION_ASSET_ID, raster_overlay_name=RASTER_OVERLAY_NAME, ) result = raster_overlay_to_add.to_dict() self.assertEqual(result["tileset_path"], TILESET_PATH) self.assertEqual(result["raster_overlay_name"], RASTER_OVERLAY_NAME) self.assertEqual(result["raster_overlay_ion_asset_id"], RASTER_OVERLAY_ION_ASSET_ID) async def test_create_raster_overlay_to_add_from_event(self): mock_event = MagicMock(spec=carb.events.IEvent) mock_event.payload = PAYLOAD_DICT raster_overlay_to_add = RasterOverlayToAdd.from_event(mock_event) self.assertIsNotNone(raster_overlay_to_add) self.assertEqual(raster_overlay_to_add.tileset_path, TILESET_PATH) self.assertEqual(raster_overlay_to_add.raster_overlay_name, RASTER_OVERLAY_NAME) self.assertEqual(raster_overlay_to_add.raster_overlay_ion_asset_id, RASTER_OVERLAY_ION_ASSET_ID) async def test_create_raster_overlay_to_add_from_empty_event(self): mock_event = MagicMock(spec=carb.events.IEvent) mock_event.payload = None raster_overlay_to_add = RasterOverlayToAdd.from_event(mock_event) self.assertIsNone(raster_overlay_to_add)
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/models/tests/__init__.py
from .asset_to_add_test import AssetToAddTest # noqa: F401 from .raster_overlay_to_add_test import RasterOverlayToAddTest # noqa: F401
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/models/tests/asset_to_add_test.py
import carb.events import omni.kit.test from unittest.mock import MagicMock from cesium.omniverse.models.asset_to_add import AssetToAdd TILESET_NAME = "fake_tileset_name" TILESET_ION_ASSET_ID = 1 RASTER_OVERLAY_NAME = "fake_raster_overlay_name" RASTER_OVERLAY_ION_ASSET_ID = 2 PAYLOAD_DICT = { "tileset_name": TILESET_NAME, "tileset_ion_asset_id": TILESET_ION_ASSET_ID, "raster_overlay_name": RASTER_OVERLAY_NAME, "raster_overlay_ion_asset_id": RASTER_OVERLAY_ION_ASSET_ID, } class AssetToAddTest(omni.kit.test.AsyncTestCase): async def setUp(self): pass async def tearDown(self): pass async def test_convert_asset_to_add_to_dict(self): asset_to_add = AssetToAdd( tileset_name=TILESET_NAME, tileset_ion_asset_id=TILESET_ION_ASSET_ID, raster_overlay_name=RASTER_OVERLAY_NAME, raster_overlay_ion_asset_id=RASTER_OVERLAY_ION_ASSET_ID, ) result = asset_to_add.to_dict() self.assertEqual(result["tileset_name"], TILESET_NAME) self.assertEqual(result["tileset_ion_asset_id"], TILESET_ION_ASSET_ID) self.assertEqual(result["raster_overlay_name"], RASTER_OVERLAY_NAME) self.assertEqual(result["raster_overlay_ion_asset_id"], RASTER_OVERLAY_ION_ASSET_ID) async def test_create_asset_to_add_from_event(self): mock_event = MagicMock(spec=carb.events.IEvent) mock_event.payload = PAYLOAD_DICT asset_to_add = AssetToAdd.from_event(mock_event) self.assertIsNotNone(asset_to_add) self.assertEqual(asset_to_add.tileset_name, TILESET_NAME) self.assertEqual(asset_to_add.tileset_ion_asset_id, TILESET_ION_ASSET_ID) self.assertEqual(asset_to_add.raster_overlay_name, RASTER_OVERLAY_NAME) self.assertEqual(asset_to_add.raster_overlay_ion_asset_id, RASTER_OVERLAY_ION_ASSET_ID) async def test_create_asset_to_add_from_empty_event(self): mock_event = MagicMock(spec=carb.events.IEvent) mock_event.payload = None asset_to_add = AssetToAdd.from_event(mock_event) self.assertIsNone(asset_to_add)
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/tests/__init__.py
# For Python testing within Omniverse, it only looks in the `.tests` submodule in whatever is defined # as an extensions Python module. For organization purposes, we then import all of our tests from our other # testing submodules. from .extension_test import * # noqa: F401 F403 from ..models.tests import * # noqa: F401 F403 from ..ui.tests import * # noqa: F401 F403 from ..ui.models.tests import * # noqa: F401 F403
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/tests/utils.py
from pathlib import Path import omni.kit.app def get_golden_img_dir(): manager = omni.kit.app.get_app().get_extension_manager() ext_id = manager.get_extension_id_by_module("cesium.omniverse") return Path(manager.get_extension_path(ext_id)).joinpath("images/tests/ui/pass_fail_widget") async def wait_for_update(wait_frames=10): for _ in range(wait_frames): await omni.kit.app.get_app().next_update_async()
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/tests/extension_test.py
import omni.kit.test import omni.kit.ui_test as ui_test import omni.usd import pxr.Usd import cesium.usd from typing import Optional _window_ref: Optional[ui_test.WidgetRef] = None class ExtensionTest(omni.kit.test.AsyncTestCase): async def setUp(self): global _window_ref # can be removed (or at least decreased) once there is no delay # required before spawning the cesium window. See: # https://github.com/CesiumGS/cesium-omniverse/pull/423 await ui_test.wait_n_updates(24) _window_ref = ui_test.find("Cesium") async def tearDown(self): pass async def test_cesium_window_opens(self): global _window_ref self.assertIsNotNone(_window_ref) async def test_window_docked(self): global _window_ref # docked is false if the window is not in focus, # as may be the case if other extensions are loaded await _window_ref.focus() self.assertTrue(_window_ref.window.docked) async def test_blank_tileset(self): global _window_ref blankTilesetButton = _window_ref.find("**/Button[*].text=='Blank 3D Tiles Tileset'") self.assertIsNotNone(blankTilesetButton) stage: pxr.Usd.Stage = omni.usd.get_context().get_stage() self.assertIsNotNone(stage) self.assertFalse(any([i.IsA(cesium.usd.plugins.CesiumUsdSchemas.Tileset) for i in stage.Traverse()])) await blankTilesetButton.click() await ui_test.wait_n_updates(2) # passes without, but seems prudent self.assertTrue(any([i.IsA(cesium.usd.plugins.CesiumUsdSchemas.Tileset) for i in stage.Traverse()]))
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/utils/custom_fields.py
import omni.ui as ui READ_ONLY_STYLE = {"color": ui.color("#888888")} def string_field_with_label(label_text, model=None, enabled=True): with ui.HStack(spacing=4, height=20): ui.Label(label_text, height=20, width=100) field = ui.StringField(height=20, enabled=enabled) if not enabled: field.style = READ_ONLY_STYLE if model: field.model = model return field def int_field_with_label(label_text, model=None, enabled=True): with ui.HStack(spacing=4, height=20): ui.Label(label_text, height=20, width=100) field = ui.IntField(height=20, enabled=enabled) if not enabled: field.style = READ_ONLY_STYLE if model: field.model = model return field def float_field_with_label(label_text, model=None, enabled=True): with ui.HStack(spacing=4, height=20): ui.Label(label_text, height=20, width=100) field = ui.FloatField(height=20, enabled=enabled, precision=7) if not enabled: field.style = READ_ONLY_STYLE if model: field.model = model return field
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/utils/__init__.py
from .utils import * # noqa: F401 F403
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/utils/utils.py
from typing import Optional, Callable import omni.usd import omni.kit import omni.ui as ui async def wait_n_frames(n: int) -> None: for i in range(0, n): await omni.kit.app.get_app().next_update_async() async def dock_window_async( window: Optional[ui.Window], target: str = "Stage", position: ui.DockPosition = ui.DockPosition.SAME ) -> None: if window is None: return # Wait five frame await wait_n_frames(5) stage_window = ui.Workspace.get_window(target) window.dock_in(stage_window, position, 1) window.focus() async def perform_action_after_n_frames_async(n: int, action: Callable[[], None]) -> None: await wait_n_frames(n) action() def str_is_empty_or_none(s: Optional[str]) -> bool: if s is None: return True if s == "": return True return False
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/utils/cesium_interface.py
from ..bindings import acquire_cesium_omniverse_interface class CesiumInterfaceManager: def __init__(self): # Acquires the interface. Is a singleton. self.interface = acquire_cesium_omniverse_interface() def __enter__(self): return self.interface def __exit__(self, exc_type, exc_val, exc_tb): # We release the interface when we pull down the plugin. pass
CesiumGS/cesium-omniverse/exts/cesium.omniverse/doc/README.md
# Cesium for Omniverse Cesium for Omniverse enables building 3D geospatial applications and experiences with 3D Tiles and open standards in NVIDIA Omniverse, a real-time 3D graphics collaboration development platform. Cesium for Omniverse is an extension for Omniverse's Kit-based applications such as USD Composer, a reference application for large-scale world building and advanced 3D scene composition of Universal Scene Description (USD)-based workflows, and Omniverse Code, an integrated development environment (IDE) for developers. Cesium for Omniverse enables developers to create geospatial and enterprise metaverse, simulations, digital twins, and other real-world applications in precise geospatial context and stream massive real-word 3D content. By combining a high-accuracy full-scale WGS84 globe, open APIs and open standards for spatial indexing such as 3D Tiles, and cloud-based real-world content from Cesium ion with Omniverse, this extension enables rich 3D geospatial workflows and applications in Omniverse, which adds real-time ray tracing and AI-powered analytics. ### Cesium for Omniverse and the 3D Geospatial Ecosystem Cesium for Omniverse streams real-world 3D content such as high-resolution photogrammetry, terrain, imagery, and 3D buildings from Cesium ion and other sources, available as optional commercial subscriptions. The extension includes Cesium ion integration for instant access to global high-resolution 3D content ready for runtime streaming. Cesium ion users can also leverage cloud-based 3D tiling pipelines to create end-to-end workflows to transform massive heterogenous content into semantically-rich 3D Tiles, ready for streaming to Omniverse. Cesium for Omniverse supports cloud and private network content and services based on open standards and APIs. You are free to use any combination of supported content sources, standards, APIs with Cesium for Omniverse. Using Cesium ion helps support Cesium for Omniverse development. ### License Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html). Cesium for Omniverse is free for both commercial and non-commercial use.
CesiumGS/cesium-omniverse/exts/cesium.omniverse/config/extension.toml
[package] version = "0.19.0" category = "simulation" feature = false app = false title = "Cesium for Omniverse" description = "High-accuracy full-scale WGS84 globe for Omniverse" authors = "Cesium GS Inc." repository = "https://github.com/CesiumGS/cesium-omniverse" keywords = [ "cesium", "omniverse", "geospatial", "3D Tiles", "glTF", "globe", "earth", "simulation", ] # Paths are relative to the extension folder changelog = "doc/CHANGES.md" readme = "doc/README.md" preview_image = "doc/resources/preview.jpg" icon = "doc/resources/icon.png" [package.target] kit = ["105.1"] [package.writeTarget] kit = true python = false # Which extensions this extension depends on [dependencies] "cesium.usd.plugins" = { version = "0.4.0" } "usdrt.scenegraph" = {} "omni.ui" = {} "omni.usd" = {} "omni.ui.scene" = {} "omni.usd.libs" = {} "omni.kit.commands" = {} "omni.kit.pipapi" = {} "omni.kit.uiapp" = {} "omni.kit.viewport.utility" = {} "omni.kit.property.usd" = {} "omni.kit.menu.utils" = {} "omni.kit.capture.viewport" = {} # Main python module this extension provides, it will be publicly available as "import cesium.omniverse" [[python.module]] name = "cesium.omniverse" [python.pipapi] archiveDirs = ["vendor"] [[native.plugin]] path = "bin/cesium.omniverse.plugin" [settings] exts."cesium.omniverse".defaultAccessToken = "" persistent.exts."cesium.omniverse".userAccessToken = "" exts."cesium.omniverse".showOnStartup = true [[test]] args = [ "--/renderer/enabled=rtx", "--/renderer/active=rtx", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--/app/file/ignoreUnsavedOnExit=true", ] dependencies = [ "omni.hydra.pxr", "omni.kit.mainwindow", "omni.kit.ui_test", "omni.kit.test_suite.helpers", "omni.kit.window.file", "omni.kit.viewport.window", ] pythonTests.include = ["cesium.omniverse.*"] pythonTests.exclude = [] pythonTests.unreliable = [ "*test_window_docked", # window does not dock when tests run from the empty test kit via the omniverse app ] timeout = 180
CesiumGS/cesium-omniverse/apps/cesium.omniverse.dev.python.debug.kit
[package] title = "Cesium For Omniverse Python Debugging App" version = "0.0.0" app = true [dependencies] "cesium.omniverse.dev" = {} "omni.kit.debug.vscode" = {} "omni.kit.debug.python" = {} [settings] app.window.title = "Cesium For Omniverse Python Debugging App" [settings.app.exts] folders.'++' = [ "${app}", # Find other applications in this folder "${app}/exts", # Find extensions in this folder "${app}/../exts", # Find cesium.omniverse and cesium.usd.schemas "${app}/../extern/nvidia/app/extscache" # Find omni.kit.window.material_graph ]
CesiumGS/cesium-omniverse/apps/cesium.performance.kit
[package] title = "Cesium For Omniverse Performance Testing App" version = "0.0.0" app = true [dependencies] "cesium.omniverse.dev.trace" = {} "cesium.performance.app" = {} [settings] app.window.title = "Cesium For Omniverse Performance Testing App" [settings.app.exts] folders.'++' = [ "${app}", # Find other applications in this folder "${app}/exts", # Find extensions in this folder "${app}/../exts", # Find cesium.omniverse and cesium.usd.schemas "${app}/../extern/nvidia/app/extscache" # Find omni.kit.window.material_graph ]
CesiumGS/cesium-omniverse/apps/cesium.omniverse.dev.kit
[package] title = "Cesium For Omniverse Testing App" version = "0.0.0" app = true [dependencies] # Include basic configuration (that brings most of basic extensions) "omni.app.dev" = {} "omni.kit.window.material_graph" = {optional = true} "cesium.omniverse" = {} "cesium.powertools" = {} "omni.curve.manipulator" = {} # "omni.example.ui" = {} # "omni.kit.documentation.ui.style" = {} [settings] app.window.title = "Cesium for Omniverse Testing App" app.useFabricSceneDelegate = false app.usdrt.scene_delegate.enableProxyCubes = false app.usdrt.scene_delegate.geometryStreaming.enabled = false omnihydra.parallelHydraSprimSync = false app.fastShutdown = true [settings.app.exts] folders.'++' = [ "${app}", # Find other applications in this folder "${app}/exts", # Find extensions in this folder "${app}/../exts", # Find cesium.omniverse and cesium.usd.schemas "${app}/../extern/nvidia/app/extscache" # Find omni.kit.window.material_graph ]
CesiumGS/cesium-omniverse/apps/cesium.omniverse.cpp.tests.runner.kit
[package] title = "Cesium For Omniverse Tests App" version = "0.0.0" app = true [dependencies] "omni.app.dev" = {} "cesium.omniverse.cpp.tests" = {} [settings] app.window.title = "Cesium for Omniverse Tests App" app.useFabricSceneDelegate = true [settings.app.exts] folders.'++' = [ "${app}", # Find other applications in this folder "${app}/exts", # Find extensions in this folder "${app}/../exts", # Find cesium.omniverse and cesium.usd.schemas "${app}/../extern/nvidia/app/extscache" # Find omni.kit.window.material_graph ]
CesiumGS/cesium-omniverse/apps/cesium.omniverse.dev.trace.kit
[package] title = "Cesium For Omniverse Performance Tracing App" version = "0.0.0" app = true [dependencies] "cesium.omniverse.dev" = {} [settings] app.window.title = "Cesium For Omniverse Performance Tracing App" app.fastShutdown = false [settings.app.exts] folders.'++' = [ "${app}", # Find other applications in this folder "${app}/exts", # Find extensions in this folder "${app}/../exts", # Find cesium.omniverse and cesium.usd.schemas "${app}/../extern/nvidia/app/extscache" # Find omni.kit.window.material_graph ]
CesiumGS/cesium-omniverse/apps/exts/cesium.performance.app/cesium/performance/app/extension.py
from functools import partial import asyncio import time from typing import Callable, List, Optional import logging import carb.events import omni.ext import omni.ui as ui import omni.usd import omni.kit.app as app import omni.kit.ui from omni.kit.viewport.utility import get_active_viewport from pxr import Gf, Sdf, UsdGeom from .performance_window import CesiumPerformanceWindow from .fps_sampler import FpsSampler from cesium.omniverse.bindings import acquire_cesium_omniverse_interface, release_cesium_omniverse_interface from cesium.omniverse.utils import wait_n_frames, dock_window_async from cesium.usd.plugins.CesiumUsdSchemas import ( Data as CesiumData, Georeference as CesiumGeoreference, IonRasterOverlay as CesiumIonRasterOverlay, Tileset as CesiumTileset, Tokens as CesiumTokens, ) ION_ACCESS_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI0Y2ZjNzY3NC04MWIyLTQyN2ItODg3Zi0zYzk3MmQxZWYxMmIiLCJpZCI6MjU5LCJpYXQiOjE3MTE5NzkyNzl9.GuvRiyuJO14zjA5_mIwgocOShmF4EUj2xbmikcCeXxs" # noqa: E501 GOOGLE_3D_TILES_ION_ID = 2275207 CESIUM_DATA_PRIM_PATH = "/Cesium" CESIUM_GEOREFERENCE_PRIM_PATH = "/CesiumGeoreference" CESIUM_CAMERA_PATH = "/Camera" class CesiumPerformanceExtension(omni.ext.IExt): def __init__(self): super().__init__() self._logger = logging.getLogger(__name__) self._performance_window: Optional[CesiumPerformanceWindow] = None self._view_new_york_city_subscription: Optional[carb.events.ISubscription] = None self._view_paris_subscription: Optional[carb.events.ISubscription] = None self._view_grand_canyon_subscription: Optional[carb.events.ISubscription] = None self._view_tour_subscription: Optional[carb.events.ISubscription] = None self._view_new_york_city_google_subscription: Optional[carb.events.ISubscription] = None self._view_paris_google_subscription: Optional[carb.events.ISubscription] = None self._view_grand_canyon_google_subscription: Optional[carb.events.ISubscription] = None self._view_tour_google_subscription: Optional[carb.events.ISubscription] = None self._stop_subscription: Optional[carb.events.ISubscription] = None self._on_stage_subscription: Optional[carb.events.ISubscription] = None self._update_frame_subscription: Optional[carb.events.ISubscription] = None self._tileset_loaded_subscription: Optional[carb.events.ISubscription] = None self._camera_path: Optional[str] = None self._tileset_path: Optional[str] = None self._active: bool = False self._start_time: float = 0.0 self._fps_sampler: FpsSampler = FpsSampler() def on_startup(self): global _cesium_omniverse_interface _cesium_omniverse_interface = acquire_cesium_omniverse_interface() self._setup_menus() self._show_and_dock_startup_windows() bus = app.get_app().get_message_bus_event_stream() view_new_york_city_event = carb.events.type_from_string("cesium.performance.VIEW_NEW_YORK_CITY") self._view_new_york_city_subscription = bus.create_subscription_to_pop_by_type( view_new_york_city_event, self._view_new_york_city ) view_paris_event = carb.events.type_from_string("cesium.performance.VIEW_PARIS") self._view_paris_subscription = bus.create_subscription_to_pop_by_type(view_paris_event, self._view_paris) view_grand_canyon_event = carb.events.type_from_string("cesium.performance.VIEW_GRAND_CANYON") self._view_grand_canyon_subscription = bus.create_subscription_to_pop_by_type( view_grand_canyon_event, self._view_grand_canyon ) view_tour_event = carb.events.type_from_string("cesium.performance.VIEW_TOUR") self._view_tour_subscription = bus.create_subscription_to_pop_by_type(view_tour_event, self._view_tour) view_new_york_city_google_event = carb.events.type_from_string("cesium.performance.VIEW_NEW_YORK_CITY_GOOGLE") self._view_new_york_city_google_subscription = bus.create_subscription_to_pop_by_type( view_new_york_city_google_event, self._view_new_york_city_google ) view_paris_google_event = carb.events.type_from_string("cesium.performance.VIEW_PARIS_GOOGLE") self._view_paris_google_subscription = bus.create_subscription_to_pop_by_type( view_paris_google_event, self._view_paris_google ) view_grand_canyon_google_event = carb.events.type_from_string("cesium.performance.VIEW_GRAND_CANYON_GOOGLE") self._view_grand_canyon_google_subscription = bus.create_subscription_to_pop_by_type( view_grand_canyon_google_event, self._view_grand_canyon_google ) view_tour_google_event = carb.events.type_from_string("cesium.performance.VIEW_TOUR_GOOGLE") self._view_tour_google_subscription = bus.create_subscription_to_pop_by_type( view_tour_google_event, self._view_tour_google ) stop_event = carb.events.type_from_string("cesium.performance.STOP") self._stop_subscription = bus.create_subscription_to_pop_by_type(stop_event, self._on_stop) usd_context = omni.usd.get_context() if usd_context.get_stage_state() == omni.usd.StageState.OPENED: self._on_stage_opened() self._on_stage_subscription = usd_context.get_stage_event_stream().create_subscription_to_pop( self._on_stage_event, name="cesium.performance.ON_STAGE_EVENT" ) update_stream = app.get_app().get_update_event_stream() self._update_frame_subscription = update_stream.create_subscription_to_pop( self._on_update_frame, name="cesium.performance.ON_UPDATE_FRAME" ) def on_shutdown(self): self._clear_scene() if self._view_new_york_city_subscription is not None: self._view_new_york_city_subscription.unsubscribe() self._view_new_york_city_subscription = None if self._view_paris_subscription is not None: self._view_paris_subscription.unsubscribe() self._view_paris_subscription = None if self._view_grand_canyon_subscription is not None: self._view_grand_canyon_subscription.unsubscribe() self._view_grand_canyon_subscription = None if self._view_tour_subscription is not None: self._view_tour_subscription.unsubscribe() self._view_tour_subscription = None if self._view_new_york_city_google_subscription is not None: self._view_new_york_city_google_subscription.unsubscribe() self._view_new_york_city_google_subscription = None if self._view_paris_google_subscription is not None: self._view_paris_google_subscription.unsubscribe() self._view_paris_google_subscription = None if self._view_grand_canyon_google_subscription is not None: self._view_grand_canyon_google_subscription.unsubscribe() self._view_grand_canyon_google_subscription = None if self._view_tour_google_subscription is not None: self._view_tour_google_subscription.unsubscribe() self._view_tour_google_subscription = None if self._stop_subscription is not None: self._stop_subscription.unsubscribe() self._stop_subscription = None if self._on_stage_subscription is not None: self._on_stage_subscription.unsubscribe() self._on_stage_subscription = None if self._update_frame_subscription is not None: self._update_frame_subscription.unsubscribe() self._update_frame_subscription = None self._fps_sampler.destroy() self._destroy_performance_window() release_cesium_omniverse_interface(_cesium_omniverse_interface) def _setup_menus(self): ui.Workspace.set_show_window_fn( CesiumPerformanceWindow.WINDOW_NAME, partial(self._show_performance_window, None) ) editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: editor_menu.add_item( CesiumPerformanceWindow.MENU_PATH, self._show_performance_window, toggle=True, value=True ) def _show_and_dock_startup_windows(self): ui.Workspace.show_window(CesiumPerformanceWindow.WINDOW_NAME) asyncio.ensure_future(dock_window_async(self._performance_window, target="Property")) def _destroy_performance_window(self): if self._performance_window is not None: self._performance_window.destroy() self._performance_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 CesiumPerformanceWindow.MENU_PATH: self._destroy_performance_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_performance_window(self, _menu, value): if value: self._performance_window = CesiumPerformanceWindow(_cesium_omniverse_interface, width=300, height=400) self._performance_window.set_visibility_changed_fn( partial(self._visibility_changed_fn, CesiumPerformanceWindow.MENU_PATH) ) elif self._performance_window is not None: self._performance_window.visible = False def _on_update_frame(self, _e: carb.events.IEvent): if self._active is True: duration = self._get_duration() self._update_duration_ui(duration) self._update_fps_ui(self._fps_sampler.get_fps()) def _on_stage_event(self, _e: carb.events.IEvent): usd_context = omni.usd.get_context() if usd_context.get_stage_state() == omni.usd.StageState.OPENED: self._on_stage_opened() def _on_stage_opened(self): self._camera_path = self._create_camera(CESIUM_CAMERA_PATH) @staticmethod def _create_tileset_ion(path: str, asset_id: int, access_token: str) -> str: stage = omni.usd.get_context().get_stage() tileset_path = omni.usd.get_stage_next_free_path(stage, path, False) tileset = CesiumTileset.Define(stage, tileset_path) assert tileset.GetPrim().IsValid() tileset.GetIonAssetIdAttr().Set(asset_id) tileset.GetIonAccessTokenAttr().Set(access_token) tileset.GetSourceTypeAttr().Set(CesiumTokens.ion) return tileset_path @staticmethod def _create_tileset_google() -> str: stage = omni.usd.get_context().get_stage() tileset_path = omni.usd.get_stage_next_free_path(stage, "/Google_3D_Tiles", False) tileset = CesiumTileset.Define(stage, tileset_path) tileset.GetIonAssetIdAttr().Set(GOOGLE_3D_TILES_ION_ID) tileset.GetIonAccessTokenAttr().Set(ION_ACCESS_TOKEN) tileset.GetSourceTypeAttr().Set(CesiumTokens.ion) return tileset_path @staticmethod def _create_raster_overlay_ion(path: str, asset_id: int, access_token: str) -> str: stage = omni.usd.get_context().get_stage() raster_overlay_path = omni.usd.get_stage_next_free_path(stage, path, False) raster_overlay = CesiumIonRasterOverlay.Define(stage, raster_overlay_path) assert raster_overlay.GetPrim().IsValid() parent = raster_overlay.GetPrim().GetParent() assert parent.IsA(CesiumTileset) tileset_prim = CesiumTileset.Get(stage, parent.GetPath()) tileset_prim.GetRasterOverlayBindingRel().AddTarget(raster_overlay_path) raster_overlay.GetIonAssetIdAttr().Set(asset_id) raster_overlay.GetIonAccessTokenAttr().Set(access_token) return raster_overlay_path @staticmethod def _create_camera(path: str) -> str: stage = omni.usd.get_context().get_stage() if stage.GetPrimAtPath(path): return path camera = UsdGeom.Camera.Define(stage, path) assert camera.GetPrim().IsValid() camera.GetClippingRangeAttr().Set(Gf.Vec2f(1.0, 100000000.0)) return path @staticmethod def _get_raster_overlay_path(tileset_path: str, raster_overlay_name: str) -> str: return Sdf.Path(tileset_path).AppendPath(raster_overlay_name).pathString @staticmethod def _set_georeference(longitude: float, latitude: float, height: float): stage = omni.usd.get_context().get_stage() cesium_georeference = CesiumGeoreference.Get(stage, CESIUM_GEOREFERENCE_PRIM_PATH) assert cesium_georeference.GetPrim().IsValid() cesium_georeference.GetGeoreferenceOriginLongitudeAttr().Set(longitude) cesium_georeference.GetGeoreferenceOriginLatitudeAttr().Set(latitude) cesium_georeference.GetGeoreferenceOriginHeightAttr().Set(height) def _set_camera( self, translate: Gf.Vec3d, rotate: Gf.Vec3f, focal_length: float, horizontal_aperture: float, vertical_aperture: float, ): stage = omni.usd.get_context().get_stage() viewport = get_active_viewport() viewport.set_active_camera(self._camera_path) camera = UsdGeom.Camera.Get(stage, self._camera_path) camera.GetFocalLengthAttr().Set(focal_length) camera.GetHorizontalApertureAttr().Set(horizontal_aperture) camera.GetVerticalApertureAttr().Set(vertical_aperture) xform_common_api = UsdGeom.XformCommonAPI(camera.GetPrim()) xform_common_api.SetTranslate(translate) xform_common_api.SetRotate(rotate, UsdGeom.XformCommonAPI.RotationOrderYXZ) @staticmethod def _get_tileset(path: str) -> CesiumTileset: stage = omni.usd.get_context().get_stage() tileset = CesiumTileset.Get(stage, path) assert tileset.GetPrim().IsValid() return tileset @staticmethod def _get_cesium_data() -> CesiumData: stage = omni.usd.get_context().get_stage() cesium_data = CesiumData.Get(stage, CESIUM_DATA_PRIM_PATH) assert cesium_data.GetPrim().IsValid() return cesium_data @staticmethod def _remove_prim(path: str): stage = omni.usd.get_context().get_stage() stage.RemovePrim(path) def _setup_location_new_york_city(self): self._set_georeference(-74.0060, 40.7128, 50.0) self._set_camera( Gf.Vec3d(-176516.8372437113, 33877.019622553846, 197777.19771945066), Gf.Vec3f(-7.9392824, -37.71652, -6.0970836), 18.14756, 20.955, 15.2908, ) def _setup_location_paris(self): self._set_georeference(2.3522, 48.8566, 100.0) self._set_camera( Gf.Vec3d(-285275.1368718885, 780.3607448845705, 35392.91845506678), Gf.Vec3f(0.46399376, 65.245544, -1.0061567), 18.14756, 20.955, 15.2908, ) def _setup_location_grand_canyon(self): self._set_georeference(-112.3535, 36.2679, 2100.0) self._set_camera( Gf.Vec3d(-339866.7567928189, 27967.440239271935, -59650.894693908194), Gf.Vec3f(5.532731, -129.35608, -6.704948), 18.14756, 20.955, 15.2908, ) def _view_new_york_city(self, _e: carb.events.IEvent): self._logger.warning("View New York City") self._clear_scene() self._setup_location_new_york_city() tileset_path = self._create_tileset_ion("/Cesium_World_Terrain", 1, ION_ACCESS_TOKEN) self._create_raster_overlay_ion( self._get_raster_overlay_path(tileset_path, "Bing_Maps_Aerial_Imagery"), 2, ION_ACCESS_TOKEN, ) self._load_tileset(tileset_path, self._tileset_loaded) def _view_paris(self, _e: carb.events.IEvent): self._logger.warning("View Paris") self._clear_scene() self._setup_location_paris() tileset_path = self._create_tileset_ion("/Cesium_World_Terrain", 1, ION_ACCESS_TOKEN) self._create_raster_overlay_ion( self._get_raster_overlay_path(tileset_path, "Bing_Maps_Aerial_Imagery"), 2, ION_ACCESS_TOKEN, ) self._load_tileset(tileset_path, self._tileset_loaded) def _view_grand_canyon(self, _e: carb.events.IEvent): self._logger.warning("View Grand Canyon") self._clear_scene() self._setup_location_grand_canyon() tileset_path = self._create_tileset_ion("/Cesium_World_Terrain", 1, ION_ACCESS_TOKEN) self._create_raster_overlay_ion( self._get_raster_overlay_path(tileset_path, "Bing_Maps_Aerial_Imagery"), 2, ION_ACCESS_TOKEN, ) self._load_tileset(tileset_path, self._tileset_loaded) def _view_tour(self, _e: carb.events.IEvent): self._logger.warning("View Tour") self._clear_scene() tileset_path = self._create_tileset_ion("/Cesium_World_Terrain", 1, ION_ACCESS_TOKEN) self._create_raster_overlay_ion( self._get_raster_overlay_path(tileset_path, "Bing_Maps_Aerial_Imagery"), 2, ION_ACCESS_TOKEN, ) def tour_stop_0(): self._setup_location_new_york_city() def tour_stop_1(): self._setup_location_paris() def tour_stop_2(): self._setup_location_grand_canyon() tour = Tour(self, [tour_stop_0, tour_stop_1, tour_stop_2], self._tileset_loaded) self._load_tileset(tileset_path, tour.tour_stop_loaded) def _view_new_york_city_google(self, _e: carb.events.IEvent): self._logger.warning("View New York City Google") self._clear_scene() self._setup_location_new_york_city() tileset_path = self._create_tileset_google() self._load_tileset(tileset_path, self._tileset_loaded) def _view_paris_google(self, _e: carb.events.IEvent): self._logger.warning("View Paris Google") self._clear_scene() self._setup_location_paris() tileset_path = self._create_tileset_google() self._load_tileset(tileset_path, self._tileset_loaded) def _view_grand_canyon_google(self, _e: carb.events.IEvent): self._logger.warning("View Grand Canyon Google") self._clear_scene() self._setup_location_grand_canyon() tileset_path = self._create_tileset_google() self._load_tileset(tileset_path, self._tileset_loaded) def _view_tour_google(self, _e: carb.events.IEvent): self._logger.warning("View Tour Google") self._clear_scene() tileset_path = self._create_tileset_google() def tour_stop_0(): self._setup_location_new_york_city() def tour_stop_1(): self._setup_location_paris() def tour_stop_2(): self._setup_location_grand_canyon() tour = Tour(self, [tour_stop_0, tour_stop_1, tour_stop_2], self._tileset_loaded) self._load_tileset(tileset_path, tour.tour_stop_loaded) def _load_tileset(self, tileset_path: str, tileset_loaded: Callable): tileset = self._get_tileset(tileset_path) cesium_data = self._get_cesium_data() assert self._performance_window is not None bus = app.get_app().get_message_bus_event_stream() tileset_loaded_event = carb.events.type_from_string("cesium.omniverse.TILESET_LOADED") self._tileset_loaded_subscription = bus.create_subscription_to_pop_by_type( tileset_loaded_event, tileset_loaded ) random_colors = self._performance_window.get_random_colors() forbid_holes = self._performance_window.get_forbid_holes() frustum_culling = self._performance_window.get_frustum_culling() main_thread_loading_time_limit = self._performance_window.get_main_thread_loading_time_limit_model() cesium_data.GetDebugRandomColorsAttr().Set(random_colors) tileset.GetForbidHolesAttr().Set(forbid_holes) tileset.GetEnableFrustumCullingAttr().Set(frustum_culling) tileset.GetMainThreadLoadingTimeLimitAttr().Set(main_thread_loading_time_limit) self._tileset_path = tileset_path self._active = True self._start_time = time.time() self._fps_sampler.start() def _tileset_loaded(self, _e: carb.events.IEvent): self._stop() duration = self._get_duration() self._update_duration_ui(duration) self._update_fps_mean_ui(self._fps_sampler.get_mean()) self._update_fps_median_ui(self._fps_sampler.get_median()) self._update_fps_low_ui(self._fps_sampler.get_low()) self._update_fps_high_ui(self._fps_sampler.get_high()) self._logger.warning("Loaded in {} seconds".format(duration)) def _get_duration(self) -> float: current_time = time.time() duration = current_time - self._start_time return duration def _update_duration_ui(self, value: float): if self._performance_window is not None: self._performance_window.set_duration(value) def _update_fps_ui(self, value: float): if self._performance_window is not None: self._performance_window.set_fps(value) def _update_fps_mean_ui(self, value: float): if self._performance_window is not None: self._performance_window.set_fps_mean(value) def _update_fps_median_ui(self, value: float): if self._performance_window is not None: self._performance_window.set_fps_median(value) def _update_fps_low_ui(self, value: float): if self._performance_window is not None: self._performance_window.set_fps_low(value) def _update_fps_high_ui(self, value: float): if self._performance_window is not None: self._performance_window.set_fps_high(value) def _clear_scene(self): self._stop() self._update_duration_ui(0.0) self._update_fps_ui(0.0) self._update_fps_mean_ui(0.0) self._update_fps_median_ui(0.0) self._update_fps_low_ui(0.0) self._update_fps_high_ui(0.0) if self._tileset_path is not None: self._remove_prim(self._tileset_path) def _on_stop(self, _e: carb.events.IEvent): self._stop() def _stop(self): self._active = False self._fps_sampler.stop() if self._tileset_loaded_subscription is not None: self._tileset_loaded_subscription.unsubscribe() self._tileset_loaded_subscription = None class Tour: def __init__(self, ext: CesiumPerformanceExtension, tour_stops: List[Callable], tour_complete: Callable): self._ext: CesiumPerformanceExtension = ext self._tour_stops: List[Callable] = tour_stops self._tour_complete: Callable = tour_complete self._current_stop: int = 0 self._duration: float = 0.0 assert len(tour_stops) > 0 tour_stops[0]() def tour_stop_loaded(self, _e: carb.events.IEvent): duration = self._ext._get_duration() current_duration = duration - self._duration self._duration = duration self._ext._logger.warning("Tour stop {} loaded in {} seconds".format(self._current_stop, current_duration)) if self._current_stop == len(self._tour_stops) - 1: self._tour_complete(_e) else: self._current_stop += 1 self._tour_stops[self._current_stop]()
CesiumGS/cesium-omniverse/apps/exts/cesium.performance.app/cesium/performance/app/__init__.py
from .extension import * # noqa: F401 F403
CesiumGS/cesium-omniverse/apps/exts/cesium.performance.app/cesium/performance/app/performance_window.py
import logging import carb.events import omni.kit.app as app import omni.ui as ui from cesium.omniverse.bindings import ICesiumOmniverseInterface RANDOM_COLORS_TEXT = "Random colors" FORBID_HOLES_TEXT = "Forbid holes" FRUSTUM_CULLING_TEXT = "Frustum culling" TRACING_ENABLED_TEXT = "Tracing enabled" MAIN_THREAD_LOADING_TIME_LIMIT_TEXT = "Main thread loading time limit (ms)" NEW_YORK_CITY_TEXT = "New York City" PARIS_TEXT = "Paris" GRAND_CANYON_TEXT = "Grand Canyon" TOUR_TEXT = "Tour" NEW_YORK_CITY_GOOGLE_TEXT = "New York City (Google)" PARIS_GOOGLE_TEXT = "Paris (Google)" GRAND_CANYON_GOOGLE_TEXT = "Grand Canyon (Google)" TOUR_GOOGLE_TEXT = "Tour (Google)" DURATION_TEXT = "Duration (seconds)" FPS_TEXT = "FPS" FPS_MEAN_TEXT = "FPS (mean)" FPS_MEDIAN_TEXT = "FPS (median)" FPS_LOW_TEXT = "FPS (low)" FPS_HIGH_TEXT = "FPS (high)" class CesiumPerformanceWindow(ui.Window): WINDOW_NAME = "Cesium Performance Testing" MENU_PATH = f"Window/Cesium/{WINDOW_NAME}" def __init__(self, cesium_omniverse_interface: ICesiumOmniverseInterface, **kwargs): super().__init__(CesiumPerformanceWindow.WINDOW_NAME, **kwargs) self._cesium_omniverse_interface = cesium_omniverse_interface self._logger = logging.getLogger(__name__) self._random_colors_checkbox_model = ui.SimpleBoolModel(False) self._forbid_holes_checkbox_model = ui.SimpleBoolModel(False) self._frustum_culling_checkbox_model = ui.SimpleBoolModel(True) self._main_thread_loading_time_limit_model = ui.SimpleFloatModel(0.0) self._duration_model = ui.SimpleFloatModel(0.0) self._fps_model = ui.SimpleFloatModel(0.0) self._fps_mean_model = ui.SimpleFloatModel(0.0) self._fps_median_model = ui.SimpleFloatModel(0.0) self._fps_low_model = ui.SimpleFloatModel(0.0) self._fps_high_model = ui.SimpleFloatModel(0.0) self.frame.set_build_fn(self._build_fn) def destroy(self) -> None: super().destroy() def _build_fn(self): with ui.VStack(spacing=10): with ui.VStack(spacing=4): with ui.HStack(height=16): ui.Label("Options", height=0) ui.Spacer() for label, model in [ (RANDOM_COLORS_TEXT, self._random_colors_checkbox_model), (FORBID_HOLES_TEXT, self._forbid_holes_checkbox_model), (FRUSTUM_CULLING_TEXT, self._frustum_culling_checkbox_model), ]: with ui.HStack(height=0): ui.Label(label, height=0) ui.CheckBox(model) with ui.HStack(height=0): ui.Label(MAIN_THREAD_LOADING_TIME_LIMIT_TEXT, height=0) ui.StringField(self._main_thread_loading_time_limit_model) with ui.HStack(height=16): tracing_label = ui.Label(TRACING_ENABLED_TEXT, height=0) tracing_label.set_tooltip( "Enabled when the project is configured with -D CESIUM_OMNI_ENABLE_TRACING=ON" ) enabled_string = "ON" if self._cesium_omniverse_interface.is_tracing_enabled() else "OFF" ui.Label(enabled_string, height=0) with ui.VStack(spacing=0): ui.Label("Scenarios", height=16) for label, callback in [ (NEW_YORK_CITY_TEXT, self._view_new_york_city), (PARIS_TEXT, self._view_paris), (GRAND_CANYON_TEXT, self._view_grand_canyon), (TOUR_TEXT, self._view_tour), (NEW_YORK_CITY_GOOGLE_TEXT, self._view_new_york_city_google), (PARIS_GOOGLE_TEXT, self._view_paris_google), (GRAND_CANYON_GOOGLE_TEXT, self._view_grand_canyon_google), (TOUR_GOOGLE_TEXT, self._view_tour_google), ]: ui.Button(label, height=20, clicked_fn=callback) with ui.VStack(spacing=4): with ui.HStack(height=16): ui.Label("Stats", height=0) ui.Spacer() for label, model in [ (DURATION_TEXT, self._duration_model), (FPS_TEXT, self._fps_model), (FPS_MEAN_TEXT, self._fps_mean_model), (FPS_MEDIAN_TEXT, self._fps_median_model), (FPS_LOW_TEXT, self._fps_low_model), (FPS_HIGH_TEXT, self._fps_high_model), ]: with ui.HStack(height=0): ui.Label(label, height=0) ui.StringField(model=model, height=0, read_only=True) with ui.VStack(spacing=0): ui.Button("Stop", height=16, clicked_fn=self._stop) def _view_new_york_city(self): bus = app.get_app().get_message_bus_event_stream() view_new_york_city_event = carb.events.type_from_string("cesium.performance.VIEW_NEW_YORK_CITY") bus.push(view_new_york_city_event) def _view_paris(self): bus = app.get_app().get_message_bus_event_stream() view_paris_event = carb.events.type_from_string("cesium.performance.VIEW_PARIS") bus.push(view_paris_event) def _view_grand_canyon(self): bus = app.get_app().get_message_bus_event_stream() view_grand_canyon_event = carb.events.type_from_string("cesium.performance.VIEW_GRAND_CANYON") bus.push(view_grand_canyon_event) def _view_tour(self): bus = app.get_app().get_message_bus_event_stream() view_tour_event = carb.events.type_from_string("cesium.performance.VIEW_TOUR") bus.push(view_tour_event) def _view_new_york_city_google(self): bus = app.get_app().get_message_bus_event_stream() view_new_york_city_google_event = carb.events.type_from_string("cesium.performance.VIEW_NEW_YORK_CITY_GOOGLE") bus.push(view_new_york_city_google_event) def _view_paris_google(self): bus = app.get_app().get_message_bus_event_stream() view_paris_google_event = carb.events.type_from_string("cesium.performance.VIEW_PARIS_GOOGLE") bus.push(view_paris_google_event) def _view_grand_canyon_google(self): bus = app.get_app().get_message_bus_event_stream() view_grand_canyon_google_event = carb.events.type_from_string("cesium.performance.VIEW_GRAND_CANYON_GOOGLE") bus.push(view_grand_canyon_google_event) def _view_tour_google(self): bus = app.get_app().get_message_bus_event_stream() view_tour_google_event = carb.events.type_from_string("cesium.performance.VIEW_TOUR_GOOGLE") bus.push(view_tour_google_event) def _stop(self): bus = app.get_app().get_message_bus_event_stream() stop_event = carb.events.type_from_string("cesium.performance.STOP") bus.push(stop_event) def get_random_colors(self) -> bool: return self._random_colors_checkbox_model.get_value_as_bool() def get_forbid_holes(self) -> bool: return self._forbid_holes_checkbox_model.get_value_as_bool() def get_frustum_culling(self) -> bool: return self._frustum_culling_checkbox_model.get_value_as_bool() def get_main_thread_loading_time_limit_model(self) -> float: return self._main_thread_loading_time_limit_model.get_value_as_float() def set_duration(self, value: float): self._duration_model.set_value(value) def set_fps(self, value: float): self._fps_model.set_value(value) def set_fps_mean(self, value: float): self._fps_mean_model.set_value(value) def set_fps_median(self, value: float): self._fps_median_model.set_value(value) def set_fps_low(self, value: float): self._fps_low_model.set_value(value) def set_fps_high(self, value: float): self._fps_high_model.set_value(value)
CesiumGS/cesium-omniverse/apps/exts/cesium.performance.app/cesium/performance/app/fps_sampler.py
import array import time import carb.events import omni.kit.app as app import statistics from omni.kit.viewport.utility import get_active_viewport FREQUENCY_IN_SECONDS: float = 0.025 class FpsSampler: def __init__( self, ): self._last_time: float = 0.0 self._active: bool = False self._fps = 0.0 self._samples = array.array("f") self._median: float = 0.0 self._mean: float = 0.0 self._low: float = 0.0 self._high: float = 0.0 self._viewport = get_active_viewport() update_stream = app.get_app().get_update_event_stream() self._update_frame_subscription = update_stream.create_subscription_to_pop( self._on_update_frame, name="cesium.performance.ON_UPDATE_FRAME" ) def __del__(self): self.destroy() def destroy(self): if self._update_frame_subscription is not None: self._update_frame_subscription.unsubscribe() self._update_frame_subscription = None def start(self): self._last_time = time.time() self._active = True def stop(self): self._active = False if len(self._samples) > 0: self._mean = statistics.mean(self._samples) self._median = statistics.median(self._samples) self._low = min(self._samples) self._high = max(self._samples) self._samples = array.array("f") def get_mean(self): assert not self._active return self._mean def get_median(self): assert not self._active return self._median def get_low(self): assert not self._active return self._low def get_high(self): assert not self._active return self._high def get_fps(self): assert self._active return self._fps def _on_update_frame(self, _e: carb.events.IEvent): if not self._active: return current_time = time.time() elapsed = current_time - self._last_time if elapsed > FREQUENCY_IN_SECONDS: fps = self._viewport.fps self._samples.append(fps) self._last_time = current_time self._fps = fps
CesiumGS/cesium-omniverse/apps/exts/cesium.performance.app/config/extension.toml
[package] title = "Cesium for Omniverse Performance Testing Extension" version = "0.0.0" app = false toggleable = false [dependencies] "cesium.omniverse" = {} [[python.module]] name = "cesium.performance.app"
CesiumGS/cesium-omniverse/scripts/copy_to_exts.py
""" This file is a post build step run by cmake that copies over the CHANGES.md and related resources to the exts/docs folder for packaging. """ import re import shutil from dataclasses import dataclass from pathlib import Path from typing import List @dataclass class PathPair: """ Represents a source and relative destination pair. :arg source: The source path for the file. :arg relative_destination: The relative destination for the file. """ source: Path relative_destination: str = "" def find_resources(path: Path) -> List[PathPair]: """ Finds all resources within a file and returns them as a list of PathPairs. The search is done using a regular expression looking for all links that contain the substring "docs/resources". NOTE: This **only** works with relative paths. Absolute paths in the file read will fail. :param path: The file to search. :return: A list containing PathPairs of all resources found in the file. """ regex = re.compile(r"!\[.*]\((.*docs/(resources.*?))\)") root_path = path.parent.resolve() resources: List[PathPair] = [] with open(path.resolve(), "r") as f: for line in f.readlines(): match = regex.search(line) if match is not None: source = root_path.joinpath(match.group(1)) relative_destination = match.group(2) resources.append(PathPair(source, relative_destination)) return resources def copy_to_destination(pair: PathPair, destination: Path) -> None: """ Copies the file based on the path and relative destination contained in the pair. NOTE: This uses shutils so if you're on a version of Python older than 3.8 this will be slow. :param pair: The PathPair for the copy operation. :param destination: The path of the destination directory. """ true_destination = ( destination.joinpath(pair.relative_destination) if pair.relative_destination != "" else destination ) # In the event that true_destination isn't a direct file path, we need to take the source filename and append it # to true_destination. if true_destination.is_dir(): true_destination = true_destination.joinpath(pair.source.name) true_destination.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(pair.source, true_destination) def main() -> int: project_root = Path(__file__).parent.parent destination = project_root.joinpath("exts/cesium.omniverse/doc") changes_path = project_root.joinpath("CHANGES.md") try: # Turning off formatting here for readability. # fmt: off paths_to_copy: List[PathPair] = [ PathPair(changes_path), *find_resources(changes_path) ] # fmt: on for pair in paths_to_copy: copy_to_destination(pair, destination) except Exception as e: print(e) return 1 return 0 exit(main())
CesiumGS/cesium-omniverse/scripts/build_package_almalinux8.sh
#!/bin/bash # Make sure to run this script from the root cesium-omniverse directory # Delete existing build folder sudo rm -rf build-package # Start the docker container docker build --tag cesiumgs/cesium-omniverse:almalinux8 -f docker/AlmaLinux8.Dockerfile . container_id=$(docker run -it -d --volume $PWD:/var/app cesiumgs/cesium-omniverse:almalinux8) # Run package commands inside docker container package_cmd=" cmake -B build-package -D CMAKE_BUILD_TYPE=Release CESIUM_OMNI_ENABLE_TESTS=OFF -D CESIUM_OMNI_ENABLE_DOCUMENTATION=OFF -D CESIUM_OMNI_ENABLE_SANITIZERS=OFF -D CESIUM_OMNI_ENABLE_LINTERS=OFF && cmake --build build-package --parallel 8 && cmake --build build-package --target install && cmake --build build-package --target package " docker exec ${container_id} /bin/sh -c "${package_cmd}" # Clean up docker stop ${container_id} docker rm ${container_id}
CesiumGS/cesium-omniverse/scripts/vscode_build.py
#!/usr/bin/env python3 import sys import subprocess import multiprocessing import os import platform import shutil try: import pty except Exception: pass import webbrowser from typing import List, NamedTuple def is_windows(): return platform.system() == "Windows" def is_linux(): return platform.system() == "Linux" def process(cmd: List[str]): print("Run: " + " ".join(cmd)) if is_linux(): # Using pty instead of subprocess to get terminal colors result = pty.spawn(cmd) if result != 0: sys.exit(result) else: p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) for line in p.stdout: print(line, end="") p.communicate() if p.returncode != 0: raise subprocess.CalledProcessError(p.returncode, p.args) def open_browser(html: str): html = os.path.realpath(html) html = "file://{}".format(html) webbrowser.open(html, new=2) class Args(NamedTuple): task: str build_folder: str build_type: str compiler_name: str tracing: bool verbose: bool kit_debug: bool parallel: bool build_only: bool def c_compiler_to_cpp_compiler(compiler_name: str): cpp = compiler_name cpp = cpp.replace("gcc", "g++") cpp = cpp.replace("clang", "clang++") return cpp def get_cmake_configure_command(args: Args): cmd = ["cmake", "-B", args.build_folder] # Release is the default build type, so no need to pass CMAKE_BUILD_TYPE if args.build_type != "Release": cmd.extend(("-D", "CMAKE_BUILD_TYPE={}".format(args.build_type))) if args.tracing: cmd.extend(("-D", "CESIUM_OMNI_ENABLE_TRACING=ON")) if args.kit_debug: cmd.extend(("-D", "CESIUM_OMNI_USE_NVIDIA_DEBUG_LIBRARIES=ON")) if is_windows(): cmd.extend(("-G", "Ninja Multi-Config", "-D", "CMAKE_C_COMPILER=cl", "-D", "CMAKE_CXX_COMPILER=cl")) return cmd if args.compiler_name == "default": return cmd c_compiler = args.compiler_name cpp_compiler = c_compiler_to_cpp_compiler(args.compiler_name) cmd.extend(("-D", "CMAKE_C_COMPILER={}".format(c_compiler))) cmd.extend(("-D", "CMAKE_CXX_COMPILER={}".format(cpp_compiler))) return cmd def get_cmake_build_command(args: Args, target: str): cmd = ["cmake", "--build", args.build_folder] if is_windows(): cmd.extend(("--config", args.build_type)) if target: cmd.extend(("--target", target)) if args.verbose: cmd.append("--verbose") if args.parallel: # use every core except one so that computer doesn't go too slow cores = max(1, multiprocessing.cpu_count() - 1) cmd.extend(("--parallel", str(cores))) return cmd def get_cmake_install_command(args: Args): cmd = ["cmake", "--install", args.build_folder] if is_windows(): cmd.extend(("--config", args.build_type)) return cmd def configure(args: Args): configure_cmd = get_cmake_configure_command(args) process(configure_cmd) def build(args: Args): build_cmd = get_cmake_build_command(args, None) install_kit_cmd = get_cmake_install_command(args) if not args.build_only: configure_cmd = get_cmake_configure_command(args) process(configure_cmd) process(build_cmd) process(install_kit_cmd) def coverage(args: Args): if is_windows(): print("Coverage is not supported for Windows") return configure_cmd = get_cmake_configure_command(args) build_cmd = get_cmake_build_command(args, "generate-coverage") html = "{}/coverage/index.html".format(args.build_folder) process(configure_cmd) process(build_cmd) open_browser(html) def documentation(args: Args): configure_cmd = get_cmake_configure_command(args) documentation_cmd = get_cmake_build_command(args, "generate-documentation") html = "{}/docs/html/index.html".format(args.build_folder) process(configure_cmd) process(documentation_cmd) open_browser(html) def install(args: Args): configure_cmd = get_cmake_configure_command(args) install_cmd = get_cmake_build_command(args, "install") process(configure_cmd) process(install_cmd) def clean(args: Args): if os.path.exists(args.build_folder) and os.path.isdir(args.build_folder): shutil.rmtree(args.build_folder) def format(args: Args): format_cmd = get_cmake_build_command(args, "clang-format-fix-all") process(format_cmd) def lint(args: Args): clang_tidy_cmd = get_cmake_build_command(args, "clang-tidy") process(clang_tidy_cmd) def lint_fix(args: Args): clang_tidy_cmd = get_cmake_build_command(args, "clang-tidy-fix") process(clang_tidy_cmd) def dependency_graph(args: Args): configure_cmd = get_cmake_configure_command(args) conan_packages_path = os.path.join(args.build_folder, "Conan_Packages") dependency_html = os.path.join(args.build_folder, "dependency_graph.html") dependency_cmd = ["conan", "info", args.build_folder, "-if", conan_packages_path, "--graph", dependency_html] process(configure_cmd) process(dependency_cmd) open_browser(dependency_html) def get_build_folder_name(build_type: str, compiler_name: str): folder_name = "build" if is_windows(): return folder_name if build_type != "Release": folder_name += "-{}".format(build_type.lower()) if compiler_name != "default": folder_name += "-{}".format(compiler_name) return folder_name def get_bin_folder_name(build_type: str, compiler_name: str): build_folder_name = get_build_folder_name(build_type, compiler_name) if is_windows(): bin_folder_name = "{}/bin/{}".format(build_folder_name, build_type) else: bin_folder_name = "{}/bin".format(build_folder_name) return bin_folder_name def main(av: List[str]): print(av) task = av[0] build_type = av[1] if len(av) >= 2 else "Release" compiler_name = av[2] if len(av) >= 3 else "default" build_folder = get_build_folder_name(build_type, compiler_name) tracing = True if len(av) >= 4 and av[3] == "--tracing" else False verbose = True if len(av) >= 4 and av[3] == "--verbose" else False kit_debug = True if len(av) >= 4 and av[3] == "--kit-debug" else False parallel = False if len(av) >= 5 and av[4] == "--no-parallel" else True build_only = True if len(av) >= 4 and av[3] == "--build-only" else False args = Args(task, build_folder, build_type, compiler_name, tracing, verbose, kit_debug, parallel, build_only) if task == "configure": configure(args) elif task == "build": build(args) elif task == "clean": clean(args) elif task == "coverage": coverage(args) elif task == "documentation": documentation(args) elif task == "install": install(args) elif task == "format": format(args) elif task == "lint": lint(args) elif task == "lint-fix": lint_fix(args) elif task == "dependency-graph": dependency_graph(args) if __name__ == "__main__": try: main(sys.argv[1:]) except Exception as e: print(e) exit(1)
CesiumGS/cesium-omniverse/scripts/build_package_centos7.sh
#!/bin/bash # Make sure to run this script from the root cesium-omniverse directory # Delete existing build folder sudo rm -rf build-package # Start the docker container docker build --tag cesiumgs/cesium-omniverse:centos7 -f docker/CentOS7.Dockerfile . container_id=$(docker run -it -d --volume $PWD:/var/app cesiumgs/cesium-omniverse:centos7) # Run package commands inside docker container package_cmd=" cmake -B build-package -D CMAKE_BUILD_TYPE=Release CESIUM_OMNI_ENABLE_TESTS=OFF -D CESIUM_OMNI_ENABLE_DOCUMENTATION=OFF -D CESIUM_OMNI_ENABLE_SANITIZERS=OFF -D CESIUM_OMNI_ENABLE_LINTERS=OFF && cmake --build build-package --parallel 8 && cmake --build build-package --target install && cmake --build build-package --target package " docker exec ${container_id} /bin/sh -c "${package_cmd}" # Clean up docker stop ${container_id} docker rm ${container_id}
CesiumGS/cesium-omniverse/scripts/clang_tidy.py
#!/usr/bin/env python3 import argparse import sys import shutil from utils import utils from typing import List def parse_args(av: List[str]): parser = argparse.ArgumentParser(description="Run / check clang-tidy on staged cpp files.") parser.add_argument( "--clang-tidy-executable", help="Specific clang-tidy binary to use.", action="store", required=False ) return parser.parse_known_args(av) def main(av: List[str]): known_args, clang_tidy_args = parse_args(av) project_root = utils.get_project_root() clang_tidy_executable = known_args.clang_tidy_executable if not clang_tidy_executable: clang_tidy_executable = shutil.which("clang-tidy") project_root = utils.get_project_root() candidate_files = [ f.as_posix() for f in utils.get_staged_git_files(project_root) if f.suffix in utils.CPP_EXTENSIONS ] cmd = [clang_tidy_executable] + clang_tidy_args + candidate_files if len(candidate_files) > 0: print("Running clang-tidy") utils.run_command_and_echo_on_error(cmd) else: print("Skipping clang-tidy (no cpp files staged)") if __name__ == "__main__": main(sys.argv[1:])
CesiumGS/cesium-omniverse/scripts/run_python_unit_tests.sh
#!/bin/bash set -e SCRIPT_DIR=$(dirname ${BASH_SOURCE}) KIT_DIR="$SCRIPT_DIR/../extern/nvidia/_build/target-deps/kit-sdk" exec "$KIT_DIR/kit" --enable omni.kit.test --/app/enableStdoutOutput=0 --/exts/omni.kit.test/testExts/0='cesium.omniverse' --ext-folder "$KIT_DIR/extscore" --ext-folder "$KIT_DIR/exts" --ext-folder "$KIT_DIR/apps" --ext-folder "$SCRIPT_DIR/../exts" --/exts/omni.kit.test/testExtApp="$SCRIPT_DIR/../apps/cesium.omniverse.dev.kit" --/exts/omni.kit.test/testExtOutputPath="$SCRIPT_DIR/../_testoutput" --portable-root "$KIT_DIR/" --/telemetry/mode=test "$@"
CesiumGS/cesium-omniverse/scripts/run_python_unit_tests.bat
@echo off setlocal set KIT_DIR=%~dp0\..\extern\nvidia\_build\target-deps\kit-sdk call "%KIT_DIR%\kit.exe" --enable omni.kit.test --/app/enableStdoutOutput=0 --/exts/omni.kit.test/testExts/0='cesium.omniverse' --ext-folder "%KIT_DIR%/extscore" --ext-folder "%KIT_DIR%/exts" --ext-folder "%KIT_DIR%/apps" --ext-folder "%~dp0/../exts" --/exts/omni.kit.test/testExtApp="%~dp0/../apps/cesium.omniverse.dev.kit" --/exts/omni.kit.test/testExtOutputPath="%~dp0/../_testoutput" --portable-root "%KIT_DIR%/" --/telemetry/mode=test %*
CesiumGS/cesium-omniverse/scripts/interactive_python_unit_tests.sh
#!/bin/bash set -e SCRIPT_DIR=$(dirname ${BASH_SOURCE}) KIT_DIR="$SCRIPT_DIR/../extern/nvidia/_build/target-deps/kit-sdk" exec "$KIT_DIR/kit" --enable omni.kit.test --dev --/app/enableStdoutOutput=0 --/exts/omni.kit.test/testExts/0='cesium.omniverse' --ext-folder "$KIT_DIR/extscore" --ext-folder "$KIT_DIR/exts" --ext-folder "$KIT_DIR/apps" --ext-folder "$SCRIPT_DIR/../exts" --/exts/omni.kit.test/testExtApp="$SCRIPT_DIR/../apps/cesium.omniverse.dev.kit" --/exts/omni.kit.test/testExtOutputPath="$SCRIPT_DIR/../_testoutput" --portable-root "$KIT_DIR/" --/telemetry/mode=test "$@"
CesiumGS/cesium-omniverse/scripts/update_certs.py
#! /usr/bin/python3 """ Intended to be called in the This script updates the certificates used for any requests that use the core Context class. While some certs are available on the system, they may not be consistent or updated. This ensures all certs are uniform and up to date see: https://github.com/CesiumGS/cesium-omniverse/issues/306 """ import requests import sys import os def main(): # --- establish source/destination for certs --- if len(sys.argv) < 2: print("must provide a filepath for the updated certs") return -1 CERT_URL = "https://curl.se/ca/cacert.pem" CERT_FILE_PATH = sys.argv[1] # --- ensure directory structure exists ---- os.makedirs(os.path.dirname(CERT_FILE_PATH), exist_ok=True) # --- fetch and write the cert file ---- req = requests.get(CERT_URL) if req.status_code != 200: print(f"failed to fetch certificates from {CERT_URL}") return -1 # explicit encoding is required for windows with open(CERT_FILE_PATH, "w", encoding="utf-8") as f: f.write(req.text) return 0 if __name__ == "__main__": sys.exit(main())
CesiumGS/cesium-omniverse/scripts/interactive_python_unit_tests.bat
@echo off setlocal set KIT_DIR=%~dp0\..\extern\nvidia\_build\target-deps\kit-sdk call "%KIT_DIR%\kit.exe" --enable omni.kit.test --dev --/app/enableStdoutOutput=0 --/exts/omni.kit.test/testExts/0='cesium.omniverse' --ext-folder "%KIT_DIR%/extscore" --ext-folder "%KIT_DIR%/exts" --ext-folder "%KIT_DIR%/apps" --ext-folder "%~dp0/../exts" --/exts/omni.kit.test/testExtApp="%~dp0/../apps/cesium.omniverse.dev.kit" --/exts/omni.kit.test/testExtOutputPath="%~dp0/../_testoutput" --portable-root "%KIT_DIR%/" --/telemetry/mode=test %*
CesiumGS/cesium-omniverse/scripts/generate_coverage.sh
#! /bin/bash # make sure we're in the root dir of the repo cd `dirname "${BASH_SOURCE[0]}"`/.. echo "Building with coverage enabled" cmake -B build-debug -D CMAKE_BUILD_TYPE=Debug -D CESIUM_OMNI_ENABLE_COVERAGE=true cmake --build build-debug --target install --parallel 8 # reset the debug build to have coverage disabled, otherwise future builds will still have it cmake -B build-debug -D CMAKE_BUILD_TYPE=Debug -D CESIUM_OMNI_ENABLE_COVERAGE=false echo "removing old coverage files" find . -name '*.gcda' -delete echo "Starting tests extension, please exit manually any time after omniverse has fully loaded" ./extern/nvidia/_build/target-deps/kit-sdk/kit ./apps/cesium.omniverse.cpp.tests.runner.kit > /dev/null echo "Gathering coverage data" # delete GCDA files after processing # print text output # generate HTML report with annotated source code mkdir -p coverage gcovr --delete --txt --html-details "coverage/index.html" --filter=src --filter=include echo "opening report" open coverage/index.html
CesiumGS/cesium-omniverse/scripts/generate_third_party_license_json.py
#!/usr/bin/env python3 import json import os import shlex import subprocess import argparse from typing import List import sys from pathlib import Path def main(argv: List[str]): args = parse_args(argv) project_dir = args.project_dir build_dir = args.build_dir libraries_to_skip = args.skip.split(',') cmd = "conan info {} -if {} -j".format(build_dir, os.path.join(build_dir, 'Conan_Packages')) cmd = shlex.split(cmd, posix=(os.name == 'posix')) try: output = subprocess.check_output(cmd).decode('utf-8') json_output = output.split(os.linesep, 2)[1] third_party_json = json.loads(json_output) except subprocess.CalledProcessError as error: cmd_string = ' '.join(error.cmd) raise RuntimeError('Conan command \'{}\' failed with error {}. Third party JSON creation aborted.' .format(cmd_string, error.returncode)) third_party_json = generate_conan_third_party_json( third_party_json, libraries_to_skip) third_party_extra_json = json.loads(Path(project_dir).joinpath( 'ThirdParty.extra.json').read_text()) # Handle ThirdParty.extra.json for element in third_party_extra_json: if 'override' in element: found_match = False for match in third_party_json: if match['name'] == element['name']: found_match = True break if found_match: del element['override'] third_party_json.remove(match) combined = {**match, **element} third_party_json.append(combined) else: raise RuntimeError('Could not find library to override: \'{}\'. Third party JSON creation aborted.' .format(element.name)) else: third_party_json.append(element) third_party_json.sort(key=lambda obj: obj['name'].lower()) third_party_json_path = os.path.join(project_dir, 'ThirdParty.json') with open(third_party_json_path, 'w', newline='\n') as json_file: json.dump(third_party_json, json_file, indent=4) json_file.write('\n') def parse_args(argv: List[str]): parser = argparse.ArgumentParser( description='Create third party license json from Conan info and ThirdParty.extra.json.' ) parser.add_argument('--project-dir', help='The project directory.', action='store', required='true' ) parser.add_argument('--build-dir', help='The CMake build directory. From CMake variable PROJECT_BINARY_DIR.', action='store', required='true' ) parser.add_argument('--skip', help='Comma separated list of libraries to skip.', action='store', ) return parser.parse_args(argv) def generate_conan_third_party_json(third_party_json, libraries_to_skip): result = [] for library in third_party_json: # skip the `conanfile` object, as its NOT a real third party library if library['reference'] == 'conanfile.txt': continue display_name = library['display_name'] url = library['homepage'] license = library['license'] licenses = [] for lc in license: licenses.extend(lc.split(', ')) display_name_pieces = display_name.split('/') name = display_name_pieces[0] version = display_name_pieces[1] # skip libraries that aren't included in the executable if name in libraries_to_skip: continue result.append({ 'name': name, 'license': licenses, 'version': version, 'url': url }) return result if __name__ == '__main__': main(sys.argv[1:])
CesiumGS/cesium-omniverse/scripts/build_package_windows.bat
@echo off rmdir /s /q build-package if %errorlevel% neq 0 exit /b %errorlevel% cmd /c cmake -B build-package -D CMAKE_CONFIGURATION_TYPES=Release -D CESIUM_OMNI_ENABLE_TESTS=OFF -D CESIUM_OMNI_ENABLE_DOCUMENTATION=OFF -D CESIUM_OMNI_ENABLE_SANITIZERS=OFF -D CESIUM_OMNI_ENABLE_LINTERS=OFF if %errorlevel% neq 0 exit /b %errorlevel% cmd /c cmake --build build-package --config Release if %errorlevel% neq 0 exit /b %errorlevel% cmd /c cmake --build build-package --target install --config Release if %errorlevel% neq 0 exit /b %errorlevel% cmd /c cmake --build build-package --target package --config Release if %errorlevel% neq 0 exit /b %errorlevel%
CesiumGS/cesium-omniverse/scripts/vscode_build_launcher.bat
:: Initialize the MSVC C++ development environment before running the python script :: This ensures that environment variables are populated and CMake can find cl.exe when using the Ninja generator @echo off :: Check if vswhere is in the path already (e.g. if installed with chocolatey) where /q vswhere if %ERRORLEVEL% equ 0 ( :: Found vswhere, now get the full path for /f "delims=" %%i in ('where vswhere') do set vswhere_path="%%i" ) else ( :: Otherwise look for vswhere in the Visual Studio Installer directory set vswhere_path="%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" ) if not exist %vswhere_path% ( echo Could not find vswhere.exe exit /b 1 ) echo vswhere.exe path: %vswhere_path% :: Find vsdevcmd.bat in the latest Visual Studio installation :: See https://github.com/microsoft/vswhere/wiki/Find-VC for /f "usebackq tokens=*" %%i in (`%vswhere_path% -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath`) do set vsdevcmd_path="%%i\Common7\Tools\vsdevcmd.bat" if not exist %vsdevcmd_path% ( echo "Could not find vsdevcmd.bat" exit /b 1 ) echo vsdevcmd.bat path: %vsdevcmd_path% :: Call vsdevcmd.bat. This will start the developer command prompt and populate MSVC environment variables. call %vsdevcmd_path% -arch=x64 -host_arch=x64 :: Now run our python script python3 %~dp0\vscode_build.py %*
CesiumGS/cesium-omniverse/scripts/clang_format.py
#!/usr/bin/env python3 import argparse import sys import subprocess import shutil import shlex from utils import utils from pathlib import Path from typing import List def clang_format_on_path(clang_format_binary: str, absolute_path: Path) -> str: cmd = "{} -style=file {}".format(shlex.quote(clang_format_binary), shlex.quote(str(absolute_path))) cmd = shlex.split(cmd) result = subprocess.check_output(cmd) return result.decode("utf-8", "replace") def clang_format_in_place(clang_format_binary: str, absolute_path: Path): cmd = "{} -style=file -i {}".format(shlex.quote(clang_format_binary), shlex.quote(str(absolute_path))) cmd = shlex.split(cmd) subprocess.check_output(cmd) def parse_args(av: List[str]): parser = argparse.ArgumentParser(description="Run / check clang-formatting.") parser.add_argument( "--clang-format-executable", help="Specific clang-format binary to use.", action="store", required=False ) parser.add_argument( "--source-directories", help='Directories (relative to project root) to recursively scan for cpp files (e.g "src", "include"...)', nargs="+", required=True, ) run_type = parser.add_mutually_exclusive_group(required=True) run_type.add_argument( "--fix", help="Apply clang-format formatting to source in-place (destructive)", action="store_true" ) run_type.add_argument("--check", help="Check if source matches clang-format rules", action="store_true") scope_type = parser.add_mutually_exclusive_group(required=True) scope_type.add_argument("--all", help="Process all valid source files.", action="store_true") scope_type.add_argument("--staged", help="Process only staged source files.", action="store_true") return parser.parse_args(av) def main(av: List[str]): if not shutil.which("git"): raise RuntimeError("Could not find git in path") project_root_directory = utils.get_project_root() args = parse_args(av) # Use user provided clang_format binary if provided clang_format_binary = args.clang_format_executable if clang_format_binary: clang_format_binary = shutil.which(clang_format_binary) if not clang_format_binary: clang_format_binary = shutil.which("clang-format") if not clang_format_binary: raise RuntimeError("Could not find clang-format in system path") mode = "all" if args.all else "staged" source_directories = args.source_directories # Generate list of source_files to check / fix. source_files: List[utils.SourceFile] = utils.get_source_files(source_directories, args.all) failed_files: List[utils.FailedFile] = [] # Fix or check formatting for each file for src in source_files: absolute_path = project_root_directory.joinpath(src.relative_path) if args.check: old_text = ( absolute_path.read_text(encoding="utf-8") if not src.staged else utils.get_staged_file_text(src.relative_path) ) new_text = clang_format_on_path(clang_format_binary, absolute_path) diff = utils.unidiff_output(old_text, new_text) if diff != "": failed_files.append(utils.FailedFile(src.relative_path, diff)) else: clang_format_in_place(clang_format_binary, absolute_path) if len(source_files) == 0: print("clang-format ({} files): No files found, nothing to do.".format(mode)) sys.exit(0) if args.fix: print("Ran clang-format -style=file -i on {} files".format(mode)) sys.exit(0) if len(failed_files) == 0: print("clang-format ({} files) passes.".format(mode)) sys.exit(0) print("clang-format ({} files) failed on the following files: ".format(mode)) for failure in failed_files: print("{}".format(failure.relative_path)) print(failure.diff) sys.exit(len(failed_files)) if __name__ == "__main__": main(sys.argv[1:])
CesiumGS/cesium-omniverse/scripts/copy_from_dir.py
import sys from pathlib import Path from shutil import copy2 # Broken out for formatting reasons, since tabs within HEREDOCs will be output. usage_message = """Invalid arguments. Usage: copy_from_dir.py <glob-pattern> <source-dir-path> <destination-dir-path> Please fix your command and try again. """ def main(): if len(sys.argv) < 4: print(usage_message) return 1 glob_pattern: str = sys.argv[1] source_dir = Path(sys.argv[2]).resolve() dest_dir = Path(sys.argv[3]).resolve() print(f'Performing file copy with glob pattern "{glob_pattern}"') print(f"\tSource: {source_dir}") print(f"\tDestination: {dest_dir}\n") source_files = source_dir.glob(glob_pattern) for f in source_files: source_path = source_dir / f copy2(source_path, dest_dir, follow_symlinks=True) print(f"Copied {source_path}") return 0 if __name__ == "__main__": sys.exit(main())
CesiumGS/cesium-omniverse/scripts/utils/__init__.py
CesiumGS/cesium-omniverse/scripts/utils/utils.py
#!/usr/bin/env python3 import subprocess import shlex import os import glob import sys from pathlib import Path from typing import List, NamedTuple, Set import difflib CPP_EXTENSIONS = [".cpp", ".h", ".cxx", ".hxx", ".hpp", ".cc", ".inl"] def get_project_root() -> Path: try: cmd = shlex.split('git rev-parse --show-toplevel') output = subprocess.check_output( cmd).strip().decode('utf-8', 'replace') return Path(output) except subprocess.CalledProcessError: raise RuntimeError('command must be ran inside .git repo') def get_staged_git_files(project_root: Path) -> List[Path]: cmd = shlex.split("git diff --cached --name-only --diff-filter=ACMRT") paths = subprocess.check_output(cmd).decode('utf-8').splitlines() return [project_root.joinpath(p) for p in paths] def get_cmake_build_directory(project_root: Path): glob_pattern = project_root.joinpath("**/CMakeCache.txt").as_posix() results = glob.glob(glob_pattern, recursive=True) if len(results) == 0: err = "Could not find CMakeCache.txt in {}. Generate CMake configuration first.".format( project_root) raise RuntimeError(err) cmake_build_directory = os.path.realpath( os.path.join(project_root, results[0], "..")) return cmake_build_directory def run_cmake_target(cmake_build_directory, target): path = shlex.quote(cmake_build_directory) cmd = shlex.split("cmake --build {} --target {}".format(path, target)) run_command_and_echo_on_error(cmd) def run_command_and_echo_on_error(cmd: List[str]): try: subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as e: print("Command \"{}\" failed:".format(' '.join(cmd))) print(e.output.decode('utf-8')) sys.exit(1) class SourceFile(NamedTuple): relative_path: Path staged: bool class FailedFile(NamedTuple): relative_path: Path diff: str def get_source_files(source_directories: List[str], modeIsAll: bool) -> List[SourceFile]: project_root = get_project_root() staged_rel_paths = get_staged_rel_paths() source_files = [] for directory in source_directories: for extension in CPP_EXTENSIONS: glob_pattern = os.path.join( project_root, directory, "**/*" + extension) glob_results = glob.glob(glob_pattern, recursive=True) for abs_path in glob_results: rel_path = Path(abs_path).relative_to(project_root) source_files.append(SourceFile( rel_path, rel_path in staged_rel_paths)) return list(filter(lambda source_file: source_file.staged or modeIsAll, source_files)) def get_staged_rel_paths() -> Set[str]: cmd = shlex.split("git diff --cached --name-only --diff-filter=ACMRT") staged_rel_paths = subprocess.check_output(cmd) staged_rel_paths = staged_rel_paths.decode('utf-8', 'replace') return set([Path(path) for path in staged_rel_paths.splitlines()]) def get_staged_file_text(relative_path: Path) -> str: cmd = "git show :{}".format(shlex.quote(str(relative_path.as_posix()))) cmd = shlex.split(cmd) output = subprocess.check_output(cmd).decode('utf-8', 'replace') return output COLOR_SUPPORT = False try: import colorama colorama.init() COLOR_SUPPORT = True def color_diff(diff): for line in diff: if line.startswith('+'): yield colorama.Fore.GREEN + line + colorama.Fore.RESET elif line.startswith('-'): yield colorama.Fore.RED + line + colorama.Fore.RESET elif line.startswith('^'): yield colorama.Fore.BLUE + line + colorama.Fore.RESET else: yield line except ImportError: pass def unidiff_output(expected: str, actual: str): expected = expected.splitlines(1) actual = actual.splitlines(1) diff = difflib.unified_diff(expected, actual) if COLOR_SUPPORT: diff = color_diff(diff) return ''.join(diff)
CesiumGS/cesium-omniverse/include/cesium/omniverse/CesiumOmniverse.h
#pragma once #include "cesium/omniverse/AssetTroubleshootingDetails.h" #include "cesium/omniverse/RenderStatistics.h" #include "cesium/omniverse/SetDefaultTokenResult.h" #include "cesium/omniverse/TokenTroubleshootingDetails.h" #include <carb/Interface.h> #include <cstdint> #include <memory> #include <optional> #include <vector> namespace cesium::omniverse { class CesiumIonSession; struct ViewportApi { double viewMatrix[16]; // NOLINT(modernize-avoid-c-arrays) double projMatrix[16]; // NOLINT(modernize-avoid-c-arrays) double width; double height; }; class ICesiumOmniverseInterface { public: CARB_PLUGIN_INTERFACE("cesium::omniverse::ICesiumOmniverseInterface", 0, 0); /** * @brief Call this on extension startup. * * @param cesiumExtensionLocation Path to the Cesium Omniverse extension location. */ virtual void onStartup(const char* cesiumExtensionLocation) noexcept = 0; /** * @brief Call this on extension shutdown. */ virtual void onShutdown() noexcept = 0; /** * @brief Reloads a tileset. * * @param tilesetPath The tileset sdf path. If there's no tileset with this path nothing happens. */ virtual void reloadTileset(const char* tilesetPath) noexcept = 0; /** * @brief Updates all tilesets this frame. * * @param viewports The viewports. * @param count The number of viewports. * @param waitForLoadingTiles Whether to wait for all tiles to load before continuing. */ virtual void onUpdateFrame(const ViewportApi* viewports, uint64_t count, bool waitForLoadingTiles) noexcept = 0; /** * @brief Updates the reference to the USD stage for the C++ layer. * * @param stageId The id of the current stage. */ virtual void onUsdStageChanged(long stageId) noexcept = 0; /** * @brief Connects to Cesium ion. */ virtual void connectToIon() noexcept = 0; /** * @brief Gets the active Cesium ion session. */ virtual std::optional<std::shared_ptr<CesiumIonSession>> getSession() noexcept = 0; /** * @brief Get the path of the active Cesium ion server. */ virtual std::string getServerPath() noexcept = 0; /** * @brief Gets all Cesium ion sessions. */ virtual std::vector<std::shared_ptr<CesiumIonSession>> getSessions() noexcept = 0; /** * @brief Get all Cesium ion server paths. */ virtual std::vector<std::string> getServerPaths() noexcept = 0; /** * @brief Gets the last result with code and message of setting the default token. * * @return A struct with a code and message. 0 is successful. */ virtual SetDefaultTokenResult getSetDefaultTokenResult() noexcept = 0; /** * @brief Boolean to check if the default token is set. * * @return True if the default token is set. */ virtual bool isDefaultTokenSet() noexcept = 0; /** * @brief Creates a new token using the specified name. * * @param name The name for the new token. */ virtual void createToken(const char* name) noexcept = 0; /** * @brief Selects an existing token associated with the logged in account. * * @param id The ID of the selected token. */ virtual void selectToken(const char* id, const char* token) noexcept = 0; /** * @brief Used for the specify token action by the set project default token window. * * @param token The desired token. */ virtual void specifyToken(const char* token) noexcept = 0; virtual std::optional<AssetTroubleshootingDetails> getAssetTroubleshootingDetails() noexcept = 0; virtual std::optional<TokenTroubleshootingDetails> getAssetTokenTroubleshootingDetails() noexcept = 0; virtual std::optional<TokenTroubleshootingDetails> getDefaultTokenTroubleshootingDetails() noexcept = 0; virtual void updateTroubleshootingDetails( const char* tilesetPath, int64_t tilesetIonAssetId, uint64_t tokenEventId, uint64_t assetEventId) noexcept = 0; virtual void updateTroubleshootingDetails( const char* tilesetPath, int64_t tilesetIonAssetId, int64_t rasterOverlayIonAssetId, uint64_t tokenEventId, uint64_t assetEventId) noexcept = 0; /** * @brief Prints the Fabric stage. For debugging only. * * @returns A string representation of the Fabric stage. */ virtual std::string printFabricStage() noexcept = 0; /** * @brief Get render statistics. For debugging only. * * @returns Object containing render statistics. */ virtual RenderStatistics getRenderStatistics() noexcept = 0; virtual bool creditsAvailable() noexcept = 0; virtual std::vector<std::pair<std::string, bool>> getCredits() noexcept = 0; virtual void creditsStartNextFrame() noexcept = 0; virtual bool isTracingEnabled() noexcept = 0; /** * @brief Clear the asset accessor cache. */ virtual void clearAccessorCache() = 0; }; } // namespace cesium::omniverse
CesiumGS/cesium-omniverse/tests/CMakeLists.txt
add_subdirectory(bindings) add_subdirectory(src) add_subdirectory(include) add_test(NAME tests_extension COMMAND extern/nvidia/_build/target-deps/kit-sdk/kit ./apps/cesium.omniverse.cpp.tests.runner.kit)
CesiumGS/cesium-omniverse/tests/src/ExampleTests.cpp
/* * A collection of simple tests to demonstrate Doctest */ #include "testUtils.h" #include <doctest/doctest.h> #include <array> #include <cstdint> #include <iostream> #include <list> #include <stdexcept> #include <vector> #include <yaml-cpp/yaml.h> const std::string CONFIG_PATH = "tests/configs/exampleConfig.yaml"; // Test Suites are not required, but this sort of grouping makes it possible // to select which tests do/don't run via command line options TEST_SUITE("Example Tests") { // ---------------------------------------------- // Basic Tests // ---------------------------------------------- TEST_CASE("The most basic test") { CHECK(1 + 1 == 2); } TEST_CASE("Demonstrating Subcases") { // This initialization is shared between all subcases int x = 1; // Note that these two subcases run independantly of each other! SUBCASE("Increment") { x += 1; CHECK(x == 2); } SUBCASE("Decrement") { x -= 1; CHECK(x == 0); } // Flow returns here after each independant subcase, so we can test // shared effects here CHECK(x != 1); } // A few notes on subcases: // - You can nest subcases // - Subcases work by creating multiple calls to the higher level case, // where each call proceeds to only one of the subcases. If you generate // excessive subcases, watch out for a stack overflow. void runPositiveCheck(int64_t val) { // helper function for parameterized test method 1 CHECK(val > 0); } TEST_CASE("Demonstrate Parameterized Tests - method 1") { // Generate the data you want the tests to iterate over std::list<uint32_t> dataContainer = {42, 64, 8675309, 1024}; for (auto i : dataContainer) { CAPTURE(i); runPositiveCheck(i); } } TEST_CASE("Demonstrate Parameterized Tests - method 2") { // Generate the data you want the tests to iterate over uint32_t item; std::list<uint32_t> dataContainer = {42, 64, 8675309, 1024}; // This macro from doctestUtils.h will generate a subcase per datum DOCTEST_VALUE_PARAMETERIZED_DATA(item, dataContainer); // this check will now be run for each datum CHECK(item > 0); } // ---------------------------------------------- // YAML Config Examples // ---------------------------------------------- std::string transmogrifier(const std::string& s) { // an example function with differing output for some scenarios if (s == "scenario2") { return "bar"; } return "foo"; } void checkAgainstExpectedResults(const std::string& scenarioName, const YAML::Node& expectedResults) { // we have to specify the type of the desired data from the config via as() CHECK(3.14159 == expectedResults["pi"].as<double>()); CHECK(2 == expectedResults["onlyEvenPrime"].as<int>()); // as() does work for some non-scalar types, such as vectors, lists, and maps // for adding custom types to the config, see: // https://github.com/jbeder/yaml-cpp/wiki/Tutorial#converting-tofrom-native-data-types const auto fib = expectedResults["fibonacciSeq"].as<std::vector<int>>(); CHECK(fib[2] + fib[3] == fib[4]); // More complicated checks can be done with helper functions that take the scenario as input CHECK(transmogrifier(scenarioName) == expectedResults["transmogrifierOutput"].as<std::string>()); } TEST_CASE("Use a config file to detail multiple scenarios") { YAML::Node configRoot = YAML::LoadFile(CONFIG_PATH); // The config file has default parameters and // an override for one or more scenarios std::vector<std::string> scenarios = {"scenario1", "scenario2", "scenario3"}; for (const auto& s : scenarios) { ConfigMap conf = getScenarioConfig(s, configRoot); checkAgainstExpectedResults(s, conf); } } // ---------------------------------------------- // Misc. // ---------------------------------------------- TEST_CASE("A few other useful macros") { // The most common test macro is CHECK, but others are available // Here are just a few // Any failures here will prevent the rest of the test from running REQUIRE(0 == 0); // Make sure the enclosed code does/doesn't throw an exception CHECK_THROWS(throw "test exception!"); CHECK_NOTHROW(if (false) throw "should not throw"); // Prints a warning if the assert fails, but does not fail the test WARN(true); } }
CesiumGS/cesium-omniverse/tests/src/GltfTests.cpp
#include "testUtils.h" #include "cesium/omniverse/FabricMaterialInfo.h" #include "cesium/omniverse/FabricVertexAttributeAccessors.h" #include "cesium/omniverse/GltfUtil.h" #include <CesiumGltf/Material.h> #include <CesiumGltf/MeshPrimitive.h> #include <CesiumGltf/Model.h> #include <CesiumGltfReader/GltfReader.h> #include <doctest/doctest.h> #include <cstddef> #include <cstdio> #include <filesystem> #include <fstream> #include <iostream> #include <optional> #include <stdexcept> #include <string> #include <vector> #include <gsl/span> #include <yaml-cpp/yaml.h> using namespace cesium::omniverse; const std::string ASSET_DIR = "tests/testAssets/gltfs"; const std::string CONFIG_PATH = "tests/configs/gltfConfig.yaml"; // simplifies casting when comparing some material queries to expected output from config bool operator==(const glm::dvec3& v3, const std::vector<double>& v) { return v.size() == 3 && v3[0] == v[0] && v3[1] == v[1] && v3[2] == v[2]; } TEST_SUITE("Test GltfUtil") { void checkGltfExpectedResults(const std::filesystem::path& gltfFileName, const YAML::Node& expectedResults) { // --- Load Gltf --- std::ifstream gltfStream(gltfFileName, std::ifstream::binary); gltfStream.seekg(0, std::ios::end); auto gltfFileLength = gltfStream.tellg(); gltfStream.seekg(0, std::ios::beg); std::vector<std::byte> gltfBuf(static_cast<uint64_t>(gltfFileLength)); gltfStream.read((char*)&gltfBuf[0], gltfFileLength); CesiumGltfReader::GltfReader reader; auto gltf = reader.readGltf( gsl::span(reinterpret_cast<const std::byte*>(gltfBuf.data()), static_cast<uint64_t>(gltfFileLength))); if (!gltf.errors.empty()) { for (const auto& err : gltf.errors) { std::cerr << err; } throw std::runtime_error("failed to parse model"); } // gltf.model is a std::optional<CesiumGltf::Model>, make sure it exists if (!(gltf.model && gltf.model->meshes.size() > 0)) { throw std::runtime_error("test model is empty"); } // --- Begin checks --- const auto& prim = gltf.model->meshes[0].primitives[0]; const auto& model = *gltf.model; CHECK(GltfUtil::hasNormals(model, prim, false) == expectedResults["hasNormals"].as<bool>()); CHECK(GltfUtil::hasTexcoords(model, prim, 0) == expectedResults["hasTexcoords"].as<bool>()); CHECK( GltfUtil::hasRasterOverlayTexcoords(model, prim, 0) == expectedResults["hasRasterOverlayTexcoords"].as<bool>()); CHECK(GltfUtil::hasVertexColors(model, prim, 0) == expectedResults["hasVertexColors"].as<bool>()); CHECK(GltfUtil::hasMaterial(prim) == expectedResults["hasMaterial"].as<bool>()); // material tests if (GltfUtil::hasMaterial(prim)) { const auto& matInfo = GltfUtil::getMaterialInfo(model, prim); CHECK(matInfo.alphaCutoff == expectedResults["alphaCutoff"].as<double>()); CHECK(matInfo.alphaMode == static_cast<FabricAlphaMode>(expectedResults["alphaMode"].as<int32_t>())); CHECK(matInfo.baseAlpha == expectedResults["baseAlpha"].as<double>()); CHECK(matInfo.baseColorFactor == expectedResults["baseColorFactor"].as<std::vector<double>>()); CHECK(matInfo.emissiveFactor == expectedResults["emissiveFactor"].as<std::vector<double>>()); CHECK(matInfo.metallicFactor == expectedResults["metallicFactor"].as<double>()); CHECK(matInfo.roughnessFactor == expectedResults["roughnessFactor"].as<double>()); CHECK(matInfo.doubleSided == expectedResults["doubleSided"].as<bool>()); CHECK(matInfo.hasVertexColors == expectedResults["hasVertexColors"].as<bool>()); } // Accessor smoke tests PositionsAccessor positions; IndicesAccessor indices; positions = GltfUtil::getPositions(model, prim); CHECK(positions.size() > 0); indices = GltfUtil::getIndices(model, prim, positions); CHECK(indices.size() > 0); if (GltfUtil::hasNormals(model, prim, false)) { CHECK(GltfUtil::getNormals(model, prim, positions, indices, false).size() > 0); } if (GltfUtil::hasVertexColors(model, prim, 0)) { CHECK(GltfUtil::getVertexColors(model, prim, 0).size() > 0); } if (GltfUtil::hasTexcoords(model, prim, 0)) { CHECK(GltfUtil::getTexcoords(model, prim, 0).size() > 0); } if (GltfUtil::hasRasterOverlayTexcoords(model, prim, 0)) { CHECK(GltfUtil::getRasterOverlayTexcoords(model, prim, 0).size() > 0); } CHECK(GltfUtil::getExtent(model, prim) != std::nullopt); } TEST_CASE("Default getter smoke tests") { CHECK_NOTHROW(GltfUtil::getDefaultMaterialInfo()); CHECK_NOTHROW(GltfUtil::getDefaultTextureInfo()); } TEST_CASE("Check helper functions on various models") { std::vector<std::string> gltfFiles; // get list of gltf test files for (auto const& i : std::filesystem::directory_iterator(ASSET_DIR)) { std::filesystem::path fname = i.path().filename(); if (fname.extension() == ".gltf" || fname.extension() == ".glb") { gltfFiles.push_back(fname.string()); } } // parse test config yaml const auto configRoot = YAML::LoadFile(CONFIG_PATH); const auto basePath = std::filesystem::path(ASSET_DIR); for (auto const& fileName : gltfFiles) { // attach filename to any failed checks CAPTURE(fileName); const auto conf = getScenarioConfig(fileName, configRoot); // the / operator concatonates file paths checkGltfExpectedResults(basePath / fileName, conf); } } }
CesiumGS/cesium-omniverse/tests/src/ObjectPoolTests.cpp
#include "testUtils.h" #include <cesium/omniverse/ObjectPool.h> #include <doctest/doctest.h> #include <algorithm> #include <cstdint> #include <cstdlib> #include <memory> #include <queue> constexpr int MAX_TESTED_POOL_SIZE = 1024; // The max size pool to randomly generate // ObjectPool is a virtual class so we cannot directly instantiate it for // testing, and instantiating the classes that implement it (FabricGeometryPool, // FabricMaterialPool, and FabricTexturePool) requires mocking more complicated // classes, so we create a bare-bones class here. class MockObject { public: MockObject(uint64_t objectId) { id = objectId; active = false; }; uint64_t id; bool active; }; class MockObjectPool final : public cesium::omniverse::ObjectPool<MockObject> { protected: std::shared_ptr<MockObject> createObject(uint64_t objectId) const override { return std::make_shared<MockObject>(objectId); }; void setActive(MockObject* obj, bool active) const override { obj->active = active; }; }; void testRandomSequenceOfCmds(MockObjectPool& opl, int numEvents, bool setCap) { // Track the objects we've acquired so we can release them std::queue<std::shared_ptr<MockObject>> activeObjects; // The total number of acquires performed, which becomes the minimum // expected size of the pool auto maxActiveCount = opl.getNumberActive(); // Perform a random sequence of acquires/releases while // ensuring we only release what we've acquired for (int i = 0; i < numEvents; ++i) { if (!activeObjects.empty() && rand() % 2 == 0) { opl.release(activeObjects.front()); activeObjects.pop(); } else { activeObjects.push(opl.acquire()); } maxActiveCount = std::max(maxActiveCount, activeObjects.size()); if (setCap && i == numEvents / 2) { // At the halfway point, try resetting the capacity // Ensure the new size is GTE, avoiding rollover uint64_t guaranteedGTE = std::max(opl.getCapacity(), opl.getCapacity() + static_cast<uint64_t>(rand() % MAX_TESTED_POOL_SIZE)); opl.setCapacity(guaranteedGTE); } } auto numActive = activeObjects.size(); // Ensure our math matches CHECK(opl.getNumberActive() == numActive); // Make sure there's capacity for all objects CHECK(opl.getCapacity() >= numActive + opl.getNumberInactive()); CHECK(opl.getCapacity() >= maxActiveCount); // The percent active is calculated out of the pool's total capacity // which must be gte our max observed active count float expectedPercentActive; if (maxActiveCount != 0) { expectedPercentActive = (float)numActive / (float)maxActiveCount; } else { expectedPercentActive = 1; } CHECK(opl.computePercentActive() <= expectedPercentActive); } // ---- Begin tests ---- TEST_SUITE("Test ObjectPool") { TEST_CASE("Test initializiation") { MockObjectPool opl = MockObjectPool(); SUBCASE("Initial capacity") { CHECK(opl.getCapacity() == 0); } SUBCASE("Initial active") { CHECK(opl.getNumberActive() == 0); } SUBCASE("Initial inactive") { CHECK(opl.getNumberInactive() == 0); } SUBCASE("Initial percent active") { // Initial percent active is assumed to be 100% in parts of the code CHECK(opl.computePercentActive() == 1); } } TEST_CASE("Test acquire/release") { MockObjectPool opl = MockObjectPool(); // Generate a random number of actions to perform int numEvents; std::list<int> randEventCounts; fillWithRandomInts(randEventCounts, 0, MAX_TESTED_POOL_SIZE, NUM_TEST_REPETITIONS); SUBCASE("Test repeated acquires") { DOCTEST_VALUE_PARAMETERIZED_DATA(numEvents, randEventCounts); for (int i = 0; i < numEvents; ++i) { opl.acquire(); } CHECK(opl.getNumberActive() == numEvents); CHECK(opl.getCapacity() >= numEvents); } SUBCASE("Test random acquire/release patterns") { DOCTEST_VALUE_PARAMETERIZED_DATA(numEvents, randEventCounts); testRandomSequenceOfCmds(opl, numEvents, false); } SUBCASE("Test random setting capacity") { DOCTEST_VALUE_PARAMETERIZED_DATA(numEvents, randEventCounts); testRandomSequenceOfCmds(opl, numEvents, true); } } }
CesiumGS/cesium-omniverse/tests/src/tilesetTests.cpp
#include "tilesetTests.h" #include "testUtils.h" #include "cesium/omniverse/AssetRegistry.h" #include "cesium/omniverse/Context.h" #include "cesium/omniverse/OmniTileset.h" #include "cesium/omniverse/UsdUtil.h" #include <CesiumUsdSchemas/tileset.h> #include <carb/dictionary/DictionaryUtils.h> #include <carb/events/IEvents.h> #include <doctest/doctest.h> #include <omni/kit/IApp.h> #include <memory> pxr::SdfPath endToEndTilesetPath; bool endToEndTilesetLoaded = false; carb::events::ISubscriptionPtr endToEndTilesetSubscriptionPtr; class TilesetLoadListener; std::unique_ptr<TilesetLoadListener> tilesetLoadListener; using namespace cesium::omniverse; class TilesetLoadListener final : public carb::events::IEventListener { public: uint64_t refCount = 0; void onEvent(carb::events::IEvent* e [[maybe_unused]]) override { endToEndTilesetLoaded = true; }; uint64_t addRef() override { return ++refCount; }; uint64_t release() override { return --refCount; }; }; void setUpTilesetTests(Context* pContext, const pxr::SdfPath& rootPath) { // Create a listener for tileset load events auto app = carb::getCachedInterface<omni::kit::IApp>(); auto bus = app->getMessageBusEventStream(); auto tilesetLoadedEvent = carb::events::typeFromString("cesium.omniverse.TILESET_LOADED"); tilesetLoadListener = std::make_unique<TilesetLoadListener>(); endToEndTilesetSubscriptionPtr = bus->createSubscriptionToPushByType(tilesetLoadedEvent, tilesetLoadListener.get()); // Load a local test tileset endToEndTilesetPath = UsdUtil::makeUniquePath(pContext->getUsdStage(), rootPath, "endToEndTileset"); auto endToEndTileset = UsdUtil::defineCesiumTileset(pContext->getUsdStage(), endToEndTilesetPath); std::string tilesetFilePath = "file://" TEST_WORKING_DIRECTORY "/tests/testAssets/tilesets/Tileset/tileset.json"; endToEndTileset.GetSourceTypeAttr().Set(pxr::TfToken("url")); endToEndTileset.GetUrlAttr().Set(tilesetFilePath); } void cleanUpTilesetTests(const pxr::UsdStageRefPtr& stage) { endToEndTilesetSubscriptionPtr->unsubscribe(); stage->RemovePrim(endToEndTilesetPath); tilesetLoadListener.reset(); } TEST_SUITE("Tileset tests") { TEST_CASE("End to end test") { // set by the TilesetLoadListener when any tileset successfully loads CHECK(endToEndTilesetLoaded); } }
CesiumGS/cesium-omniverse/tests/src/testUtils.cpp
#include "testUtils.h" #include <unordered_map> #include <variant> #include <yaml-cpp/node/detail/iterator_fwd.h> #include <yaml-cpp/node/node.h> #include <yaml-cpp/node/parse.h> #include <yaml-cpp/node/type.h> #include <yaml-cpp/yaml.h> void fillWithRandomInts(std::list<int>& lst, int min, int max, int n) { for (int i = 0; i < n; ++i) { // The odd order here is to avoid issues with rollover int x = (rand() % (max - min)) + min; lst.push_back(x); } } ConfigMap getScenarioConfig(const std::string& scenario, YAML::Node configRoot) { ConfigMap sConfig = ConfigMap(); const auto& defaultConfig = configRoot["scenarios"]["default"]; for (YAML::const_iterator it = defaultConfig.begin(); it != defaultConfig.end(); ++it) { sConfig[it->first.as<std::string>()] = it->second; } const auto& overrides = configRoot["scenarios"][scenario]; for (auto it = overrides.begin(); it != overrides.end(); ++it) { sConfig[it->first.as<std::string>()] = it->second; } return sConfig; }
CesiumGS/cesium-omniverse/tests/src/CMakeLists.txt
include(Macros) glob_files(SOURCES "${CMAKE_CURRENT_LIST_DIR}/*.cpp") get_property(ADDITIONAL_LIBRARIES GLOBAL PROPERTY NVIDIA_ADDITIONAL_LIBRARIES_PROPERTY) # cmake-format: off setup_lib( TARGET_NAME cesium.omniverse.cpp.tests.plugin TYPE # Carbonite Plugins needs to be shared libraries SHARED SOURCES ${SOURCES} INCLUDE_DIRS "${PROJECT_SOURCE_DIR}/tests/include" LIBRARIES CesiumOmniverseCore doctest::doctest yaml-cpp::yaml-cpp ADDITIONAL_LIBRARIES # Unfortunately we need this in both cesium.omniverse.plugin and CesiumOmniverseCore because we're bypassing # CMake's built-in dependency system "${ADDITIONAL_LIBRARIES}" CXX_FLAGS ${CESIUM_OMNI_CXX_FLAGS} CXX_FLAGS_DEBUG ${CESIUM_OMNI_CXX_FLAGS_DEBUG} CXX_DEFINES ${CESIUM_OMNI_CXX_DEFINES} CXX_DEFINES_DEBUG ${CESIUM_OMNI_CXX_DEFINES_DEBUG} ) # cmake-format: on
CesiumGS/cesium-omniverse/tests/src/CesiumOmniverseCppTests.cpp
#define CARB_EXPORTS #define DOCTEST_CONFIG_IMPLEMENT #define DOCTEST_CONFIG_IMPLEMENTATION_IN_DLL #define DOCTEST_CONFIG_SUPER_FAST_ASSERTS #include "CesiumOmniverseCppTests.h" #include "UsdUtilTests.h" #include "testUtils.h" #include "tilesetTests.h" #include "cesium/omniverse/Context.h" #include "cesium/omniverse/Logger.h" #include <carb/PluginUtils.h> #include <cesium/omniverse/UsdUtil.h> #include <doctest/doctest.h> #include <omni/fabric/IFabric.h> #include <omni/kit/IApp.h> #include <pxr/usd/sdf/path.h> #include <pxr/usd/usd/stage.h> #include <iostream> namespace cesium::omniverse::tests { class CesiumOmniverseCppTestsPlugin final : public ICesiumOmniverseCppTestsInterface { public: void onStartup(const char* cesiumExtensionLocation) noexcept override { _pContext = std::make_unique<Context>(cesiumExtensionLocation); } void onShutdown() noexcept override { _pContext = nullptr; } void setUpTests(long int stage_id) noexcept override { // This runs after the stage has been created, but at least one frame // before runAllTests. This is to allow time for USD notifications to // propogate, as prims cannot be created and used on the same frame. _pContext->getLogger()->info("Setting up Cesium Omniverse Tests with stage id: {}", stage_id); _pContext->onUsdStageChanged(stage_id); auto rootPath = cesium::omniverse::UsdUtil::getRootPath(_pContext->getUsdStage()); setUpUsdUtilTests(_pContext.get(), rootPath); setUpTilesetTests(_pContext.get(), rootPath); } void runAllTests() noexcept override { _pContext->getLogger()->info("Running Cesium Omniverse Tests"); // construct a doctest context doctest::Context context; // Some tests contain relative paths rooted in the top level project dir // so we set this as the working directory std::filesystem::path oldWorkingDir = std::filesystem::current_path(); std::filesystem::current_path(TEST_WORKING_DIRECTORY); // run test suites context.run(); // restore the previous working directory std::filesystem::current_path(oldWorkingDir); _pContext->getLogger()->info("Cesium Omniverse tests complete"); _pContext->getLogger()->info("Cleaning up after tests"); cleanUpAfterTests(); _pContext->getLogger()->info("Cesium Omniverse test prims removed"); } void cleanUpAfterTests() noexcept { // delete any test related prims here auto pUsdStage = _pContext->getUsdStage(); cleanUpUsdUtilTests(pUsdStage); cleanUpTilesetTests(pUsdStage); } private: std::unique_ptr<Context> _pContext; }; } // namespace cesium::omniverse::tests const struct carb::PluginImplDesc pluginImplDesc = { "cesium.omniverse.cpp.tests.plugin", "Cesium Omniverse Tests Plugin.", "Cesium", carb::PluginHotReload::eDisabled, "dev"}; #ifdef CESIUM_OMNI_CLANG #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments" #endif CARB_PLUGIN_IMPL(pluginImplDesc, cesium::omniverse::tests::CesiumOmniverseCppTestsPlugin) CARB_PLUGIN_IMPL_DEPS(omni::fabric::IFabric, omni::kit::IApp, carb::settings::ISettings) #ifdef CESIUM_OMNI_CLANG #pragma clang diagnostic pop #endif void fillInterface([[maybe_unused]] cesium::omniverse::tests::CesiumOmniverseCppTestsPlugin& iface) {}
CesiumGS/cesium-omniverse/tests/src/UsdUtilTests.cpp
#include "UsdUtilTests.h" #include "testUtils.h" #include "cesium/omniverse/Context.h" #include "cesium/omniverse/UsdUtil.h" #include <CesiumUsdSchemas/data.h> #include <CesiumUsdSchemas/georeference.h> #include <CesiumUsdSchemas/globeAnchorAPI.h> #include <CesiumUsdSchemas/ionRasterOverlay.h> #include <CesiumUsdSchemas/ionServer.h> #include <CesiumUsdSchemas/session.h> #include <CesiumUsdSchemas/tileset.h> #include <doctest/doctest.h> #include <glm/ext/matrix_double4x4.hpp> #include <pxr/usd/usdGeom/cube.h> #include <pxr/usd/usdGeom/xformCommonAPI.h> #include <pxr/usd/usdGeom/xformable.h> // define prim paths globally to cut down on repeated definitions // name the paths after the function to be tested so they can easily be paired up later pxr::SdfPath defineCesiumDataPath; pxr::SdfPath defineCesiumSessionPath; pxr::SdfPath defineCesiumGeoreferencePath; pxr::SdfPath defineCesiumTilesetPath; pxr::SdfPath defineCesiumIonRasterOverlayPath; pxr::SdfPath defineGlobeAnchorPath; pxr::CesiumSession getOrCreateCesiumSessionPrim; using namespace cesium::omniverse; using namespace cesium::omniverse::UsdUtil; const Context* pContext; void setUpUsdUtilTests(cesium::omniverse::Context* context, const pxr::SdfPath& rootPath) { // might as well name the prims after the function as well, to ensure uniqueness and clarity defineCesiumDataPath = rootPath.AppendChild(pxr::TfToken("defineCesiumData")); defineCesiumSessionPath = rootPath.AppendChild(pxr::TfToken("defineCesiumSession")); defineCesiumGeoreferencePath = rootPath.AppendChild(pxr::TfToken("defineCesiumGeoreference")); defineCesiumIonRasterOverlayPath = rootPath.AppendChild(pxr::TfToken("defineCesiumIonRasterOverlay")); defineCesiumTilesetPath = rootPath.AppendChild(pxr::TfToken("defineCesiumTileset")); defineGlobeAnchorPath = rootPath.AppendChild(pxr::TfToken("defineGlobeAnchor")); defineCesiumData(context->getUsdStage(), defineCesiumDataPath); defineCesiumSession(context->getUsdStage(), defineCesiumSessionPath); defineCesiumGeoreference(context->getUsdStage(), defineCesiumGeoreferencePath); defineCesiumTileset(context->getUsdStage(), defineCesiumTilesetPath); defineCesiumIonRasterOverlay(context->getUsdStage(), defineCesiumIonRasterOverlayPath); // defineGlobeAnchor(globeAnchorPath); getOrCreateCesiumSessionPrim = getOrCreateCesiumSession(context->getUsdStage()); pContext = context; } void cleanUpUsdUtilTests(const pxr::UsdStageRefPtr& stage) { // might as well name the prims after the function as well, to ensure uniqueness and clarity stage->RemovePrim(defineCesiumDataPath); stage->RemovePrim(defineCesiumSessionPath); stage->RemovePrim(defineCesiumGeoreferencePath); stage->RemovePrim(defineCesiumIonRasterOverlayPath); stage->RemovePrim(defineCesiumTilesetPath); stage->RemovePrim(defineGlobeAnchorPath); // stage->RemovePrim(globeAnchorPath); stage->RemovePrim(getOrCreateCesiumSessionPrim.GetPath()); } TEST_SUITE("UsdUtil tests") { TEST_CASE("Check expected initial state") { auto cesiumObjPath = pxr::SdfPath("/Cesium"); CHECK(primExists(pContext->getUsdStage(), cesiumObjPath)); // TODO can we check something invisible here too? CHECK(isPrimVisible(pContext->getUsdStage(), cesiumObjPath)); } TEST_CASE("Check glm/usd conversion functions") { glm::dmat4 matrix(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); // Round-trip conversion of usd/glm matrix CHECK(matrix == usdToGlmMatrix(glmToUsdMatrix(matrix))); } TEST_CASE("Tests that require prim creation") { auto primPath = makeUniquePath(pContext->getUsdStage(), getRootPath(pContext->getUsdStage()), "CesiumTestPrim"); auto prim = pContext->getUsdStage()->DefinePrim(primPath); // Intentionally try the same prim name auto cubePath = makeUniquePath(pContext->getUsdStage(), getRootPath(pContext->getUsdStage()), "CesiumTestPrim"); // Tests makeUniquePath actually returns unique paths CHECK(primPath.GetPrimPath() != cubePath.GetPrimPath()); auto cube = pxr::UsdGeomCube::Define(pContext->getUsdStage(), cubePath); auto xformApiCube = pxr::UsdGeomXformCommonAPI(cube); xformApiCube.SetRotate({30, 60, 90}); xformApiCube.SetScale({5, 12, 13}); xformApiCube.SetTranslate({3, 4, 5}); auto xformableCube = pxr::UsdGeomXformable(cube); pxr::GfMatrix4d cubeXform; bool xformStackResetNeeded [[maybe_unused]]; xformableCube.GetLocalTransformation(&cubeXform, &xformStackResetNeeded); CHECK(usdToGlmMatrix(cubeXform) == computePrimLocalToWorldTransform(pContext->getUsdStage(), cubePath)); pContext->getUsdStage()->RemovePrim(primPath); pContext->getUsdStage()->RemovePrim(cubePath); } TEST_CASE("Test UTF-8 path names") { for (int i = 0; i < NUM_TEST_REPETITIONS; ++i) { std::string randomUTF8String = "safe_name_test"; randomUTF8String.reserve(64); for (long unsigned int ii = 0; ii < randomUTF8String.capacity() - randomUTF8String.size(); ++ii) { char randChar = (char)(rand() % 0xE007F); randomUTF8String.append(&randChar); } auto safeUniquePath = makeUniquePath(pContext->getUsdStage(), getRootPath(pContext->getUsdStage()), randomUTF8String); pContext->getUsdStage()->DefinePrim(safeUniquePath); CHECK(primExists(pContext->getUsdStage(), safeUniquePath)); pContext->getUsdStage()->RemovePrim(safeUniquePath); CHECK_FALSE(primExists(pContext->getUsdStage(), safeUniquePath)); } } TEST_CASE("Cesium helper functions") { auto rootPath = getRootPath(pContext->getUsdStage()); CHECK(isCesiumData(pContext->getUsdStage(), defineCesiumDataPath)); CHECK(isCesiumSession(pContext->getUsdStage(), defineCesiumSessionPath)); CHECK(isCesiumGeoreference(pContext->getUsdStage(), defineCesiumGeoreferencePath)); CHECK(isCesiumTileset(pContext->getUsdStage(), defineCesiumTilesetPath)); CHECK(isCesiumIonRasterOverlay(pContext->getUsdStage(), defineCesiumIonRasterOverlayPath)); // CHECK(hasCesiumGlobeAnchor(pContext->getUsdStage(), globeAnchorPath)); CHECK(isCesiumSession(pContext->getUsdStage(), getOrCreateCesiumSessionPrim.GetPath())); } TEST_CASE("Smoke tests") { // functions for which we do not yet have better tests, // but we can at least verify they don't throw CHECK_NOTHROW(getDynamicTextureProviderAssetPathToken("foo")); CHECK_NOTHROW(getUsdUpAxis(pContext->getUsdStage())); CHECK(getUsdMetersPerUnit(pContext->getUsdStage()) > 0); } }
CesiumGS/cesium-omniverse/tests/configs/exampleConfig.yaml
--- # One way to use the config file is to generate multiple scenarios with # variations on some known parameters. If most of the scenarios have a # parameter at one particular value, it can make sense to establish that as # the default, then we only need to list the changes from that default. # See the gltf test config for a real use-case scenarios: default: # currently supported data types for the testUtils methods: # float pi : 3.14159 # int onlyEvenPrime : 2 # string transmogrifierOutput : "foo" # sequence fibonacciSeq : - 1 - 1 - 2 - 3 - 5 # an example override for a given item scenario2: transmogrifierOutput : "bar"
CesiumGS/cesium-omniverse/tests/configs/gltfConfig.yaml
--- # scenarios: default: hasNormals : True hasTexcoords : True hasRasterOverlayTexcoords : False hasVertexColors : False doubleSided : False # Material Attributes hasMaterial : True alphaMode : 0 alphaCutoff : 0.5 baseAlpha : 1.0 metallicFactor : 1.0 roughnessFactor : 1.0 baseColorTextureWrapS : 10497 # opengl enum for "repeat" baseColorTextureWrapT : 10497 emissiveFactor: - 0 - 0 - 0 baseColorFactor: - 1 - 1 - 1 # Note: all files should all be .glbs. Anything that uses or queries # accessors requires (included in some tests) requires a call to # CesiumGltfReader::resolveExternalData, which proved to be complicated to integrate. Duck.glb: hasTexcoords : True metallicFactor : 0 Mesh_Primitives_00.glb: hasNormals : False hasTexcoords : False baseColorFactor: - 0 - 1 - 0 Mesh_PrimitivesUV_00.glb: hasNormals : False hasTexcoords : False Mesh_PrimitivesUV_06.glb: hasVertexColors : True Mesh_PrimitivesUV_08.glb: hasVertexColors : True Material_07.glb: metallicFactor : 0.0 emissiveFactor : - 1 - 1 - 1 baseColorFactor : - 0.2 - 0.2 - 0.2 Material_AlphaBlend_05.glb: hasNormals : False hasTexcoords : True alphaMode : 2 baseAlpha : 0.7 Material_AlphaBlend_06.glb: hasNormals : False hasVertexColors : True hasTexcoords : True alphaMode : 2 baseAlpha : 0.7 Material_AlphaMask_04.glb: hasNormals : False hasTexcoords : True alphaMode : 1 alphaCutoff : 0.0 Material_AlphaMask_06.glb: hasNormals : False hasTexcoords : True alphaMode : 1 alphaCutoff : 0.6 baseAlpha : 0.7 Mesh_PrimitiveVertexColor_00.glb: hasMaterial : False hasTexcoords : False hasVertexColors : True Mesh_PrimitiveVertexColor_01.glb: hasMaterial : False hasTexcoords : False hasVertexColors : True Mesh_PrimitiveVertexColor_02.glb: hasMaterial : False hasTexcoords : False hasVertexColors : True Mesh_PrimitiveVertexColor_03.glb: hasMaterial : False hasTexcoords : False hasVertexColors : True Mesh_PrimitiveVertexColor_04.glb: hasMaterial : False hasTexcoords : False hasVertexColors : True Mesh_PrimitiveVertexColor_05.glb: hasMaterial : False hasTexcoords : False hasVertexColors : True
CesiumGS/cesium-omniverse/tests/bindings/PythonBindings.cpp
#include "CesiumOmniverseCppTests.h" #include <carb/BindingsPythonUtils.h> #ifdef CESIUM_OMNI_CLANG #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments" #endif CARB_BINDINGS("cesium.omniverse.cpp.tests.python") #ifdef CESIUM_OMNI_CLANG #pragma clang diagnostic pop #endif DISABLE_PYBIND11_DYNAMIC_CAST(cesium::omniverse::tests::ICesiumOmniverseCppTestsInterface) PYBIND11_MODULE(CesiumOmniverseCppTestsPythonBindings, m) { using namespace cesium::omniverse::tests; m.doc() = "pybind11 cesium.omniverse.cpp.tests bindings"; // clang-format off carb::defineInterfaceClass<ICesiumOmniverseCppTestsInterface>( m, "ICesiumOmniverseCppTestsInterface", "acquire_cesium_omniverse_tests_interface", "release_cesium_omniverse_tests_interface") .def("set_up_tests", &ICesiumOmniverseCppTestsInterface::setUpTests) .def("run_all_tests", &ICesiumOmniverseCppTestsInterface::runAllTests) .def("on_startup", &ICesiumOmniverseCppTestsInterface::onStartup) .def("on_shutdown", &ICesiumOmniverseCppTestsInterface::onShutdown); // clang-format on }
CesiumGS/cesium-omniverse/tests/bindings/CMakeLists.txt
include(Macros) glob_files(SOURCES "${CMAKE_CURRENT_LIST_DIR}/*.cpp") # cmake-format: off setup_python_module( PYTHON_DIR # Use the same Python version as Omniverse (Python 3.10) "${PROJECT_SOURCE_DIR}/extern/nvidia/_build/target-deps/python" TARGET_NAME CesiumOmniverseCppTestsPythonBindings SOURCES ${SOURCES} LIBRARIES cesium.omniverse.cpp.tests.plugin CXX_FLAGS ${CESIUM_OMNI_CXX_FLAGS} CXX_FLAGS_DEBUG ${CESIUM_OMNI_CXX_FLAGS_DEBUG} CXX_DEFINES ${CESIUM_OMNI_CXX_DEFINES} CXX_DEFINES_DEBUG ${CESIUM_OMNI_CXX_DEFINES_DEBUG} ) # cmake-format: on
CesiumGS/cesium-omniverse/tests/include/tilesetTests.h
#pragma once #include <pxr/usd/usd/common.h> namespace cesium::omniverse { class Context; } void setUpTilesetTests(cesium::omniverse::Context* pContext, const pxr::SdfPath& rootPath); void cleanUpTilesetTests(const pxr::UsdStageRefPtr& stage);
CesiumGS/cesium-omniverse/tests/include/CesiumOmniverseCppTests.h
#pragma once #include <carb/Interface.h> namespace cesium::omniverse::tests { class ICesiumOmniverseCppTestsInterface { public: CARB_PLUGIN_INTERFACE("cesium::omniverse::tests::ICesiumOmniverseCppTestsInterface", 0, 0); /** * @brief Call this on extension startup. * * @param cesiumExtensionLocation Path to the Cesium Omniverse extension location. */ virtual void onStartup(const char* cesiumExtensionLocation) noexcept = 0; /** * @brief Call this on extension shutdown. */ virtual void onShutdown() noexcept = 0; /** * @brief To be run at least one fram prior to `runAllTests` in order to * allow time for USD notifications to propogate. */ virtual void setUpTests(long int stage_id) noexcept = 0; /** * @brief Collects and runs all the doctest tests defined in adjacent .cpp files */ virtual void runAllTests() noexcept = 0; }; } // namespace cesium::omniverse::tests
CesiumGS/cesium-omniverse/tests/include/CMakeLists.txt
# replace a string in the utils header with the intended working dir for the test executable set(TEST_WORKING_DIRECTORY "${PROJECT_SOURCE_DIR}") configure_file("${CMAKE_CURRENT_LIST_DIR}/testUtils.h.in" "${CMAKE_CURRENT_LIST_DIR}/testUtils.h")
CesiumGS/cesium-omniverse/tests/include/UsdUtilTests.h
#pragma once #include <pxr/usd/usd/common.h> namespace cesium::omniverse { class Context; } void setUpUsdUtilTests(cesium::omniverse::Context* pContext, const pxr::SdfPath& rootPath); void cleanUpUsdUtilTests(const pxr::UsdStageRefPtr& stage);
CesiumGS/cesium-omniverse/docs/README.md
# Cesium for Omniverse Documentation ## Usage - [Developer Setup](./developer-setup/README.md) - [Release Guide](./release-guide/README.md) ## General Omniverse Tips - [Omniverse Connector & Live Sync for SketchUp](./connectors/README.md) - [Programmatically Changing Settings](./kit/README.md) - [Building USD On Ubuntu 22.04](./developer-setup/building_usd_on_ubuntu2204.md)
CesiumGS/cesium-omniverse/docs/onboarding/README.md
## What is Omniverse? Omniverse is a tool that provides an interface for various other tools to interact with a shared 3d environment. The core of this is a USD stage and a Fabric stage. The tools that interact with these stages do so via extensions. To better understand extensions and how they're defined, check out the [official Omniverse extension template](https://github.com/NVIDIA-Omniverse/kit-extension-template) for a "hello world" extension. There is also a similar [C++ extension template](https://github.com/NVIDIA-Omniverse/kit-extension-template-cpp). ### Our Extensions/Apps - Cesium for Omniverse ("The main extension") - Responsible for streaming geospatial data onto the stages, and providing the user interface. - Cesium Usd plugins - Required by the main extension to facilitatge interactions with the USD stage. - Cesium Powertools - Helpful additions for developers, such as one-click ways to open debug interfaces and print the fabric stage. - Cesium Cpp Tests - Tests of the C++ code underlying the main extension. For more info see [the testing guide](../testing-guide/README.md) - The Performance App - Used to get general timing of an interactive session. See [the testing guide](../testing-guide/README.md) for how to run. ## Project File Structure Some self-explanatory directories have been ommitted. - `apps` - Tools that use the extensions, such as the performance testing app, but are not themselves extensions - `docker` - Docker configuration for AlmaLinux 8 CI builds - `exts` - This is where extension code is kept. The file structure follows the pattern: ``` exts └── dot.separated.name ├── bin │ ├── libdot.separated.name.plugin.so └── dot └── separated └── name └── codeNeededByExtension └── __init__.py └── extension.py ``` - `genStubs.*`- auto-generates stub files for python bindings, which are not functionally required but greatly improve intellisense. - `src`/`include` - There are several `src`/`include` subdirs throughout the project, but this top level one is only for code used in the python bindings for the main extension. - `regenerate_schema.*` - changes to our usd schema require using this script. - `scripts` - useful scripts for development that do not contribute to any extension function. - `tests` - c++ related test code used by the Tests Extension. For python related test code, check `exts/cesium.omniverse/cesium/omniverse/tests`. For more details, see the [testing guide](../testing-guide/README.md)
CesiumGS/cesium-omniverse/docs/release-guide/README.md
# Releasing a new version of Cesium for Omniverse This is the process we follow when releasing a new version of Cesium for Omniverse on GitHub. 1. [Release a new version of Cesium for Omniverse Samples](#releasing-a-new-version-of-cesium-for-omniverse-samples). 2. Make sure the latest commit in `main` is passing CI. 3. Download the latest build from S3. In the AWS management console (InternalServices AWS account), go to the bucket [`cesium-builds/cesium-omniverse/main`](https://s3.console.aws.amazon.com/s3/buckets/cesium-builds?region=us-east-1&prefix=cesium-omniverse/main/&showversions=false), find the appropriate date and commit hash to download the AlmaLinux and Windows zip files (e.g. `CesiumGS-cesium-omniverse-linux-x86_64-xxxxxxx.zip` and `CesiumGS-cesium-omniverse-windows-x86_64-xxxxxxx.zip`) 4. Verify that the Linux package loads in USD Composer (see instructions below). 5. Verify that the Windows package loads in USD Composer (see instructions below). 6. Update the project `VERSION` in [CMakeLists.txt](../../CMakeLists.txt). 7. Update the extension `version` in [cesium.omniverse/config/extension.toml](../../exts/cesium.omniverse/config/extension.toml). This should be the same version as above. 8. If any changes have been made to the Cesium USD schemas since last release: * Update the extension `version` in [cesium.usd.plugins/config/extension.toml](../../exts/cesium.usd.plugins/config/extension.toml) * Update the `cesium.usd.plugins` dependency version in [cesium.omniverse/config/extension.toml](../../exts/cesium.omniverse/config/extension.toml) 9. Update [`CHANGES.md`](../../CHANGES.md). 10. Update `ION_ACCESS_TOKEN` in [`extension.py`](../../apps/exts/cesium.performance.app/cesium/performance/app/extension.py) within `cesium.performance.app` using the newly generated keys. 11. Create a branch, e.g. `git checkout -b release-0.0.0`. 12. Commit the changes, e.g. `git commit -am "0.0.0 release"`. 13. Push the commit, e.g. `git push origin release-0.0.0`. 14. Open a PR and merge the branch with "Rebase and merge". 15. Tag the release, e.g. `git tag -a v0.0.0 -m "0.0.0 release"`. 16. Push the tag, e.g. `git push origin v0.0.0`. 17. Wait for CI to pass. 18. Download the latest build from S3. In the AWS management console (InternalServices AWS account), go to the bucket [`cesium-builds/cesium-omniverse`](https://s3.console.aws.amazon.com/s3/buckets/cesium-builds?prefix=cesium-omniverse/&region=us-east-1), find the folder with the new tag and download the AlmaLinux and Windows zip files (e.g. `CesiumGS-cesium-omniverse-linux-x86_64-v0.0.0.zip` and `CesiumGS-cesium-omniverse-windows-x86_64-v0.0.0.zip` ) 19. Create a new release on GitHub: https://github.com/CesiumGS/cesium-omniverse/releases/new. * Chose the new tag. * Copy the changelog into the description. Follow the format used in previous releases. * Upload the Linux and Windows release zip files. # Releasing a new version of Cesium for Omniverse Samples 1. Create a new access token using the CesiumJS ion account. * The name of the token should match "Cesium for Omniverse Samples vX.X.X - Delete on April 1st, 2023" where the version is the same as the Cesium for Omniverse release and the expiry date is two months later than present. * The scope of the token should be "assets:read" for all assets. 2. Replace the `cesium:projectDefaultIonAccessToken` property in each `.usda` file with the new access token. 3. Verify that all the USD files load in Cesium for Omniverse. 4. Update `CHANGES.md`. 5. Commit the changes, e.g. `git commit -am "0.0.0 release"`. 6. Push the commit, e.g. `git push origin main`. 7. Tag the release, e.g. `git tag -a v0.0.0 -m "0.0.0 release"`. 8. Push the tag, e.g. `git push origin v0.0.0`. 9. Download the repo as a zip file. 10. Extract the zip file. 11. Rename the extracted folder, e.g. rename `cesium-omniverse-samples-main` to `CesiumOmniverseSamples-v0.0.0`. 12. Create a zip file of the folder 13. Create a new release on GitHub: https://github.com/CesiumGS/cesium-omniverse-samples/releases/new. * Choose the new tag. * Copy the changelog into the description. Follow the format used in previous releases. * Upload the zip file. # Verify Package After the package is built, verify that the extension loads in USD Composer: * Open USD Composer * Open the extensions window and remove Cesium for Omniverse from the list of search paths (if it exists) * Close USD Composer * Unzip the package to `$USERHOME$/Documents/Kit/Shared/exts` * Open USD Composer * Open the extensions window and enable autoload for Cesium for Omniverse * Restart USD Composer * Verify that there aren't any console errors * Verify that you can load Cesium World Terrain and OSM buildings * Delete the extensions from `$USERHOME$/Documents/Kit/Shared/exts`
CesiumGS/cesium-omniverse/docs/release-guide/push-docker-image.md
# Pushing the Docker Image for AlmaLinux 8 builds. We use a docker image for our AlmaLinux 8 builds that contains all of our build dependencies, so we don't have to build the image from scratch on each build. This document outlines how to build and push this to Docker Hub. ## Installing Docker Install [Docker Desktop](https://docs.docker.com/desktop/install/ubuntu/). You will need a license for this and access to our account. On Linux, docker is run as root. To avoid the requirement for `sudo`, you should add your user to the `docker` group: ```shell sudo usermod -aG docker $USER ``` To use the new group membership without logging out of your session completely, you can "relogin" in the same shell by typing: ```shell su - $USER ``` Note: this creates a new login shell and may behave differently from your expectations in a windowed environment e.g., GNOME. In particular, `ssh` logins and `git` may not work anymore. ## Building the container Confirm that you have push access to the [container repo](https://hub.docker.com/r/cesiumgs/omniverse-almalinux8-build). ### Log in Log into docker using: ```shell docker login ``` ### Build the docker image After making your changes to the docker file, execute: ```shell docker build --tag cesiumgs/omniverse-almalinux8-build:$TAGNAME -f docker/AlmaLinux8.Dockerfile . --no-cache ``` You should replace `TAGNAME` with the current date in `YYYY-MM-DD` format. So if it's the 29th of August, 2023, you would use `2023-08-29`. ### Push the image to Docker Hub The build will take some time. Once it is finished, execute the following to push the image to Docker Hub: ```shell docker push cesiumgs/omniverse-almalinux8-build:$TAGNAME ``` Again, you should replace `$TAGNAME` with the current date in `YYYY-MM-DD` format. So if it's the 29th of August, 2023, you would use `2023-08-29`. ### Update CI.Dockerfile The `docker/CI.Dockerfile` file is used as part of the AlmaLinux 8 build step in our GitHub actions. You will need to update the version of the Docker image used to the tagged version you just uploaded.
CesiumGS/cesium-omniverse/docs/testing-guide/README.md
# Testing Guide ## Performance Test App Provides some general metrics for how long it takes to load tiles. Can be run with: ```bash extern/nvidia/_build/target-deps/kit-sdk/kit ./apps/cesium.performance.kit ``` The is intentionally no vs code launch configuration out of concern that debug related setting could slow the app down. ## Python Tests Python tests are run through `pytest` (see full documentation [here](https://docs.pytest.org/en/latest/)). To run these tests with the proper sourcing and environment, simpy run: ```bash scripts/run_python_unit_tests.(bat|sh) ``` You can also run these tests via the app. Open the extensions window while running omniverse. Find and select the Cesium for Omniverse Extension, then navigate to its Tests tab. The "Run Extension Tests" button will run the python tests (not the C++ tests). ## C++ Tests (The Tests Extension) C++ tests are run through `doctest`, which is set up and run via the Tests Extension. Normally `doctest` can be run via the command line, but since much of the code we test can only run properly inside omniverse, we run the tests there too. The easiest way to run the tests extension is via the launch configuration in vs code. Simply go to the `run and debug` dropdown and launch the `Tests Extension`. The testing output is provided in the terminal used to launch everything. Failed tests will be caught by the debugger, though you may need to go one level up in the execution stack to see the `CHECK` being called. To run the extension via the command line, simply pass the tests extension's kit config file to kit with ```bash extern/nvidia/_build/target-deps/kit-sdk/kit ./apps/cesium.omniverse.cpp.tests.runner.kit ``` [doctest documentation](https://bit.ly/doctest-docs) can be found here. ## How do I add a new test? ### Python `pytest` will auto-discover functions matching the pattern `test_.*` (and other patterns). If you want your tests to be included in the tests for the main extension, import it into `exts/cesium.omniverse/cesium/omniverse/tests/__init__.py`. See [extension_test.py](../../exts/cesium.omniverse/cesium/omniverse/tests/extension_test.py) for an example ### C++ `TEST_SUITE`s and `TEST_CASE`s defined in `tests/src/*.cpp` will be auto-discovered by the `run_all_tests` function in `tests/src/CesiumOmniverseCppTests.cpp`. These macros perform some automagic function definitions, so they are best left outside of other function/class definitions. See `tests/src/ExampleTests.cpp` for examples of basic tests and more advanced use cases, such as using a config file to define expected outputs or parameterizing tests. To create a new set of tests for a class that doesn't already have a relevant tests cpp file, say `myCesiumClass.cpp`: - create `tests/src/myCesiumClassTests.cpp` and `tests/include/myCesiumClassTests.h` - define any setup and cleanup required for the tests in functions in `myCesiumClassTests.cpp`. This can be anything that has to happen on a different frame than the tests, such as prim creation or removal. - expose the setup and cleanup functions in `myCesiumClassTests.h` - call the setup in `setUpTests()` in `tests/src/CesiumOmniverseCppTests.cpp` - call the cleanup in `cleanUpAfterTests()` in `tests/src/CesiumOmniverseCppTests.cpp` - define a `TEST_SUITE` in `myCesiumClassTests.cpp`, and place your `TEST_CASE`(s) in it Any tests defined in the new test suite will be auto-discovered and run when `runAllTests()` (bound to `run_all_tests()`) is called. Classes that do not require setup/cleanup can skip the header and any steps related to setup/cleanup functions.
CesiumGS/cesium-omniverse/docs/developer-setup/README.md
<!-- omit in toc --> # Cesium for Omniverse - [Prerequisites](#prerequisites) - [Linux](#linux) - [Windows](#windows) - [Clone the repository](#clone-the-repository) - [Build](#build) - [Linux](#linux-1) - [Windows](#windows-1) - [Docker](#docker) - [Advanced build options](#advanced-build-options) - [Unit Tests](#unit-tests) - [Coverage](#coverage) - [Documentation](#documentation) - [Installing](#installing) - [Tracing](#tracing) - [Sanitizers](#sanitizers) - [Formatting](#formatting) - [Linting](#linting) - [Packaging](#packaging) - [Build Linux Package (Local)](#build-linux-package-local) - [Build Windows Package (Local)](#build-windows-package-local) - [VSCode](#vscode) - [Workspaces](#workspaces) - [Tasks](#tasks) - [Launching/Debugging](#launchingdebugging) - [Project Structure](#project-structure) - [Third Party Libraries](#third-party-libraries) - [Overriding Packman Libraries](#overriding-packman-libraries) ## Prerequisites See [Linux](#linux) or [Windows](#windows) for step-by-step installation instructions - Linux (Ubuntu 22.04+ or equivalent) or Windows - Clang 15+, GCC 9+, or Visual Studio 2022+ - Python 3.10+ - For Conan and scripts - CMake 3.22+ - Build system generator - Make - Build system (Linux only) - Conan - Third party C++ library management - gcovr - Code coverage (Linux only) - Doxygen - Documentation - clang-format - Code formatting - clang-tidy - Linting and static code analysis (Linux only) ### Linux - Ensure the correct NVIDIA drivers are installed (not the default open source driver) and that the GPU can be identified ```sh nvidia-smi ``` - Install dependencies (for Ubuntu 22.04 - other Linux distributions should be similar) ```sh sudo apt install -y gcc-9 g++-9 clang-15 python3 python3-pip cmake make git doxygen clang-format-15 clang-tidy-15 clangd-15 gcovr ``` - Install Conan with pip because Conan is not in Ubuntu's package manager ```sh sudo pip3 install conan==1.64.0 ``` - Install `cmake-format` ```sh sudo pip3 install cmake-format ``` - Install `black` and `flake8` ```sh pip3 install black==23.1.0 flake8==6.0.0 ``` - Add symlinks the clang-15 tools so that the correct version is chosen when running `clang-format`, `clang-tidy`, etc ```sh sudo ln -s /usr/bin/clang-15 /usr/bin/clang sudo ln -s /usr/bin/clang++-15 /usr/bin/clang++ sudo ln -s /usr/bin/clang-format-15 /usr/bin/clang-format sudo ln -s /usr/bin/clang-tidy-15 /usr/bin/clang-tidy sudo ln -s /usr/bin/run-clang-tidy-15 /usr/bin/run-clang-tidy sudo ln -s /usr/bin/llvm-cov-15 /usr/bin/llvm-cov sudo ln -s /usr/bin/clangd-15 /usr/bin/clangd ``` - Or, you can use the `update-alternatives` program to create the links and manage versions. This is an approach you can use in a script or on the command line: ```sh clangprogs="/usr/bin/clang*-15 /usr/bin/run-clang-tidy-15 /usr/bin/llvm-cov-15" for prog in $clangprogs do linked=${prog%%-15} generic=${linked##*/} update-alternatives --install $linked $generic $prog 15 done ``` - Then refresh the shell so that newly added dependencies are available in the path. ```sh exec bash ``` ### Windows There are two ways to install prerequisites for Windows, [manually](#install-manually) or [with Chocolatey](#install-with-chocolatey). Chocolately is quicker to set up but may conflict with existing installations. We use Chocolatey for CI. <!-- omit in toc --> #### Install manually - Install Visual Studio 2022 Professional: https://visualstudio.microsoft.com/downloads/ - Select `Desktop Development with C++` and use the default components - Install Git: https://git-scm.com/downloads - Use defaults - Install LLVM 15.0.7: https://llvm.org/builds - When prompted, select `Add LLVM to the system PATH for all users` - Install CMake: https://cmake.org/download - When prompted, select `Add CMake to the system PATH for all users` - Install Python (version 3.x): https://www.python.org/downloads - Select `Add Python 3.x to PATH` - Create a symbolic link called `python3.exe` that points to the actual `python` (version 3.x) executable. This is necessary for some of the scripts to run correctly when `#!/usr/bin/env python3` is at the top of the file. Open Command Prompt as administrator and enter: ```sh where python cd <first_path_in_list> mklink python3.exe python.exe ``` - Install `requests` module for Python ```sh pip3 install requests ``` - Install `cmake-format` ```sh pip3 install cmake-format ``` - Install `black` and `flake8` ```sh pip3 install black==23.1.0 flake8==6.0.0 ``` - Install `colorama` to enable color diff support ```sh pip3 install colorama ``` - Install Conan ```sh pip3 install conan==1.64.0 ``` - Install Doxygen: https://www.doxygen.nl/download.html - After installation, add the install location to your `PATH`. Open PowerShell as administrator and enter: ```sh [Environment]::SetEnvironmentVariable("Path", $env:Path + ";C:\Program Files\doxygen\bin", "Machine") ``` - Enable Long Paths. This ensures that all Conan libraries are installed in `~/.conan`. Open PowerShell as administrator and enter: ```sh New-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem" -Name "LongPathsEnabled" -Value 1 -PropertyType DWORD -Force ``` - Then refresh PowerShell so that newly added dependencies are available in the path. ```sh refreshenv ``` <!-- omit in toc --> #### Install with Chocolatey - Install [Chocolatey](https://docs.chocolatey.org/en-us/choco/setup) and then install dependencies ```sh choco install -y visualstudio2022professional visualstudio2022-workload-nativedesktop python cmake ninja git doxygen.install vswhere --installargs 'ADD_CMAKE_TO_PATH=System' ``` ```sh choco install -y llvm --version=15.0.7 ``` ```sh choco install -y conan --version 1.64.0 ``` > **Note:** If you see a warning like `Chocolatey detected you are not running from an elevated command shell`, reopen Command Prompt as administrator - Create a symbolic link called `python3.exe` that points to the actual `python` (version 3.x) executable. This is necessary for some of the scripts to run correctly when `#!/usr/bin/env python3` is at the top of the file. ```sh where python cd <first_path_in_list> mklink python3.exe python.exe ``` - Install `requests` ```sh pip3 install requests ``` - Install `cmake-format` ```sh pip3 install cmake-format ``` - Install `black` and `flake8` ```sh pip3 install black==23.1.0 flake8==6.0.0 ``` - Install `colorama` to enable color diff support ```sh pip3 install colorama ``` - Enable Long Paths. This ensures that all Conan libraries are installed correctly. Open PowerShell as administrator and enter: ```sh New-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem" -Name "LongPathsEnabled" -Value 1 -PropertyType DWORD -Force ``` - Then refresh PowerShell so that newly added dependencies are available in the path. ```sh refreshenv ``` ## Clone the repository ```sh git clone [email protected]:CesiumGS/cesium-omniverse.git --recurse-submodules ``` If you forget the `--recurse-submodules`, nothing will work because the Git submodules will be missing. You should be able to fix it with ```sh git submodule update --init --recursive ``` ## Build ### Linux ```sh ## Release cmake -B build cmake --build build --target install --parallel 8 ## Debug cmake -B build-debug -D CMAKE_BUILD_TYPE=Debug cmake --build build-debug --target install --parallel 8 ``` Binaries will be written to `build/bin`. Shared libraries and static libraries will be written to `build/lib`. ### Windows ```sh ## Release cmake -B build cmake --build build --config Release --target install --parallel 8 ## Debug cmake -B build cmake --build build --config Debug --target install --parallel 8 ``` Binaries and shared libraries will be written to `build/bin/Release`. Static libraries and python modules will be written to `build/lib/Release`. CMake will select the most recent version of Visual Studio on your system unless overridden with a generator (e.g. `-G "Visual Studio 17 2022"`). ### Docker Install [Docker Engine CE For Ubuntu](https://docs.docker.com/engine/install/ubuntu/) Enter the container: ```sh docker build --tag cesiumgs/cesium-omniverse:almalinux8 -f docker/AlmaLinux8.Dockerfile . docker run --rm --interactive --tty --volume $PWD:/var/app cesiumgs/cesium-omniverse:almalinux8 ``` Once inside the container, build like usual. Note that linters are turned off. It won't affect the build, it just means there won't be code formatting or linting. It will build fine with GCC. ```sh cmake -B build -D CESIUM_OMNI_ENABLE_LINTERS=OFF cmake --build build ``` ### Advanced build options For faster builds, use the `--parallel` option ```sh cmake -B build cmake --build build --parallel 8 ``` To use a specific C/C++ compiler, set `CMAKE_CXX_COMPILER` and `CMAKE_C_COMPILER` ```sh cmake -B build -D CMAKE_CXX_COMPILER=clang++-15 -D CMAKE_C_COMPILER=clang-15 cmake --build build ``` Make sure to use a different build folder for each compiler, otherwise you may see an error from Conan like ``` Library [name] not found in package, might be system one. ``` This error can also be avoided by deleting `build/CMakeCache.txt` before switching compilers. To view verbose output from the compiler, use the `--verbose` option ```sh cmake -B build cmake --build build --verbose ``` To change the build configuration, set `CMAKE_BUILD_TYPE` to one of the following values: - `Debug`: Required for coverage - `Release`: Used for production builds - `RelWithDebInfo`: Similar to `Release` but has debug symbols - `MinSizeRel`: Similar to `Release` but smaller compile size On Linux ```sh cmake -B build-relwithdebinfo -D CMAKE_BUILD_TYPE=RelWithDebInfo cmake --build build-relwithdebinfo ``` On Windows ```sh cmake -B build cmake --build build --config RelWithDebInfo ``` Note that Windows (MSVC) is a multi-configuration generator meaning all four build configurations are created during the configure step and the specific configuration is chosen during the build step. If using Visual Studio there will be a dropdown to select the build configuration. Ninja is also supported as an alternative to the MSVC generator. To build with Ninja locally open `x64 Native Tools Command Prompt for VS 2022` and run: ``` cmake -B build -D CMAKE_C_COMPILER=cl -D CMAKE_CXX_COMPILER=cl -G "Ninja Multi-Config" cmake --build build --config Release --parallel 8 ``` ## Unit Tests Unit tests can be run by starting the Cesium Omniverse Tests extension inside Omniverse. ## Coverage It's a good idea to generate code coverage frequently to ensure that you're adequately testing new features. To do so run ```sh cmake -B build-debug -D CMAKE_BUILD_TYPE=Debug cmake --build build-debug --target generate-coverage ``` Once finished, the coverage report will be located at `build-debug/coverage/index.html`. Notes: - Coverage is disabled in `Release` mode because it would be inaccurate and we don't want coverage instrumentation in our release binaries anyway - Coverage is not supported on Windows ## Documentation ```sh cmake -B build cmake --build build --target generate-documentation ``` Once finished, documentation will be located at `build/docs/html/index.html`. ## Installing To install `CesiumOmniverse` into the Omniverse Kit extension run: ```sh cmake -B build cmake --build build --target install ``` This will install the libraries to `exts/cesium.omniverse/bin`. <!-- omit in toc --> ### Advanced Install Instructions In some cases it's helpful to produce a self-contained build that can be tested outside of Omniverse. The instructions below are intended for debugging purposes only. To install `CesiumOmniverse` onto the local system run: On Linux ```sh cmake -B build cmake --build build cmake --install build --component library --prefix /path/to/install/location ``` On Windows ```sh cmake -B build cmake --build build --config Release cmake --install build --config Release --component library --prefix /path/to/install/location ``` ## Tracing To enable performance tracing set `CESIUM_OMNI_ENABLE_TRACING`: ```sh cmake -B build -D CESIUM_OMNI_ENABLE_TRACING=ON cmake --build build ``` A file called `cesium-trace-xxxxxxxxxxx.json` will be saved to the `exts/cesium-omniverse` folder when the program exits. This file can then be inspected in `chrome://tracing/`. Note that the JSON output may get truncated if the program closes unexpectedly - e.g. when the debugging session is stopped or the program crashes - or if `app.fastShutdown` is `true` (like with Omniverse Create and `cesium.omniverse.dev.kit`). Therefore the best workflow for performance tracing is to run `cesium.omniverse.dev.trace.kit` and close the window normally. ## Sanitizers When sanitizers are enabled they will check for mistakes that are difficult to catch at compile time, such as reading past the end of an array or dereferencing a null pointer. Sanitizers should not be used for production builds because they inject these checks into the binaries themselves, creating some runtime overhead. Sanitizers - ASAN - [Address sanitizer](https://clang.llvm.org/docs/AddressSanitizer.html) - UBSAN - [Undefined behavior sanitizer](https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html) > **Note:** memory leak detection is not supported on Windows currently. See https://github.com/google/sanitizers/issues/1026#issuecomment-850404983 > **Note:** memory leak detection does not work while debugging with gdb. See https://stackoverflow.com/questions/54022889/leaksanitizer-not-working-under-gdb-in-ubuntu-18-04 To verify that sanitization is working, add the following code to any cpp file. ```c++ int arr[4] = {0}; arr[argc + 1000] = 0; ``` After running, it should print something like ``` main.cpp:114:22: runtime error: index 1001 out of bounds for type 'int [4]' main.cpp:114:24: runtime error: store to address 0x7ffe16f44c44 with insufficient space for an object of type 'int' 0x7ffe16f44c44: note: pointer points here 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ^ ``` ## Formatting To format code based on the [`.clang-format`](./.clang-format) configuration file ```sh cmake -B build cmake --build build --target clang-format-fix-all ``` The full list of targets is below: - `clang-format-fix-all` - Formats all code - `clang-format-fix-staged` - Formats staged code - `clang-format-check-all` - Checks for formatting problems in all code - `clang-format-check-staged` - Checks for formatting problems in staged code Please note that the `clang-format-fix-all` and `clang-format-fix-staged` targets will add fixes in the working area, not in the staging area. We also have a Git hook that is installed on project configuration that will check if the staging area is properly formatted before permitting a commit. ## Linting `clang-tidy` is run during the build to catch common coding errors. `clang-tidy` is used for linting and static code analysis based on the [`.clang-tidy`](./.clang-tidy) configuration file. We also generate CMake targets to run these tools manually Run `clang-tidy`: ```sh cmake -B build cmake --build build --target clang-tidy ``` ## Packaging ### Build Linux Package (Local) Linux packages are built in the AlmaLinux 8 Docker container. A Red Hat Enterprise Linux 8 compatible OS is the [minimum OS required by Omniverse](https://docs.omniverse.nvidia.com/app_view/common/technical-requirements.html#suggested-minimums-by-product) and uses glibc 2.18 which is compatible with nearly all modern Linux distributions. It's recommended to build AlmaLinux 8 packages in a separate clone of cesium-omniverse since the Docker container will overwrite files in the `extern/nvidia/_build` and `exts` folders. Run the following shell script from the root cesium-omniverse directory: ```sh ./scripts/build_package_almalinux8.sh ``` The resulting `.zip` file will be written to the `build-package` directory (e.g. `CesiumGS-cesium-omniverse-linux-x86_64-v0.0.0.zip`) ### Build Windows Package (Local) Run the following batch script from the root cesium-omniverse directory: ```sh ./scripts/build_package_windows.bat ``` The resulting `.zip` file will be written to the `build-package` directory (e.g. `CesiumGS-cesium-omniverse-windows-x86_64-v0.0.0.zip`) ## VSCode We use VSCode as our primary IDE for development. While everything can be done on the command line the `.vscode` project folder has built-in tasks for building, running unit tests, generating documentation, etc. ### Workspaces Each workspace contains recommended extensions and settings for VSCode development. Make sure to open the workspace for your OS instead of opening the `cesium-omniverse` folder directly. - [cesium-omniverse-linux.code-workspace](./.vscode/cesium-omniverse-linux.code-workspace) - [cesium-omniverse-windows.code-workspace](./.vscode/cesium-omniverse-windows.code-workspace) ### Tasks [`.vscode/tasks.json`](./.vscode/tasks.json) comes with the following tasks: - Configure - configures the project - Build (advanced) - configures and builds the project - Build (tracing) - configures and builds the project with tracing enabled - Build (kit debug) - configures and builds the project using NVIDIA debug libraries - Build (verbose) - configures and builds the project with verbose output - Build (debug) - configures and builds the project in debug mode with the default compiler - Build (release) - configures and builds the project in release mode with the default compiler - Build Only (debug) - builds the project in debug mode with the default compiler - Build Only (release) - builds the project in release mode with the default compiler - Clean - cleans the build directory - Coverage - generates a coverage report and opens a web browser showing the results - Documentation - generates documentation and opens a web browser showing the results - Format - formats the code with clang-format - Lint - runs clang-tidy - Lint Fix - runs clang-tidy and fixes issues - Dependency Graph - shows the third party library dependency graph To run a task: - `Ctrl + Shift + B` and select the task, e.g. `Build` - Select the build type and compiler (if applicable) ### Launching/Debugging Windows and Linux versions of `launch.json` are provided in the `.vscode` folder. * On Windows copy `launch.windows.json` and rename it to `launch.json`. * On Linux copy `launch.linux.json` and rename it to `launch.json`. Alternatively, create a symlink so that `launch.json` always stays up-to-date: ```sh # Windows - Command Prompt As Administrator cd .vscode mklink launch.json launch.windows.json ``` ```sh # Linux cd .vscode sudo ln -s launch.linux.json launch.json ``` Then select a configuration from the `Run and Debug` panel, such as `Kit App`, and click the green arrow. > **Note:** Most configurations run a build-only prelaunch task. This assumes the project has already been configured. When debugging for the first time make sure to configure the project first by pressing `Ctrl + Shift + B` and running `Build (debug)`. > **Note:** For running the `Performance Tracing` configuration, make sure the project has been configured with tracing enabled by pressing `Ctrl + Shift + B` and running `Build (tracing)`. > **Note:** For running the `Development App (Kit Debug)` configuration make sure the project has been built with NVIDIA debug libraries by pressing `Ctrl + Shift + B` and running `Build (kit debug)`. > **Note:** For Python debugging, first run `Python Debugging (start)`, then wait for Omniverse to load, then run `Python Debugging (attach)`. Now you can set breakpoints in both the C++ and Python code. <!-- omit in toc --> #### Launch/Debug Troubleshooting - When running in debug within vscode, if you find execution halting at a breakpoint outside the cesium codebase, you may need to uncheck "C++: on throw" under the "Breakpoints" section of the "Run and Debug" panel. - On Linux, if you are given an error or warning about IOMMU, you may need to turn this off in the BIOS. IOMMU also goes by the name of Intel VT-d and AMD-Vi. - On Linux, if repeated `"[Omniverse app]" is not responding` prompts to either force quit or wait, you may want to extend the global timeout for such events from the default 5s to 30s with the following command (for gnome): ```sh gsettings set org.gnome.mutter check-alive-timeout 30000 ``` ## Project Structure - `src` - Source code for the CesiumOmniverse library - `include` - Include directory for the CesiumOmniverse library - `tests` - Unit tests - `extern` - Third-party dependencies that aren't on Conan - `cmake` - CMake helper files - `scripts` - Build scripts and Git hooks - `docker` - Docker files ## Third Party Libraries We use [Conan](https://conan.io/) as our C++ third party package manager for dependencies that are public and not changed often. Third party libraries are always built from source and are cached on the local system for subsequent builds. To add a new dependency to Conan - Add it to [AddConanDependencies.cmake](./cmake/AddConanDependencies.cmake) - Call `find_package` in [CMakeLists.txt](./CMakeLists.txt) - Add the library to the `LIBRARIES` field in any relevant `setup_lib` or `setup_app` calls Some dependencies are pulled in as Git submodules instead. When adding a new git submodule add the license to [ThirdParty.extra.json](./ThirdParty.extra.json). [ThirdParty.json](./ThirdParty.json) is autogenerated and combines [ThirdParty.extra.json](./ThirdParty.extra.json) and Conan dependencies. ### Overriding Packman Libraries The external dependencies from Nvidia use Nvidia's packman tool to fetch and install. The dependency files are found at `/extern/nvidia/deps` in this repository. You can override these by using a `*.packman.xml.user` file. For example, to override the version of kit you can create a user file called `kit-sdk.packman.xml.user` next to `kit-sdk.packman.xml` in the `deps` directory. You can then use standard packman configurations within this file, such as: ```xml <project toolsVersion="5.6"> <dependency name="kit_sdk" linkPath="../_build/target-deps/kit-sdk/"> <package name="kit-sdk" version="105.0.1+release.109439.ed961c5c.tc.${platform}.release"/> </dependency> <dependency name="kit_sdk_debug" linkPath="../_build/target-deps/kit-sdk-debug/"> <package name="kit-sdk" version="105.0.1+release.109439.ed961c5c.tc.${platform}.debug"/> </dependency> </project> ``` The above configuration would override the version of the Kit SDK used to `105.0.1+release.109439.ed961c5c.tc`. These user files are ignored by the `.gitignore` so it is safe to test out prerelease and private versions of new libraries.
CesiumGS/cesium-omniverse/docs/developer-setup/building_usd_on_ubuntu2204.md
# Building Pixar's USD 22.11 for Ubuntu 22.04 _Last Updated: 2022/01/12_ Building Pixar's USD 22.11 on Ubuntu 22.04 can be difficult. This guide aims to help those who wish to download and compile USD on their system. For most people, [using the Nvidia binaries should suffice and is the recommended option](https://developer.nvidia.com/usd). If those do not work for you, or you wish to have a self-compiled version, this guide is for you. ## Prerequisites You need: - Python 3.7 from the Deadsnakes PPA: https://launchpad.net/~deadsnakes/+archive/ubuntu/ppa - GCC 11 - Cmake - USD downloaded from the GitHub repository: https://github.com/PixarAnimationStudios/USD ## Python Setup As of writing, USD targets Python 3.7. On Ubuntu you need to use the [Deadsnakes PPA](https://launchpad.net/~deadsnakes/+archive/ubuntu/ppa) to get this. You need the following packages: - python3.7 - python3.7-dev - libpython3.7 - libpython3.7-dev Once you have Python 3.7, you need to install `PyOpenGL` and `PySide2`. **You cannot use your normal system `pip` command for this!** The correct command is: ```shell python3.7 -m pip install PyOpenGL PySide2 ``` ## Fixing Boost USD currently targets Boost 1.70 on Linux, which has issues compiling on Ubuntu 22.04. USD supports up to Boost 1.76 on account of issues in MacOS. We can use this to our advantage. Apply the below patchfile to the repository to fix this. ``` diff --git a/build_scripts/build_usd.py b/build_scripts/build_usd.py index 5d3861d0a..96dd1c0a4 100644 --- a/build_scripts/build_usd.py +++ b/build_scripts/build_usd.py @@ -695,7 +695,7 @@ if MacOS(): BOOST_URL = "https://boostorg.jfrog.io/artifactory/main/release/1.76.0/source/boost_1_76_0.tar.gz" BOOST_VERSION_FILE = "include/boost/version.hpp" elif Linux(): - BOOST_URL = "https://boostorg.jfrog.io/artifactory/main/release/1.70.0/source/boost_1_70_0.tar.gz" + BOOST_URL = "https://boostorg.jfrog.io/artifactory/main/release/1.76.0/source/boost_1_76_0.tar.gz" BOOST_VERSION_FILE = "include/boost/version.hpp" elif Windows(): # The default installation of boost on Windows puts headers in a versioned ``` ## Building USD **NOTE: At this time, only a limited number of install options have been tested. YMMV.** We can use the USD build scripts to build USD as we normally would, but we need to provide some additional options for Python for this to work correctly. If you just need to quickly get this built, use the following command from the USD repository's directory. It builds the USD and the tools including `usdview`, placing them in `~/.local/USD`. If you want to learn more, read on below. ```shell python3.7m build_scripts/build_usd.py ~/.local/USD \ --tools \ --usd-imaging \ --usdview \ --build-python-info /usr/bin/python3.7m /usr/include/python3.7m /usr/lib/python3.7/config-3.7m-x86_64-linux-gnu/libpython3.7m.so 3.7 ``` The important line here is the `--build-python-info` line. This takes, in order, the Python executable, include directory, library, and version. Using the Deadsnakes PPA, these are: - `PYTHON_EXECUTABLE` : `/usr/bin/python3.7m` - `PYTHON_INCLUDE_DIR` : `/usr/include/python3.7m` - `PYTHON_LIBRARY` : `/usr/lib/python3.7/config-3.7m-x86_64-linux-gnu/libpython3.7m.so` - `PYTHON_VERSION` : `3.7` Do note that we are using the `pymalloc` versions of Python. The Deadsnakes PPA version of Python 3.7 is compiled using `pymalloc` and `/usr/bin/python3.7` simply symlinks to `/usr/bin/python3.7m`. You could use the symlinks, but there is **NOT** a symlink for `libpython3.7m.so`, so you need to at least provide the direct path to that. ## Afterword There are a lot of other options for building USD. If you use the command `python3.7m build_scripts/build_usd.py --help` you can get a list of all these commands. Your mileage may vary with compiling these other features.
CesiumGS/cesium-omniverse/docs/connectors/README.md
# Connectors Helpful guides for setting up various connectors with Omniverse. - [SketchUp Connector](./sketchup/README.md)
CesiumGS/cesium-omniverse/docs/connectors/sketchup/README.md
Introduction ============ This documentation is designed as a supplement guide for the [official Nvidia documentation on the SketchUp Connector](https://docs.omniverse.nvidia.com/con_connect/con_connect/sketchup.html) for Omniverse. While there are some intersections, the primary goal of this documentation is to get someone new to SketchUp, Omniverse, and Cesium for Omniverse up and running quickly. It is strongly advised that the reader take the time to [review the entire official documentation fully](https://docs.omniverse.nvidia.com/con_connect/con_connect/sketchup.html). Installing Omniverse Connector for SketchUp =========================================== Installing the connector can be done through the Exchange Tab in the Omniverse Launcher. The connector requires a SketchUp Pro license. More details can be found in the [Installing the Connector](https://docs.omniverse.nvidia.com/con_connect/con_connect/sketchup.html#installing-the-connector) section of the official docs. Instructions ------------ 1. Ensure that SketchUp is closed. 2. Navigate to the Exchange Tab 3. Search for "SketchUp" 4. Click on "Trimble SketchUp Omniverse Connector" 5. Click Install Using Omniverse Connector for SketchUp ====================================== **NOTE:** The [official documentation](https://docs.omniverse.nvidia.com/con_connect/con_connect/sketchup.html#connecting-to-view-local) has a section on connecting locally to Omniverse for editing. This section in the official guide is slightly out of date and does not contain details about working with Nucleus at the time of writing, but is worth a read before continuing further. The Omniverse Toolbar --------------------- Once installed and in a project, the Omniverse Toolbar can be dragged to the toolbar area. The diagram below describes all of the functions. ![Omniverse Toolbar](resources/sketchup_toolbar.jpg) Configuring SketchUp for Omniverse with Nucleus ----------------------------------------------- Once you have started a new project with the correct scale for your needs, you will need to ensure that the settings are properly configured for your Nucleus server. The "Do Not Use Nucleus" checkbox **must be unchecked** for Live Editing with Nucleus to work. **WARNING:** Every time you start or open a new project you must go into the settings dialog and uncheck "Do Not Use Nucleus" at the time of this writing. It is unclear if this is intended or a bug. It is also recommended that *Send to locally installed Viewer* is configured to use either the latest View or Create, and *Create Send To Omniverse output as:*' has "Prop" selected. All other settings can be set to the user’s liking. ![SketchUp Settings](resources/sketchup_settings.png) Signing into Omniverse ---------------------- Click the *Sign In to Omniverse* button and enter in the host name for your Nucleus server. This will open your browser to finish the sign in process. Exporting to Nucleus -------------------- Once configured correctly, you can export to Nucleus by using either the *Publish Project* or *Publish Prop* button. *Publish Project* produces a `*.project.usd` file and associated directory and *Publish Prop* produces a single `*.usd` file containing the relevant information. **NOTE:** As publishing a prop is more relevant to our needs, this section only goes into further details about *Publish Prop*. Publishing a project is more or less identical steps. When the user presses the *Publish Prop* button in order to publish a new prop, a dialog appears similar to the one below. The flow for saving to Nucleus is: 1. Ensure your SketchUp project is saved. 2. Select the path you want to use in Omniverse Nucleus 3. Enter the name of the file after the path in the *File Name* field. (Extension not required.) 4. Click *Export* In this screenshot, we are saving a file named "docdemo.usd" to the Library folder within Nucleus. ![Export Dialog](resources/sketchup_export.png) **NOTE:** The *Show Publish Options* button is a quick way to open the settings dialog if you forget to open settings and uncheck *Do Not Use Nucleus* checkbox when you opened or started your project. If you are resuming work on a prop and want to properly link to Nucleus so it recieves your latest edits, simply follow the same instructions but choose the file you want in the picker. This will create a new session with Omniverse so you can continue syncing your SketchUp file with Nucleus. Failure to do so when you reopen your file will result in Nucleus not receiving the changes. Live Editing ------------ Live editing with the SketchUp Connector does work however it appears to be unidirectional in the direction of Omniverse. In order to enable Live Editing, click the *Live Sync Mode* button in the middle of the Omniverse Toolbar. This will open a dialog: ![Live Sync Dialog](resources/sketchup_live_sync.png) Once the dialog is open, ensure that the *Live Sync* checkbox is checked and Live Editing will be enabled. Once you make changes they will be automatically shared with Omniverse. **WARNING:** Do not close the Omniverse Live Sync dialog box or click the *Connect USD* button. Doing so will both clear the link you currently have with Nucleus for the file, and will end the Live Sync session. We have confirmed with Nvidia that this is intended behavior. References ========== - [Official Nvidia Omniverse Documentation](https://docs.omniverse.nvidia.com/con_connect/con_connect/sketchup.html)
CesiumGS/cesium-omniverse/docs/kit/README.md
# So you want to programmatically change a setting in Omniverse? An optional first step is to copy the settings. The easiest way to do this is to dump them out when one of our functions in `window.py` is called. This snippet will help: ```python import json import carb.settings with open("<path to desired dump file>", "w") as fh: fh.write(json.dumps(carb.settings.get_settings().get("/"))) ``` Having these settings isn't required but it may be helpful. Once pretty printed using the JSON formatter of your choice, it can help you find file paths to help in your search, and you can take a closer look at all of the current settings. In the case of this ticket, we needed to set a setting for the RTX renderer. A quick search of the `tokens` object gives us this path: ``` c:/users/amorris/appdata/local/ov/pkg/code-2022.2.0/kit/exts/omni.rtx.settings.core ``` Perform a grep in this folder for the menu item you wish to configure programmatically. In this case, I searched for `Normal & Tangent Space Generation Mode`. That should direct you to the file where the widget is available, and you should find the following: ```python tbnMode = ["AUTO", "CPU", "GPU", "Force GPU"] self._add_setting_combo("Normal & Tangent Space Generation Mode", "/rtx/hydra/TBNFrameMode", tbnMode) ``` The most important piece here is the path `/rtx/hydra/TBNFrameMode`. This refers to the path in the settings. Once you have this, programmatically changing the setting is simple: ```python import carb.settings carb.settings.get_settings().set("/rtx/hydra/TBNFrameMode", 1) ``` If you are unsure about what the type of the value for the setting should be, I suggest checking the JSON dump of the settings. The path `/rtx/hydra/TBNFrameMode` refers to, from root, the rtx object, the child hydra object, and followed by the TBNFrameMode property within. You can also search for the property, but beware that there may be multiple that are unrelated. For example, `TBNFrameMode` has three results total, but only one is relevant to our needs.
CesiumGS/cesium-omniverse/extern/CMakeLists.txt
include(Macros) # cmake-format: off add_external_project( PROJECT_NAME cesium-native LIBRARIES Cesium3DTilesSelection Cesium3DTilesReader Cesium3DTilesContent CesiumRasterOverlays CesiumGltfReader CesiumGltfContent CesiumGltf CesiumJsonReader CesiumGeospatial CesiumGeometry CesiumIonClient CesiumAsync CesiumUtility async++ csprng draco ktx_read modp_b64 s2geometry spdlog tinyxml2 uriparser webpdecoder turbojpeg meshoptimizer sqlite3 OPTIONS CESIUM_TESTS_ENABLED=OFF CESIUM_COVERAGE_ENABLED=OFF CESIUM_TRACING_ENABLED=${CESIUM_OMNI_ENABLE_TRACING} PROJECT_EXTERN_DIRECTORY "${PROJECT_SOURCE_DIR}/extern" EXPECTED_DEBUG_POSTFIX "d" ) # cmake-format: on if(NOT ${USE_NVIDIA_RELEASE_LIBRARIES}) execute_process(COMMAND "${Python3_EXECUTABLE}" "${SCRIPTS_DIRECTORY}/copy_from_dir.py" "*.user.xml" "${PROJECT_SOURCE_DIR}/extern/nvidia/debug-deps" "${PROJECT_SOURCE_DIR}/extern/nvidia/deps") endif() if(WIN32) set(NVIDIA_PLATFORM_NAME "windows-x86_64") elseif(UNIX AND NOT APPLE) set(NVIDIA_PLATFORM_NAME "linux-x86_64") else() message(FATAL_ERROR "Only Windows and Linux are supported") endif() if(UNIX) execute_process(COMMAND bash -c "${PROJECT_SOURCE_DIR}/extern/nvidia/build.sh --platform ${NVIDIA_PLATFORM_NAME}" RESULT_VARIABLE exit_code) elseif(WIN32) execute_process(COMMAND cmd /C "${PROJECT_SOURCE_DIR}/extern/nvidia/build.bat --platform ${NVIDIA_PLATFORM_NAME}" RESULT_VARIABLE exit_code) endif() # cmake-format: off if(exit_code AND NOT exit_code EQUAL 0) message(FATAL_ERROR "Gathering Nvidia libraries failed") endif() # cmake-format: on # Add a symlink to USD Composer (create) so that we can use its extensions (e.g. omni.kit.window.material_graph) in our internal applications if(UNIX) execute_process(COMMAND bash -c "${PROJECT_SOURCE_DIR}/extern/nvidia/link_app.sh --app create" RESULT_VARIABLE exit_code) elseif(WIN32) execute_process(COMMAND cmd /C "${PROJECT_SOURCE_DIR}/extern/nvidia/link_app.bat --app create" RESULT_VARIABLE exit_code) endif() # cmake-format: off if(exit_code AND NOT exit_code EQUAL 0) message(WARNING "Could not find USD Composer which contains the material graph extension needed by cesium.omniverse.dev.kit. While Cesium for Omniverse will still build fine, running cesium.omniverse.dev.kit will fail.") endif() # cmake-format: on set(NVIDIA_RELEASE_FOLDER_NAME "release") if(${USE_NVIDIA_RELEASE_LIBRARIES}) set(NVIDIA_DEBUG_FOLDER_NAME "release") else() set(NVIDIA_DEBUG_FOLDER_NAME "debug") endif() set(NVIDIA_BUILD_DIR "${PROJECT_SOURCE_DIR}/extern/nvidia/_build") set(NVIDIA_USD_ROOT "${NVIDIA_BUILD_DIR}/target-deps/usd") set(PYTHON_ROOT "${NVIDIA_BUILD_DIR}/target-deps/python") set(USDRT_ROOT "${NVIDIA_BUILD_DIR}/target-deps/usdrt") set(CARB_ROOT "${NVIDIA_BUILD_DIR}/target-deps/carb_sdk_plugins") set(KIT_SDK_ROOT "${NVIDIA_BUILD_DIR}/target-deps/kit-sdk") set(PYBIND11_ROOT "${NVIDIA_BUILD_DIR}/target-deps/pybind11") set(CUDA_ROOT "${NVIDIA_BUILD_DIR}/target-deps/cuda") set(NVIDIA_USD_LIBRARIES ar arch gf js kind ndr pcp plug sdf sdr tf trace usd usdGeom usdLux usdShade usdUI usdUtils usdVol vt work) # Add base USD libraries set(NVIDIA_USD_TARGET_NAMES ${NVIDIA_USD_LIBRARIES}) set(NVIDIA_USD_RELEASE_LIBRARIES ${NVIDIA_USD_LIBRARIES}) set(NVIDIA_USD_DEBUG_LIBRARIES ${NVIDIA_USD_LIBRARIES}) # Add TBB set(NVIDIA_USD_TARGET_NAMES ${NVIDIA_USD_TARGET_NAMES} tbb) set(NVIDIA_USD_RELEASE_LIBRARIES ${NVIDIA_USD_RELEASE_LIBRARIES} tbb) if(WIN32) set(NVIDIA_USD_DEBUG_LIBRARIES ${NVIDIA_USD_DEBUG_LIBRARIES} tbb_debug) else() set(NVIDIA_USD_DEBUG_LIBRARIES ${NVIDIA_USD_DEBUG_LIBRARIES} tbb) endif() # Add boost python set(NVIDIA_USD_TARGET_NAMES ${NVIDIA_USD_TARGET_NAMES} boost_python310) if(WIN32) set(NVIDIA_USD_RELEASE_LIBRARIES ${NVIDIA_USD_RELEASE_LIBRARIES} boost_python310-vc142-mt-x64-1_76) set(NVIDIA_USD_DEBUG_LIBRARIES ${NVIDIA_USD_DEBUG_LIBRARIES} boost_python310-vc142-mt-gd-x64-1_76) else() set(NVIDIA_USD_RELEASE_LIBRARIES ${NVIDIA_USD_RELEASE_LIBRARIES} boost_python310) set(NVIDIA_USD_DEBUG_LIBRARIES ${NVIDIA_USD_DEBUG_LIBRARIES} boost_python310) endif() if(${USE_NVIDIA_RELEASE_LIBRARIES}) set(NVIDIA_USD_DEBUG_LIBRARIES ${NVIDIA_USD_RELEASE_LIBRARIES}) endif() # cmake-format: off add_prebuilt_project( RELEASE_INCLUDE_DIR "${NVIDIA_USD_ROOT}/${NVIDIA_RELEASE_FOLDER_NAME}/include" DEBUG_INCLUDE_DIR "${NVIDIA_USD_ROOT}/${NVIDIA_DEBUG_FOLDER_NAME}/include" RELEASE_LIBRARY_DIR "${NVIDIA_USD_ROOT}/${NVIDIA_RELEASE_FOLDER_NAME}/lib" DEBUG_LIBRARY_DIR "${NVIDIA_USD_ROOT}/${NVIDIA_DEBUG_FOLDER_NAME}/lib" RELEASE_LIBRARIES ${NVIDIA_USD_RELEASE_LIBRARIES} DEBUG_LIBRARIES ${NVIDIA_USD_DEBUG_LIBRARIES} TARGET_NAMES ${NVIDIA_USD_TARGET_NAMES} ) # cmake-format: on if(WIN32) # cmake-format: off add_prebuilt_project( RELEASE_INCLUDE_DIR "${PYTHON_ROOT}/include" DEBUG_INCLUDE_DIR "${PYTHON_ROOT}/include" RELEASE_LIBRARY_DIR "${PYTHON_ROOT}/libs" RELEASE_DLL_DIR "${PYTHON_ROOT}" DEBUG_LIBRARY_DIR "${PYTHON_ROOT}/libs" DEBUG_DLL_DIR "${PYTHON_ROOT}" RELEASE_LIBRARIES python310 DEBUG_LIBRARIES python310 TARGET_NAMES python310 ) # cmake-format: on else() # cmake-format: off add_prebuilt_project( RELEASE_INCLUDE_DIR "${PYTHON_ROOT}/include/python3.10" DEBUG_INCLUDE_DIR "${PYTHON_ROOT}/include/python3.10" RELEASE_LIBRARY_DIR "${PYTHON_ROOT}/lib" DEBUG_LIBRARY_DIR "${PYTHON_ROOT}/lib" RELEASE_LIBRARIES python3.10 DEBUG_LIBRARIES python3.10 TARGET_NAMES python310 ) # cmake-format: on endif() # cmake-format: off add_prebuilt_project( RELEASE_INCLUDE_DIR "${USDRT_ROOT}/include/usdrt_only" DEBUG_INCLUDE_DIR "${USDRT_ROOT}/include/usdrt_only" RELEASE_LIBRARY_DIR "${USDRT_ROOT}/_build/${NVIDIA_PLATFORM_NAME}/${NVIDIA_RELEASE_FOLDER_NAME}/usdrt_only" DEBUG_LIBRARY_DIR "${USDRT_ROOT}/_build/${NVIDIA_PLATFORM_NAME}/${NVIDIA_DEBUG_FOLDER_NAME}/usdrt_only" RELEASE_LIBRARIES omni.fabric.plugin DEBUG_LIBRARIES omni.fabric.plugin TARGET_NAMES fabric ) # cmake-format: on # cmake-format: off add_prebuilt_project( RELEASE_INCLUDE_DIR "${CARB_ROOT}/include" DEBUG_INCLUDE_DIR "${CARB_ROOT}/include" RELEASE_LIBRARY_DIR "${CARB_ROOT}/_build/${NVIDIA_PLATFORM_NAME}/${NVIDIA_RELEASE_FOLDER_NAME}" DEBUG_LIBRARY_DIR "${CARB_ROOT}/_build/${NVIDIA_PLATFORM_NAME}/${NVIDIA_DEBUG_FOLDER_NAME}" RELEASE_LIBRARIES carb DEBUG_LIBRARIES carb TARGET_NAMES carb ) # cmake-format: on # cmake-format: off add_prebuilt_project_header_only( INCLUDE_DIR "${KIT_SDK_ROOT}/dev/include" TARGET_NAME omni_kit ) # cmake-format: on # cmake-format: off add_prebuilt_project_header_only( INCLUDE_DIR "${PYBIND11_ROOT}" TARGET_NAME pybind11 ) # cmake-format: on if(WIN32) # cmake-format: off add_prebuilt_project_import_library_only( RELEASE_INCLUDE_DIR "${CUDA_ROOT}" DEBUG_INCLUDE_DIR "${CUDA_ROOT}" RELEASE_LIBRARY_DIR "${CUDA_ROOT}/cuda/lib/x64" DEBUG_LIBRARY_DIR "${CUDA_ROOT}/cuda/lib/x64" RELEASE_LIBRARIES cuda DEBUG_LIBRARIES cuda TARGET_NAMES cuda ) # cmake-format: on else() # Find the directory containing libcuda.so, e.g. /usr/lib/x86_64-linux-gnu find_library( CUDA_DRIVER_LIB cuda REQUIRED NO_CACHE) get_filename_component(CUDA_DRIVER_DIR "${CUDA_DRIVER_LIB}" DIRECTORY) # cmake-format: off add_prebuilt_project( RELEASE_INCLUDE_DIR "${CUDA_ROOT}" DEBUG_INCLUDE_DIR "${CUDA_ROOT}" RELEASE_LIBRARY_DIR "${CUDA_DRIVER_DIR}" DEBUG_LIBRARY_DIR "${CUDA_DRIVER_DIR}" RELEASE_LIBRARIES cuda DEBUG_LIBRARIES cuda TARGET_NAMES cuda) # cmake-format: on endif() if(WIN32) # cmake-format: off add_prebuilt_project( RELEASE_INCLUDE_DIR "${CUDA_ROOT}" DEBUG_INCLUDE_DIR "${CUDA_ROOT}" RELEASE_LIBRARY_DIR "${CUDA_ROOT}/cuda/lib/x64" RELEASE_DLL_DIR "${CUDA_ROOT}/cuda/bin" DEBUG_LIBRARY_DIR "${CUDA_ROOT}/cuda/lib/x64" DEBUG_DLL_DIR "${CUDA_ROOT}/cuda/bin" RELEASE_LIBRARIES nvrtc DEBUG_LIBRARIES nvrtc RELEASE_DLL_LIBRARIES nvrtc64_112_0 DEBUG_DLL_LIBRARIES nvrtc64_112_0 TARGET_NAMES nvrtc ) # cmake-format: on else() # cmake-format: off add_prebuilt_project( RELEASE_INCLUDE_DIR "${CUDA_ROOT}" DEBUG_INCLUDE_DIR "${CUDA_ROOT}" RELEASE_LIBRARY_DIR "${CUDA_ROOT}/cuda/lib64" DEBUG_LIBRARY_DIR "${CUDA_ROOT}/cuda/lib64" RELEASE_LIBRARIES nvrtc DEBUG_LIBRARIES nvrtc TARGET_NAMES nvrtc ) # cmake-format: on endif() # cmake-format: off # omni.ui gives us access to DynamicTextureProvider.h add_prebuilt_project( RELEASE_INCLUDE_DIR "${KIT_SDK_ROOT}/dev/include" DEBUG_INCLUDE_DIR "${KIT_SDK_ROOT}/dev/include" RELEASE_LIBRARY_DIR "${KIT_SDK_ROOT}/exts/omni.ui/bin" DEBUG_LIBRARY_DIR "${KIT_SDK_ROOT}/exts/omni.ui/bin" RELEASE_LIBRARIES omni.ui DEBUG_LIBRARIES omni.ui TARGET_NAMES omni_ui ) # cmake-format: on if(WIN32) set(NVIDIA_ADDITIONAL_LIBRARIES "${PROJECT_SOURCE_DIR}/extern/nvidia/_build/target-deps/kit-sdk/exts/omni.kit.renderer.imgui/bin/imgui.dll" "${PROJECT_SOURCE_DIR}/extern/nvidia/_build/target-deps/kit-sdk/exts/omni.kit.renderer.imgui/bin/deps/freetype.dll" ) set_property(GLOBAL PROPERTY NVIDIA_ADDITIONAL_LIBRARIES_PROPERTY "${NVIDIA_ADDITIONAL_LIBRARIES}") else() set(NVIDIA_ADDITIONAL_SEARCH_PATHS "$<TARGET_FILE_DIR:python310>" "$<TARGET_FILE_DIR:usd>" "$<TARGET_FILE_DIR:carb>" # This is where freetype is located on Linux "${PROJECT_SOURCE_DIR}/extern/nvidia/_build/target-deps/kit-sdk/exts/omni.kit.renderer.imgui/bin/deps") set(NVIDIA_ADDITIONAL_LINK_DIRECTORIES # This is where freetype is located on Linux. Needed by imgui which doesn't set its rpath properly "${PROJECT_SOURCE_DIR}/extern/nvidia/_build/target-deps/kit-sdk/exts/omni.kit.renderer.imgui/bin/deps") set_property(GLOBAL PROPERTY NVIDIA_ADDITIONAL_SEARCH_PATHS_PROPERTY "${NVIDIA_ADDITIONAL_SEARCH_PATHS}") set_property(GLOBAL PROPERTY NVIDIA_ADDITIONAL_LINK_DIRECTORIES_PROPERTY "${NVIDIA_ADDITIONAL_LINK_DIRECTORIES}") endif()