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    // TODO: is it possible to somehow use `is_collectible` here which requires
109    // sprite_cfg?
110    let (collect_pos, _, collect_cam_ray) = find_pos(|b: Block| {
111        b.get_sprite()
112            .is_some_and(|s| s.default_tool() == Some(None))
113    });
114    let (mine_pos, _, mine_cam_ray) = if active_mine_tool.is_some() {
115        find_pos(|b: Block| b.mine_tool().is_some())
116    } else {
117        (None, None, None)
118    };
119    let (solid_pos, place_block_pos, solid_cam_ray) = find_pos(|b: Block| b.is_filled());
120
121    // See if ray hits entities
122    // Don't cast through blocks, (hence why use shortest_cam_dist from non-entity
123    // targets) Could check for intersection with entity from last frame to
124    // narrow this down
125    let cast_dist = solid_cam_ray
126        .as_ref()
127        .map(|(d, _)| d.min(MAX_TARGET_RANGE))
128        .unwrap_or(MAX_TARGET_RANGE);
129
130    let uids = ecs.read_storage::<Uid>();
131
132    // Need to raycast by distance to cam
133    // But also filter out by distance to the player (but this only needs to be done
134    // on final result)
135    let mut nearby = (
136        &ecs.entities(),
137        &positions,
138        scales.maybe(),
139        &ecs.read_storage::<comp::Body>(),
140        ecs.read_storage::<comp::PickupItem>().maybe(),
141        !&ecs.read_storage::<Is<Mount>>(),
142        ecs.read_storage::<Is<Rider>>().maybe(),
143    )
144        .join()
145        .filter(|(e, _, _, _, _, _, _)| *e != player_entity)
146        .filter_map(|(e, p, s, b, i, _, is_rider)| {
147            const RADIUS_SCALE: f32 = 3.0;
148            // TODO: use collider radius instead of body radius?
149            let radius = s.map_or(1.0, |s| s.0) * b.max_radius() * RADIUS_SCALE;
150            // Move position up from the feet
151            let pos = Vec3::new(p.0.x, p.0.y, p.0.z + radius);
152            // Distance squared from camera to the entity
153            let dist_sqr = pos.distance_squared(cam_pos);
154            // We only care about interacting with entities that contain items,
155            // or are not inanimate (to trade with), and are not riding the player.
156            let not_riding_player = is_rider.is_none_or(|is_rider| Some(&is_rider.mount) != uids.get(viewpoint_entity));
157            if (i.is_some() || !matches!(b, comp::Body::Object(_))) && not_riding_player {
158                Some((e, pos, radius, dist_sqr))
159            } else {
160                None
161            }
162        })
163        // Roughly filter out entities farther than ray distance
164        .filter(|(_, _, r, d_sqr)| *d_sqr <= cast_dist.powi(2) + 2.0 * cast_dist * r + r.powi(2))
165        // Ignore entities intersecting the camera
166        .filter(|(_, _, r, d_sqr)| *d_sqr > r.powi(2))
167        // Substract sphere radius from distance to the camera
168        .map(|(e, p, r, d_sqr)| (e, p, r, d_sqr.sqrt() - r))
169        .collect::<Vec<_>>();
170    // Sort by distance
171    nearby.sort_unstable_by(|a, b| a.3.partial_cmp(&b.3).unwrap());
172
173    let seg_ray = LineSegment3 {
174        start: cam_pos,
175        end: cam_pos + cam_dir * cast_dist,
176    };
177    // TODO: fuzzy borders
178    let entity_target = nearby
179        .iter()
180        .map(|(e, p, r, _)| (e, *p, r))
181        // Find first one that intersects the ray segment
182        .find(|(_, p, r)| seg_ray.projected_point(*p).distance_squared(*p) < r.powi(2))
183        .and_then(|(e, p, _)| {
184            // Get the entity's cylinder
185            let target_cylinder = Cylinder::from_components(
186                p,
187                scales.get(*e).copied(),
188                colliders.get(*e),
189                char_states.get(*e),
190            );
191
192            let dist_to_player = player_cylinder.min_distance(target_cylinder);
193            if dist_to_player < MAX_TARGET_RANGE {
194                Some(Target {
195                    kind: Entity(*e),
196                    position: p,
197                    distance: dist_to_player,
198                })
199            } else { None }
200        });
201
202    let solid_ray_dist = solid_cam_ray.map(|r| r.0);
203    let terrain_target = solid_pos
204        .zip(solid_ray_dist)
205        .map(|(position, distance)| Target {
206            kind: Terrain,
207            distance,
208            position,
209        });
210
211    let build_target = if let (true, Some(distance)) = (can_build, solid_ray_dist) {
212        place_block_pos
213            .zip(solid_pos)
214            .map(|(place_pos, position)| Target {
215                kind: Build(place_pos),
216                distance,
217                position,
218            })
219    } else {
220        None
221    };
222
223    let collect_target = collect_pos
224        .zip(collect_cam_ray)
225        .map(|(position, ray)| Target {
226            kind: Collectable,
227            distance: ray.0,
228            position,
229        });
230
231    let mine_target = mine_pos.zip(mine_cam_ray).map(|(position, ray)| Target {
232        kind: Mine,
233        distance: ray.0,
234        position,
235    });
236
237    // Return multiple possible targets
238    // GameInput events determine which target to use.
239    (
240        build_target,
241        collect_target,
242        entity_target,
243        mine_target,
244        terrain_target,
245    )
246}
247
248pub(super) fn ray_entities(
249    client: &Client,
250    start: Vec3<f32>,
251    end: Vec3<f32>,
252    cast_dist: f32,
253) -> (f32, Option<Entity>) {
254    let player_entity = client.entity();
255    let ecs = client.state().ecs();
256    let positions = ecs.read_storage::<comp::Pos>();
257    let colliders = ecs.read_storage::<comp::Collider>();
258
259    let mut nearby = (
260        &ecs.entities(),
261        &positions,
262        &colliders,
263    )
264        .join()
265        .filter(|(e, _, _)| *e != player_entity)
266        .map(|(e, p, c)| {
267            let height = c.get_height();
268            let radius = c.bounding_radius().max(height / 2.0);
269            // Move position up from the feet
270            let pos = Vec3::new(p.0.x, p.0.y, p.0.z + c.get_z_limits(1.0).0 + height/2.0);
271            // Distance squared from start to the entity
272            let dist_sqr = pos.distance_squared(start);
273            (e, pos, radius, dist_sqr, c)
274        })
275        // Roughly filter out entities farther than ray distance
276        .filter(|(_, _, _, d_sqr, _)| *d_sqr <= cast_dist.powi(2))
277        .collect::<Vec<_>>();
278    // Sort by distance
279    nearby.sort_unstable_by(|a, b| a.3.partial_cmp(&b.3).unwrap());
280
281    let seg_ray = LineSegment3 { start, end };
282
283    let entity = nearby.iter().find_map(|(e, p, r, _, c)| {
284        let nearest = seg_ray.projected_point(*p);
285
286        match c {
287            comp::Collider::CapsulePrism {
288                p0,
289                p1,
290                radius,
291                z_min,
292                z_max,
293            } => {
294                // Check if the nearest point is within the capsule's inclusive radius (radius
295                // from center to furthest possible edge corner) If not, then
296                // the ray doesn't intersect the capsule at all and we can skip it
297                if nearest.distance_squared(*p) > (r * 3.0_f32.sqrt()).powi(2) {
298                    return None;
299                }
300
301                let entity_rotation = ecs
302                    .read_storage::<comp::Ori>()
303                    .get(*e)
304                    .copied()
305                    .unwrap_or_default();
306                let entity_position = ecs.read_storage::<comp::Pos>().get(*e).copied().unwrap();
307                let world_p0 = entity_position.0
308                    + (entity_rotation.to_quat()
309                        * Vec3::new(p0.x, p0.y, z_min + c.get_height() / 2.0));
310                let world_p1 = entity_position.0
311                    + (entity_rotation.to_quat()
312                        * Vec3::new(p1.x, p1.y, z_min + c.get_height() / 2.0));
313
314                // Get the closest points between the ray and the capsule's line segment
315                // If the capsule's line segment is a point, then the closest point is the point
316                // itself
317                let (p_a, p_b) = if p0 != p1 {
318                    let seg_capsule = LineSegment3 {
319                        start: world_p0,
320                        end: world_p1,
321                    };
322                    closest_points_3d(seg_ray, seg_capsule)
323                } else {
324                    let nearest = seg_ray.projected_point(world_p0);
325                    (nearest, world_p0)
326                };
327
328                // Check if the distance between the closest points are within the capsule
329                // prism's radius on the xy plane and if the closest points are
330                // within the capsule prism's z range
331                let distance = p_a.xy().distance_squared(p_b.xy());
332                if distance < radius.powi(2)
333                    && p_a.z >= entity_position.0.z + z_min
334                    && p_a.z <= entity_position.0.z + z_max
335                {
336                    return Some((p_a.distance(start), Entity(*e)));
337                }
338
339                // If all else fails, then the ray doesn't intersect the capsule
340                None
341            },
342            // TODO: handle other collider types, for now just use the bounding sphere
343            _ => {
344                if nearest.distance_squared(*p) < r.powi(2) {
345                    return Some((nearest.distance(start), Entity(*e)));
346                }
347                None
348            },
349        }
350    });
351    entity
352        .map(|(dist, e)| (dist, Some(e)))
353        .unwrap_or((cast_dist, None))
354}