From 956604e4c7f8b2855c98373d8ca7375aacab21f9 Mon Sep 17 00:00:00 2001 From: Matty Date: Mon, 8 Apr 2024 19:00:04 -0400 Subject: [PATCH] Meshing for `Triangle3d` primitive (#12686) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit # Objective - Ongoing work for #10572 - Implement the `Meshable` trait for `Triangle3d`, allowing 3d triangle primitives to produce meshes. ## Solution The `Meshable` trait for `Triangle3d` directly produces a `Mesh`, much like that of `Triangle2d`. The mesh consists only of a single triangle (the triangle itself), and its vertex data consists of: - Vertex positions, which are the triangle's vertices themselves (i.e. the triangle provides its own coordinates in mesh space directly) - Normals, which are all the normal of the triangle itself - Indices, which are directly inferred from the vertex order (note that this is slightly different than `Triangle2d` which, because of its lower dimension, has an orientation which can be corrected for so that it always faces "the right way") - UV coordinates, which are produced as follows: 1. The first coordinate is coincident with the `ab` direction of the triangle. 2. The second coordinate maps to be perpendicular to the first in mesh space, so that the UV-mapping is skew-free. 3. The UV-coordinates map to the smallest rectangle possible containing the triangle, given the preceding constraints. Here is a visual demonstration; here, the `ab` direction of the triangle is horizontal, left to right — the point `c` moves, expanding the bounding rectangle of the triangle when it pushes past `a` or `b`: Screenshot 2024-03-23 at 5 36 01 PM Screenshot 2024-03-23 at 5 38 12 PM Screenshot 2024-03-23 at 5 37 15 PM The UV-mapping of `Triangle2d` has also been changed to use the same logic. --- ## Changelog - Implemented `Meshable` for `Triangle3d`. - Changed UV-mapping of `Triangle2d` to match that of `Triangle3d`. ## Migration Guide The UV-mapping of `Triangle2d` has changed with this PR; the main difference is that the UVs are no longer dependent on the triangle's absolute coordinates, but instead follow translations of the triangle itself in its definition. If you depended on the old UV-coordinates for `Triangle2d`, then you will have to update affected areas to use the new ones which, briefly, can be described as follows: - The first coordinate is parallel to the line between the first two vertices of the triangle. - The second coordinate is orthogonal to this, pointing in the direction of the third point. Generally speaking, this means that the first two points will have coordinates `[_, 0.]`, while the third coordinate will be `[_, 1.]`, with the exact values depending on the position of the third point relative to the first two. For acute triangles, the first two vertices always have UV-coordinates `[0., 0.]` and `[1., 0.]` respectively. For obtuse triangles, the third point will have coordinate `[0., 1.]` or `[1., 1.]`, with the coordinate of one of the two other points shifting to maintain proportionality. For example: - The default `Triangle2d` has UV-coordinates `[0., 0.]`, `[0., 1.]`, [`0.5, 1.]`. - The triangle with vertices `vec2(0., 0.)`, `vec2(1., 0.)`, `vec2(2., 1.)` has UV-coordinates `[0., 0.]`, `[0.5, 0.]`, `[1., 1.]`. - The triangle with vertices `vec2(0., 0.)`, `vec2(1., 0.)`, `vec2(-2., 1.)` has UV-coordinates `[2./3., 0.]`, `[1., 0.]`, `[0., 1.]`. ## Discussion ### Design considerations 1. There are a number of ways to UV-map a triangle (at least two of which are fairly natural); for instance, we could instead declare the second axis to be essentially `bc` so that the vertices are always `[0., 0.]`, `[0., 1.]`, and `[1., 0.]`. I chose this method instead because it is skew-free, so that the sampling from textures has only bilinear scaling. I think this is better for cases where a relatively "uniform" texture is mapped to the triangle, but it's possible that we might want to support the other thing in the future. Thankfully, we already have the capability of easily expanding to do that with Builders if the need arises. This could also allow us to provide things like barycentric subdivision. 2. Presently, the mesh-creation code for `Triangle3d` is set up to never fail, even in the case that the triangle is degenerate. I have mixed feelings about this, but none of our other primitive meshes fail, so I decided to take the same approach. Maybe this is something that could be worth revisiting in the future across the board. --------- Co-authored-by: Alice Cecile Co-authored-by: Jakub Marcowski <37378746+Chubercik@users.noreply.github.com> --- .../bevy_render/src/mesh/primitives/dim2.rs | 29 ++--- .../src/mesh/primitives/dim3/mod.rs | 1 + .../src/mesh/primitives/dim3/triangle3d.rs | 114 ++++++++++++++++++ 3 files changed, 128 insertions(+), 16 deletions(-) create mode 100644 crates/bevy_render/src/mesh/primitives/dim3/triangle3d.rs diff --git a/crates/bevy_render/src/mesh/primitives/dim2.rs b/crates/bevy_render/src/mesh/primitives/dim2.rs index e10d7c845ce6a..b928a195a2e13 100644 --- a/crates/bevy_render/src/mesh/primitives/dim2.rs +++ b/crates/bevy_render/src/mesh/primitives/dim2.rs @@ -1,14 +1,13 @@ use crate::{ + mesh::primitives::dim3::triangle3d, mesh::{Indices, Mesh}, render_asset::RenderAssetUsages, }; use super::Meshable; -use bevy_math::{ - primitives::{ - Annulus, Capsule2d, Circle, Ellipse, Rectangle, RegularPolygon, Triangle2d, WindingOrder, - }, - Vec2, +use bevy_math::primitives::{ + Annulus, Capsule2d, Circle, Ellipse, Rectangle, RegularPolygon, Triangle2d, Triangle3d, + WindingOrder, }; use wgpu::PrimitiveTopology; @@ -317,25 +316,23 @@ impl Meshable for Triangle2d { type Output = Mesh; fn mesh(&self) -> Self::Output { - let [a, b, c] = self.vertices; + let vertices_3d = self.vertices.map(|v| v.extend(0.)); - let positions = vec![[a.x, a.y, 0.0], [b.x, b.y, 0.0], [c.x, c.y, 0.0]]; + let positions: Vec<_> = vertices_3d.into(); let normals = vec![[0.0, 0.0, 1.0]; 3]; - // The extents of the bounding box of the triangle, - // used to compute the UV coordinates of the points. - let extents = a.min(b).min(c).abs().max(a.max(b).max(c)) * Vec2::new(1.0, -1.0); - let uvs = vec![ - a / extents / 2.0 + 0.5, - b / extents / 2.0 + 0.5, - c / extents / 2.0 + 0.5, - ]; + let uvs: Vec<_> = triangle3d::uv_coords(&Triangle3d::new( + vertices_3d[0], + vertices_3d[1], + vertices_3d[2], + )) + .into(); let is_ccw = self.winding_order() == WindingOrder::CounterClockwise; let indices = if is_ccw { Indices::U32(vec![0, 1, 2]) } else { - Indices::U32(vec![0, 2, 1]) + Indices::U32(vec![2, 1, 0]) }; Mesh::new( diff --git a/crates/bevy_render/src/mesh/primitives/dim3/mod.rs b/crates/bevy_render/src/mesh/primitives/dim3/mod.rs index e2b337bb31934..3f98557f70a72 100644 --- a/crates/bevy_render/src/mesh/primitives/dim3/mod.rs +++ b/crates/bevy_render/src/mesh/primitives/dim3/mod.rs @@ -4,6 +4,7 @@ mod cylinder; mod plane; mod sphere; mod torus; +pub(crate) mod triangle3d; pub use capsule::*; pub use cylinder::*; diff --git a/crates/bevy_render/src/mesh/primitives/dim3/triangle3d.rs b/crates/bevy_render/src/mesh/primitives/dim3/triangle3d.rs new file mode 100644 index 0000000000000..4eb0fba32f9a3 --- /dev/null +++ b/crates/bevy_render/src/mesh/primitives/dim3/triangle3d.rs @@ -0,0 +1,114 @@ +use bevy_math::{primitives::Triangle3d, Vec3}; +use wgpu::PrimitiveTopology; + +use crate::{ + mesh::{Indices, Mesh, Meshable}, + render_asset::RenderAssetUsages, +}; + +impl Meshable for Triangle3d { + type Output = Mesh; + + fn mesh(&self) -> Self::Output { + let positions: Vec<_> = self.vertices.into(); + let uvs: Vec<_> = uv_coords(self).into(); + + // Every vertex has the normal of the face of the triangle (or zero if the triangle is degenerate). + let normal: Vec3 = self.normal().map_or(Vec3::ZERO, |n| n.into()); + let normals = vec![normal; 3]; + + let indices = Indices::U32(vec![0, 1, 2]); + + Mesh::new( + PrimitiveTopology::TriangleList, + RenderAssetUsages::default(), + ) + .with_inserted_indices(indices) + .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, positions) + .with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, normals) + .with_inserted_attribute(Mesh::ATTRIBUTE_UV_0, uvs) + } +} + +/// Unskewed uv-coordinates for a [`Triangle3d`]. +#[inline] +pub(crate) fn uv_coords(triangle: &Triangle3d) -> [[f32; 2]; 3] { + let [a, b, c] = triangle.vertices; + + let main_length = a.distance(b); + let Some(x) = (b - a).try_normalize() else { + return [[0., 0.], [1., 0.], [0., 1.]]; + }; + let y = c - a; + + // `x` corresponds to one of the axes in uv-coordinates; + // to uv-map the triangle without skewing, we use the orthogonalization + // of `y` with respect to `x` as the second direction and construct a rectangle that + // contains `triangle`. + let y_proj = y.project_onto_normalized(x); + + // `offset` represents the x-coordinate of the point `c`; note that x has been shrunk by a + // factor of `main_length`, so `offset` follows it. + let offset = y_proj.dot(x) / main_length; + + // Obtuse triangle leaning to the left => x direction extends to the left, shifting a from 0. + if offset < 0. { + let total_length = 1. - offset; + let a_uv = [offset.abs() / total_length, 0.]; + let b_uv = [1., 0.]; + let c_uv = [0., 1.]; + + [a_uv, b_uv, c_uv] + } + // Obtuse triangle leaning to the right => x direction extends to the right, shifting b from 1. + else if offset > 1. { + let a_uv = [0., 0.]; + let b_uv = [1. / offset, 0.]; + let c_uv = [1., 1.]; + + [a_uv, b_uv, c_uv] + } + // Acute triangle => no extending necessary; a remains at 0 and b remains at 1. + else { + let a_uv = [0., 0.]; + let b_uv = [1., 0.]; + let c_uv = [offset, 1.]; + + [a_uv, b_uv, c_uv] + } +} + +impl From for Mesh { + fn from(triangle: Triangle3d) -> Self { + triangle.mesh() + } +} + +#[cfg(test)] +mod tests { + use super::uv_coords; + use bevy_math::primitives::Triangle3d; + + #[test] + fn uv_test() { + use bevy_math::vec3; + let mut triangle = Triangle3d::new(vec3(0., 0., 0.), vec3(2., 0., 0.), vec3(-1., 1., 0.)); + + let [a_uv, b_uv, c_uv] = uv_coords(&triangle); + assert_eq!(a_uv, [1. / 3., 0.]); + assert_eq!(b_uv, [1., 0.]); + assert_eq!(c_uv, [0., 1.]); + + triangle.vertices[2] = vec3(3., 1., 0.); + let [a_uv, b_uv, c_uv] = uv_coords(&triangle); + assert_eq!(a_uv, [0., 0.]); + assert_eq!(b_uv, [2. / 3., 0.]); + assert_eq!(c_uv, [1., 1.]); + + triangle.vertices[2] = vec3(2., 1., 0.); + let [a_uv, b_uv, c_uv] = uv_coords(&triangle); + assert_eq!(a_uv, [0., 0.]); + assert_eq!(b_uv, [1., 0.]); + assert_eq!(c_uv, [1., 1.]); + } +}