Repository navigation
Adds tiled camera views to Kit Visualizer and Newton Visualizer - #5696
Conversation
Rebase the PR onto current develop and keep only the branch-specific visualizer changes.
Greptile SummaryThis PR adds tiled camera image views to the Kit and Newton visualizers, introduces a new
Confidence Score: 3/5Several correctness issues in the new visualizer paths need resolution before merging. The default
Important Files Changed
Sequence DiagramsequenceDiagram
participant Env as DirectRLEnv / ManagerBasedEnv
participant Sim as SimulationContext
participant SDP as SceneDataProvider
participant Viz as KitVisualizer / NewtonVisualizer
participant Cam as Camera sensor
participant UI as Kit UI / Newton ImageLogger
Env->>Sim: register_interactive_scene(scene)
Sim->>SDP: set_interactive_scene(scene)
Note over SDP: camera sensors discoverable
Env->>Viz: initialize(scene_data_provider)
Viz->>SDP: get_camera_sensors() or create_visualizer_camera()
Viz->>Cam: ensure_camera_initialized()
Viz->>Viz: _update_owned_camera_poses()
loop Every sim step
Sim->>Viz: update(dt)
Viz->>Viz: _update_owned_camera_poses()
alt KitVisualizer only
Viz->>Viz: _sync_camera_pose_updates_to_kit()
Viz->>Viz: _set_generated_usd_camera_poses()
end
Viz->>Cam: "camera.update(force_recompute=True)"
Cam-->>Viz: rgb tensor [N, H, W, 3]
Viz->>Viz: compose_rgb_grid_tensor(rgb)
Viz->>UI: ByteImageProvider / log_image()
end
Env->>Viz: close()
Viz->>Cam: __del__()
Viz->>Viz: remove_generated_prims()
|
| if self._camera_sensor is not None and self._camera_is_owned: | ||
| cleanup = getattr(self._camera_sensor, "__del__", None) | ||
| if callable(cleanup): | ||
| cleanup() | ||
| remove_generated_prims(self._generated_camera_prim_paths) |
There was a problem hiding this comment.
Direct
__del__ invocation is unsafe
Calling camera_sensor.__del__() manually is a Python anti-pattern. __del__ is a finalizer called by the garbage collector; invoking it directly means the GC may call it a second time after close(), leading to double-free / double-cleanup. The Camera class should expose a proper close() or reset() lifecycle method; if none exists, simply nulling the reference and letting the GC reclaim it is safer than hand-triggering the destructor.
The same pattern appears in newton_visualizer.py.
| lookat = torch.as_tensor(target, dtype=torch.float32, device="cpu").reshape(1, 3) | ||
| up_axis = UsdGeom.GetStageUpAxis(usd_stage) | ||
| rotation_matrix = create_rotation_matrix_from_view(eye, lookat, up_axis=up_axis, device="cpu") | ||
| if torch.isnan(rotation_matrix).any(): | ||
| raise ValueError("[KitVisualizer] Cannot set camera pose because eye and lookat are degenerate.") | ||
| quat_xyzw = quat_from_matrix(rotation_matrix)[0] | ||
| quat_gf = Gf.Quatd( | ||
| float(quat_xyzw[3]), | ||
| Gf.Vec3d(float(quat_xyzw[0]), float(quat_xyzw[1]), float(quat_xyzw[2])), | ||
| ) | ||
|
|
||
| camera_xform.AddTranslateOp().Set(Gf.Vec3d(float(eye[0, 0]), float(eye[0, 1]), float(eye[0, 2]))) | ||
| camera_xform.AddOrientOp(UsdGeom.XformOp.PrecisionDouble).Set(quat_gf) | ||
|
|
||
| def _apply_cfg_camera_pose_if_configured(self) -> None: |
There was a problem hiding this comment.
USD stage mutated per camera per frame
_set_usd_camera_pose calls UsdGeom.Camera.Define(), ClearXformOpOrder(), AddTranslateOp().Set(), and AddOrientOp().Set() on every _update_camera_image_panel tick, for every tile. With the default tiled_cam_num=57, that is ~228 USD stage write operations per frame. Consider caching the UsdGeom.XformOp handles after the first author and calling only .Set() on subsequent frames, which avoids the per-frame op-order rebuild overhead.
| tiled_cam_num: int = 57 | ||
| """Number of camera tiles to show when tiled_cam_env_indices is None, capped at 100.""" |
There was a problem hiding this comment.
Suspicious default value for
tiled_cam_num
57 is an unusual default for a tile count. Common ergonomic defaults are powers of two or round numbers (e.g. 16, 32). A value of 57 also exceeds typical screen tile layouts without an obvious rationale, and may reflect a debug value left in from development.
| tiled_cam_num: int = 57 | |
| """Number of camera tiles to show when tiled_cam_env_indices is None, capped at 100.""" | |
| tiled_cam_num: int = 16 | |
| """Number of camera tiles to show when tiled_cam_env_indices is None, capped at 100.""" |
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
| metadata = {"num_envs": num_envs} | ||
| self._env_ids = self._compute_visualized_env_ids() | ||
| self._model = NewtonManager.get_model() |
There was a problem hiding this comment.
DISPLAY check is Linux-only and inverts expected behavior on macOS/Windows
os.environ.get("DISPLAY") returns None on macOS and Windows (where DISPLAY is never set), so not os.environ.get("DISPLAY") evaluates to True on those platforms even for a fully interactive desktop session, forcing headless mode incorrectly. Consider using sys.platform to gate the check, or platform-specific approaches (e.g. check DISPLAY on Linux, use different logic or no check on macOS/Windows).
There was a problem hiding this comment.
Isaac Lab Review
Thanks for adding tiled camera views to Kit and Newton visualizers! This is a significant feature addition that enables multi-robot observation. I've reviewed the implementation with focus on rendering correctness, buffer management, and tile indexing.
🔍 Key Observations
Architecture
The design cleanly separates:
- Utility functions in
camera_view.pyfor env resolution, tile composition, and pose handling - Visualizer-specific integration in Kit and Newton backends
- Shared configuration in
VisualizerCfg
The 100-tile cap (VISUALIZER_TILED_CAMERA_MAX_TILES) is a reasonable safeguard for memory/performance.
💡 Suggestions
1. Potential Division by Zero in Tile Resolution
File: source/isaaclab/isaaclab/envs/utils/camera_view.py:154-156
def compute_tile_resolution(window_width: int, window_height: int, num_tiles: int) -> tuple[int, int]:
cols = max(1, math.ceil(math.sqrt(max(1, num_tiles))))
rows = math.ceil(max(1, num_tiles) / cols)
return max(1, int(window_width) // cols), max(1, int(window_height) // rows)The defensive max(1, ...) wrapping is good, but consider what happens if window_width or window_height are 0 or negative. The function would return valid dimensions but potentially cause issues downstream. Adding input validation could make this more robust:
if window_width <= 0 or window_height <= 0:
raise ValueError(f"Window dimensions must be positive, got {window_width}x{window_height}")2. Race Condition in GPU Image Upload Fallback
File: source/isaaclab_visualizers/isaaclab_visualizers/kit/kit_visualizer.py:457-476
def _upload_camera_image_to_panel(self, image: np.ndarray | torch.Tensor) -> None:
if isinstance(image, torch.Tensor):
if image.is_cuda:
try:
# GPU upload path
...
except Exception as exc:
if not self._warned_gpu_upload_failure:
logger.warning(...)
self._warned_gpu_upload_failure = True
image = image.detach().contiguous().cpu().numpy() # FallbackThe fallback path executes regardless of whether the GPU upload succeeded or failed. After a successful GPU upload, the code continues to also do CPU upload. Consider adding a return after the successful GPU path:
try:
... # GPU upload
return # <-- Add this
except Exception as exc:
... # Log warning
# Fall through to CPU path3. Memory Retention in GPU Upload Tensor
File: source/isaaclab_visualizers/isaaclab_visualizers/kit/kit_visualizer.py:461
self._camera_gpu_upload_tensor = imageStoring the tensor prevents premature deallocation during async GPU operations, which is correct. However, this tensor persists until the next upload or visualizer close. For long-running sessions with large tiled views, consider whether this is significant. A comment explaining why this field exists would help future maintainers.
4. Silent Pass on Missing Target Prims
File: source/isaaclab/isaaclab/envs/utils/camera_view.py:211-224
In prim_world_positions, when the FrameView fallback to USD XformCache fails:
prim = stage.GetPrimAtPath(prim_path)
if not prim.IsValid():
raise RuntimeError(f"tiled_cam_target_prim_path resolved to missing prim: {prim_path!r}.")This raises for completely missing prims, which is good. However, the broader try/except at line 207 catches all exceptions from FrameView, which could silently mask real issues. Consider narrowing the exception type or logging at debug level.
5. Test Coverage for Multi-Camera Tile Indexing
File: source/isaaclab/test/markers/test_visualization_markers.py
The test reorganization is thorough, but I didn't see explicit tests for the new camera view helpers in camera_view.py. Consider adding unit tests for:
resolve_tiled_env_indiceswith edge cases (0 envs, more requested than available)compose_rgb_grid_tensorwith various batch sizescompute_tile_resolutionboundary conditions
6. Documentation Note
File: docs/source/features/visualization.rst:217
The documentation correctly notes that Kit tiled camera views require --enable_cameras. This is a common gotcha, so the prominent note is appreciated.
✅ What Looks Good
- Clean separation between generated and existing camera sensor paths
- Proper cleanup of generated camera prims in
close() - Deferred startup message pattern (
_log_viewer_url/flush_startup_messages) improves UX - Good defensive coding with max-tile caps and env bounds checking
- The focal length to vertical FOV conversion using USD's standard aperture is correct
🔧 Minor Nits
- Unused import hint:
numpy as npappears in type hint contexts but actual usage is via torch - verify np is needed - Magic numbers: The
15.2908aperture constant could benefit from a named constant with a doc comment referencing the USD spec
Overall this is a well-structured feature addition. The suggestions above are mostly defensive hardening and documentation improvements rather than correctness issues.
Update (d98d4b6): Reviewed the incremental changes since my previous review:
✅ Good Cleanup
- Removed
base_scene_data_provider.py— This abstract interface appears to have been unused scaffolding. Removing dead code is welcome. - Removed unused test and helper functions in contact sensor (
_flatten_metadata,_broadcast_metadata_kind) and their test — Good hygiene removing unused code. - Removed
test_rerun_visualizer_marker_failure_still_ends_frame— If this test was testing removed functionality, deletion is appropriate.
📝 Minor Changes Noted
focal_lengthdefault: 12.0 → 15.0 — Slightly wider field of view. This seems like a UX tuning choice; no concerns.- Documentation wording: "tiled camera image view" → "tiled camera panel" — Cleaner terminology.
- Newton visualizer: Replaced
getattr(self, "_image_logger", None)with directself._image_loggeraccess — This is cleaner assuming_image_loggeris always initialized (even toNone) in__init__. Verified this is the case from the earlier review.
🔍 One Question
The removal of BaseSceneDataProvider is fairly substantial (79 lines of abstract interface). If this interface was planned for future use or part of a broader abstraction, ensure it's not needed by other planned backends. If it was truly unused, good riddance!
No new concerns with this incremental update. The PR continues to look solid.
Update (32f92a9): Reviewed the incremental changes since last review:
✅ Major Cleanup — Newton Renderer Simplification
- Removed compatibility shims in
newton_warp_renderer.py— Deleted ~60 lines ofhasattr()version-check fallbacks. The code now assumes a consistent Newton API with:self.newton_sensor.utils.compute_pinhole_camera_rays()self.newton_sensor.utils.create_default_light()newton.geometry.refit_bvh_shape()always present
- Removed
_create_sensor_config()and_apply_render_context_config()— These polymorphic config builders handled multiple Newton package layouts. Their removal suggests the team has standardized on a single Newton version.
utils module or have the alternate Config/RenderConfig split, this will break. This is likely intentional as part of a min-version bump.
📝 Other Changes
- Default config propagation — New
_apply_default_visualizer_cfg()insimulation_context.pycopies fields fromdefault_visualizer_cfgto backend-specific configs created via CLI. Good for consistent defaults across visualizer types. - Default value changes in
VisualizerCfg:tiled_cam_view:False→True(tiled cameras now on by default!)tiled_cam_num:57→16(more reasonable default tile count)
- Cleanup pattern change —
kit_visualizer.pyandnewton_visualizer.pynow callself._camera_sensor.__del__()directly instead ofgetattr(..., "__del__", None). This assumes the camera sensor always has a__del__method. - Documentation refinement — Section renamed "Camera Pose Behavior" → "Camera Modes" with cleaner formatting.
- New test —
test_default_visualizer_cfg_applies_to_cli_created_configs()verifies the default config propagation logic.
🔍 Minor Concern
Calling __del__() directly is unusual Python (normally left to garbage collector). It works if the destructor is idempotent, but ensure the camera sensor handles being explicitly destructed. A dedicated close() or cleanup() method would be more conventional.
Overall: Good simplification removing version-compatibility cruft. The Newton API has clearly stabilized.
Update (58e89e7): Reviewed the incremental changes since last review:
This commit adds ~3,800 lines of new code across 59 new/modified files. The changes have nothing to do with tiled camera views (the PR title). Instead, this commit:
- Adds Newton VBD deformable body support — Complete new physics backend integration
- Creates new deformable object APIs —
DeformableObject,DeformableObjectData,VBDSolverCfg - Adds coupled rigid-deformable solvers —
CoupledMJWarpVBDSolverCfg,CoupledFeatherstoneVBDSolverCfg - Creates new task environments —
Isaac-Lift-Soft-Franka-v0,Isaac-Lift-Cloth-Franka-v0 - Modifies PhysX deformable APIs — Deprecates old config names, adds backend-specific configs
- Adds extensive test suites — 717 lines in
test_deformable_object.pyalone
🛑 Recommendation: Split This PR
This commit should be a separate PR. Mixing unrelated large features makes review difficult and git history unclear. The visualizer tiled camera feature (PR title) is complete and should be merged separately from this Newton deformable integration.
📝 Quick Review of Deformable Changes
Despite the scope concern, the deformable implementation looks reasonable:
✅ Good patterns:
- Clean backend abstraction with
DeformableBodyPropertiesBaseCfgbase class - Newton-specific configs (
NewtonDeformableBodyPropertiesCfg) properly namespaced - Fabric sync for particle positions via
_sync_particle_pointskernel - Per-world builder hooks for multi-env deformable cloning
__del__()calls on camera sensors removed (line changes in visualizers) — This is actually an improvement fixing the earlier concern- Large amount of untested integration code with Newton backend — Runtime errors possible
DeformableBodyMaterialCfgandSurfaceDeformableBodyMaterialCfgdeprecated but still used in new task configs
Minor Visualizer Changes (Actual PR Scope)
- Kit visualizer now caches camera XformOps to avoid repeated USD queries — Performance improvement
- Added dirty flag pattern for camera pose updates — Avoids redundant syncs
- Removed
__del__()direct calls — Good cleanup per previous review suggestion
The visualizer changes in this commit are fine. The deformable integration needs its own PR for proper review.
Update (6c8a5a8): Reviewed the incremental changes since last review:
✅ Good DRY Refactoring
This commit extracts common scene_data_provider handling into the base class:
def _set_scene_data_provider(self, scene_data_provider: SceneDataProvider) -> SceneDataProvider:
"""Store the scene data provider shared by all visualizer backends."""
if scene_data_provider is None:
raise RuntimeError(f"{self.__class__.__name__} requires a scene_data_provider.")
self._scene_data_provider = scene_data_provider
return scene_data_providerChanges:
- New helper method in
BaseVisualizer— Consolidates null-checking and storage that was duplicated across Kit, Newton, Rerun, and Viser visualizers - Removed redundant
self._scene_data_provider = Nonefrom each visualizer's__init__— The base class now owns this attribute - Fixed duplicate test function — Removed the duplicated
test_web_visualizer_cfgs_do_not_open_browser_by_defaulttest - Added changelog entries — Properly documented the fixes for isaaclab and isaaclab_newton
📝 Minor Note
The changelog entry mentions "shared visualizer defaults for CLI-created visualizer configs" which appears to reference work from the previous commits (the _apply_default_visualizer_cfg() logic), making this a combined changelog for the feature branch. Good practice.
✅ Clean refactor. The pattern of returning the provider (return scene_data_provider) allows for fluent chaining in the initialize() methods — nice touch.
Update (9b5e682): Reviewed the incremental changes since last review:
✅ Module Reorganization — isaaclab.scene_data
This commit consolidates SceneDataProvider, SceneDataBackend, and SceneDataFormat into a new isaaclab.scene_data subpackage. This is a breaking change (documented in changelog fragments) but improves code organization:
- Moved
scene_data_backend.pyfromisaaclab.physics→isaaclab.scene_data - Moved
scene_data_provider.pyfromisaaclab.scene→isaaclab.scene_data - Updated all imports across physics backends, visualizers, and docs
- Enhanced
SceneDataFormatwith proper docstrings and Sphinx autodoc handling
✅ Bug Fixes
-
Removed duplicate
dispatch_callbacks()call insimulation_context.py— Good catch, the previous code was callingvis_marker_registry.dispatch_callbacks()twice per frame. -
Fixed stale
SimulationContextreference innewton_manager.py— Changed fromPhysicsManager._simtoSimulationContext.instance(). This prevents issues when the simulation context is recreated.
📝 Previous Inline Comments Status
- ✅ Direct
__del__invocation (P1) — Fixed! Camera sensors are now cleaned up by setting toNonerather than calling__del__()directly. - ✅ USD stage mutations per frame (P2) — Fixed! XformOps are now cached in
_generated_camera_xform_opsand reused. - ✅
env_idsparameter not forwarded (P2) — Fixed!apply_camera_view_from_originsnow passesenv_idstoset_world_poses_from_view. - ⏸️
tiled_cam_num=57default (P2) — Was already fixed in earlier commit (now defaults to 16). - ⏸️ DISPLAY check Linux-only (P2) — Still present but unchanged in this commit.
✅ Clean refactor. No new concerns with this incremental update. The previous inline comment issues have been addressed.
Description
Adds tiled camera views to Kit Visualizer and Newton Visualizer
Expands visualizer cfg to included tiled_camera fields
Adds a feature for tiled cameras to follow/track robot bodies
I will add some tiled visualizer tests once Isaac Sim CI image can be moved to latest develop.
Type of change
Screenshots
Please attach before and after screenshots of the change if applicable.
Checklist
pre-commitchecks with./isaaclab.sh --formatconfig/extension.tomlfileCONTRIBUTORS.mdor my name already exists there