From b4e04f9d9f4e5954b07514db893b7b54367bce44 Mon Sep 17 00:00:00 2001 From: Lynn <62256001+lynn-lumen@users.noreply.github.com> Date: Thu, 17 Oct 2024 00:21:01 +0200 Subject: [PATCH] Remove write access to `ConvexPolygon.vertices` (#15965) # Objective - Fixes #15963 ## Solution - Implement `TryFrom for ConvexPolygon` - Implement `From> for Polygon` - Remove `pub` from `vertices` - Add `ConvexPolygon::vertices()` to get read only access to the vertices of a convex polygon. --- crates/bevy_math/src/primitives/dim2.rs | 24 +++++++++++++++++++++++- crates/bevy_mesh/src/primitives/dim2.rs | 2 +- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/crates/bevy_math/src/primitives/dim2.rs b/crates/bevy_math/src/primitives/dim2.rs index 53397fe07a..d734a1879d 100644 --- a/crates/bevy_math/src/primitives/dim2.rs +++ b/crates/bevy_math/src/primitives/dim2.rs @@ -1592,6 +1592,14 @@ impl Polygon { } } +impl From> for Polygon { + fn from(val: ConvexPolygon) -> Self { + Polygon { + vertices: val.vertices, + } + } +} + /// A convex polygon with `N` vertices. #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] @@ -1603,7 +1611,7 @@ impl Polygon { pub struct ConvexPolygon { /// The vertices of the [`ConvexPolygon`]. #[cfg_attr(feature = "serialize", serde(with = "super::serde::array"))] - pub vertices: [Vec2; N], + vertices: [Vec2; N], } impl Primitive2d for ConvexPolygon {} @@ -1651,6 +1659,20 @@ impl ConvexPolygon { pub fn new_unchecked(vertices: [Vec2; N]) -> Self { Self { vertices } } + + /// Get the vertices of this polygon + #[inline(always)] + pub fn vertices(&self) -> &[Vec2; N] { + &self.vertices + } +} + +impl TryFrom> for ConvexPolygon { + type Error = ConvexPolygonError; + + fn try_from(val: Polygon) -> Result { + ConvexPolygon::new(val.vertices) + } } /// A polygon with a variable number of vertices, allocated on the heap diff --git a/crates/bevy_mesh/src/primitives/dim2.rs b/crates/bevy_mesh/src/primitives/dim2.rs index a8b3237b7a..f978a8f1d6 100644 --- a/crates/bevy_mesh/src/primitives/dim2.rs +++ b/crates/bevy_mesh/src/primitives/dim2.rs @@ -408,7 +408,7 @@ impl Meshable for ConvexPolygon { fn mesh(&self) -> Self::Output { Self::Output { - vertices: self.vertices, + vertices: *self.vertices(), } } }