Skip to main content

avian3d/debug_render/
configuration.rs

1use crate::prelude::*;
2use bevy::{color::palettes::css::*, prelude::*};
3
4/// Gizmos used for debug rendering physics. See [`PhysicsDebugPlugin`]
5///
6/// You can configure what is rendered by inserting the [`PhysicsGizmos`] configuration group
7/// or by getting it from the `GizmoConfigStore` resource and mutating the returned configuration.
8///
9/// To configure the debug rendering of specific entities, use the [`DebugRender`] component.
10///
11/// # Example
12///
13/// ```no_run
14#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
15#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
16/// use bevy::prelude::*;
17///
18/// fn main() {
19///     App::new()
20///         .add_plugins((
21///             DefaultPlugins,
22///             PhysicsPlugins::default(),
23///             // Enables debug rendering
24///             PhysicsDebugPlugin,
25///         ))
26///         // Overwrite default debug rendering configuration (optional)
27///         .insert_gizmo_config(
28///             PhysicsGizmos {
29///                 aabb_color: Some(Color::WHITE),
30///                 ..default()
31///             },
32///             GizmoConfig::default(),
33///         )
34///         .run();
35/// }
36///
37/// fn setup(mut commands: Commands) {
38///     // This rigid body and its collider and AABB will get rendered
39#[cfg_attr(
40    feature = "2d",
41    doc = "    commands.spawn((RigidBody::Dynamic, Collider::circle(0.5)));"
42)]
43#[cfg_attr(
44    feature = "3d",
45    doc = "    commands.spawn((RigidBody::Dynamic, Collider::sphere(0.5)));"
46)]
47/// }
48/// ```
49#[derive(Reflect, GizmoConfigGroup)]
50#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
51#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
52pub struct PhysicsGizmos {
53    /// The lengths of the axes drawn for an entity at the center of mass.
54    pub axis_lengths: Option<Vector>,
55    /// The color of the [AABBs](ColliderAabb). If `None`, the AABBs will not be rendered.
56    pub aabb_color: Option<Color>,
57    /// The color of the [collider](Collider) wireframes. If `None`, the colliders will not be rendered.
58    pub collider_color: Option<Color>,
59    /// The colors (in HSLA) for [sleeping](Sleeping) bodies will be multiplied by this array.
60    /// If `None`, sleeping will have no effect on the colors.
61    pub sleeping_color_multiplier: Option<[f32; 4]>,
62    /// The color used for the [collider](Collider) wireframes of bodies that were treated as
63    /// fast-moving and swept by [Continuous Collision Detection](crate::dynamics::ccd) during the
64    /// last physics step. If `None`, fast bodies use the normal [`collider_color`](Self::collider_color).
65    pub fast_body_color: Option<Color>,
66    /// The color used for the [collider](Collider) wireframes of bodies whose motion was stopped at
67    /// a time of impact by [Continuous Collision Detection](crate::dynamics::ccd) during the last
68    /// physics step. Takes priority over [`fast_body_color`](Self::fast_body_color). If `None`,
69    /// these bodies use the normal [`collider_color`](Self::collider_color).
70    pub time_of_impact_color: Option<Color>,
71    /// The color of the contact points. If `None`, the contact points will not be rendered.
72    pub contact_point_color: Option<Color>,
73    /// The color of the contact normals. If `None`, the contact normals will not be rendered.
74    pub contact_normal_color: Option<Color>,
75    /// The scale used for contact normals.
76    pub contact_normal_scale: ContactGizmoScale,
77    /// The color of the lines drawn from the centers of bodies to their joint anchors.
78    pub joint_anchor_color: Option<Color>,
79    /// The color of the lines drawn between joint anchors, indicating the separation.
80    pub joint_separation_color: Option<Color>,
81    /// The color used for the rays in [raycasts](spatial_query#raycasting).
82    pub raycast_color: Option<Color>,
83    /// The color used for the hit points in [raycasts](spatial_query#raycasting).
84    pub raycast_point_color: Option<Color>,
85    /// The color used for the hit normals in [raycasts](spatial_query#raycasting).
86    pub raycast_normal_color: Option<Color>,
87    /// The color used for the ray in [shapecasts](spatial_query#shapecasting).
88    pub shapecast_color: Option<Color>,
89    /// The color used for the shape in [shapecasts](spatial_query#shapecasting).
90    pub shapecast_shape_color: Option<Color>,
91    /// The color used for the hit points in [shapecasts](spatial_query#shapecasting).
92    pub shapecast_point_color: Option<Color>,
93    /// The color used for the hit normals in [shapecasts](spatial_query#shapecasting).
94    pub shapecast_normal_color: Option<Color>,
95    /// The color used for the line between the origin and the projected point when drawing [point projections](spatial_query#point-projection).
96    pub point_projection_color: Option<Color>,
97    /// The color used for the origin of [point projections](spatial_query#point-projection).
98    pub point_projection_origin_color: Option<Color>,
99    /// The color used for the projected points of [point projections](spatial_query#point-projection).
100    pub point_projection_point_color: Option<Color>,
101    /// The color used for the shape used for [shape intersection](SpatialQuery::shape_intersections) tests.
102    pub shape_intersection_shape_color: Option<Color>,
103    /// The color used for the intersecting colliders of [shape intersection](SpatialQuery::shape_intersections) tests.
104    pub shape_intersection_color: Option<Color>,
105    /// The color used for the bounds of [`PhysicsIsland`](dynamics::solver::islands::PhysicsIsland)s.
106    pub island_color: Option<Color>,
107    /// The color used for [`ColliderTree`](crate::collider_tree) nodes.
108    pub collider_tree_color: Option<Color>,
109    /// Determines if the visibility of entities with [colliders](Collider) should be set to `Visibility::Hidden`,
110    /// which will only show the debug renders.
111    pub hide_meshes: bool,
112}
113
114impl Default for PhysicsGizmos {
115    fn default() -> Self {
116        Self {
117            axis_lengths: Some(Vector::splat(0.5)),
118            aabb_color: None,
119            collider_color: Some(ORANGE.into()),
120            sleeping_color_multiplier: Some([1.0, 1.0, 0.4, 1.0]),
121            fast_body_color: Some(SALMON.into()),
122            time_of_impact_color: Some(Color::srgb(0.0, 1.0, 0.0)),
123            contact_point_color: None,
124            contact_normal_color: None,
125            contact_normal_scale: ContactGizmoScale::default(),
126            joint_anchor_color: Some(PINK.into()),
127            joint_separation_color: Some(RED.into()),
128            raycast_color: Some(RED.into()),
129            raycast_point_color: Some(YELLOW.into()),
130            raycast_normal_color: Some(PINK.into()),
131            shapecast_color: Some(RED.into()),
132            shapecast_shape_color: Some(Color::srgb(0.4, 0.6, 1.0)),
133            shapecast_point_color: Some(YELLOW.into()),
134            shapecast_normal_color: Some(PINK.into()),
135            point_projection_color: Some(Color::WHITE),
136            point_projection_origin_color: Some(Color::WHITE),
137            point_projection_point_color: Some(YELLOW.into()),
138            shape_intersection_shape_color: Some(Color::WHITE),
139            shape_intersection_color: Some(YELLOW.into()),
140            island_color: None,
141            collider_tree_color: None,
142            hide_meshes: false,
143        }
144    }
145}
146
147/// The scale used for contact normals rendered using gizmos.
148#[derive(Reflect, Clone, Copy, PartialEq)]
149#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
150#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
151#[reflect(PartialEq)]
152pub enum ContactGizmoScale {
153    /// The length of the rendered contact normal is constant.
154    Constant(f32),
155    /// The length of the rendered contact normal is scaled by the contact force and the given scaling factor.
156    Scaled(f32),
157}
158
159impl Default for ContactGizmoScale {
160    fn default() -> Self {
161        Self::Scaled(0.025)
162    }
163}
164
165impl PhysicsGizmos {
166    /// Creates a [`PhysicsGizmos`] configuration with all rendering options enabled.
167    pub fn all() -> Self {
168        Self {
169            axis_lengths: Some(Vector::splat(0.5)),
170            aabb_color: Some(Color::srgb(0.8, 0.8, 0.8)),
171            collider_color: Some(ORANGE.into()),
172            sleeping_color_multiplier: Some([1.0, 1.0, 0.4, 1.0]),
173            fast_body_color: Some(SALMON.into()),
174            time_of_impact_color: Some(Color::srgb(0.0, 1.0, 0.0)),
175            contact_point_color: Some(LIGHT_CYAN.into()),
176            contact_normal_color: Some(RED.into()),
177            contact_normal_scale: ContactGizmoScale::default(),
178            joint_anchor_color: Some(PINK.into()),
179            joint_separation_color: Some(RED.into()),
180            raycast_color: Some(RED.into()),
181            raycast_point_color: Some(YELLOW.into()),
182            raycast_normal_color: Some(PINK.into()),
183            shapecast_color: Some(RED.into()),
184            shapecast_shape_color: Some(Color::srgb(0.4, 0.6, 1.0)),
185            shapecast_point_color: Some(YELLOW.into()),
186            shapecast_normal_color: Some(PINK.into()),
187            point_projection_color: Some(Color::WHITE),
188            point_projection_origin_color: Some(Color::WHITE),
189            point_projection_point_color: Some(YELLOW.into()),
190            shape_intersection_shape_color: Some(Color::WHITE),
191            shape_intersection_color: Some(YELLOW.into()),
192            island_color: Some(RED.into()),
193            collider_tree_color: Some(Color::WHITE),
194            hide_meshes: true,
195        }
196    }
197
198    /// Creates a [`PhysicsGizmos`] configuration with debug rendering enabled but all options turned off.
199    ///
200    /// Note: this doesn't affect entities with [`DebugRender`] component; their debug gizmos will be visible.
201    pub fn none() -> Self {
202        Self {
203            axis_lengths: None,
204            aabb_color: None,
205            collider_color: None,
206            sleeping_color_multiplier: None,
207            fast_body_color: None,
208            time_of_impact_color: None,
209            contact_point_color: None,
210            contact_normal_color: None,
211            contact_normal_scale: ContactGizmoScale::default(),
212            joint_anchor_color: None,
213            joint_separation_color: None,
214            raycast_color: None,
215            raycast_point_color: None,
216            raycast_normal_color: None,
217            shapecast_color: None,
218            shapecast_shape_color: None,
219            shapecast_point_color: None,
220            shapecast_normal_color: None,
221            point_projection_color: None,
222            point_projection_origin_color: None,
223            point_projection_point_color: None,
224            shape_intersection_shape_color: None,
225            shape_intersection_color: None,
226            island_color: None,
227            collider_tree_color: None,
228            hide_meshes: false,
229        }
230    }
231
232    /// Creates a [`PhysicsGizmos`] configuration with the given lengths for the axes
233    /// that are drawn for the entity at the center of mass. Other debug rendering options will be disabled.
234    pub fn axes(axis_lengths: Vector) -> Self {
235        Self {
236            axis_lengths: Some(axis_lengths),
237            ..Self::none()
238        }
239    }
240
241    /// Creates a [`PhysicsGizmos`] configuration with a given AABB color.
242    /// Other debug rendering options will be disabled.
243    pub fn aabbs(color: Color) -> Self {
244        Self {
245            aabb_color: Some(color),
246            ..Self::none()
247        }
248    }
249
250    /// Creates a [`PhysicsGizmos`] configuration with a given collider color.
251    /// Other debug rendering options will be disabled.
252    pub fn colliders(color: Color) -> Self {
253        Self {
254            collider_color: Some(color),
255            ..Self::none()
256        }
257    }
258
259    /// Creates a [`PhysicsGizmos`] configuration with a given contact point color.
260    /// Other debug rendering options will be disabled.
261    pub fn contact_points(color: Color) -> Self {
262        Self {
263            contact_point_color: Some(color),
264            ..Self::none()
265        }
266    }
267
268    /// Creates a [`PhysicsGizmos`] configuration with a given contact normal color.
269    /// Other debug rendering options will be disabled.
270    pub fn contact_normals(color: Color) -> Self {
271        Self {
272            contact_normal_color: Some(color),
273            ..Self::none()
274        }
275    }
276
277    /// Creates a [`PhysicsGizmos`] configuration with given colors for
278    /// joint anchors and separation distances. Other debug rendering options will be disabled.
279    pub fn joints(anchor_color: Option<Color>, separation_color: Option<Color>) -> Self {
280        Self {
281            joint_anchor_color: anchor_color,
282            joint_separation_color: separation_color,
283            ..Self::none()
284        }
285    }
286
287    /// Sets the lengths of the axes drawn for the entity.
288    pub fn with_axes(mut self, axis_lengths: Vector) -> Self {
289        self.axis_lengths = Some(axis_lengths);
290        self
291    }
292
293    /// Sets the AABB color.
294    pub fn with_aabb_color(mut self, color: Color) -> Self {
295        self.aabb_color = Some(color);
296        self
297    }
298
299    /// Sets the collider color.
300    pub fn with_collider_color(mut self, color: Color) -> Self {
301        self.collider_color = Some(color);
302        self
303    }
304
305    /// Sets the multiplier used for the colors (in HSLA) of [sleeping](Sleeping) bodies.
306    pub fn with_sleeping_color_multiplier(mut self, color_multiplier: [f32; 4]) -> Self {
307        self.sleeping_color_multiplier = Some(color_multiplier);
308        self
309    }
310
311    /// Sets the contact point color.
312    pub fn with_contact_point_color(mut self, color: Color) -> Self {
313        self.contact_point_color = Some(color);
314        self
315    }
316
317    /// Sets the contact normal color.
318    pub fn with_contact_normal_color(mut self, color: Color) -> Self {
319        self.contact_normal_color = Some(color);
320        self
321    }
322
323    /// Sets the contact normal scale.
324    pub fn with_contact_normal_scale(mut self, scale: ContactGizmoScale) -> Self {
325        self.contact_normal_scale = scale;
326        self
327    }
328
329    /// Sets the colors used for debug rendering joints.
330    pub fn with_joint_colors(anchor_color: Option<Color>, separation_color: Option<Color>) -> Self {
331        Self {
332            joint_anchor_color: anchor_color,
333            joint_separation_color: separation_color,
334            ..Self::none()
335        }
336    }
337
338    /// Sets the colors used for debug rendering raycasts.
339    pub fn with_raycast_colors(
340        mut self,
341        ray: Option<Color>,
342        hit_point: Option<Color>,
343        hit_normal: Option<Color>,
344    ) -> Self {
345        self.raycast_color = ray;
346        self.raycast_point_color = hit_point;
347        self.raycast_normal_color = hit_normal;
348        self
349    }
350
351    /// Sets the colors used for debug rendering shapecasts.
352    pub fn with_shapecast_colors(
353        mut self,
354        ray: Option<Color>,
355        shape: Option<Color>,
356        hit_point: Option<Color>,
357        hit_normal: Option<Color>,
358    ) -> Self {
359        self.shapecast_color = ray;
360        self.shapecast_shape_color = shape;
361        self.shapecast_point_color = hit_point;
362        self.shapecast_normal_color = hit_normal;
363        self
364    }
365
366    /// Sets the visibility of the entity's visual mesh.
367    pub fn with_mesh_visibility(mut self, is_visible: bool) -> Self {
368        self.hide_meshes = !is_visible;
369        self
370    }
371
372    /// Disables axis debug rendering.
373    pub fn without_axes(mut self) -> Self {
374        self.axis_lengths = None;
375        self
376    }
377
378    /// Disables AABB debug rendering.
379    pub fn without_aabbs(mut self) -> Self {
380        self.aabb_color = None;
381        self
382    }
383
384    /// Disables collider debug rendering.
385    pub fn without_colliders(mut self) -> Self {
386        self.collider_color = None;
387        self
388    }
389
390    /// Disables contact point debug rendering.
391    pub fn without_contact_points(mut self) -> Self {
392        self.contact_point_color = None;
393        self
394    }
395
396    /// Disables contact normal debug rendering.
397    pub fn without_contact_normals(mut self) -> Self {
398        self.contact_normal_color = None;
399        self
400    }
401
402    /// Disables joint debug rendering.
403    pub fn without_joints(mut self) -> Self {
404        self.joint_anchor_color = None;
405        self.joint_separation_color = None;
406        self
407    }
408
409    /// Disables raycast debug rendering.
410    pub fn without_raycasts(mut self) -> Self {
411        self.raycast_color = None;
412        self.raycast_point_color = None;
413        self.raycast_normal_color = None;
414        self
415    }
416
417    /// Disables shapecast debug rendering.
418    pub fn without_shapecasts(mut self) -> Self {
419        self.shapecast_color = None;
420        self.shapecast_shape_color = None;
421        self.shapecast_point_color = None;
422        self.shapecast_normal_color = None;
423        self
424    }
425}
426
427/// A component for the debug render configuration of an entity. See [`PhysicsDebugPlugin`].
428///
429/// This overwrites the global [`PhysicsGizmos`] for this specific entity.
430///
431/// # Example
432///
433/// ```no_run
434#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
435#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
436/// use bevy::prelude::*;
437///
438/// fn main() {
439///     App::new()
440///         .add_plugins((
441///             DefaultPlugins,
442///             PhysicsPlugins::default(),
443///             // Enables debug rendering
444///             PhysicsDebugPlugin,
445///         ))
446///         .run();
447/// }
448///
449/// fn setup(mut commands: Commands) {
450///     // This rigid body and its collider and AABB will get rendered
451///     commands.spawn((
452///         RigidBody::Dynamic,
453#[cfg_attr(feature = "2d", doc = "        Collider::circle(0.5),")]
454#[cfg_attr(feature = "3d", doc = "        Collider::sphere(0.5),")]
455///         // Overwrite default collider color (optional)
456///         DebugRender::default().with_collider_color(Color::srgb(1.0, 0.0, 0.0)),
457///     ));
458/// }
459/// ```
460#[derive(Component, Reflect, Clone, Copy, PartialEq)]
461#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
462#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
463#[reflect(Component, PartialEq)]
464pub struct DebugRender {
465    /// The lengths of the axes drawn for the entity at the center of mass.
466    pub axis_lengths: Option<Vector>,
467    /// The color of the [AABB](ColliderAabb). If `None`, the AABB will not be rendered.
468    pub aabb_color: Option<Color>,
469    /// The color of the [collider](Collider) wireframe. If `None`, the collider will not be rendered.
470    pub collider_color: Option<Color>,
471    /// If the entity is [sleeping](Sleeping), its colors (in HSLA) will be multiplied by this array.
472    /// If `None`, sleeping will have no effect on the colors.
473    pub sleeping_color_multiplier: Option<[f32; 4]>,
474    /// Determines if the entity's visibility should be set to `Visibility::Hidden`, which will only show the debug render.
475    pub hide_mesh: bool,
476}
477
478impl Default for DebugRender {
479    fn default() -> Self {
480        Self {
481            #[cfg(feature = "2d")]
482            axis_lengths: Some(Vector::new(5.0, 5.0)),
483            #[cfg(feature = "3d")]
484            axis_lengths: Some(Vector::new(0.5, 0.5, 0.5)),
485            aabb_color: None,
486            collider_color: Some(ORANGE.into()),
487            sleeping_color_multiplier: Some([1.0, 1.0, 0.4, 1.0]),
488            hide_mesh: false,
489        }
490    }
491}
492
493impl DebugRender {
494    /// Creates a [`DebugRender`] configuration with all rendering options enabled.
495    pub fn all() -> Self {
496        Self {
497            #[cfg(feature = "2d")]
498            axis_lengths: Some(Vector::new(5.0, 5.0)),
499            #[cfg(feature = "3d")]
500            axis_lengths: Some(Vector::new(0.5, 0.5, 0.5)),
501            aabb_color: Some(Color::srgb(0.8, 0.8, 0.8)),
502            collider_color: Some(ORANGE.into()),
503            sleeping_color_multiplier: Some([1.0, 1.0, 0.4, 1.0]),
504            hide_mesh: true,
505        }
506    }
507
508    /// Disables all debug rendering for this entity.
509    pub fn none() -> Self {
510        Self {
511            axis_lengths: None,
512            aabb_color: None,
513            collider_color: None,
514            sleeping_color_multiplier: None,
515            hide_mesh: false,
516        }
517    }
518
519    /// Creates a [`DebugRender`] configuration with the given lengths for the axes
520    /// that are drawn for the entity at the center of mass. Other debug rendering options will be disabled.
521    pub fn axes(axis_lengths: Vector) -> Self {
522        Self {
523            axis_lengths: Some(axis_lengths),
524            ..Self::none()
525        }
526    }
527
528    /// Creates a [`DebugRender`] configuration with a given AABB color.
529    /// Other debug rendering options will be disabled.
530    pub fn aabb(color: Color) -> Self {
531        Self {
532            aabb_color: Some(color),
533            ..Self::none()
534        }
535    }
536
537    /// Creates a [`DebugRender`] configuration with a given collider color.
538    /// Other debug rendering options will be disabled.
539    pub fn collider(color: Color) -> Self {
540        Self {
541            collider_color: Some(color),
542            ..Self::none()
543        }
544    }
545
546    /// Sets the lengths of the axes drawn for the entity at the center of mass.
547    pub fn with_axes(mut self, axis_lengths: Vector) -> Self {
548        self.axis_lengths = Some(axis_lengths);
549        self
550    }
551
552    /// Sets the AABB color.
553    pub fn with_aabb_color(mut self, color: Color) -> Self {
554        self.aabb_color = Some(color);
555        self
556    }
557
558    /// Sets the collider color.
559    pub fn with_collider_color(mut self, color: Color) -> Self {
560        self.collider_color = Some(color);
561        self
562    }
563
564    /// Sets the multiplier used for the colors (in HSLA) of [sleeping](Sleeping) bodies.
565    pub fn with_sleeping_color_multiplier(mut self, color_multiplier: [f32; 4]) -> Self {
566        self.sleeping_color_multiplier = Some(color_multiplier);
567        self
568    }
569
570    /// Sets the visibility of the entity's visual mesh.
571    pub fn with_mesh_visibility(mut self, is_visible: bool) -> Self {
572        self.hide_mesh = !is_visible;
573        self
574    }
575
576    /// Disables axis debug rendering.
577    pub fn without_axes(mut self) -> Self {
578        self.axis_lengths = None;
579        self
580    }
581
582    /// Disables AABB debug rendering.
583    pub fn without_aabb(mut self) -> Self {
584        self.aabb_color = None;
585        self
586    }
587
588    /// Disables collider debug rendering.
589    pub fn without_collider(mut self) -> Self {
590        self.collider_color = None;
591        self
592    }
593}