veloren_voxygen/session/
target.rs

1use specs::{Join, LendJoin, WorldExt};
2use vek::*;
3
4use client::{self, Client};
5use common::{
6    comp::{self, tool::ToolKind},
7    consts::MAX_PICKUP_RANGE,
8    link::Is,
9    mounting::{Mount, Rider},
10    terrain::Block,
11    uid::Uid,
12    util::{
13        find_dist::{Cylinder, FindDist},
14        lines::closest_points_3d,
15    },
16    vol::ReadVol,
17};
18use common_base::span;
19
20#[derive(Clone, Copy, Debug)]
21pub struct Target<T> {
22    pub kind: T,
23    pub distance: f32,
24    pub position: Vec3<f32>,
25}
26
27#[derive(Clone, Copy, Debug)]
28pub struct Build(pub Vec3<f32>);
29
30#[derive(Clone, Copy, Debug)]
31pub struct Collectable;
32
33#[derive(Clone, Copy, Debug)]
34pub struct Entity(pub specs::Entity);
35
36#[derive(Clone, Copy, Debug)]
37pub struct Mine;
38
39#[derive(Clone, Copy, Debug)]
40// line of sight (if not bocked by entity). Not build/mine mode dependent.
41pub struct Terrain;
42
43impl<T> Target<T> {
44    pub fn position_int(self) -> Vec3<i32> { self.position.map(|p| p.floor() as i32) }
45}
46
47/// Max distance an entity can be "targeted"
48pub const MAX_TARGET_RANGE: f32 = 300.0;
49
50/// Calculate what the cursor is pointing at within the 3d scene
51pub(super) fn targets_under_cursor(
52    client: &Client,
53    cam_pos: Vec3<f32>,
54    cam_dir: Vec3<f32>,
55    can_build: bool,
56    active_mine_tool: Option<ToolKind>,
57    viewpoint_entity: specs::Entity,
58) -> (
59    Option<Target<Build>>,
60    Option<Target<Collectable>>,
61    Option<Target<Entity>>,
62    Option<Target<Mine>>,
63    Option<Target<Terrain>>,
64) {
65    span!(_guard, "targets_under_cursor");
66    // Choose a spot above the player's head for item distance checks
67    let player_entity = client.entity();
68    let ecs = client.state().ecs();
69    let positions = ecs.read_storage::<comp::Pos>();
70    let player_pos = match positions.get(player_entity) {
71        Some(pos) => pos.0,
72        None => cam_pos, // Should never happen, but a safe fallback
73    };
74    let scales = ecs.read_storage();
75    let colliders = ecs.read_storage();
76    let char_states = ecs.read_storage();
77    // Get the player's cylinder
78    let player_cylinder = Cylinder::from_components(
79        player_pos,
80        scales.get(player_entity).copied(),
81        colliders.get(player_entity),
82        char_states.get(player_entity),
83    );
84    let terrain = client.state().terrain();
85
86    let find_pos = |hit: fn(Block) -> bool| {
87        let cam_ray = terrain
88            .ray(cam_pos, cam_pos + cam_dir * 100.0)
89            .until(|block| hit(*block))
90            .cast();
91        let cam_ray = (cam_ray.0, cam_ray.1.map(|x| x.copied()));
92        let cam_dist = cam_ray.0;
93
94        if matches!(
95            cam_ray.1,
96            Ok(Some(_)) if player_cylinder.min_distance(cam_pos + cam_dir * (cam_dist + 0.01)) <= MAX_PICKUP_RANGE
97        ) {
98            (
99                Some(cam_pos + cam_dir * (cam_dist + 0.01)),
100                Some(cam_pos + cam_dir * (cam_dist - 0.01)),
101                Some(cam_ray),
102            )
103        } else {
104            (None, None, None)
105        }
106    };
107
108    let (collect_pos, _, collect_cam_ray) = find_pos(|b: Block| b.is_directly_collectible());
109    let (mine_pos, _, mine_cam_ray) = if active_mine_tool.is_some() {
110        find_pos(|b: Block| b.mine_tool().is_some())
111    } else {
112        (None, None, None)
113    };
114    let (solid_pos, place_block_pos, solid_cam_ray) = find_pos(|b: Block| b.is_filled());
115
116    // See if ray hits entities
117    // Don't cast through blocks, (hence why use shortest_cam_dist from non-entity
118    // targets) Could check for intersection with entity from last frame to
119    // narrow this down
120    let cast_dist = solid_cam_ray
121        .as_ref()
122        .map(|(d, _)| d.min(MAX_TARGET_RANGE))
123        .unwrap_or(MAX_TARGET_RANGE);
124
125    let uids = ecs.read_storage::<Uid>();
126
127    // Need to raycast by distance to cam
128    // But also filter out by distance to the player (but this only needs to be done
129    // on final result)
130    let mut nearby = (
131        &ecs.entities(),
132        &positions,
133        scales.maybe(),
134        &ecs.read_storage::<comp::Body>(),
135        ecs.read_storage::<comp::PickupItem>().maybe(),
136        !&ecs.read_storage::<Is<Mount>>(),
137        ecs.read_storage::<Is<Rider>>().maybe(),
138    )
139        .join()
140        .filter(|(e, _, _, _, _, _, _)| *e != player_entity)
141        .filter_map(|(e, p, s, b, i, _, is_rider)| {
142            const RADIUS_SCALE: f32 = 3.0;
143            // TODO: use collider radius instead of body radius?
144            let radius = s.map_or(1.0, |s| s.0) * b.max_radius() * RADIUS_SCALE;
145            // Move position up from the feet
146            let pos = Vec3::new(p.0.x, p.0.y, p.0.z + radius);
147            // Distance squared from camera to the entity
148            let dist_sqr = pos.distance_squared(cam_pos);
149            // We only care about interacting with entities that contain items,
150            // or are not inanimate (to trade with), and are not riding the player.
151            let not_riding_player = is_rider.is_none_or(|is_rider| Some(&is_rider.mount) != uids.get(viewpoint_entity));
152            if (i.is_some() || !matches!(b, comp::Body::Object(_))) && not_riding_player {
153                Some((e, pos, radius, dist_sqr))
154            } else {
155                None
156            }
157        })
158        // Roughly filter out entities farther than ray distance
159        .filter(|(_, _, r, d_sqr)| *d_sqr <= cast_dist.powi(2) + 2.0 * cast_dist * r + r.powi(2))
160        // Ignore entities intersecting the camera
161        .filter(|(_, _, r, d_sqr)| *d_sqr > r.powi(2))
162        // Substract sphere radius from distance to the camera
163        .map(|(e, p, r, d_sqr)| (e, p, r, d_sqr.sqrt() - r))
164        .collect::<Vec<_>>();
165    // Sort by distance
166    nearby.sort_unstable_by(|a, b| a.3.partial_cmp(&b.3).unwrap());
167
168    let seg_ray = LineSegment3 {
169        start: cam_pos,
170        end: cam_pos + cam_dir * cast_dist,
171    };
172    // TODO: fuzzy borders
173    let entity_target = nearby
174        .iter()
175        .map(|(e, p, r, _)| (e, *p, r))
176        // Find first one that intersects the ray segment
177        .find(|(_, p, r)| seg_ray.projected_point(*p).distance_squared(*p) < r.powi(2))
178        .and_then(|(e, p, _)| {
179            // Get the entity's cylinder
180            let target_cylinder = Cylinder::from_components(
181                p,
182                scales.get(*e).copied(),
183                colliders.get(*e),
184                char_states.get(*e),
185            );
186
187            let dist_to_player = player_cylinder.min_distance(target_cylinder);
188            if dist_to_player < MAX_TARGET_RANGE {
189                Some(Target {
190                    kind: Entity(*e),
191                    position: p,
192                    distance: dist_to_player,
193                })
194            } else { None }
195        });
196
197    let solid_ray_dist = solid_cam_ray.map(|r| r.0);
198    let terrain_target = solid_pos
199        .zip(solid_ray_dist)
200        .map(|(position, distance)| Target {
201            kind: Terrain,
202            distance,
203            position,
204        });
205
206    let build_target = if let (true, Some(distance)) = (can_build, solid_ray_dist) {
207        place_block_pos
208            .zip(solid_pos)
209            .map(|(place_pos, position)| Target {
210                kind: Build(place_pos),
211                distance,
212                position,
213            })
214    } else {
215        None
216    };
217
218    let collect_target = collect_pos
219        .zip(collect_cam_ray)
220        .map(|(position, ray)| Target {
221            kind: Collectable,
222            distance: ray.0,
223            position,
224        });
225
226    let mine_target = mine_pos.zip(mine_cam_ray).map(|(position, ray)| Target {
227        kind: Mine,
228        distance: ray.0,
229        position,
230    });
231
232    // Return multiple possible targets
233    // GameInput events determine which target to use.
234    (
235        build_target,
236        collect_target,
237        entity_target,
238        mine_target,
239        terrain_target,
240    )
241}
242
243pub(super) fn ray_entities(
244    client: &Client,
245    start: Vec3<f32>,
246    end: Vec3<f32>,
247    cast_dist: f32,
248) -> (f32, Option<Entity>) {
249    let player_entity = client.entity();
250    let ecs = client.state().ecs();
251    let positions = ecs.read_storage::<comp::Pos>();
252    let colliders = ecs.read_storage::<comp::Collider>();
253
254    let mut nearby = (
255        &ecs.entities(),
256        &positions,
257        &colliders,
258    )
259        .join()
260        .filter(|(e, _, _)| *e != player_entity)
261        .map(|(e, p, c)| {
262            let height = c.get_height();
263            let radius = c.bounding_radius().max(height / 2.0);
264            // Move position up from the feet
265            let pos = Vec3::new(p.0.x, p.0.y, p.0.z + c.get_z_limits(1.0).0 + height/2.0);
266            // Distance squared from start to the entity
267            let dist_sqr = pos.distance_squared(start);
268            (e, pos, radius, dist_sqr, c)
269        })
270        // Roughly filter out entities farther than ray distance
271        .filter(|(_, _, _, d_sqr, _)| *d_sqr <= cast_dist.powi(2))
272        .collect::<Vec<_>>();
273    // Sort by distance
274    nearby.sort_unstable_by(|a, b| a.3.partial_cmp(&b.3).unwrap());
275
276    let seg_ray = LineSegment3 { start, end };
277
278    let entity = nearby.iter().find_map(|(e, p, r, _, c)| {
279        let nearest = seg_ray.projected_point(*p);
280
281        match c {
282            comp::Collider::CapsulePrism {
283                p0,
284                p1,
285                radius,
286                z_min,
287                z_max,
288            } => {
289                // Check if the nearest point is within the capsule's inclusive radius (radius
290                // from center to furthest possible edge corner) If not, then
291                // the ray doesn't intersect the capsule at all and we can skip it
292                if nearest.distance_squared(*p) > (r * 3.0_f32.sqrt()).powi(2) {
293                    return None;
294                }
295
296                let entity_rotation = ecs
297                    .read_storage::<comp::Ori>()
298                    .get(*e)
299                    .copied()
300                    .unwrap_or_default();
301                let entity_position = ecs.read_storage::<comp::Pos>().get(*e).copied().unwrap();
302                let world_p0 = entity_position.0
303                    + (entity_rotation.to_quat()
304                        * Vec3::new(p0.x, p0.y, z_min + c.get_height() / 2.0));
305                let world_p1 = entity_position.0
306                    + (entity_rotation.to_quat()
307                        * Vec3::new(p1.x, p1.y, z_min + c.get_height() / 2.0));
308
309                // Get the closest points between the ray and the capsule's line segment
310                // If the capsule's line segment is a point, then the closest point is the point
311                // itself
312                let (p_a, p_b) = if p0 != p1 {
313                    let seg_capsule = LineSegment3 {
314                        start: world_p0,
315                        end: world_p1,
316                    };
317                    closest_points_3d(seg_ray, seg_capsule)
318                } else {
319                    let nearest = seg_ray.projected_point(world_p0);
320                    (nearest, world_p0)
321                };
322
323                // Check if the distance between the closest points are within the capsule
324                // prism's radius on the xy plane and if the closest points are
325                // within the capsule prism's z range
326                let distance = p_a.xy().distance_squared(p_b.xy());
327                if distance < radius.powi(2)
328                    && p_a.z >= entity_position.0.z + z_min
329                    && p_a.z <= entity_position.0.z + z_max
330                {
331                    return Some((p_a.distance(start), Entity(*e)));
332                }
333
334                // If all else fails, then the ray doesn't intersect the capsule
335                None
336            },
337            // TODO: handle other collider types, for now just use the bounding sphere
338            _ => {
339                if nearest.distance_squared(*p) < r.powi(2) {
340                    return Some((nearest.distance(start), Entity(*e)));
341                }
342                None
343            },
344        }
345    });
346    entity
347        .map(|(dist, e)| (dist, Some(e)))
348        .unwrap_or((cast_dist, None))
349}