From 10daca0947213da1b4049f3667fb697ff5df501f Mon Sep 17 00:00:00 2001 From: Beni Bachmann Date: Mon, 31 Mar 2025 20:50:15 +0200 Subject: [PATCH] Return triangle index instead of vertex index (Fixes #18081) (#18647) # Objective - Fixes #18081 - Enable use-cases like getting UVs or texture colors for the hit point (which are currently not possible due to this bug). ## Solution - Return the triangle index instead of the first vertex index of the triangle. ## Testing Tested successfully with my project which does a raycast to get the UV coordinates of the hit. My code: ```rust fn get_uv( mesh: &Mesh, attribute: &MeshVertexAttribute, hit: &RayMeshHit, _gizmos: &mut Gizmos, ) -> Result { let (a, b, c) = get_indices(mesh, hit)?; let attrs = mesh .attribute(*attribute) .ok_or_eyre(format!("Attribute {:?} not found", &attribute))?; let all_uvs: &Vec<[f32; 2]> = match &attrs { VertexAttributeValues::Float32x2(positions) => positions, _ => bail!("Unexpected types in {:?}", Mesh::ATTRIBUTE_UV_0), }; let bary = hit.barycentric_coords; Ok(Vec2::from_array(all_uvs[a]) * bary.x + Vec2::from_array(all_uvs[b]) * bary.y + Vec2::from_array(all_uvs[c]) * bary.z) } fn get_indices(mesh: &Mesh, hit: &RayMeshHit) -> Result<(usize, usize, usize)> { let i = hit .triangle_index .ok_or_eyre("Intersection Index not found")?; Ok(mesh.indices().map_or_else( || (i, i + 1, i + 2), |indices| match indices { Indices::U16(indices) => ( indices[i * 3] as usize, indices[i * 3 + 1] as usize, indices[i * 3 + 2] as usize, ), Indices::U32(indices) => ( indices[i * 3] as usize, indices[i * 3 + 1] as usize, indices[i * 3 + 2] as usize, ), }, )) } ``` PS: created a new PR because the old one was coming from and targeting the wrong branches --- crates/bevy_picking/src/mesh_picking/ray_cast/intersections.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/bevy_picking/src/mesh_picking/ray_cast/intersections.rs b/crates/bevy_picking/src/mesh_picking/ray_cast/intersections.rs index b0f2750b53..9988a96e19 100644 --- a/crates/bevy_picking/src/mesh_picking/ray_cast/intersections.rs +++ b/crates/bevy_picking/src/mesh_picking/ray_cast/intersections.rs @@ -189,7 +189,7 @@ pub fn ray_mesh_intersection + Clone + Copy>( .transform_vector3(ray.direction * hit.distance) .length(), triangle: Some(tri_vertices.map(|v| mesh_transform.transform_point3(v))), - triangle_index: Some(a), + triangle_index: Some(tri_idx), }) }) }