This commit is contained in:
1 parent
d1a56f77cc
commit
0e7aed40f1
21 files changed
+1253
-19
No files matched your search
@@ -39,6 +39,7 @@ pub use viewport::brush_tool;
|
||||
pub use viewport::camera;
|
||||
pub use viewport::gizmos;
|
||||
pub use viewport::material_drop;
|
||||
pub use viewport::physics_placement;
|
||||
pub use viewport::render_view;
|
||||
pub use viewport::rendering_diagnostics;
|
||||
pub use viewport::selection;
|
||||
@@ -68,6 +69,7 @@ use history::EditorHistoryPlugin;
|
||||
use infra::EditorInfraPlugin;
|
||||
use material_drop::MaterialDropPlugin;
|
||||
use operators::OperatorPlugin;
|
||||
use physics_placement::PhysicsPlacementPlugin;
|
||||
use play::audio_preview::AudioPreviewPlugin;
|
||||
use play::PlaySessionPlugin;
|
||||
use project::collaboration::CollaborationPlugin;
|
||||
@@ -119,6 +121,7 @@ impl PluginGroup for EditorPluginGroup {
|
||||
.add(AudioPreviewPlugin)
|
||||
.add(ActorIconsPlugin)
|
||||
.add(MaterialDropPlugin)
|
||||
.add(PhysicsPlacementPlugin)
|
||||
.add(EditorSelectionPlugin)
|
||||
.add(SelectionOutlinePlugin)
|
||||
.add(EditorGizmoPlugin)
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use avian3d::prelude::{Physics, PhysicsTime};
|
||||
use bevy::prelude::*;
|
||||
use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
|
||||
use bevy_egui::PrimaryEguiContext;
|
||||
use game::player::PlayerCamera;
|
||||
use game::{GameInputEnabled, GameInputFocused, SimEnabled};
|
||||
use protocol::PlayerInputIntent;
|
||||
use protocol::{PlayerInputIntent, SIM_TICK_RATE_HZ};
|
||||
use sim::{Crouching, Grounded, JumpState, Player, PlayerVelocity};
|
||||
|
||||
use crate::camera::EditorCamera;
|
||||
@@ -195,6 +198,7 @@ pub(crate) fn sync_mode_resources_and_cameras(
|
||||
mut step: ResMut<PlayStepOnce>,
|
||||
mut input_enabled: ResMut<GameInputEnabled>,
|
||||
mut sim_enabled: ResMut<SimEnabled>,
|
||||
mut physics_time: ResMut<Time<Physics>>,
|
||||
mut editor_cameras: Query<&mut Camera, With<EditorCamera>>,
|
||||
mut player_cameras: Query<&mut Camera, (With<PlayerCamera>, Without<EditorCamera>)>,
|
||||
mut egui_cameras: Query<
|
||||
@@ -212,9 +216,11 @@ pub(crate) fn sync_mode_resources_and_cameras(
|
||||
let ejected = playing && *possession == PlayPossession::Ejected;
|
||||
let possessed = playing && *possession == PlayPossession::Possessed;
|
||||
|
||||
sim_enabled.0 = playing && (!paused.0 || step.0);
|
||||
let stepping = step.0;
|
||||
sim_enabled.0 = playing && (!paused.0 || stepping);
|
||||
input_enabled.0 = possessed && !paused.0;
|
||||
if step.0 {
|
||||
sync_editor_physics_clock(&mut physics_time, playing, paused.0, stepping);
|
||||
if stepping {
|
||||
step.0 = false;
|
||||
}
|
||||
|
||||
@@ -240,6 +246,22 @@ pub(crate) fn sync_mode_resources_and_cameras(
|
||||
}
|
||||
}
|
||||
|
||||
fn sync_editor_physics_clock(
|
||||
physics_time: &mut Time<Physics>,
|
||||
playing: bool,
|
||||
paused: bool,
|
||||
stepping: bool,
|
||||
) {
|
||||
if playing && !paused {
|
||||
physics_time.unpause();
|
||||
return;
|
||||
}
|
||||
physics_time.pause();
|
||||
if playing && stepping {
|
||||
physics_time.advance_by(Duration::from_secs_f64(1.0 / SIM_TICK_RATE_HZ as f64));
|
||||
}
|
||||
}
|
||||
|
||||
fn sync_play_input_focus(
|
||||
mode: Res<State<EditorMode>>,
|
||||
possession: Res<PlayPossession>,
|
||||
@@ -414,3 +436,29 @@ pub fn toggle_play_possession_world(world: &mut World) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn editor_physics_clock_tracks_edit_play_pause_and_single_step() {
|
||||
let mut time = Time::<Physics>::default();
|
||||
|
||||
sync_editor_physics_clock(&mut time, false, false, false);
|
||||
assert!(time.is_paused());
|
||||
|
||||
sync_editor_physics_clock(&mut time, true, false, false);
|
||||
assert!(!time.is_paused());
|
||||
|
||||
sync_editor_physics_clock(&mut time, true, true, false);
|
||||
assert!(time.is_paused());
|
||||
|
||||
sync_editor_physics_clock(&mut time, true, true, true);
|
||||
assert!(time.is_paused());
|
||||
assert_eq!(
|
||||
time.delta(),
|
||||
Duration::from_secs_f64(1.0 / SIM_TICK_RATE_HZ as f64)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,10 @@ use crate::state::PlayPossession;
|
||||
use crate::viewport::actor_icons::ActorIconSettings;
|
||||
use crate::viewport::brush_edit::{BrushEditMode, BrushElementSelection};
|
||||
use crate::viewport::brush_tool::{BrushToolPhase, BrushToolState};
|
||||
use crate::viewport::physics_placement::{
|
||||
begin_physics_placement, request_physics_placement, PhysicsPlacementPhase,
|
||||
PhysicsPlacementRequest, PhysicsPlacementState,
|
||||
};
|
||||
use crate::viewport::terrain_paint::{TerrainPaintMode, TerrainPaintState};
|
||||
use crate::viewport::terrain_sculpt::{TerrainSculptMode, TerrainSculptState};
|
||||
use crate::viewport::{
|
||||
@@ -146,11 +150,12 @@ pub fn viewport_tab_ui(
|
||||
return;
|
||||
}
|
||||
|
||||
scene_view_overlay_toolbar(world, ui.ctx(), rect);
|
||||
scene_view_overlay_toolbar(world, ui.ctx(), rect, selected_entities);
|
||||
scene_view_selection_hud(world, ui.ctx(), rect, selected_entities);
|
||||
scene_view_brush_draw_hints(world, ui.ctx(), rect);
|
||||
scene_view_terrain_sculpt_hints(world, ui.ctx(), rect);
|
||||
scene_view_terrain_paint_hints(world, ui.ctx(), rect);
|
||||
scene_view_physics_placement_hud(world, ui.ctx(), rect);
|
||||
scene_view_render_badge(world, ui.ctx(), rect);
|
||||
scene_view_brush_mode_badge(world, ui.ctx(), rect);
|
||||
scene_view_volume_hud(world, ui.ctx(), rect);
|
||||
@@ -582,7 +587,12 @@ fn scene_view_volume_hud(world: &World, ctx: &egui::Context, scene_rect: egui::R
|
||||
});
|
||||
}
|
||||
|
||||
fn scene_view_overlay_toolbar(world: &mut World, ctx: &egui::Context, scene_rect: egui::Rect) {
|
||||
fn scene_view_overlay_toolbar(
|
||||
world: &mut World,
|
||||
ctx: &egui::Context,
|
||||
scene_rect: egui::Rect,
|
||||
selected_entities: &SelectedEntities,
|
||||
) {
|
||||
let mut options_open = world.resource::<ViewportUiState>().options_open;
|
||||
let mut shortcuts_open = world.resource::<ViewportUiState>().shortcuts_open;
|
||||
let terrain_selected = world
|
||||
@@ -737,6 +747,56 @@ fn scene_view_overlay_toolbar(world: &mut World, ctx: &egui::Context, scene_rect
|
||||
}
|
||||
}
|
||||
|
||||
let placement_active = world.resource::<PhysicsPlacementState>().active();
|
||||
ui.separator();
|
||||
if placement_active {
|
||||
let phase = world.resource::<PhysicsPlacementState>().phase;
|
||||
ui.label(
|
||||
egui::RichText::new(phase.label())
|
||||
.color(match phase {
|
||||
PhysicsPlacementPhase::Settled => SUCCESS,
|
||||
PhysicsPlacementPhase::TimedOut => WARNING,
|
||||
_ => SELECTION,
|
||||
})
|
||||
.strong()
|
||||
.small(),
|
||||
);
|
||||
if icon_button_small(
|
||||
ui,
|
||||
icons::CHECK,
|
||||
"Commit physics placement (Enter when settled)",
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
request_physics_placement(world, PhysicsPlacementRequest::Commit);
|
||||
}
|
||||
if icon_button_small(ui, icons::X, "Cancel physics placement (Esc)")
|
||||
.clicked()
|
||||
{
|
||||
request_physics_placement(world, PhysicsPlacementRequest::Cancel);
|
||||
}
|
||||
} else {
|
||||
let selected = selected_entities.iter().collect::<Vec<_>>();
|
||||
let can_start = !selected.is_empty();
|
||||
let clicked = ui
|
||||
.add_enabled(
|
||||
can_start,
|
||||
egui::Button::new(phosphor_icon(icons::HAND_ARROW_DOWN, 16.0)),
|
||||
)
|
||||
.on_hover_text(if can_start {
|
||||
"Release selected props into physics"
|
||||
} else {
|
||||
"Select one or more props to place with physics"
|
||||
})
|
||||
.clicked();
|
||||
if clicked && begin_physics_placement(world, selected).is_ok() {
|
||||
world.resource_mut::<TerrainSculptState>().stop();
|
||||
world.resource_mut::<TerrainPaintState>().stop();
|
||||
world.resource_mut::<BrushToolState>().cancel();
|
||||
world.resource_mut::<ViewportClick>().0 = None;
|
||||
}
|
||||
}
|
||||
|
||||
let sculpt_active = world.resource::<TerrainSculptState>().active;
|
||||
let paint_active = world.resource::<TerrainPaintState>().active;
|
||||
if terrain_selected.is_some() || sculpt_active || paint_active {
|
||||
@@ -950,6 +1010,66 @@ fn scene_view_overlay_toolbar(world: &mut World, ctx: &egui::Context, scene_rect
|
||||
world.resource_mut::<ViewportUiState>().shortcuts_open = shortcuts_open;
|
||||
}
|
||||
|
||||
fn scene_view_physics_placement_hud(world: &World, ctx: &egui::Context, scene_rect: egui::Rect) {
|
||||
let state = world.resource::<PhysicsPlacementState>();
|
||||
if !state.active() {
|
||||
let Some(error) = state.last_error.as_deref() else {
|
||||
return;
|
||||
};
|
||||
egui::Area::new(egui::Id::new("scene_view_physics_placement_error"))
|
||||
.fixed_pos(scene_rect.left_top() + egui::vec2(8.0, 52.0))
|
||||
.interactable(false)
|
||||
.show(ctx, |ui| {
|
||||
overlay_chip_frame().show(ui, |ui| {
|
||||
ui.label(
|
||||
egui::RichText::new("Physics placement unavailable")
|
||||
.color(ERROR)
|
||||
.strong(),
|
||||
);
|
||||
for line in error.lines().take(4) {
|
||||
ui.label(egui::RichText::new(line).color(TEXT_DIM).small());
|
||||
}
|
||||
});
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
egui::Area::new(egui::Id::new("scene_view_physics_placement_hud"))
|
||||
.fixed_pos(scene_rect.left_top() + egui::vec2(8.0, 52.0))
|
||||
.interactable(false)
|
||||
.show(ctx, |ui| {
|
||||
overlay_chip_frame().show(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(phosphor_icon(icons::HAND_ARROW_DOWN, 16.0).color(SELECTION));
|
||||
ui.label(
|
||||
egui::RichText::new(format!("Physics Placement / {}", state.phase.label()))
|
||||
.color(match state.phase {
|
||||
PhysicsPlacementPhase::Settled => SUCCESS,
|
||||
PhysicsPlacementPhase::TimedOut => WARNING,
|
||||
_ => SELECTION,
|
||||
})
|
||||
.strong(),
|
||||
);
|
||||
ui.label(
|
||||
egui::RichText::new(format!(
|
||||
"{} props / {:.1}s",
|
||||
state.selected_count,
|
||||
state.simulated_seconds()
|
||||
))
|
||||
.color(TEXT_DIM)
|
||||
.monospace()
|
||||
.small(),
|
||||
);
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
key_hint(ui, "Esc", "Cancel");
|
||||
key_hint(ui, "Enter", "Commit when settled");
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn scene_options_popover(
|
||||
world: &mut World,
|
||||
ctx: &egui::Context,
|
||||
|
||||
@@ -8,6 +8,7 @@ pub mod camera;
|
||||
pub mod gizmos;
|
||||
pub mod material_drop;
|
||||
mod panel;
|
||||
pub mod physics_placement;
|
||||
pub mod render_view;
|
||||
pub mod rendering_diagnostics;
|
||||
pub mod selection;
|
||||
@@ -26,6 +27,7 @@ pub use brush_edit::{BrushEditMode, BrushEditPlugin, BrushElementSelection};
|
||||
pub use brush_tool::{BrushToolPlugin, BrushToolState};
|
||||
pub use material_drop::{MaterialDropFeedback, MaterialDropPlugin, MaterialDropState};
|
||||
pub use panel::*;
|
||||
pub use physics_placement::{PhysicsPlacementPlugin, PhysicsPlacementState};
|
||||
pub use terrain_paint::{TerrainPaintMode, TerrainPaintPlugin, TerrainPaintState};
|
||||
pub use terrain_sculpt::{TerrainSculptMode, TerrainSculptPlugin, TerrainSculptState};
|
||||
pub use viewport_mode::EditorViewportMode;
|
||||
@@ -0,0 +1,670 @@
|
||||
//! Transactional gravity placement using the editor's hydrated Avian world.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::time::Duration;
|
||||
|
||||
use avian3d::prelude::*;
|
||||
use bevy::prelude::*;
|
||||
use shared::{
|
||||
authoring_component_active, AuthoringComponentStates, ColliderDesc, InspectorOrder,
|
||||
PhysicsBody, RigidBodyDesc, COMPONENT_COLLIDER_DESC, COMPONENT_PHYSICS_BODY,
|
||||
COMPONENT_RIGID_BODY_DESC,
|
||||
};
|
||||
|
||||
use crate::history::set_transform_group_with_history;
|
||||
use crate::operators::{ActiveOperator, OperatorPhase, OperatorStatus};
|
||||
use crate::state::EditorMode;
|
||||
use crate::ui::selection_ops::{entity_name, is_mutable_level_object};
|
||||
|
||||
const STEP_HZ: f64 = 120.0;
|
||||
const STEPS_PER_FRAME: usize = 4;
|
||||
const SETTLE_LINEAR_SPEED: f32 = 0.04;
|
||||
const SETTLE_ANGULAR_SPEED: f32 = 0.04;
|
||||
const SETTLE_STEPS: u32 = 30;
|
||||
const MAX_STEPS: u32 = 1_200;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum PhysicsPlacementPhase {
|
||||
#[default]
|
||||
Inactive,
|
||||
Dropping,
|
||||
Settled,
|
||||
TimedOut,
|
||||
}
|
||||
|
||||
impl PhysicsPlacementPhase {
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Inactive => "Inactive",
|
||||
Self::Dropping => "Simulating",
|
||||
Self::Settled => "Settled",
|
||||
Self::TimedOut => "Preview stopped",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum PhysicsPlacementRequest {
|
||||
#[default]
|
||||
None,
|
||||
Commit,
|
||||
Cancel,
|
||||
}
|
||||
|
||||
#[derive(Component, Debug, Clone, Copy, Default)]
|
||||
pub struct PhysicsPlacementPreview;
|
||||
|
||||
#[derive(Resource, Debug, Default)]
|
||||
pub struct PhysicsPlacementState {
|
||||
pub phase: PhysicsPlacementPhase,
|
||||
pub request: PhysicsPlacementRequest,
|
||||
pub last_error: Option<String>,
|
||||
pub selected_count: usize,
|
||||
pub simulated_steps: u32,
|
||||
session: Option<PlacementSession>,
|
||||
}
|
||||
|
||||
impl PhysicsPlacementState {
|
||||
pub fn active(&self) -> bool {
|
||||
self.session.is_some()
|
||||
}
|
||||
|
||||
pub fn simulated_seconds(&self) -> f32 {
|
||||
self.simulated_steps as f32 / STEP_HZ as f32
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct PlacementSession {
|
||||
selected: Vec<BodySnapshot>,
|
||||
frozen: Vec<BodySnapshot>,
|
||||
stable_steps: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct BodySnapshot {
|
||||
entity: Entity,
|
||||
transform: Transform,
|
||||
position: Option<Position>,
|
||||
rotation: Option<Rotation>,
|
||||
rigid_body: RigidBody,
|
||||
linear_velocity: Option<LinearVelocity>,
|
||||
angular_velocity: Option<AngularVelocity>,
|
||||
gravity_scale: Option<GravityScale>,
|
||||
sleeping: bool,
|
||||
sleeping_disabled: bool,
|
||||
rigid_body_disabled: bool,
|
||||
}
|
||||
|
||||
impl BodySnapshot {
|
||||
fn capture(world: &World, entity: Entity) -> Result<Self, String> {
|
||||
Ok(Self {
|
||||
entity,
|
||||
transform: world
|
||||
.get::<Transform>(entity)
|
||||
.copied()
|
||||
.ok_or_else(|| format!("{} has no Transform", entity_name(world, entity)))?,
|
||||
position: world.get::<Position>(entity).copied(),
|
||||
rotation: world.get::<Rotation>(entity).copied(),
|
||||
rigid_body: world.get::<RigidBody>(entity).copied().ok_or_else(|| {
|
||||
format!("{} has no hydrated rigid body", entity_name(world, entity))
|
||||
})?,
|
||||
linear_velocity: world.get::<LinearVelocity>(entity).copied(),
|
||||
angular_velocity: world.get::<AngularVelocity>(entity).copied(),
|
||||
gravity_scale: world.get::<GravityScale>(entity).copied(),
|
||||
sleeping: world.get::<Sleeping>(entity).is_some(),
|
||||
sleeping_disabled: world.get::<SleepingDisabled>(entity).is_some(),
|
||||
rigid_body_disabled: world.get::<RigidBodyDisabled>(entity).is_some(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct PhysicsPlacementPlugin;
|
||||
|
||||
impl Plugin for PhysicsPlacementPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_resource::<PhysicsPlacementState>()
|
||||
.add_systems(PostStartup, pause_physics_for_editor)
|
||||
.add_systems(PostUpdate, tick_physics_placement)
|
||||
.add_systems(OnExit(EditorMode::Editing), cancel_physics_placement);
|
||||
}
|
||||
}
|
||||
|
||||
fn pause_physics_for_editor(mut physics_time: ResMut<Time<Physics>>) {
|
||||
physics_time.pause();
|
||||
}
|
||||
|
||||
pub fn begin_physics_placement(
|
||||
world: &mut World,
|
||||
selected: impl IntoIterator<Item = Entity>,
|
||||
) -> Result<(), String> {
|
||||
if *world.resource::<State<EditorMode>>().get() != EditorMode::Editing {
|
||||
return placement_error(world, "Physics placement is available only in Edit mode");
|
||||
}
|
||||
if world.resource::<PhysicsPlacementState>().active() {
|
||||
return placement_error(world, "A physics placement preview is already active");
|
||||
}
|
||||
|
||||
let mut unique = HashSet::new();
|
||||
let selected = selected
|
||||
.into_iter()
|
||||
.filter(|entity| unique.insert(*entity))
|
||||
.collect::<Vec<_>>();
|
||||
validate_selection(world, &selected)?;
|
||||
|
||||
let selected_set = selected.iter().copied().collect::<HashSet<_>>();
|
||||
let selected_snapshots = selected
|
||||
.iter()
|
||||
.map(|entity| BodySnapshot::capture(world, *entity))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
let movable = world
|
||||
.query::<(Entity, &RigidBody)>()
|
||||
.iter(world)
|
||||
.filter_map(|(entity, body)| {
|
||||
(!selected_set.contains(&entity) && *body != RigidBody::Static).then_some(entity)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let frozen_snapshots = movable
|
||||
.iter()
|
||||
.map(|entity| BodySnapshot::capture(world, *entity))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
for snapshot in &frozen_snapshots {
|
||||
if let Ok(mut entity) = world.get_entity_mut(snapshot.entity) {
|
||||
entity.insert(RigidBody::Static);
|
||||
}
|
||||
}
|
||||
for snapshot in &selected_snapshots {
|
||||
let global = world
|
||||
.get::<GlobalTransform>(snapshot.entity)
|
||||
.copied()
|
||||
.unwrap_or_else(|| GlobalTransform::from(snapshot.transform));
|
||||
if let Ok(mut entity) = world.get_entity_mut(snapshot.entity) {
|
||||
entity.insert((
|
||||
RigidBody::Dynamic,
|
||||
LinearVelocity::ZERO,
|
||||
AngularVelocity::ZERO,
|
||||
GravityScale(1.0),
|
||||
Position(global.translation()),
|
||||
Rotation(global.rotation()),
|
||||
PhysicsPlacementPreview,
|
||||
));
|
||||
entity.remove::<Sleeping>();
|
||||
entity.remove::<RigidBodyDisabled>();
|
||||
}
|
||||
}
|
||||
|
||||
let selected_count = selected_snapshots.len();
|
||||
let mut state = world.resource_mut::<PhysicsPlacementState>();
|
||||
state.phase = PhysicsPlacementPhase::Dropping;
|
||||
state.request = PhysicsPlacementRequest::None;
|
||||
state.last_error = None;
|
||||
state.selected_count = selected_count;
|
||||
state.simulated_steps = 0;
|
||||
state.session = Some(PlacementSession {
|
||||
selected: selected_snapshots,
|
||||
frozen: frozen_snapshots,
|
||||
stable_steps: 0,
|
||||
});
|
||||
set_operator_status(
|
||||
world,
|
||||
OperatorPhase::Preview,
|
||||
format!("Dropping {selected_count} selected prop(s)"),
|
||||
Vec::new(),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn request_physics_placement(world: &mut World, request: PhysicsPlacementRequest) {
|
||||
if world.resource::<PhysicsPlacementState>().active() {
|
||||
world.resource_mut::<PhysicsPlacementState>().request = request;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cancel_physics_placement(world: &mut World) {
|
||||
finish_physics_placement(world, false);
|
||||
}
|
||||
|
||||
pub fn commit_physics_placement(world: &mut World) {
|
||||
finish_physics_placement(world, true);
|
||||
}
|
||||
|
||||
fn finish_physics_placement(world: &mut World, commit: bool) {
|
||||
let Some(mut state) = world.remove_resource::<PhysicsPlacementState>() else {
|
||||
return;
|
||||
};
|
||||
let Some(session) = state.session.take() else {
|
||||
world.insert_resource(state);
|
||||
return;
|
||||
};
|
||||
|
||||
let final_transforms = session
|
||||
.selected
|
||||
.iter()
|
||||
.filter_map(|snapshot| {
|
||||
world
|
||||
.get::<Transform>(snapshot.entity)
|
||||
.copied()
|
||||
.map(|transform| (snapshot.entity, transform))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
for snapshot in &session.frozen {
|
||||
restore_snapshot(world, snapshot, true);
|
||||
}
|
||||
for snapshot in &session.selected {
|
||||
restore_snapshot(world, snapshot, !commit);
|
||||
if let Ok(mut entity) = world.get_entity_mut(snapshot.entity) {
|
||||
entity.remove::<PhysicsPlacementPreview>();
|
||||
}
|
||||
}
|
||||
|
||||
if commit {
|
||||
let changes = session.selected.iter().filter_map(|snapshot| {
|
||||
final_transforms
|
||||
.iter()
|
||||
.find(|(entity, _)| *entity == snapshot.entity)
|
||||
.map(|(_, new)| (snapshot.entity, snapshot.transform, *new))
|
||||
});
|
||||
set_transform_group_with_history(world, changes);
|
||||
}
|
||||
|
||||
state.phase = PhysicsPlacementPhase::Inactive;
|
||||
state.request = PhysicsPlacementRequest::None;
|
||||
state.selected_count = 0;
|
||||
state.simulated_steps = 0;
|
||||
state.last_error = None;
|
||||
world.insert_resource(state);
|
||||
clear_operator_status(world);
|
||||
}
|
||||
|
||||
fn tick_physics_placement(world: &mut World) {
|
||||
let escape = world
|
||||
.get_resource::<ButtonInput<KeyCode>>()
|
||||
.is_some_and(|keys| keys.just_pressed(KeyCode::Escape));
|
||||
let enter = world
|
||||
.get_resource::<ButtonInput<KeyCode>>()
|
||||
.is_some_and(|keys| keys.just_pressed(KeyCode::Enter));
|
||||
let request = world.resource::<PhysicsPlacementState>().request;
|
||||
let settled = matches!(
|
||||
world.resource::<PhysicsPlacementState>().phase,
|
||||
PhysicsPlacementPhase::Settled | PhysicsPlacementPhase::TimedOut
|
||||
);
|
||||
if escape || request == PhysicsPlacementRequest::Cancel {
|
||||
cancel_physics_placement(world);
|
||||
return;
|
||||
}
|
||||
if request == PhysicsPlacementRequest::Commit || (enter && settled) {
|
||||
commit_physics_placement(world);
|
||||
return;
|
||||
}
|
||||
if world.resource::<PhysicsPlacementState>().phase != PhysicsPlacementPhase::Dropping {
|
||||
return;
|
||||
}
|
||||
|
||||
for _ in 0..STEPS_PER_FRAME {
|
||||
world
|
||||
.resource_mut::<Time<Physics>>()
|
||||
.advance_by(Duration::from_secs_f64(1.0 / STEP_HZ));
|
||||
world.run_schedule(FixedPostUpdate);
|
||||
}
|
||||
|
||||
let Some(mut state) = world.remove_resource::<PhysicsPlacementState>() else {
|
||||
return;
|
||||
};
|
||||
state.simulated_steps = state.simulated_steps.saturating_add(STEPS_PER_FRAME as u32);
|
||||
let Some(session) = state.session.as_mut() else {
|
||||
world.insert_resource(state);
|
||||
return;
|
||||
};
|
||||
let at_rest = session.selected.iter().all(|snapshot| {
|
||||
let linear = world
|
||||
.get::<LinearVelocity>(snapshot.entity)
|
||||
.map_or(0.0, |velocity| velocity.length());
|
||||
let angular = world
|
||||
.get::<AngularVelocity>(snapshot.entity)
|
||||
.map_or(0.0, |velocity| velocity.length());
|
||||
(linear <= SETTLE_LINEAR_SPEED && angular <= SETTLE_ANGULAR_SPEED)
|
||||
|| world.get::<Sleeping>(snapshot.entity).is_some()
|
||||
});
|
||||
session.stable_steps = if at_rest {
|
||||
session.stable_steps.saturating_add(STEPS_PER_FRAME as u32)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
|
||||
let mut status = None;
|
||||
if session.stable_steps >= SETTLE_STEPS {
|
||||
state.phase = PhysicsPlacementPhase::Settled;
|
||||
status = Some((
|
||||
OperatorPhase::Preview,
|
||||
"Placement settled; commit or cancel".to_string(),
|
||||
Vec::new(),
|
||||
));
|
||||
} else if state.simulated_steps >= MAX_STEPS {
|
||||
state.phase = PhysicsPlacementPhase::TimedOut;
|
||||
status = Some((
|
||||
OperatorPhase::Preview,
|
||||
"Placement reached its 10 second preview limit".to_string(),
|
||||
vec!["Bodies are still moving; commit the current pose or cancel".to_string()],
|
||||
));
|
||||
}
|
||||
world.insert_resource(state);
|
||||
if let Some((phase, hint, warnings)) = status {
|
||||
set_operator_status(world, phase, hint, warnings);
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_selection(world: &mut World, selected: &[Entity]) -> Result<(), String> {
|
||||
if selected.is_empty() {
|
||||
return placement_error(world, "Select at least one prop to place with physics");
|
||||
}
|
||||
let mut problems = Vec::new();
|
||||
for entity in selected {
|
||||
let name = entity_name(world, *entity);
|
||||
if !is_mutable_level_object(world, *entity) {
|
||||
problems.push(format!(
|
||||
"{name}: selection is locked, linked, or not a level object"
|
||||
));
|
||||
continue;
|
||||
}
|
||||
let states = world.get::<AuthoringComponentStates>(*entity);
|
||||
let order = world.get::<InspectorOrder>(*entity);
|
||||
let split_body = world.get::<RigidBodyDesc>(*entity).is_some()
|
||||
&& authoring_component_active(states, order, COMPONENT_RIGID_BODY_DESC);
|
||||
let split_collider = world.get::<ColliderDesc>(*entity).filter(|collider| {
|
||||
collider.enabled
|
||||
&& !collider.is_trigger
|
||||
&& authoring_component_active(states, order, COMPONENT_COLLIDER_DESC)
|
||||
});
|
||||
let legacy = world.get::<PhysicsBody>(*entity).is_some()
|
||||
&& authoring_component_active(states, order, COMPONENT_PHYSICS_BODY);
|
||||
if !split_body && !legacy {
|
||||
problems.push(format!("{name}: add and enable a Rigid Body component"));
|
||||
}
|
||||
if split_collider.is_none() && !legacy {
|
||||
problems.push(format!(
|
||||
"{name}: add and enable a non-trigger Collider component"
|
||||
));
|
||||
}
|
||||
if world.get::<RigidBody>(*entity).is_none() {
|
||||
problems.push(format!("{name}: rigid body has not hydrated yet"));
|
||||
}
|
||||
if !has_runtime_collider(world, *entity) {
|
||||
problems.push(format!(
|
||||
"{name}: collider has not hydrated or finished cooking"
|
||||
));
|
||||
}
|
||||
}
|
||||
if problems.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
placement_error(world, problems.join("\n"))
|
||||
}
|
||||
}
|
||||
|
||||
fn has_runtime_collider(world: &World, root: Entity) -> bool {
|
||||
let mut pending = vec![root];
|
||||
while let Some(entity) = pending.pop() {
|
||||
if world.get::<Collider>(entity).is_some() {
|
||||
return true;
|
||||
}
|
||||
if let Some(children) = world.get::<Children>(entity) {
|
||||
pending.extend(children.iter());
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn restore_snapshot(world: &mut World, snapshot: &BodySnapshot, restore_pose: bool) {
|
||||
let Ok(mut entity) = world.get_entity_mut(snapshot.entity) else {
|
||||
return;
|
||||
};
|
||||
entity.insert(snapshot.rigid_body);
|
||||
restore_optional(&mut entity, snapshot.linear_velocity);
|
||||
restore_optional(&mut entity, snapshot.angular_velocity);
|
||||
restore_optional(&mut entity, snapshot.gravity_scale);
|
||||
restore_marker::<Sleeping>(&mut entity, snapshot.sleeping);
|
||||
restore_marker::<SleepingDisabled>(&mut entity, snapshot.sleeping_disabled);
|
||||
restore_marker::<RigidBodyDisabled>(&mut entity, snapshot.rigid_body_disabled);
|
||||
if restore_pose {
|
||||
entity.insert(snapshot.transform);
|
||||
restore_optional(&mut entity, snapshot.position);
|
||||
restore_optional(&mut entity, snapshot.rotation);
|
||||
}
|
||||
}
|
||||
|
||||
fn restore_optional<T: Component + Clone>(entity: &mut EntityWorldMut<'_>, value: Option<T>) {
|
||||
if let Some(value) = value {
|
||||
entity.insert(value);
|
||||
} else {
|
||||
entity.remove::<T>();
|
||||
}
|
||||
}
|
||||
|
||||
fn restore_marker<T: Component + Default>(entity: &mut EntityWorldMut<'_>, present: bool) {
|
||||
if present {
|
||||
entity.insert(T::default());
|
||||
} else {
|
||||
entity.remove::<T>();
|
||||
}
|
||||
}
|
||||
|
||||
fn placement_error<T>(world: &mut World, message: impl Into<String>) -> Result<T, String> {
|
||||
let message = message.into();
|
||||
world.resource_mut::<PhysicsPlacementState>().last_error = Some(message.clone());
|
||||
set_operator_status(
|
||||
world,
|
||||
OperatorPhase::Blocked,
|
||||
"Physics placement could not start".to_string(),
|
||||
message.lines().map(str::to_string).collect(),
|
||||
);
|
||||
Err(message)
|
||||
}
|
||||
|
||||
fn set_operator_status(
|
||||
world: &mut World,
|
||||
phase: OperatorPhase,
|
||||
hint: String,
|
||||
warnings: Vec<String>,
|
||||
) {
|
||||
if let Some(mut operator) = world.get_resource_mut::<ActiveOperator>() {
|
||||
operator.status = Some(OperatorStatus {
|
||||
id: "physics.placement".to_string(),
|
||||
label: "Physics Placement".to_string(),
|
||||
phase,
|
||||
hint,
|
||||
warnings,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn clear_operator_status(world: &mut World) {
|
||||
if let Some(mut operator) = world.get_resource_mut::<ActiveOperator>() {
|
||||
if operator
|
||||
.status
|
||||
.as_ref()
|
||||
.is_some_and(|status| status.id == "physics.placement")
|
||||
{
|
||||
operator.status = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::history::{apply_command_undo, EditorHistory};
|
||||
use bevy::asset::{AssetApp, AssetPlugin};
|
||||
use bevy::state::app::StatesPlugin;
|
||||
use shared::LevelObject;
|
||||
|
||||
fn app_with_physics() -> App {
|
||||
let mut app = App::new();
|
||||
app.add_plugins((
|
||||
MinimalPlugins,
|
||||
AssetPlugin::default(),
|
||||
StatesPlugin,
|
||||
TransformPlugin,
|
||||
PhysicsPlugins::default(),
|
||||
))
|
||||
.init_asset::<Mesh>()
|
||||
.init_state::<EditorMode>()
|
||||
.init_resource::<PhysicsPlacementState>()
|
||||
.init_resource::<EditorHistory>();
|
||||
app.finish();
|
||||
app.cleanup();
|
||||
app.update();
|
||||
app.world_mut().resource_mut::<Time<Physics>>().pause();
|
||||
app
|
||||
}
|
||||
|
||||
fn spawn_placeable(world: &mut World, name: &str, transform: Transform) -> Entity {
|
||||
world
|
||||
.spawn((
|
||||
Name::new(name.to_string()),
|
||||
LevelObject,
|
||||
RigidBodyDesc::default(),
|
||||
ColliderDesc::default(),
|
||||
RigidBody::Static,
|
||||
Collider::cuboid(1.0, 1.0, 1.0),
|
||||
transform,
|
||||
))
|
||||
.id()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reports_missing_authoring_prerequisites_without_starting() {
|
||||
let mut app = app_with_physics();
|
||||
let entity = app
|
||||
.world_mut()
|
||||
.spawn((Name::new("No Physics"), LevelObject, Transform::default()))
|
||||
.id();
|
||||
|
||||
let error = begin_physics_placement(app.world_mut(), [entity]).unwrap_err();
|
||||
|
||||
assert!(error.contains("add and enable a Rigid Body"));
|
||||
assert!(error.contains("add and enable a non-trigger Collider"));
|
||||
assert!(!app.world().resource::<PhysicsPlacementState>().active());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_restores_selected_and_unrelated_motion_state_exactly() {
|
||||
let mut app = app_with_physics();
|
||||
let selected = spawn_placeable(
|
||||
app.world_mut(),
|
||||
"Selected",
|
||||
Transform::from_xyz(1.0, 4.0, 2.0),
|
||||
);
|
||||
app.world_mut().entity_mut(selected).insert((
|
||||
RigidBody::Kinematic,
|
||||
LinearVelocity(Vec3::new(1.0, 2.0, 3.0)),
|
||||
AngularVelocity(Vec3::new(0.1, 0.2, 0.3)),
|
||||
GravityScale(0.25),
|
||||
SleepingDisabled,
|
||||
));
|
||||
let unrelated = app
|
||||
.world_mut()
|
||||
.spawn((
|
||||
RigidBody::Dynamic,
|
||||
Collider::sphere(0.5),
|
||||
LinearVelocity(Vec3::X * 3.0),
|
||||
Transform::from_xyz(8.0, 2.0, 0.0),
|
||||
))
|
||||
.id();
|
||||
app.update();
|
||||
|
||||
begin_physics_placement(app.world_mut(), [selected]).unwrap();
|
||||
assert_eq!(
|
||||
app.world().get::<RigidBody>(selected),
|
||||
Some(&RigidBody::Dynamic)
|
||||
);
|
||||
assert_eq!(
|
||||
app.world().get::<RigidBody>(unrelated),
|
||||
Some(&RigidBody::Static)
|
||||
);
|
||||
for _ in 0..10 {
|
||||
tick_physics_placement(app.world_mut());
|
||||
}
|
||||
assert!(
|
||||
app.world()
|
||||
.get::<Transform>(selected)
|
||||
.unwrap()
|
||||
.translation
|
||||
.y
|
||||
< 4.0
|
||||
);
|
||||
|
||||
cancel_physics_placement(app.world_mut());
|
||||
|
||||
assert_eq!(
|
||||
app.world().get::<Transform>(selected).unwrap().translation,
|
||||
Vec3::new(1.0, 4.0, 2.0)
|
||||
);
|
||||
assert_eq!(
|
||||
app.world().get::<RigidBody>(selected),
|
||||
Some(&RigidBody::Kinematic)
|
||||
);
|
||||
assert_eq!(
|
||||
app.world().get::<LinearVelocity>(selected),
|
||||
Some(&LinearVelocity(Vec3::new(1.0, 2.0, 3.0)))
|
||||
);
|
||||
assert_eq!(
|
||||
app.world().get::<GravityScale>(selected),
|
||||
Some(&GravityScale(0.25))
|
||||
);
|
||||
assert!(app.world().get::<SleepingDisabled>(selected).is_some());
|
||||
assert_eq!(
|
||||
app.world().get::<RigidBody>(unrelated),
|
||||
Some(&RigidBody::Dynamic)
|
||||
);
|
||||
assert_eq!(
|
||||
app.world().get::<LinearVelocity>(unrelated),
|
||||
Some(&LinearVelocity(Vec3::X * 3.0))
|
||||
);
|
||||
assert_eq!(app.world().resource::<EditorHistory>().undo_depth(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_physics_drop_commits_once_and_undo_restores_start_transform() {
|
||||
let mut app = app_with_physics();
|
||||
app.world_mut().spawn((
|
||||
RigidBody::Static,
|
||||
Collider::cuboid(20.0, 0.5, 20.0),
|
||||
Transform::from_xyz(0.0, -0.25, 0.0),
|
||||
));
|
||||
let start = Transform::from_xyz(0.0, 4.0, 0.0);
|
||||
let prop = spawn_placeable(app.world_mut(), "Drop Prop", start);
|
||||
app.update();
|
||||
|
||||
begin_physics_placement(app.world_mut(), [prop]).unwrap();
|
||||
for _ in 0..400 {
|
||||
tick_physics_placement(app.world_mut());
|
||||
if app.world().resource::<PhysicsPlacementState>().phase
|
||||
== PhysicsPlacementPhase::Settled
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
app.world().resource::<PhysicsPlacementState>().phase,
|
||||
PhysicsPlacementPhase::Settled
|
||||
);
|
||||
let settled = *app.world().get::<Transform>(prop).unwrap();
|
||||
assert!(settled.translation.y < 1.0, "{settled:?}");
|
||||
|
||||
commit_physics_placement(app.world_mut());
|
||||
|
||||
assert_eq!(app.world().resource::<EditorHistory>().undo_depth(), 1);
|
||||
assert_eq!(
|
||||
app.world().resource::<EditorHistory>().status,
|
||||
"Undo: Move Selection"
|
||||
);
|
||||
assert_eq!(app.world().get::<RigidBody>(prop), Some(&RigidBody::Static));
|
||||
assert_eq!(*app.world().get::<Transform>(prop).unwrap(), settled);
|
||||
|
||||
apply_command_undo(app.world_mut());
|
||||
assert_eq!(*app.world().get::<Transform>(prop).unwrap(), start);
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,7 @@ use crate::visualizers::EditorVisualizerProxy;
|
||||
use bevy_egui::egui;
|
||||
|
||||
use crate::viewport::material_drop::{MaterialDropSet, MaterialDropState};
|
||||
use crate::viewport::physics_placement::PhysicsPlacementState;
|
||||
use crate::viewport::scene_view_ray;
|
||||
use crate::viewport::terrain_paint::TerrainPaintState;
|
||||
use crate::viewport::terrain_sculpt::TerrainSculptState;
|
||||
@@ -54,6 +55,7 @@ struct PickTargetQueries<'w, 's> {
|
||||
material_drop: Option<Res<'w, MaterialDropState>>,
|
||||
terrain_sculpt: Res<'w, TerrainSculptState>,
|
||||
terrain_paint: Res<'w, TerrainPaintState>,
|
||||
physics_placement: Option<Res<'w, PhysicsPlacementState>>,
|
||||
viewport_ui: Res<'w, ViewportUiState>,
|
||||
}
|
||||
|
||||
@@ -129,7 +131,13 @@ fn handle_pick_events(
|
||||
for _ in click_events.read() {}
|
||||
return Ok(());
|
||||
}
|
||||
if pick_targets.terrain_sculpt.active || pick_targets.terrain_paint.active {
|
||||
if pick_targets.terrain_sculpt.active
|
||||
|| pick_targets.terrain_paint.active
|
||||
|| pick_targets
|
||||
.physics_placement
|
||||
.as_deref()
|
||||
.is_some_and(PhysicsPlacementState::active)
|
||||
{
|
||||
viewport_click.0 = None;
|
||||
for _ in click_events.read() {}
|
||||
return Ok(());
|
||||
@@ -447,6 +455,7 @@ fn sync_gizmo_targets(
|
||||
brush_mode: Res<BrushEditMode>,
|
||||
terrain_sculpt: Res<TerrainSculptState>,
|
||||
terrain_paint: Res<TerrainPaintState>,
|
||||
physics_placement: Option<Res<PhysicsPlacementState>>,
|
||||
) {
|
||||
ui_state
|
||||
.selected_entities
|
||||
@@ -457,6 +466,9 @@ fn sync_gizmo_targets(
|
||||
|| brush_mode.is_element_mode()
|
||||
|| terrain_sculpt.active
|
||||
|| terrain_paint.active
|
||||
|| physics_placement
|
||||
.as_deref()
|
||||
.is_some_and(PhysicsPlacementState::active)
|
||||
{
|
||||
for (entity, brush_element_gizmo) in &targets {
|
||||
if brush_element_gizmo.is_none() {
|
||||
|
||||
Reference in new issue
Block a user