Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ opt-level = 3
[workspace.dependencies]
serde = { version = "1.0" }
strum = { version = "0.26", features = ["derive"] }

image = { version = "0.25", default-features = false, features = ["png"] } # Keep in sync with bevy image version
rmf_site_picking = { path = "crates/rmf_site_picking", version = "0.0.2"}
rmf_site_format = { path = "crates/rmf_site_format", version = "0.0.2" }
rmf_site_editor = { path = "crates/rmf_site_editor", version = "0.0.3"}
Expand Down
1 change: 1 addition & 0 deletions crates/rmf_site_editor/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ sdformat = {workspace = true}
gz-fuel = {workspace = true}
pathdiff = {workspace = true}
ehttp = { workspace = true, features = ["native-async"] }
image = { workspace = true}
nalgebra = {workspace = true}
anyhow = {workspace = true}
uuid = { workspace = true, features = ["v4"] }
Expand Down
60 changes: 58 additions & 2 deletions crates/rmf_site_editor/src/occupancy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use crate::{
layers::ZLayer,
mapf_rse::{MAPFDebugDisplay, NegotiationRequest},
site::{Category, LevelElevation, NameOfSite, SiteAssets},
workspace::WorkspaceSaver,
};
use bevy::{
ecs::{hierarchy::ChildOf, relationship::AncestorIter},
Expand All @@ -41,9 +42,10 @@ impl Plugin for OccupancyPlugin {
fn build(&self, app: &mut App) {
app.add_event::<CalculateGridRequest>()
.add_event::<NegotiationRequest>()
.add_event::<ExportGridRequest>()
.init_resource::<MAPFDebugDisplay>()
.init_resource::<OccupancyInfo>()
.add_systems(Update, handle_calculate_grid_request);
.add_systems(Update, (handle_mapf_request, handle_export_request));
}
}

Expand Down Expand Up @@ -128,6 +130,14 @@ impl GridRange {
}
}

pub fn width(&self) -> usize {
self.min[0].abs_diff(self.max[0]) as usize
}

pub fn height(&self) -> usize {
self.min[1].abs_diff(self.max[1]) as usize
}

pub fn include(&mut self, cell: Cell) {
self.min[0] = self.min[0].min(cell.x);
self.min[1] = self.min[1].min(cell.y);
Expand All @@ -154,6 +164,9 @@ impl GridRange {
}
}

#[derive(Event)]
pub struct ExportGridRequest;

#[derive(Event)]
pub struct CalculateGridRequest;

Expand Down Expand Up @@ -185,7 +198,50 @@ enum Group {
None,
}

fn handle_calculate_grid_request(
fn handle_export_request(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm generally not too excited about this function since it's pretty much the exact same as the one below, with one line of difference in "what we do after calculate_grid is over".

My preference would be to refactor them into a single function, on top of my head I can think of a few ways:

  • Refactor the two input events ExportGridRequest and CalculateGridRequest into a single event that has an additional field that says "what do we do with the output", we could match it and either send the saving event (your function) or send the replan event (the original function).
  • Make the function generic, perhaps as a generic parameter a closure that takes World and decides what to do after the grid is exported?
  • Bite the bullet and make this a workflow, which is quite a good fit for "sequence of operations that we need to run one after the other", so we could have the first node of the workflow that handles the calculate_grid request in a common service, then two workflows, one to calculate the occupancy grid and replan and the other one to calculate the occupancy grid and send a file dialog request.

First is quick and easy, second is possibly not a great idea, third would probably be the best but a bit more work to implement.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had done 1 earlier (before having to rewrite the entire PR): #389 (comment)

2 will make the code unnecessarily complex.

3 is a fair deal more of work but probably the correct way to handle it.

mut request: EventReader<ExportGridRequest>,
occupancy_info: Res<OccupancyInfo>,
robots: Query<Entity, With<Robot>>,
mut commands: Commands,
bodies: Query<(Entity, &Mesh3d, &Aabb, &GlobalTransform)>,
meta: Query<(
Option<&ChildOf>,
Option<&Category>,
Option<&ComputedVisualCue>,
)>,
child_of: Query<&ChildOf>,
levels: Query<Entity, With<LevelElevation>>,
sites: Query<(), With<NameOfSite>>,
mut meshes: ResMut<Assets<Mesh>>,
assets: Res<SiteAssets>,
grids: Query<Entity, With<Grid>>,
display_mapf_debug: Res<MAPFDebugDisplay>,
mut workspace_saver: WorkspaceSaver,
) {
if let Some(export_req) = request.read().last() {
let grid = CalculateGrid {
cell_size: occupancy_info.cell_size,
ignore: robots.iter().collect(),
..default()
};
calculate_grid(
&grid,
&mut commands,
&bodies,
&meta,
&child_of,
&levels,
&sites,
&mut meshes,
&assets,
&grids,
&display_mapf_debug,
);
workspace_saver.export_occupancy_to_dialog();
}
}

fn handle_mapf_request(
mut request: EventReader<CalculateGridRequest>,
occupancy_info: Res<OccupancyInfo>,
robots: Query<Entity, With<Robot>>,
Expand Down
43 changes: 42 additions & 1 deletion crates/rmf_site_editor/src/site/save.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ use std::{
};
use thiserror::Error as ThisError;

use crate::{exit_confirmation::SiteChanged, recency::RecencyRanking, site::*, ExportFormat};
use crate::{
exit_confirmation::SiteChanged, occupancy::Grid, recency::RecencyRanking, site::*, ExportFormat,
};
use rmf_site_format::*;
use sdformat::yaserde;

Expand Down Expand Up @@ -1759,6 +1761,42 @@ pub fn generate_site(
});
}

