bevy_gizmos/rounded_box.rs
1//! Additional [`GizmoBuffer`] Functions -- Rounded cuboids and rectangles
2//!
3//! Includes the implementation of [`GizmoBuffer::rounded_rect`], [`GizmoBuffer::rounded_rect_2d`] and [`GizmoBuffer::rounded_cuboid`].
4//! and assorted support items.
5
6use core::f32::consts::FRAC_PI_2;
7
8use crate::{gizmos::GizmoBuffer, prelude::GizmoConfigGroup};
9use bevy_color::Color;
10use bevy_math::{Isometry2d, Isometry3d, Quat, Vec2, Vec3};
11use bevy_transform::components::Transform;
12
13/// A builder returned by [`GizmoBuffer::rounded_rect`] and [`GizmoBuffer::rounded_rect_2d`]
14pub struct RoundedRectBuilder<'a, Config, Clear>
15where
16 Config: GizmoConfigGroup,
17 Clear: 'static + Send + Sync,
18{
19 size: Vec2,
20 gizmos: &'a mut GizmoBuffer<Config, Clear>,
21 config: RoundedBoxConfig,
22}
23/// A builder returned by [`GizmoBuffer::rounded_cuboid`]
24pub struct RoundedCuboidBuilder<'a, Config, Clear>
25where
26 Config: GizmoConfigGroup,
27 Clear: 'static + Send + Sync,
28{
29 size: Vec3,
30 gizmos: &'a mut GizmoBuffer<Config, Clear>,
31 config: RoundedBoxConfig,
32}
33struct RoundedBoxConfig {
34 isometry: Isometry3d,
35 color: Color,
36 corner_radius: f32,
37 arc_resolution: u32,
38}
39
40impl<Config, Clear> RoundedRectBuilder<'_, Config, Clear>
41where
42 Config: GizmoConfigGroup,
43 Clear: 'static + Send + Sync,
44{
45 /// Change the radius of the corners to be `corner_radius`.
46 /// The default corner radius is [min axis of size] / 10.0
47 pub fn corner_radius(mut self, corner_radius: f32) -> Self {
48 self.config.corner_radius = corner_radius;
49 self
50 }
51
52 /// Change the resolution of the arcs at the corners of the rectangle.
53 /// The default value is 8
54 pub fn arc_resolution(mut self, arc_resolution: u32) -> Self {
55 self.config.arc_resolution = arc_resolution;
56 self
57 }
58}
59
60impl<Config, Clear> RoundedCuboidBuilder<'_, Config, Clear>
61where
62 Config: GizmoConfigGroup,
63 Clear: 'static + Send + Sync,
64{
65 /// Change the radius of the edges to be `edge_radius`.
66 /// The default edge radius is [min axis of size] / 10.0
67 pub fn edge_radius(mut self, edge_radius: f32) -> Self {
68 self.config.corner_radius = edge_radius;
69 self
70 }
71
72 /// Change the resolution of the arcs at the edges of the cuboid.
73 /// The default value is 8
74 pub fn arc_resolution(mut self, arc_resolution: u32) -> Self {
75 self.config.arc_resolution = arc_resolution;
76 self
77 }
78}
79
80impl<Config, Clear> Drop for RoundedRectBuilder<'_, Config, Clear>
81where
82 Config: GizmoConfigGroup,
83 Clear: 'static + Send + Sync,
84{
85 fn drop(&mut self) {
86 if !self.gizmos.enabled {
87 return;
88 }
89 let config = &self.config;
90
91 // Calculate inner and outer half size and ensure that the edge_radius is <= any half_length
92 let mut outer_half_size = self.size.abs() / 2.0;
93 let inner_half_size =
94 (outer_half_size - Vec2::splat(config.corner_radius.abs())).max(Vec2::ZERO);
95 let corner_radius = (outer_half_size - inner_half_size).min_element();
96 let mut inner_half_size = outer_half_size - Vec2::splat(corner_radius);
97
98 if config.corner_radius < 0. {
99 core::mem::swap(&mut outer_half_size, &mut inner_half_size);
100 }
101
102 // Handle cases where the rectangle collapses into simpler shapes
103 if outer_half_size.x * outer_half_size.y == 0. {
104 self.gizmos.line(
105 config.isometry * -outer_half_size.extend(0.),
106 config.isometry * outer_half_size.extend(0.),
107 config.color,
108 );
109 return;
110 }
111 if corner_radius == 0. {
112 self.gizmos.rect(config.isometry, self.size, config.color);
113 return;
114 }
115
116 let vertices = [
117 // top right
118 Vec3::new(inner_half_size.x, outer_half_size.y, 0.),
119 Vec3::new(inner_half_size.x, inner_half_size.y, 0.),
120 Vec3::new(outer_half_size.x, inner_half_size.y, 0.),
121 // bottom right
122 Vec3::new(outer_half_size.x, -inner_half_size.y, 0.),
123 Vec3::new(inner_half_size.x, -inner_half_size.y, 0.),
124 Vec3::new(inner_half_size.x, -outer_half_size.y, 0.),
125 // bottom left
126 Vec3::new(-inner_half_size.x, -outer_half_size.y, 0.),
127 Vec3::new(-inner_half_size.x, -inner_half_size.y, 0.),
128 Vec3::new(-outer_half_size.x, -inner_half_size.y, 0.),
129 // top left
130 Vec3::new(-outer_half_size.x, inner_half_size.y, 0.),
131 Vec3::new(-inner_half_size.x, inner_half_size.y, 0.),
132 Vec3::new(-inner_half_size.x, outer_half_size.y, 0.),
133 ]
134 .map(|vec3| config.isometry * vec3);
135
136 for &[a, b, c] in vertices.as_chunks().0 {
137 self.gizmos
138 .short_arc_3d_between(b, a, c, config.color)
139 .resolution(config.arc_resolution);
140 }
141
142 let edges = if config.corner_radius > 0. {
143 [
144 (vertices[2], vertices[3]),
145 (vertices[5], vertices[6]),
146 (vertices[8], vertices[9]),
147 (vertices[11], vertices[0]),
148 ]
149 } else {
150 [
151 (vertices[0], vertices[5]),
152 (vertices[3], vertices[8]),
153 (vertices[6], vertices[11]),
154 (vertices[9], vertices[2]),
155 ]
156 };
157
158 for (start, end) in edges {
159 self.gizmos.line(start, end, config.color);
160 }
161 }
162}
163
164impl<Config, Clear> Drop for RoundedCuboidBuilder<'_, Config, Clear>
165where
166 Config: GizmoConfigGroup,
167 Clear: 'static + Send + Sync,
168{
169 fn drop(&mut self) {
170 if !self.gizmos.enabled {
171 return;
172 }
173 let config = &self.config;
174
175 // Calculate inner and outer half size and ensure that the edge_radius is <= any half_length
176 let outer_half_size = self.size.abs() / 2.0;
177 let inner_half_size =
178 (outer_half_size - Vec3::splat(config.corner_radius.abs())).max(Vec3::ZERO);
179 let mut edge_radius = (outer_half_size - inner_half_size).min_element();
180 let inner_half_size = outer_half_size - Vec3::splat(edge_radius);
181 edge_radius *= config.corner_radius.signum();
182
183 // Handle cases where the rounded cuboid collapses into simpler shapes
184 if edge_radius == 0.0 {
185 let transform = Transform::from_translation(config.isometry.translation.into())
186 .with_rotation(config.isometry.rotation)
187 .with_scale(self.size);
188 self.gizmos.cube(transform, config.color);
189 return;
190 }
191
192 let rects = [
193 (
194 Vec3::X,
195 Vec2::new(self.size.z, self.size.y),
196 Quat::from_rotation_y(FRAC_PI_2),
197 ),
198 (
199 Vec3::Y,
200 Vec2::new(self.size.x, self.size.z),
201 Quat::from_rotation_x(FRAC_PI_2),
202 ),
203 (Vec3::Z, Vec2::new(self.size.x, self.size.y), Quat::IDENTITY),
204 ];
205
206 for (position, size, rotation) in rects {
207 let local_position = position * inner_half_size;
208 self.gizmos
209 .rounded_rect(
210 config.isometry * Isometry3d::new(local_position, rotation),
211 size,
212 config.color,
213 )
214 .arc_resolution(config.arc_resolution)
215 .corner_radius(edge_radius);
216
217 self.gizmos
218 .rounded_rect(
219 config.isometry * Isometry3d::new(-local_position, rotation),
220 size,
221 config.color,
222 )
223 .arc_resolution(config.arc_resolution)
224 .corner_radius(edge_radius);
225 }
226 }
227}
228
229impl<Config, Clear> GizmoBuffer<Config, Clear>
230where
231 Config: GizmoConfigGroup,
232 Clear: 'static + Send + Sync,
233{
234 /// Draw a wireframe rectangle with rounded corners in 3D.
235 ///
236 /// # Arguments
237 ///
238 /// - `isometry` defines the translation and rotation of the rectangle.
239 /// - the translation specifies the center of the rectangle
240 /// - defines orientation of the rectangle, by default we assume the rectangle is contained in
241 /// a plane parallel to the XY plane.
242 /// - `size`: defines the size of the rectangle. This refers to the 'outer size', similar to a bounding box.
243 /// - `color`: color of the rectangle
244 ///
245 /// # Builder methods
246 ///
247 /// - The corner radius can be adjusted with the `.corner_radius(...)` method.
248 /// - The resolution of the arcs at each corner (i.e. the level of detail) can be adjusted with the
249 /// `.arc_resolution(...)` method.
250 ///
251 /// # Example
252 /// ```
253 /// # use bevy_gizmos::prelude::*;
254 /// # use bevy_math::prelude::*;
255 /// # use bevy_color::palettes::css::GREEN;
256 /// fn system(mut gizmos: Gizmos) {
257 /// gizmos.rounded_rect(
258 /// Isometry3d::IDENTITY,
259 /// Vec2::ONE,
260 /// GREEN
261 /// )
262 /// .corner_radius(0.25)
263 /// .arc_resolution(10);
264 /// }
265 /// # bevy_ecs::system::assert_is_system(system);
266 /// ```
267 pub fn rounded_rect(
268 &mut self,
269 isometry: impl Into<Isometry3d>,
270 size: Vec2,
271 color: impl Into<Color>,
272 ) -> RoundedRectBuilder<'_, Config, Clear> {
273 let corner_radius = size.min_element() * DEFAULT_CORNER_RADIUS;
274 RoundedRectBuilder {
275 gizmos: self,
276 config: RoundedBoxConfig {
277 isometry: isometry.into(),
278 color: color.into(),
279 corner_radius,
280 arc_resolution: DEFAULT_ARC_RESOLUTION,
281 },
282 size,
283 }
284 }
285
286 /// Draw a wireframe rectangle with rounded corners in 2D.
287 ///
288 /// # Arguments
289 ///
290 /// - `isometry` defines the translation and rotation of the rectangle.
291 /// - the translation specifies the center of the rectangle
292 /// - defines orientation of the rectangle, by default we assume the rectangle aligned with all axes.
293 /// - `size`: defines the size of the rectangle. This refers to the 'outer size', similar to a bounding box.
294 /// - `color`: color of the rectangle
295 ///
296 /// # Builder methods
297 ///
298 /// - The corner radius can be adjusted with the `.corner_radius(...)` method.
299 /// - The resolution of the arcs at each corner (i.e. the level of detail) can be adjusted with the
300 /// `.arc_resolution(...)` method.
301 ///
302 /// # Example
303 /// ```
304 /// # use bevy_gizmos::prelude::*;
305 /// # use bevy_math::prelude::*;
306 /// # use bevy_color::palettes::css::GREEN;
307 /// fn system(mut gizmos: Gizmos) {
308 /// gizmos.rounded_rect_2d(
309 /// Isometry2d::IDENTITY,
310 /// Vec2::ONE,
311 /// GREEN
312 /// )
313 /// .corner_radius(0.25)
314 /// .arc_resolution(10);
315 /// }
316 /// # bevy_ecs::system::assert_is_system(system);
317 /// ```
318 pub fn rounded_rect_2d(
319 &mut self,
320 isometry: impl Into<Isometry2d>,
321 size: Vec2,
322 color: impl Into<Color>,
323 ) -> RoundedRectBuilder<'_, Config, Clear> {
324 let isometry = isometry.into();
325 let corner_radius = size.min_element() * DEFAULT_CORNER_RADIUS;
326 RoundedRectBuilder {
327 gizmos: self,
328 config: RoundedBoxConfig {
329 isometry: Isometry3d::new(
330 isometry.translation.extend(0.0),
331 Quat::from_rotation_z(isometry.rotation.as_radians()),
332 ),
333 color: color.into(),
334 corner_radius,
335 arc_resolution: DEFAULT_ARC_RESOLUTION,
336 },
337 size,
338 }
339 }
340
341 /// Draw a wireframe cuboid with rounded corners in 3D.
342 ///
343 /// # Arguments
344 ///
345 /// - `isometry` defines the translation and rotation of the cuboid.
346 /// - the translation specifies the center of the cuboid
347 /// - defines orientation of the cuboid, by default we assume the cuboid aligned with all axes.
348 /// - `size`: defines the size of the cuboid. This refers to the 'outer size', similar to a bounding box.
349 /// - `color`: color of the cuboid
350 ///
351 /// # Builder methods
352 ///
353 /// - The edge radius can be adjusted with the `.edge_radius(...)` method.
354 /// - The resolution of the arcs at each edge (i.e. the level of detail) can be adjusted with the
355 /// `.arc_resolution(...)` method.
356 ///
357 /// # Example
358 /// ```
359 /// # use bevy_gizmos::prelude::*;
360 /// # use bevy_math::prelude::*;
361 /// # use bevy_color::palettes::css::GREEN;
362 /// fn system(mut gizmos: Gizmos) {
363 /// gizmos.rounded_cuboid(
364 /// Isometry3d::IDENTITY,
365 /// Vec3::ONE,
366 /// GREEN
367 /// )
368 /// .edge_radius(0.25)
369 /// .arc_resolution(10);
370 /// }
371 /// # bevy_ecs::system::assert_is_system(system);
372 /// ```
373 pub fn rounded_cuboid(
374 &mut self,
375 isometry: impl Into<Isometry3d>,
376 size: Vec3,
377 color: impl Into<Color>,
378 ) -> RoundedCuboidBuilder<'_, Config, Clear> {
379 let corner_radius = size.min_element() * DEFAULT_CORNER_RADIUS;
380 RoundedCuboidBuilder {
381 gizmos: self,
382 config: RoundedBoxConfig {
383 isometry: isometry.into(),
384 color: color.into(),
385 corner_radius,
386 arc_resolution: DEFAULT_ARC_RESOLUTION,
387 },
388 size,
389 }
390 }
391}
392
393const DEFAULT_ARC_RESOLUTION: u32 = 8;
394const DEFAULT_CORNER_RADIUS: f32 = 0.1;