- if (!line_of_sight) {
- Controlled().Velocity(glm::vec3(0.0f));
- } else if (dist > stop_dist) {
- Controlled().Velocity(norm_diff * chase_speed);
- } else if (dist < flee_dist) {
- Controlled().Velocity(norm_diff * flee_speed);
- } else {
- Controlled().Velocity(glm::vec3(0.0f));
+Player *AIController::ClosestVisiblePlayer(const Entity &e) noexcept {
+ Player *target = nullptr;
+ float distance = sight_dist;
+ const glm::ivec3 &reference(e.ChunkCoords());
+ Ray aim(e.Aim(reference));
+ for (Player &p : world.Players()) {
+ const Entity &pe = p.GetEntity();
+
+ // distance test
+ const glm::vec3 diff(pe.AbsoluteDifference(e));
+ float dist = length(diff);
+ if (dist > distance) continue;
+
+ // FOV test, 45° in each direction
+ if (dot(diff / dist, aim.dir) < sight_angle) {
+ continue;
+ }
+
+ // LOS test, assumes all entities are see-through
+ WorldCollision col;
+ if (world.Intersection(aim, reference, col) && col.depth < dist) {
+ continue;
+ }
+
+ // we got a match
+ target = &p;
+ distance = dist;
+ }
+ return target;
+}
+
+bool AIController::LineOfSight(const Entity &from, const Entity &to) const noexcept {
+ const glm::ivec3 &reference(from.ChunkCoords());
+ Ray aim(from.Aim(reference));
+ const glm::vec3 diff(to.AbsoluteDifference(from));
+ float dist = length(diff);
+ if (dist > sight_dist || dot(diff / dist, aim.dir) < sight_angle) {
+ return false;