Skip to content

Commit 956604e

Browse files
mweatherleyalice-i-cecileChubercik
authored
Meshing for Triangle3d primitive (#12686)
# 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`: <img width="1440" alt="Screenshot 2024-03-23 at 5 36 01 PM" src="https://github.com/bevyengine/bevy/assets/2975848/bef4d786-7b82-4207-abd4-ac4557d0f8b8"> <img width="1440" alt="Screenshot 2024-03-23 at 5 38 12 PM" src="https://github.com/bevyengine/bevy/assets/2975848/c0f72b8f-8e70-46fa-a750-2041ba6dfb78"> <img width="1440" alt="Screenshot 2024-03-23 at 5 37 15 PM" src="https://github.com/bevyengine/bevy/assets/2975848/db287e4f-2b0b-4fd4-8d71-88f4e7a03b7c"> 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 <[email protected]> Co-authored-by: Jakub Marcowski <[email protected]>
1 parent 934f2cf commit 956604e

File tree

3 files changed

+128
-16
lines changed

3 files changed

+128
-16
lines changed

crates/bevy_render/src/mesh/primitives/dim2.rs

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
11
use crate::{
2+
mesh::primitives::dim3::triangle3d,
23
mesh::{Indices, Mesh},
34
render_asset::RenderAssetUsages,
45
};
56

67
use super::Meshable;
7-
use bevy_math::{
8-
primitives::{
9-
Annulus, Capsule2d, Circle, Ellipse, Rectangle, RegularPolygon, Triangle2d, WindingOrder,
10-
},
11-
Vec2,
8+
use bevy_math::primitives::{
9+
Annulus, Capsule2d, Circle, Ellipse, Rectangle, RegularPolygon, Triangle2d, Triangle3d,
10+
WindingOrder,
1211
};
1312
use wgpu::PrimitiveTopology;
1413

@@ -317,25 +316,23 @@ impl Meshable for Triangle2d {
317316
type Output = Mesh;
318317

319318
fn mesh(&self) -> Self::Output {
320-
let [a, b, c] = self.vertices;
319+
let vertices_3d = self.vertices.map(|v| v.extend(0.));
321320

322-
let positions = vec![[a.x, a.y, 0.0], [b.x, b.y, 0.0], [c.x, c.y, 0.0]];
321+
let positions: Vec<_> = vertices_3d.into();
323322
let normals = vec![[0.0, 0.0, 1.0]; 3];
324323

325-
// The extents of the bounding box of the triangle,
326-
// used to compute the UV coordinates of the points.
327-
let extents = a.min(b).min(c).abs().max(a.max(b).max(c)) * Vec2::new(1.0, -1.0);
328-
let uvs = vec![
329-
a / extents / 2.0 + 0.5,
330-
b / extents / 2.0 + 0.5,
331-
c / extents / 2.0 + 0.5,
332-
];
324+
let uvs: Vec<_> = triangle3d::uv_coords(&Triangle3d::new(
325+
vertices_3d[0],
326+
vertices_3d[1],
327+
vertices_3d[2],
328+
))
329+
.into();
333330

334331
let is_ccw = self.winding_order() == WindingOrder::CounterClockwise;
335332
let indices = if is_ccw {
336333
Indices::U32(vec![0, 1, 2])
337334
} else {
338-
Indices::U32(vec![0, 2, 1])
335+
Indices::U32(vec![2, 1, 0])
339336
};
340337

341338
Mesh::new(

crates/bevy_render/src/mesh/primitives/dim3/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ mod cylinder;
44
mod plane;
55
mod sphere;
66
mod torus;
7+
pub(crate) mod triangle3d;
78

89
pub use capsule::*;
910
pub use cylinder::*;
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
use bevy_math::{primitives::Triangle3d, Vec3};
2+
use wgpu::PrimitiveTopology;
3+
4+
use crate::{
5+
mesh::{Indices, Mesh, Meshable},
6+
render_asset::RenderAssetUsages,
7+
};
8+
9+
impl Meshable for Triangle3d {
10+
type Output = Mesh;
11+
12+
fn mesh(&self) -> Self::Output {
13+
let positions: Vec<_> = self.vertices.into();
14+
let uvs: Vec<_> = uv_coords(self).into();
15+
16+
// Every vertex has the normal of the face of the triangle (or zero if the triangle is degenerate).
17+
let normal: Vec3 = self.normal().map_or(Vec3::ZERO, |n| n.into());
18+
let normals = vec![normal; 3];
19+
20+
let indices = Indices::U32(vec![0, 1, 2]);
21+
22+
Mesh::new(
23+
PrimitiveTopology::TriangleList,
24+
RenderAssetUsages::default(),
25+
)
26+
.with_inserted_indices(indices)
27+
.with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, positions)
28+
.with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, normals)
29+
.with_inserted_attribute(Mesh::ATTRIBUTE_UV_0, uvs)
30+
}
31+
}
32+
33+
/// Unskewed uv-coordinates for a [`Triangle3d`].
34+
#[inline]
35+
pub(crate) fn uv_coords(triangle: &Triangle3d) -> [[f32; 2]; 3] {
36+
let [a, b, c] = triangle.vertices;
37+
38+
let main_length = a.distance(b);
39+
let Some(x) = (b - a).try_normalize() else {
40+
return [[0., 0.], [1., 0.], [0., 1.]];
41+
};
42+
let y = c - a;
43+
44+
// `x` corresponds to one of the axes in uv-coordinates;
45+
// to uv-map the triangle without skewing, we use the orthogonalization
46+
// of `y` with respect to `x` as the second direction and construct a rectangle that
47+
// contains `triangle`.
48+
let y_proj = y.project_onto_normalized(x);
49+
50+
// `offset` represents the x-coordinate of the point `c`; note that x has been shrunk by a
51+
// factor of `main_length`, so `offset` follows it.
52+
let offset = y_proj.dot(x) / main_length;
53+
54+
// Obtuse triangle leaning to the left => x direction extends to the left, shifting a from 0.
55+
if offset < 0. {
56+
let total_length = 1. - offset;
57+
let a_uv = [offset.abs() / total_length, 0.];
58+
let b_uv = [1., 0.];
59+
let c_uv = [0., 1.];
60+
61+
[a_uv, b_uv, c_uv]
62+
}
63+
// Obtuse triangle leaning to the right => x direction extends to the right, shifting b from 1.
64+
else if offset > 1. {
65+
let a_uv = [0., 0.];
66+
let b_uv = [1. / offset, 0.];
67+
let c_uv = [1., 1.];
68+
69+
[a_uv, b_uv, c_uv]
70+
}
71+
// Acute triangle => no extending necessary; a remains at 0 and b remains at 1.
72+
else {
73+
let a_uv = [0., 0.];
74+
let b_uv = [1., 0.];
75+
let c_uv = [offset, 1.];
76+
77+
[a_uv, b_uv, c_uv]
78+
}
79+
}
80+
81+
impl From<Triangle3d> for Mesh {
82+
fn from(triangle: Triangle3d) -> Self {
83+
triangle.mesh()
84+
}
85+
}
86+
87+
#[cfg(test)]
88+
mod tests {
89+
use super::uv_coords;
90+
use bevy_math::primitives::Triangle3d;
91+
92+
#[test]
93+
fn uv_test() {
94+
use bevy_math::vec3;
95+
let mut triangle = Triangle3d::new(vec3(0., 0., 0.), vec3(2., 0., 0.), vec3(-1., 1., 0.));
96+
97+
let [a_uv, b_uv, c_uv] = uv_coords(&triangle);
98+
assert_eq!(a_uv, [1. / 3., 0.]);
99+
assert_eq!(b_uv, [1., 0.]);
100+
assert_eq!(c_uv, [0., 1.]);
101+
102+
triangle.vertices[2] = vec3(3., 1., 0.);
103+
let [a_uv, b_uv, c_uv] = uv_coords(&triangle);
104+
assert_eq!(a_uv, [0., 0.]);
105+
assert_eq!(b_uv, [2. / 3., 0.]);
106+
assert_eq!(c_uv, [1., 1.]);
107+
108+
triangle.vertices[2] = vec3(2., 1., 0.);
109+
let [a_uv, b_uv, c_uv] = uv_coords(&triangle);
110+
assert_eq!(a_uv, [0., 0.]);
111+
assert_eq!(b_uv, [1., 0.]);
112+
assert_eq!(c_uv, [1., 1.]);
113+
}
114+
}

0 commit comments

Comments
 (0)