Using Bevy's AsyncComputeTaskPool to find the shortest path to any destination among a set of potential destinations without blocking the main thread. Rust is neat!

// Find the shortest path to any tile in a set of tiles.
fn calculate_shortest_path(
    start: TilePos,
    destinations: HashSet,
    tilemap_id: TilemapId,
) -> Result>, HommletError> {
    // Resolve the operation asynchronously.
    let async_task = AsyncComputeTaskPool::get().spawn(async move {
        // For each destination tile, calculate a path.
        // Then, find the shortest path.
        AsyncComputeTaskPool::get()
            .scope(|s| {
                destinations.iter().for_each(|&destination| {
                    s.spawn(async move { path_to_tile(tilemap_id, start, destination) })
                });
            })
            .into_iter()
            .flatten()
            .min_by_key(|path| path.nodes.len())
            .ok_or(HommletError::FailedToFindPathInSet)
    });

    Ok(async_task)
}
🤙1React
0 Comments
G
G
Guest
User