pub fn export_grid(world: &mut World, path: &PathBuf) {
let mut system_state: SystemState<(Query<(&Grid, &ChildOf)>, Query<&NameInSite>)> =
SystemState::new(world);
let (grids, names) = system_state.get(&world);
let mut num_grids_saved = 0;
for (grid, parent) in grids {
let mut img = image::RgbImage::new(
(grid.range.width() + 1) as u32,
(grid.range.height() + 1) as u32,
);

img.fill(255u8);
let Ok(name) = names.get(parent.0) else {
error!("Could not get level name");
continue;
};

for cell in &grid.occupied {
img.put_pixel(
(cell.x - grid.range.min_cell().x) as u32,
(cell.y - grid.range.min_cell().y) as u32,
image::Rgb([0, 0, 0]),
);
}

let mut path = path.clone();
path.push(format!("occupancy.{}.png", name.0));
if let Err(err_str) = img.save(path) {
error!("Could not save image: {:?}", err_str);
} else {
num_grids_saved += 1;
}
}
info!("Successfully exported {} occupancy grids", num_grids_saved);
}

pub fn save_site(world: &mut World) {
let save_events: Vec<_> = world.resource_mut::<Events<SaveSite>>().drain().collect();
for save_event in save_events {
Expand Down Expand Up @@ -1917,6 +1955,9 @@ pub fn save_site(world: &mut World) {
new_path.to_str().unwrap_or("<failed to render??>")
);
}
ExportFormat::OccupancyGrid => {
export_grid(world, &new_path);
}
}
}
}
Expand Down
5 changes: 5 additions & 0 deletions crates/rmf_site_editor/src/widgets/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@ pub use inspector::*;
pub mod move_layer;
pub use move_layer::*;

pub mod occupancy_export_menu;
pub use occupancy_export_menu::*;

