Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/cloth inflator #15

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
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 CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

With the new version (See [Migration guide](https://github.com/jakobhellermann/bevy-inspector-egui/blob/main/docs/MIGRATION_GUIDE_0.15_0.16.md)),
the following changes were applied:

* (**BREAKING**) Removed `debug` feature
* Removed `bevy_inspector_egui` dependency, kept only as `dev-dependency` for examples

Expand Down
5 changes: 5 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,11 @@ default-features = false
name = "balloon"
path = "examples/balloon_example.rs"

[[example]]
name = "bouncy_balloon"
path = "examples/bouncy_balloon_example.rs"
required-features = ["rapier_collisions"]

[[example]]
name = "flag"
path = "examples/flag_example.rs"
Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -286,5 +286,9 @@ run `cargo run --example rapier_collision --features rapier_collisions`

run `cargo run --example anchors`

6. Bouncy ballon

run `cargo run --example bouncy_balloon --features rapier_collisions`

[Rapier]: https://github.com/dimforge/bevy_rapier
[Heron]: https://github.com/jcornaz/heron
76 changes: 76 additions & 0 deletions examples/bouncy_balloon_example.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
use bevy::prelude::*;
use bevy_inspector_egui::quick::{ResourceInspectorPlugin, WorldInspectorPlugin};
use bevy_rapier3d::prelude::*;
use bevy_silk::prelude::*;

mod camera_plugin;

fn main() {
App::new()
.insert_resource(AmbientLight {
color: Color::WHITE,
brightness: 1.0,
})
.add_plugins(DefaultPlugins)
.add_plugins(WorldInspectorPlugin::new())
.add_plugins(RapierPhysicsPlugin::<NoUserData>::default())
.add_plugins(RapierDebugRenderPlugin::default())
.add_plugins(ResourceInspectorPlugin::<ClothConfig>::new())
.add_plugins(camera_plugin::CameraPlugin)
.add_plugins(ClothPlugin)
.insert_resource(ClothConfig {
..Default::default()
})
.add_systems(Startup, (spawn_cloth, setup))
.run();
}

fn setup(
mut commands: Commands,
mut materials: ResMut<Assets<StandardMaterial>>,
mut meshes: ResMut<Assets<Mesh>>,
) {
commands.spawn(DirectionalLightBundle::default());
let mesh = meshes.add(shape::Cube::new(50.0).into());

// Ground
commands.spawn((
PbrBundle {
mesh,
material: materials.add(Color::WHITE.into()),
transform: Transform::from_xyz(0.0, -20.0, 0.0),
..Default::default()
},
Name::new("Ground"),
Collider::cuboid(25.0, 25.0, 25.0),
));
}

fn spawn_cloth(
mut commands: Commands,
mut materials: ResMut<Assets<StandardMaterial>>,
mut meshes: ResMut<Assets<Mesh>>,
) {
commands.spawn((
PbrBundle {
mesh: meshes.add(
shape::Icosphere {
radius: 5.0,
subdivisions: 10,
}
.try_into()
.unwrap(),
),
material: materials.add(Color::YELLOW.into()),
transform: Transform::from_xyz(0.0, 15.0, 0.0),
..Default::default()
},
ClothBuilder::new(),
ClothInflator::new(0.7),
ClothCollider {
velocity_coefficient: 2.0,
..default()
},
Name::new("Balloon"),
));
}
76 changes: 76 additions & 0 deletions src/components/cloth_inflator.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
use crate::components::cloth::StickId;
use crate::prelude::{StickMode, VertexAnchor};
use bevy::ecs::prelude::Component;
use bevy::math::Vec3;
use bevy::reflect::Reflect;

/// Cloth inflator center selection mode
#[derive(Debug, Default, Copy, Clone, Reflect)]
pub enum InflatorCenter {
#[default]
/// The center of the mesh bounding box will be selected
Aabb,
/// A custom local center
Custom(Vec3),
}

/// Cloth Inflator component. Allows to simulate inflating a cloth mesh.
///
/// This component will add an extra *centroid* point to the cloth and as many spring
/// sticks as there are points (vertice) on the cloth.
/// Pleas not that this is not an actual soft body simulation, but a very approximated
/// version using the verlet integration engine
#[derive(Debug, Default, Clone, Component, Reflect)]
pub struct ClothInflator {
/// Target minimal inflating amount
/// - `0.0` would mean no inflating
/// - `1.0` would mean *full* inflating
pub inflating_percent: f32,
/// The inflating center. This will be applied only once
pub(crate) center: InflatorCenter,
/// Optional anchor for the added center point
pub(crate) anchor: Option<VertexAnchor>,
/// The cloth sticks behaviours to edit
#[reflect(ignore)]
pub(crate) sticks: Vec<StickId>,
}

impl ClothInflator {
/// Instantiates a new inflator with the given `min_volume`
#[inline]
#[must_use]
pub const fn new(inflating_percent: f32) -> Self {
Self {
inflating_percent,
center: InflatorCenter::Aabb,
anchor: None,
sticks: vec![],
}
}

/// Defines a custom local space center instead of the default Aabb center
#[inline]
#[must_use]
pub const fn with_custom_center(mut self, center: Vec3) -> Self {
self.center = InflatorCenter::Custom(center);
self
}

/// Defines a vertex anchor for the new cloth point
#[inline]
#[must_use]
pub const fn with_anchor(mut self, anchor: VertexAnchor) -> Self {
self.anchor = Some(anchor);
self
}

#[inline]
#[must_use]
/// Computes the stick behaviour mode of the inflator
pub(crate) fn stick_mode(&self) -> StickMode {
StickMode::Spring {
min_percent: self.inflating_percent.max(0.1),
max_percent: f32::MAX,
}
}
}
2 changes: 2 additions & 0 deletions src/components/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
pub mod cloth;
/// cloth builder module
pub mod cloth_builder;
/// Cloth inflator module
pub mod cloth_inflator;
/// cloth rendering module
pub mod cloth_rendering;
/// collider module
Expand Down
11 changes: 9 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,7 @@ pub mod prelude {
pub use crate::components::collider::ClothCollider;
pub use crate::{
components::cloth_builder::ClothBuilder,
components::cloth_inflator::ClothInflator,
components::cloth_rendering::NormalComputing,
config::{AccelerationSmoothing, ClothConfig},
error::Error,
Expand All @@ -306,12 +307,18 @@ impl Plugin for ClothPlugin {
app.register_type::<ClothConfig>()
.register_type::<Wind>()
.register_type::<Winds>()
.register_type::<ClothBuilder>();
.register_type::<ClothBuilder>()
.register_type::<ClothInflator>();
app.add_systems(
Update,
(
systems::cloth::init,
(systems::cloth::update, systems::cloth::render).chain(),
(
systems::cloth::inflate,
systems::cloth::update,
systems::cloth::render,
)
.chain(),
),
);
#[cfg(feature = "rapier_collisions")]
Expand Down
36 changes: 33 additions & 3 deletions src/systems/cloth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use crate::components::cloth::Cloth;
use crate::components::cloth_builder::ClothBuilder;
use crate::components::cloth_inflator::{ClothInflator, InflatorCenter};
use crate::components::cloth_rendering::ClothRendering;
use crate::config::ClothConfig;
use crate::wind::Winds;
Expand Down Expand Up @@ -41,6 +42,12 @@ pub fn update(
}
}

pub fn inflate(mut query: Query<(&mut Cloth, &ClothInflator), Changed<ClothInflator>>) {
for (mut cloth, inflator) in query.iter_mut() {
cloth.edit_stick_modes(&inflator.sticks, inflator.stick_mode());
}
}

pub fn render(
mut cloth_query: Query<(
&Cloth,
Expand All @@ -64,16 +71,25 @@ pub fn render(

pub fn init(
mut commands: Commands,
mut query: Query<(Entity, &ClothBuilder, &GlobalTransform, &Handle<Mesh>), Added<ClothBuilder>>,
mut query: Query<
(
Entity,
&ClothBuilder,
&GlobalTransform,
&Handle<Mesh>,
Option<&mut ClothInflator>,
),
Added<ClothBuilder>,
>,
meshes: Res<Assets<Mesh>>,
) {
for (entity, builder, transform, handle) in query.iter_mut() {
for (entity, builder, transform, handle, inflator) in query.iter_mut() {
if let Some(mesh) = meshes.get(handle) {
let matrix = transform.compute_matrix();
log::debug!("Initializing Cloth entity {:?}", entity);
let rendering = ClothRendering::init(mesh, builder.normals_computing).unwrap();
let aabb = rendering.compute_aabb();
let cloth = Cloth::new(
let mut cloth = Cloth::new(
&rendering.vertex_positions,
&rendering.indices,
builder.anchored_vertex_ids(mesh),
Expand All @@ -82,6 +98,20 @@ pub fn init(
builder.default_stick_mode,
&matrix,
);
if let Some(mut inflator) = inflator {
let center = match inflator.center {
InflatorCenter::Aabb => aabb.center.into(),
InflatorCenter::Custom(c) => c,
};
let (_, sticks) = cloth.add_point(
center,
inflator.stick_mode(),
inflator.anchor,
&matrix,
|_, _| true,
);
inflator.sticks = sticks;
}
commands.entity(entity).insert((rendering, cloth, aabb));
}
}
Expand Down