bevy/crates/bevy_picking/src
Beni Bachmann 10daca0947 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<Vec2> {
    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
2025-03-31 22:33:28 +02:00
..
mesh_picking Return triangle index instead of vertex index (Fixes #18081) (#18647) 2025-03-31 22:33:28 +02:00
backend.rs Make RayMap map public (#18544) 2025-03-25 22:59:05 +01:00
events.rs bevy_reflect: Add clone registrations project-wide (#18307) 2025-03-17 18:32:35 +00:00
hover.rs bevy_reflect: Add clone registrations project-wide (#18307) 2025-03-17 18:32:35 +00:00
input.rs bevy_reflect: Add clone registrations project-wide (#18307) 2025-03-17 18:32:35 +00:00
lib.rs Unify picking backends (#17348) 2025-03-18 21:18:06 +01:00
pointer.rs bevy_reflect: Add clone registrations project-wide (#18307) 2025-03-17 18:32:35 +00:00
window.rs Renamed EventWriter::send methods to write. (#17977) 2025-02-23 21:18:52 +00:00