pub mod sdf_export_menu;
use rmf_site_egui::*;
use rmf_site_picking::{Hover, SelectionServiceStages, UiFocused};
Expand Down Expand Up @@ -168,6 +171,8 @@ impl Plugin for StandardUiPlugin {
SdfExportMenuPlugin::default(),
#[cfg(not(target_arch = "wasm32"))]
NavGraphIoPlugin::default(),
#[cfg(not(target_arch = "wasm32"))]
OccupancyExportMenuPlugin::default(),
))
.add_systems(Startup, init_ui_style)
.add_systems(
Expand Down
100 changes: 100 additions & 0 deletions crates/rmf_site_editor/src/widgets/occupancy_export_menu.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
/*
* Copyright (C) 2025 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/

use crate::{
occupancy::{CalculateGrid, ExportGridRequest, OccupancyInfo},
AppState, WorkspaceSaver,
};
use bevy::{ecs::hierarchy::ChildOf, prelude::*};
use bevy_egui::{
egui::{self, DragValue},
EguiContexts,
};
use rmf_site_egui::*;

/// Keeps track of which entity is associated to the export sdf button.
#[derive(Resource)]
pub struct OccupancyExportMenu {
export_sdf: Entity,
}

impl OccupancyExportMenu {
pub fn get(&self) -> Entity {
self.export_sdf
}
}

impl FromWorld for OccupancyExportMenu {
fn from_world(world: &mut World) -> Self {
let file_header = world.resource::<FileMenu>().get();
let export_sdf = world
.spawn((
MenuItem::Text(TextMenuItem::new("Export Occupancy")),
ChildOf(file_header),
))
.id();

OccupancyExportMenu { export_sdf }
}
}

#[derive(Default)]
struct ExportOccupancyConfig {
visible: bool,
}

fn handle_export_occupancy_menu_events(
mut menu_events: EventReader<MenuEvent>,
mut export_event: EventWriter<ExportGridRequest>,
occupancy_menu: Res<OccupancyExportMenu>,
mut occupancy_info: ResMut<OccupancyInfo>,
mut egui_context: EguiContexts,
mut configuration: Local<ExportOccupancyConfig>,
) {
for event in menu_events.read() {
if event.clicked() && event.source() == occupancy_menu.get() {
configuration.visible = true;
}
}

if !configuration.visible {
return;
}

egui::Window::new("Occupancy Export Options").show(egui_context.ctx_mut(), |ui| {
ui.horizontal(|ui| {
ui.label("Cell Size:");
ui.add(DragValue::new(&mut occupancy_info.cell_size));
});
if ui.button("Export").clicked() {
configuration.visible = false;
export_event.write(ExportGridRequest);
}
});
}

#[derive(Default)]
pub struct OccupancyExportMenuPlugin {}

impl Plugin for OccupancyExportMenuPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<OccupancyExportMenu>().add_systems(
Update,
handle_export_occupancy_menu_events.run_if(AppState::in_displaying_mode()),
);
}
}
21 changes: 21 additions & 0 deletions crates/rmf_site_editor/src/workspace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ pub enum ExportFormat {
Default,
Sdf,
NavGraph,
OccupancyGrid,
}

/// Used to keep track of visibility when switching workspace
Expand Down Expand Up @@ -518,6 +519,8 @@ pub struct WorkspaceSavingServices {
pub export_nav_graphs_to_dialog: Service<(), ()>,
/// Exports the nav graphs from the requested site to the requested path.
pub export_nav_graphs_to_path: Service<PathBuf, ()>,
/// Exports Occupancy Grid from the requested
pub export_occupancy_grid: Service<(), ()>,
}

impl FromWorld for WorkspaceSavingServices {
Expand Down Expand Up @@ -616,6 +619,16 @@ impl FromWorld for WorkspaceSavingServices {
.connect(scope.terminate)
});

let export_occupancy_grid = world.spawn_workflow(|scope, builder| {
scope
.input
.chain(builder)
.then(pick_folder)
.map_block(|path| (path, ExportFormat::OccupancyGrid))
.then(send_file_save)
.connect(scope.terminate)
});

Self {
save_workspace_to_dialog,
save_workspace_to_path,
Expand All @@ -624,6 +637,7 @@ impl FromWorld for WorkspaceSavingServices {
export_sdf_to_path,
export_nav_graphs_to_dialog,
export_nav_graphs_to_path,
export_occupancy_grid,
}
}
}
Expand Down Expand Up @@ -681,6 +695,13 @@ impl<'w, 's> WorkspaceSaver<'w, 's> {
.request(path, self.workspace_saving.export_nav_graphs_to_path)
.detach();
}

/// Request to export the occupancy grid
pub fn export_occupancy_to_dialog(&mut self) {
self.commands
.request((), self.workspace_saving.export_occupancy_grid)
.detach();
}
}

/// `SystemParam` used to request for workspace loading operations
Expand Down
Loading