Преглед изворни кода

Moved the movement, the triggers and the encounters of the entities to their own classes

- WalkmeshMovement walks, climbs and jumps the entities of a field, EntityTriggers runs the scripts of lines, touches and talks, and FieldEncounters starts the random battles. The entity manager keeps its public functions, which pass the calls on.
- Broke up the field update and the walkmesh move into smaller functions.
- Removed three unused members and an unused parameter.
- Added tests for the walkmesh height, the sides of a line and the steering around obstacles.
Iñigo Valentin пре 1 дан
родитељ
комит
2c26f130ca

+ 4 - 3
src/engine/entity/CMakeLists.txt

@@ -4,12 +4,13 @@ vgears_sources(
     EntityCollision.cpp
     EntityDirection.cpp
     EntityManager.cpp
-    EntityManagerEncounters.cpp
-    EntityManagerMovement.cpp
+    EntityManagerField.cpp
     EntityManagerPlayer.cpp
-    EntityManagerTriggers.cpp
     EntityModel.cpp
     EntityPoint.cpp
     EntityTrigger.cpp
+    EntityTriggers.cpp
+    FieldEncounters.cpp
     Walkmesh.cpp
+    WalkmeshMovement.cpp
 )

+ 98 - 176
src/engine/entity/EntityManager.cpp

@@ -41,6 +41,10 @@ const unsigned int EntityManager::BATTLE_BACKGROUND_ID = 1000;
 
 const unsigned int EntityManager::WORLD_MAP_BACKGROUND_ID = 1001;
 
+float EntityManager::GetTriangleHeight(int triangle, float x, float y, float fallback) const{
+    return movement_.GetTriangleHeight(triangle, x, y, fallback);
+}
+
 EntityManager::EntityManager():
     background_3d_(nullptr),
   player_entity_(nullptr),
@@ -48,13 +52,10 @@ EntityManager::EntityManager():
   player_move_rotation_(0),
   player_lock_(false),
   player_run_(false),
-  random_encounters_(false),
-  encounter_rate_(0),
-  encounter_table_(1),
-  encounter_distance_(0.0f),
-  encounter_last_position_(Ogre::Vector3::ZERO),
-  encounter_last_position_valid_(false),
-  encounter_safe_steps_(0)
+  movement_(
+    *this, walkmesh_, entity_, player_entity_, player_lock_, player_slip_, player_move_,
+    [this](Entity* entity, const Ogre::Vector3& position){CheckTriggers(entity, position);}
+  )
 {
     LOG_TRIVIAL("EntityManager created.");
     scene_node_ = Ogre::Root::getSingleton().getSceneManager("Scene")
@@ -80,173 +81,6 @@ EntityManager::~EntityManager(){
     LOG_TRIVIAL("EntityManager destroyed.");
 }
 
-void EntityManager::UpdateField(){
-    // Update all entity scripts
-    ScriptManager::getSingleton().Update(ScriptManager::ENTITY);
-    // The player is walking if there is a move set by the input.
-    const bool walked = player_entity_ != nullptr && player_move_ != Ogre::Vector3::ZERO;
-
-    // Set move point for player entity
-    if (player_entity_ != nullptr && player_move_ != Ogre::Vector3::ZERO){
-        Entity::State state = player_entity_->GetState();
-        if (state == Entity::WALKMESH || state == Entity::NONE){
-            // The directional keys are relative to the screen. Rotate them to the field's move
-            // rotation here, once per frame. This can't be done in Input, which runs once for each
-            // event, so the rotation would be applied several times when there is more than one
-            // event in the frame (diagonals, running, ...). player_move_ stays as the raw input,
-            // which is what ladders need.
-            // A scripted walk of an entity that isn't the player keeps the last triangle when it
-            // goes over an edge, so the stored triangle can be far from the position. Reattach to
-            // the walkmesh before moving manually, otherwise every move would be blocked.
-            const int current_triangle = player_entity_->GetMoveTriangleId();
-            bool in_current_triangle = false;
-            if (current_triangle >= 0 && current_triangle < walkmesh_.GetNumberOfTriangles()){
-                const Ogre::Vector3 position = player_entity_->GetPosition();
-                const Ogre::Vector3 A = walkmesh_.GetA(current_triangle);
-                const Ogre::Vector3 B = walkmesh_.GetB(current_triangle);
-                const Ogre::Vector3 C = walkmesh_.GetC(current_triangle);
-                in_current_triangle = Ogre::Math::pointInTri2D(
-                  Ogre::Vector2(position.x, position.y), Ogre::Vector2(A.x, A.y),
-                  Ogre::Vector2(B.x, B.y), Ogre::Vector2(C.x, C.y)
-                );
-            }
-            if (!in_current_triangle) SetEntityOnWalkmesh(player_entity_);
-
-            Ogre::Quaternion rotation;
-            rotation.FromAngleAxis(player_move_rotation_, Ogre::Vector3::UNIT_Z);
-            // Normalized, so diagonals aren't faster than straight moves.
-            Ogre::Vector3 input = player_move_;
-            input.normalise();
-            const Ogre::Vector3 walk_move = rotation * input
-              * (player_entity_->GetMoveWalkSpeed() * Timer::getSingleton().GetGameTimeDelta());
-            player_entity_->SetMovePosition(player_entity_->GetPosition() + walk_move);
-            player_entity_->SetState(Entity::WALKMESH);
-        }
-
-        // HACK: If manually moving, make playable entity solid.
-        // Some scripts 'forget' to make the playable entity solid at the end
-        // of them, and if it remains non-solid, it can't interact with lines
-        // (i.e. it cant' use gateways).
-        player_entity_->SetSolid(true);
-    }
-
-    for (unsigned int i = 0; i < entity_.size(); ++ i){
-        entity_[i]->Update();
-
-        // It's not needed to update movements it delta time == 0 (for example
-        // if time is stopped)
-        if (Timer::getSingleton().GetGameTimeDelta() == 0) continue;
-
-        // Update screen scroll.
-        Entity* scroll_entity = background_2d_.GetAutoScrollEntity();
-        if (scroll_entity == entity_[i])
-            background_2d_.SetScroll(background_2d_.GetEntityScroll(scroll_entity));
-        // Update offset.
-        if (entity_[i]->GetOffsetType() != AT_NONE) SetNextOffsetStep(entity_[i]);
-        // Update turn.
-        if (entity_[i]->GetTurnType() != AT_NONE) SetNextTurnStep(entity_[i]);
-        // Update movement.
-        switch(entity_[i]->GetState()){
-            case Entity::WALKMESH:
-                {
-                    // Try set entity on walkmesh if it's still don't has triangle.
-                    if (entity_[i]->GetMoveTriangleId() == -1){
-                        if (SetEntityOnWalkmesh(entity_[i]) == false){
-                            LOG_TRIVIAL(
-                              "Can't set entity '" + entity_[i]->GetName()
-                              + "' on walkmesh. Finish move."
-                            );
-                            entity_[i]->UnsetMove();
-                        }
-                    }
-                    // Perform move
-                    if (entity_[i]->GetState() == Entity::WALKMESH){
-                        float speed = 0;
-                        if (player_lock_ == false && player_entity_ == entity_[i]){
-                            speed = entity_[i]->GetMoveWalkSpeed();
-                            // TODO: Set as a constant.
-                            // Or even better, as a configurable variable.
-                            // The run key inverts the default movement.
-                            if (player_run_ != player_default_run_) speed *= 4;
-                        }
-                        else speed = entity_[i]->GetMoveAutoSpeed();
-                        float remaining_time = Timer::getSingleton().GetGameTimeDelta();
-                        bool is_move = false;
-                        if (entity_[i]->IsScriptedMove() && speed > 0.0f){
-                            const float max_step_time = 0.2f / speed;
-                            while (remaining_time > 0.0f && entity_[i]->GetState() == Entity::WALKMESH){
-                                const float step_time = std::min(remaining_time, max_step_time);
-                                const bool moved = PerformWalkmeshMove(entity_[i], speed, step_time);
-                                is_move = is_move || moved;
-                                if (!moved) break;
-                                remaining_time -= step_time;
-                            }
-                        }
-                        else is_move = PerformWalkmeshMove(entity_[i], speed, remaining_time);
-                        // The scripts set the animation of a scene as the default one (DFANM) and
-                        // don't set it back, but the player stands normally again as soon as they
-                        // walk in the original game (blin67_3, where Cloud ends the scene crouched).
-                        if (
-                          is_move == true && player_lock_ == false && player_entity_ == entity_[i]
-                          && entity_[i]->GetDefaultAnimationName() != "Idle"
-                        ){
-                            entity_[i]->ScriptSetDefaultAnimation("Idle");
-                        }
-                        if (entity_[i]->GetMoveAutoAnimation() == true){
-                            if (is_move == true){
-                                if (speed >= entity_[i]->GetMoveRunSpeed()){
-                                    entity_[i]->PlayAnimationContinue(
-                                      entity_[i]->GetMoveAnimationRunName()
-                                    );
-                                }
-                                else{
-                                    entity_[i]->PlayAnimationContinue(
-                                      entity_[i]->GetMoveAnimationWalkName()
-                                    );
-                                }
-                            }
-                            else if (
-                              entity_[i]->GetAnimationState() != Entity::REQUESTED_ANIMATION
-                            ){
-                                entity_[i]->PlayAnimationContinue(
-                                  entity_[i]->GetDefaultAnimationName()
-                                );
-                            }
-                        }
-                    }
-                }
-                break;
-            case Entity::LINEAR:
-                CheckTriggers(entity_[i], entity_[i]->GetPosition());
-                SetNextLinearStep(entity_[i]);
-                break;
-            case Entity::JUMP:
-                SetNextJumpStep(entity_[i]);
-                break;
-            case Entity::NEEDS_TO_REATTACH:
-                if (SetEntityOnWalkmesh(entity_[i])) entity_[i]->SetState(Entity::WALKMESH);
-                else entity_[i]->SetState(Entity::NONE);
-            case Entity::NONE:
-                CheckTriggers(entity_[i], entity_[i]->GetPosition());
-                if (entity_[i]->GetAnimationState() != Entity::REQUESTED_ANIMATION)
-                    entity_[i]->PlayAnimationContinue(entity_[i]->GetDefaultAnimationName());
-                break;
-        }
-    }
-    CheckEntityContacts();
-    // Reset player move. It already must be handled in update
-    player_move_ = Ogre::Vector3::ZERO;
-    player_run_ = false;
-    if (background_2d_.GetScrollType() != Background2D::NONE) SetNextScrollStep();
-    background_2d_.Update();
-    // This can start a battle and change the module, so it's the last thing to do.
-    UpdateEncounters(walked);
-    // The movie follows the speed of the game, so the scenes that are timed with it stay in sync.
-    // Its sound doesn't, so at any other speed they drift apart.
-    movie_player_.Update(Timer::getSingleton().GetGameTimeDelta());
-    screen_fade_.Update(Timer::getSingleton().GetGameTimeDelta());
-}
-
 void EntityManager::UpdateBattle(){
     ScriptManager::getSingleton().Update(ScriptManager::BATTLE);
     if (background_3d_ != nullptr){
@@ -442,9 +276,9 @@ void EntityManager::UpdateDebug(){
 void EntityManager::OnResize(){background_2d_.OnResize();}
 
 void EntityManager::ClearField(){
-    ClearEncounterTables();
+    encounters_.Clear();
     entities_hidden_by_battle_.clear();
-    entities_in_contact_.clear();
+    triggers_.ClearContacts();
     walkmesh_.Clear();
     background_2d_.Clear();
     screen_fade_.Clear();
@@ -531,6 +365,27 @@ void EntityManager::ClearWorld(){
 
 Walkmesh* EntityManager::GetWalkmesh(){return &walkmesh_;}
 
+bool EntityManager::IsWorldPositionBlocked(
+  const Entity* moving_entity, const Ogre::Vector3& position
+) const{
+    if (!IsWorldModule() || moving_entity == nullptr) return false;
+
+    for (const Entity* other : entity_){
+        if (other == moving_entity || !other->IsSolid()) continue;
+
+        const Ogre::Vector3 other_position = other->GetPosition();
+        const Ogre::Real dx = position.x - other_position.x;
+        const Ogre::Real dz = position.z - other_position.z;
+        const Ogre::Real radius = moving_entity->GetSolidRadius() + other->GetSolidRadius();
+        if (dx * dx + dz * dz >= radius * radius) continue;
+
+        const Ogre::Real moving_top = position.y + moving_entity->GetHeight();
+        const Ogre::Real other_top = other_position.y + other->GetHeight();
+        if (position.y < other_top && other_position.y < moving_top) return true;
+    }
+    return false;
+}
+
 Background2D* EntityManager::GetBackground2D(){return &background_2d_;}
 
 ScreenFade* EntityManager::GetScreenFade(){return &screen_fade_;}
@@ -565,6 +420,21 @@ void EntityManager::ScriptAddEntity(
   const float x, const float y, const float z, const float rotation, int index
 ){AddEntity(name, file_name, Ogre::Vector3(x, y, z), Ogre::Degree(rotation), index);}
 
+void EntityManager::AddEntityTrigger(
+  const Ogre::String& name,
+  const Ogre::Vector3& point1, const Ogre::Vector3& point2, const bool enabled
+){
+    if (IsBattleModule()){
+        LOG_WARNING("Tried to add an entity trigger but the EntityManager is in battle mode.");
+        return;
+    }
+    EntityTrigger* trigger = new EntityTrigger(name);
+    trigger->SetPoints(point1, point2);
+    trigger->SetEnabled(enabled);
+    entity_triggers_.push_back(trigger);
+    ScriptManager::getSingleton().AddEntity(ScriptManager::ENTITY, trigger->GetName(), nullptr);
+}
+
 void EntityManager::AddEntityPoint(
   const Ogre::String& name, const Ogre::Vector3& position, const float rotation
 ){
@@ -675,3 +545,55 @@ void EntityManager::SetEntityToCharacter(const char* entity_name, unsigned int c
       + "'. No entity by that name exists."
     );
 }
+
+float EntityManager::GetEncounterMultiplier() const{return FieldEncounters::GetMultiplier();}
+
+bool EntityManager::IsDebugEncounters() const{return FieldEncounters::IsDebug();}
+
+void EntityManager::SetRandomEncounters(bool active){encounters_.SetActive(active);}
+
+void EntityManager::ClearEncounterTables(){encounters_.Clear();}
+
+void EntityManager::AddEncounterTable(
+  const int id, const int rate, const std::vector<std::pair<int, int>>& battles,
+  const std::vector<std::pair<int, int>>& specials
+){
+    encounters_.AddTable(id, rate, battles, specials);
+}
+
+void EntityManager::ScriptSetEncounterTable(const int id){encounters_.SetTable(id);}
+
+int EntityManager::ScriptRollEncounterBattle() const{return encounters_.RollBattle();}
+
+void EntityManager::ScriptSetLine(
+  const char* name, const float x1, const float y1, const float z1, const float x2, const float y2,
+  const float z2
+){
+    for (EntityTrigger* trigger : entity_triggers_){
+        if (trigger->GetName() == name){
+            trigger->SetPoints(Ogre::Vector3(x1, y1, z1), Ogre::Vector3(x2, y2, z2));
+            return;
+        }
+    }
+}
+
+void EntityManager::CheckTriggers(Entity* entity, const Ogre::Vector3& position){
+    if (IsBattleModule()){
+        LOG_WARNING("Tried to check for triggers, but the EntityManager is in battle mode");
+        return;
+    }
+    // Only the player triggers the lines.
+    if (entity != player_entity_ || !entity->IsSolid() || player_lock_) return;
+    triggers_.CheckLines(entity, position, entity_triggers_);
+}
+
+void EntityManager::CheckEntityInteract(){
+    if (IsBattleModule()){
+        LOG_WARNING(
+          "Tried to check for entity interaction, but the EntityManager is in battle mode"
+        );
+        return;
+    }
+    if (player_entity_ == nullptr || player_lock_ || !player_entity_->IsSolid()) return;
+    triggers_.Interact(player_entity_, entity_, IsWorldModule());
+}

+ 50 - 268
src/engine/entity/EntityManager.h

@@ -16,8 +16,6 @@
 #pragma once
 
 #include <chrono>
-#include <set>
-#include <map>
 #include <utility>
 #include <vector>
 #include <OgreSingleton.h>
@@ -25,11 +23,14 @@
 #include "Entity.h"
 #include "EntityPoint.h"
 #include "EntityTrigger.h"
+#include "EntityTriggers.h"
+#include "FieldEncounters.h"
 #include "engine/Event.h"
 #include "engine/Manager.h"
 #include "engine/graphics/MoviePlayer.h"
 #include "engine/graphics/ScreenFade.h"
 #include "Walkmesh.h"
+#include "WalkmeshMovement.h"
 
 class EntityModel;
 
@@ -50,55 +51,6 @@ class EntityManager : public Manager, public Ogre::Singleton<EntityManager>{
          */
         virtual ~EntityManager();
 
-        /**
-         * Limits a scripted movement step to its remaining distance.
-         *
-         * @param[in] distance Distance to the target.
-         * @param[in] stop_distance Desired distance from the target.
-         * @param[in] max_step Maximum distance to move this frame.
-         * @return Distance to move this frame.
-         */
-        static float ScriptedMoveStep(float distance, float stop_distance, float max_step);
-
-        /**
-         * Decides whether an entity is a better target to interact with than the best one so far.
-         *
-         * The one the player faces more directly wins. If the angles are the same, the nearest
-         * one does.
-         *
-         * @param[in] angle Angle in degrees between where the player faces and the candidate.
-         * @param[in] distance Squared distance to the candidate.
-         * @param[in] best_angle Angle of the best candidate so far, or the largest one allowed.
-         * @param[in] best_distance Squared distance to the best candidate so far.
-         * @return True if the candidate is better.
-         */
-        static bool IsBetterInteractionTarget(
-          float angle, float distance, float best_angle, float best_distance
-        );
-
-        /**
-         * Retrieves how close to a line an entity has to be to trigger it.
-         *
-         * It's the solid radius of the entity, unless a script has made it too small, as scripts
-         * do while a scene is playing. Lines couldn't be triggered at all then.
-         *
-         * @param[in] solid_radius Solid radius of the entity.
-         * @return The distance to the line from which it triggers.
-         */
-        static float TriggerReach(float solid_radius);
-
-        /**
-         * Checks if the edge of the walkmesh stops an entity.
-         *
-         * It stops the player and the characters that wander. The characters that a script walks
-         * to a position are not stopped: the original game lets them walk off the walkmesh.
-         *
-         * @param[in] is_player Whether the entity is the player.
-         * @param[in] scripted_move Whether a script asked the entity to walk to a position.
-         * @return True if the edge of the walkmesh blocks the entity.
-         */
-        static bool WalkmeshEdgeBlocks(bool is_player, bool scripted_move);
-
         /**
          * Handles an input event.
          *
@@ -579,62 +531,6 @@ class EntityManager : public Manager, public Ogre::Singleton<EntityManager>{
 
     private:
 
-        /**
-         * Calculates the point elevation over a plane.
-         *
-         * @param[in] point Point to calculate the elevation of.
-         * @param[in] a First point of the plane.
-         * @param[in] b Second point of the plane.
-         * @param[in] c Third  point of the plane.
-         * @return The elevation of the point.
-         */
-        static float PointElevation(
-          const Ogre::Vector2& point,
-          const Ogre::Vector3& a, const Ogre::Vector3& b, const Ogre::Vector3& c
-        );
-
-        /**
-         * Determines at which side of a line a point is.
-         *
-         * @param[in] point The point to evaluate.
-         * @param[in] p1 The first point of the line.
-         * @param[in] p2 The second point of the line.
-         * @return A negative value if the point is on the "left" of the line vector, a positive
-         * value if the point is on the "right" of the vector line, or 0 if the point is part of
-         * the line. "Left" and "right" are determined by going from p1 to p2.
-         */
-        static float SideOfVector(
-          const Ogre::Vector2& point, const Ogre::Vector2& p1, const Ogre::Vector2& p2
-        );
-
-        /**
-         * Calculates the square distance between a point and a line.
-         *
-         * The calculated distance is the vector orthogonal to the line that passes by the point,
-         * i.e. the shortest distance.
-         *
-         * @param[in] point The point.
-         * @param[in] point_a First point of the line.
-         * @param[in] point_b Second point of the line.
-         * @param[out] proj Vector representing the shortest distance.
-         * @return The distance from the point to the line.
-         */
-        static float SquareDistanceToLine(
-          const Ogre::Vector3& point, const Ogre::Vector3& point_a, const Ogre::Vector3& point_b,
-          Ogre::Vector3& proj
-        );
-
-        /**
-         * Calculates the direction degree between to points.
-         *
-         * @param[in] current_point Origin point.
-         * @param[in] direction_point Next point in the direction.
-         * @return Degrees between the two points
-         */
-        static Ogre::Degree GetDirectionToPoint(
-          const Ogre::Vector3& current_point, const Ogre::Vector3& direction_point
-        );
-
         /**
          * Scale factor for battle background models.
          */
@@ -650,18 +546,6 @@ class EntityManager : public Manager, public Ogre::Singleton<EntityManager>{
          */
         static const unsigned int  WORLD_MAP_BACKGROUND_ID;
 
-        /**
-         * Priority of the script that runs when the player presses OK in front of an entity.
-         *
-         * It has to run before the scripts that fields leave running on an entity (the loops that
-         * play an animation, requested with priority 5 or 6), or the entity could not be talked to.
-         * But it can't be the highest: a script of the same entity that is requested with a higher
-         * priority (3 or smaller) has to be able to run while the talk script waits for it, as in
-         * the scenes where a talk script asks its own entity to do something and waits for it to
-         * start.
-         */
-        static const int INTERACT_SCRIPT_PRIORITY;
-
         /**
          * Updates the field entities in the manager.
          */
@@ -713,56 +597,6 @@ class EntityManager : public Manager, public Ogre::Singleton<EntityManager>{
           const Ogre::Vector3& scale, const Ogre::Quaternion& root_orientation, const int index
         );
 
-        /**
-         * Attaches an entity to the walkmesh.
-         *
-         * It sets the triangle from the entity position coordinates. To account for multiple
-         * triangles on different levels, it uses only the X and Y coordinates, and automatically
-         * sets the Z one to the closest triangle. If the manager is in battle mode, it will do
-         * nothing.
-         *
-         * @param[in] entity Entity to attach.
-         * @return True if the entity was assigned to a walkmesh triangle, false if the entity is
-         * not in a triangle or if the manager is in battle mode.
-         */
-        bool SetEntityOnWalkmesh(Entity* entity);
-
-        /**
-         * Moves an entity in the walkmesh.
-         *
-         * If the manager is in battle mode, it will do nothing.
-         *
-         * @param[in] entity Entity to move.
-         * @param[in] speed Movement speed.
-         * @param[in] delta_time Time elapsed for this movement step.
-         * @return True if the movement was possible and the entity was moved, false otherwise.
-         * If the manager is in battle mode, it will always return false.
-         */
-        bool PerformWalkmeshMove(Entity* entity, const float speed, const float delta_time);
-
-        /**
-         * Checks if the entity is crossing a walkmesh triangle border.
-         *
-         * @param[in] entity Entity to check.
-         * @param[in] position The position. @todo document more.
-         * @param[in] move_vector The move vector. @todo document more.
-         * @return True if the entity is crossing a triangle border, false otherwise. If the manager
-         * is in battle mode, it will always return false.
-         */
-        bool WalkmeshBorderCross(
-          Entity* entity, Ogre::Vector3& position, const Ogre::Vector2& move_vector
-        );
-
-        /**
-         * Checks for collisions of the entity with other entities.
-         *
-         * @param[in] entity Entity to check for collisions.
-         * @param[in] position Position of the entity.
-         * @return True if the entity is colliding with another, false otherwise. If the entity is
-         * not solid, always false. If the manager is in battle mode, it will always return false.
-         */
-        bool CheckSolidCollisions(Entity* entity, Ogre::Vector3& position);
-
         /**
          * Checks for entity triggers near a entity.
          *
@@ -787,47 +621,64 @@ class EntityManager : public Manager, public Ogre::Singleton<EntityManager>{
         void CheckEntityInteract();
 
         /**
-         * Runs the contact script (script 2) of the entities that the player touches.
-         *
-         * The script of an entity that the original game runs when the player collides with it
-         * (the old man of condor1 starts his conversation that way, and only after it can be
-         * talked to). It runs once for each touch.
+         * Moves the player entity according to the pressed directions.
          */
-        void CheckEntityContacts();
+        void ApplyPlayerInput();
 
+        /**
+         * Updates the scroll, offset, turn and movement of an entity of a field.
+         *
+         * @param[in] entity The entity.
+         */
+        void UpdateFieldEntity(Entity* entity);
 
+        /**
+         * Updates an entity that is on the walkmesh: moves it and chooses its animation.
+         *
+         * @param[in] entity The entity.
+         */
+        void UpdateWalkingEntity(Entity* entity);
 
         /**
-         * Calculates the next offset step for an entity.
+         * Updates an entity that is not moving.
          *
          * @param[in] entity The entity.
          */
-        void SetNextOffsetStep(Entity* entity);
+        void UpdateStandingEntity(Entity* entity);
 
         /**
-         * Calculates the next turn step for an entity
+         * Retrieves the speed at which an entity walks.
          *
          * @param[in] entity The entity.
+         * @return The speed.
          */
-        void SetNextTurnStep(Entity* entity);
+        float GetWalkingSpeed(const Entity* entity) const;
 
         /**
-         * Calculates and sets the next position during a linear movement.
+         * Walks an entity for the time of this frame.
          *
-         * If the manager is in battle mode, it will do nothing
+         * Scripted moves are done in small steps, so a long frame doesn't make them miss their
+         * destination.
          *
-         * @param[in] entity The moving entity.
+         * @param[in] entity The entity.
+         * @param[in] speed The speed of the entity.
+         * @return True if the entity moved.
          */
-        void SetNextLinearStep(Entity* entity);
+        bool WalkEntity(Entity* entity, const float speed);
 
         /**
-         * Calculates and sets the next position during a jump.
+         * Calculates the next offset step for an entity.
          *
-         * If the manager is in battle mode, it will do nothing
+         * @param[in] entity The entity.
+         */
+        void SetNextOffsetStep(Entity* entity);
+
+        /**
+         * Calculates the next turn step for an entity
          *
-         * @param[in] entity The jump entity.
+         * @param[in] entity The entity.
          */
-        void SetNextJumpStep(Entity* entity);
+        void SetNextTurnStep(Entity* entity);
 
         /**
          * @todo Understand and document.
@@ -855,11 +706,6 @@ class EntityManager : public Manager, public Ogre::Singleton<EntityManager>{
          */
         ScreenFade screen_fade_;
 
-        /**
-         * The entity table name.
-         */
-        Ogre::String entity_table_name_;
-
         /**
          * The list of field or world entities.
          */
@@ -913,8 +759,6 @@ class EntityManager : public Manager, public Ogre::Singleton<EntityManager>{
         /// After entering a field from the world map, the walk keys that were held are ignored until
         /// they are released, so the player starts standing still.
         bool ignore_held_walk_ = false;
-        /// Entities that the player is touching.
-        std::set<const Entity*> entities_in_contact_;
         /// Last time that a script asked for the Start button.
         std::chrono::steady_clock::time_point start_key_read_time_;
 
@@ -939,100 +783,38 @@ class EntityManager : public Manager, public Ogre::Singleton<EntityManager>{
         std::vector<Ogre::String> entity_scripts_;
 
         /**
-         * The scene node.
-         */
-        Ogre::SceneNode* scene_node_;
-
-        /**
-         * @todo Understand and document.
+         * Runs the scripts of lines, touches and talks.
          */
-        Ogre::Entity* grid_;
+        EntityTriggers triggers_;
 
         /**
-         * @todo Understand and document.
+         * Random battles of the field.
          */
-        Ogre::Entity* axis_;
+        FieldEncounters encounters_;
 
         /**
-         * Indicates if random encounters happen in the map.
+         * Moves the entities on the walkmesh.
          */
-        bool random_encounters_;
+        WalkmeshMovement movement_;
 
         /**
-         * The encounter rate of the map.
+         * The scene node.
          */
-        float encounter_rate_;
+        Ogre::SceneNode* scene_node_;
 
         /**
-         * Random encounter table of a field.
+         * @todo Understand and document.
          */
-        struct EncounterTable{
-
-            /**
-             * Encounter rate, as in the original game.
-             */
-            int rate;
-
-            /**
-             * Standard encounters: battle ID and probability (out of 64).
-             */
-            std::vector<std::pair<int, int>> battles;
-
-            /**
-             * Special encounters: battle ID and probability (out of 64).
-             */
-            std::vector<std::pair<int, int>> specials;
-        };
+        Ogre::Entity* grid_;
 
         /**
-         * Random encounter tables of the field, by ID.
+         * @todo Understand and document.
          */
-        std::map<int, EncounterTable> encounter_tables_;
+        Ogre::Entity* axis_;
 
         /**
          * Entities that were visible before a battle, hidden while it lasts.
          */
         std::vector<Entity*> entities_hidden_by_battle_;
 
-        /**
-         * ID of the encounter table in use.
-         */
-        int encounter_table_;
-
-        /**
-         * Distance walked by the player since the last step.
-         */
-        float encounter_distance_;
-
-        /**
-         * Position of the player in the last frame, to know how much it has walked.
-         */
-        Ogre::Vector3 encounter_last_position_;
-
-        /**
-         * Indicates if {@see encounter_last_position_} is valid.
-         */
-        bool encounter_last_position_valid_;
-
-        /**
-         * Steps that must be taken before encounters can happen again.
-         */
-        int encounter_safe_steps_;
-
-        /**
-         * Accumulated chance of a random encounter, out of 256 * 256. It grows while walking.
-         */
-        int encounter_accumulator_ = 0;
-
-        /**
-         * Last random battle, which is not repeated twice in a row. -1 if none.
-         */
-        int encounter_last_battle_ = -1;
-
-        /**
-         * Counts the steps of the player and starts random encounters.
-         *
-         * @param[in] walked True if the player was moved by the player's input in this frame.
-         */
-        void UpdateEncounters(const bool walked);
 };

+ 229 - 0
src/engine/entity/EntityManagerField.cpp

@@ -0,0 +1,229 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <algorithm>
+#include <cmath>
+#include <OgreMath.h>
+#include "engine/Timer.h"
+#include "engine/entity/EntityManager.h"
+#include "common/Logger.h"
+#include "engine/script/ScriptManager.h"
+
+void EntityManager::UpdateField(){
+    // Update all entity scripts
+    ScriptManager::getSingleton().Update(ScriptManager::ENTITY);
+    // The player is walking if there is a move set by the input.
+    const bool walked = player_entity_ != nullptr && player_move_ != Ogre::Vector3::ZERO;
+    if (walked) ApplyPlayerInput();
+
+    for (unsigned int i = 0; i < entity_.size(); ++ i){
+        entity_[i]->Update();
+        // It's not needed to update movements it delta time == 0 (for example
+        // if time is stopped)
+        if (Timer::getSingleton().GetGameTimeDelta() == 0) continue;
+        UpdateFieldEntity(entity_[i]);
+    }
+    if (IsFieldModule()) triggers_.CheckContacts(player_entity_, player_lock_, entity_);
+    // Reset player move. It already must be handled in update
+    player_move_ = Ogre::Vector3::ZERO;
+    player_run_ = false;
+    if (background_2d_.GetScrollType() != Background2D::NONE) SetNextScrollStep();
+    background_2d_.Update();
+    // This can start a battle and change the module, so it's the last thing to do.
+    encounters_.Update(player_entity_, player_lock_, walked);
+    // The movie follows the speed of the game, so the scenes that are timed with it stay in sync.
+    // Its sound doesn't, so at any other speed they drift apart.
+    movie_player_.Update(Timer::getSingleton().GetGameTimeDelta());
+    screen_fade_.Update(Timer::getSingleton().GetGameTimeDelta());
+}
+
+void EntityManager::ApplyPlayerInput(){
+    const Entity::State state = player_entity_->GetState();
+    if (state == Entity::WALKMESH || state == Entity::NONE){
+        // A scripted walk of an entity that isn't the player keeps the last triangle when it goes
+        // over an edge, so the stored triangle can be far from the position. Reattach to the
+        // walkmesh before moving manually, otherwise every move would be blocked.
+        if (!movement_.IsInCurrentTriangle(*player_entity_))
+            movement_.PlaceOnWalkmesh(player_entity_);
+
+        // The directional keys are relative to the screen. Rotate them to the field's move
+        // rotation here, once per frame. This can't be done in Input, which runs once for each
+        // event, so the rotation would be applied several times when there is more than one event
+        // in the frame (diagonals, running, ...). player_move_ stays as the raw input, which is
+        // what ladders need.
+        Ogre::Quaternion rotation;
+        rotation.FromAngleAxis(player_move_rotation_, Ogre::Vector3::UNIT_Z);
+        // Normalized, so diagonals aren't faster than straight moves.
+        Ogre::Vector3 input = player_move_;
+        input.normalise();
+        const Ogre::Vector3 walk_move = rotation * input
+          * (player_entity_->GetMoveWalkSpeed() * Timer::getSingleton().GetGameTimeDelta());
+        player_entity_->SetMovePosition(player_entity_->GetPosition() + walk_move);
+        player_entity_->SetState(Entity::WALKMESH);
+    }
+
+    // HACK: If manually moving, make playable entity solid.
+    // Some scripts 'forget' to make the playable entity solid at the end of them, and if it
+    // remains non-solid, it can't interact with lines (i.e. it cant' use gateways).
+    player_entity_->SetSolid(true);
+}
+
+void EntityManager::UpdateFieldEntity(Entity* entity){
+    // Update screen scroll.
+    if (background_2d_.GetAutoScrollEntity() == entity)
+        background_2d_.SetScroll(background_2d_.GetEntityScroll(entity));
+    // Update offset.
+    if (entity->GetOffsetType() != AT_NONE) SetNextOffsetStep(entity);
+    // Update turn.
+    if (entity->GetTurnType() != AT_NONE) SetNextTurnStep(entity);
+    // Update movement.
+    switch (entity->GetState()){
+        case Entity::WALKMESH:
+            UpdateWalkingEntity(entity);
+            break;
+        case Entity::LINEAR:
+            CheckTriggers(entity, entity->GetPosition());
+            movement_.LinearStep(entity);
+            break;
+        case Entity::JUMP:
+            movement_.JumpStep(entity);
+            break;
+        case Entity::NEEDS_TO_REATTACH:
+            if (movement_.PlaceOnWalkmesh(entity)) entity->SetState(Entity::WALKMESH);
+            else entity->SetState(Entity::NONE);
+            // The entity stands in this frame, whatever its new state is.
+            UpdateStandingEntity(entity);
+            break;
+        case Entity::NONE:
+            UpdateStandingEntity(entity);
+            break;
+    }
+}
+
+void EntityManager::UpdateWalkingEntity(Entity* entity){
+    // Try set entity on walkmesh if it's still don't has triangle.
+    if (entity->GetMoveTriangleId() == -1 && !movement_.PlaceOnWalkmesh(entity)){
+        LOG_TRIVIAL("Can't set entity '" + entity->GetName() + "' on walkmesh. Finish move.");
+        entity->UnsetMove();
+    }
+    if (entity->GetState() != Entity::WALKMESH) return;
+
+    const float speed = GetWalkingSpeed(entity);
+    const bool moved = WalkEntity(entity, speed);
+    // The scripts set the animation of a scene as the default one (DFANM) and don't set it back,
+    // but the player stands normally again as soon as they walk in the original game (blin67_3,
+    // where Cloud ends the scene crouched).
+    if (
+      moved && !player_lock_ && player_entity_ == entity
+      && entity->GetDefaultAnimationName() != "Idle"
+    ){
+        entity->ScriptSetDefaultAnimation("Idle");
+    }
+    if (entity->GetMoveAutoAnimation() == false) return;
+    if (moved){
+        entity->PlayAnimationContinue(
+          speed >= entity->GetMoveRunSpeed()
+            ? entity->GetMoveAnimationRunName() : entity->GetMoveAnimationWalkName()
+        );
+    }
+    else if (entity->GetAnimationState() != Entity::REQUESTED_ANIMATION)
+        entity->PlayAnimationContinue(entity->GetDefaultAnimationName());
+}
+
+void EntityManager::UpdateStandingEntity(Entity* entity){
+    CheckTriggers(entity, entity->GetPosition());
+    if (entity->GetAnimationState() != Entity::REQUESTED_ANIMATION)
+        entity->PlayAnimationContinue(entity->GetDefaultAnimationName());
+}
+
+float EntityManager::GetWalkingSpeed(const Entity* entity) const{
+    if (player_lock_ || player_entity_ != entity) return entity->GetMoveAutoSpeed();
+    float speed = entity->GetMoveWalkSpeed();
+    // TODO: Set as a constant. Or even better, as a configurable variable.
+    // The run key inverts the default movement.
+    if (player_run_ != player_default_run_) speed *= 4;
+    return speed;
+}
+
+bool EntityManager::WalkEntity(Entity* entity, const float speed){
+    float remaining_time = Timer::getSingleton().GetGameTimeDelta();
+    if (!entity->IsScriptedMove() || !(speed > 0.0f))
+        return movement_.Walk(entity, speed, remaining_time);
+    const float max_step_time = 0.2f / speed;
+    bool any_move = false;
+    while (remaining_time > 0.0f && entity->GetState() == Entity::WALKMESH){
+        const float step_time = std::min(remaining_time, max_step_time);
+        if (!movement_.Walk(entity, speed, step_time)) break;
+        any_move = true;
+        remaining_time -= step_time;
+    }
+    return any_move;
+}
+
+void EntityManager::SetNextOffsetStep(Entity* entity){
+    // TODO: Allow this while on battle mode?
+    ActionType type = entity->GetOffsetType();
+    float total = entity->GetOffsetSeconds();
+    float current = entity->GetOffsetCurrentSeconds();
+    current += Timer::getSingleton().GetGameTimeDelta();
+    current = (current > total) ? total : current;
+    Ogre::Vector3 start = entity->GetOffsetPositionStart();
+    Ogre::Vector3 end = entity->GetOffsetPositionEnd();
+    // An offset of zero seconds is done at once. Dividing would give NaN.
+    float x = (total > 0.0f) ? current / total : 1.0f;
+    if (std::isnan(x)) x = 0.0f;
+    float smooth_modifier = (type == AT_SMOOTH) ? -2 * x * x * x + 3 * x * x : x;
+    Ogre::Vector3 offset = start + (end - start) * smooth_modifier;
+    entity->SetOffset(offset);
+    if (current == total) entity->UnsetOffset();
+    else entity->SetOffsetCurrentSeconds(current);
+}
+
+void EntityManager::SetNextTurnStep(Entity* entity){
+    // TODO: Allow this while on battle mode?
+    ActionType type = entity->GetTurnType();
+    float total = entity->GetTurnSeconds();
+    float current = entity->GetTurnCurrentSeconds();
+    current += Timer::getSingleton().GetGameTimeDelta();
+    current = (current > total) ? total : current;
+    Ogre::Degree start = entity->GetTurnDirectionStart();
+    Ogre::Degree end = entity->GetTurnDirectionEnd();
+    // A turn of zero seconds is done at once. Dividing would give NaN, and a NaN rotation breaks
+    // the bounding box of the entity.
+    float x = (total > 0.0f) ? current / total : 1.0f;
+    float smooth_modifier = (type == AT_SMOOTH) ? -2 * x * x * x + 3 * x * x : x;
+    Ogre::Degree rotation = start + (end - start) * smooth_modifier;
+    entity->SetRotation(rotation);
+    if (current == total) entity->UnsetTurn();
+    else entity->SetTurnCurrentSeconds(current);
+}
+
+void EntityManager::SetNextScrollStep(){
+    // TODO: Allow this on battle mode?
+    background_2d_.UpdateScrollTarget();
+    Background2D::SCROLL_TYPE type = background_2d_.GetScrollType();
+    float total = background_2d_.GetScrollSeconds();
+    float current = background_2d_.GetScrollCurrentSeconds();
+    current += Timer::getSingleton().GetGameTimeDelta();
+    current = (current > total) ? total : current;
+    Ogre::Vector2 start = background_2d_.GetScrollPositionStart();
+    Ogre::Vector2 end = background_2d_.GetScrollPositionEnd();
+    float x = (total > 0.0f) ? current / total : 1.0f;
+    float smooth_modifier = (type == Background2D::SMOOTH) ? -2 * x * x * x + 3 * x * x : x;
+    Ogre::Vector2 scroll = start + (end - start) * smooth_modifier;
+    background_2d_.SetScroll(scroll);
+    if (current == total) background_2d_.UnsetScroll();
+    else background_2d_.SetScrollCurrentSeconds(current);
+}

+ 0 - 712
src/engine/entity/EntityManagerMovement.cpp

@@ -1,712 +0,0 @@
-/*
- * Copyright (C) 2022 The V-Gears Team
- *
- * This file is part of V-Gears
- *
- * V-Gears is free software: you can redistribute it and/or modify it under
- * terms of the GNU General Public License as published by the Free Software
- * Foundation, version 3.0 (GPLv3) of the License.
- *
- * V-Gears is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- */
-
-#include <algorithm>
-#include <cmath>
-#include <OgreMath.h>
-#include "engine/entity/EntityManager.h"
-#include "common/Logger.h"
-#include "engine/Timer.h"
-
-float EntityManager::GetTriangleHeight(int triangle, float x, float y, float fallback) const{
-    if (IsBattleModule() || triangle < 0 || triangle >= walkmesh_.GetNumberOfTriangles())
-        return fallback;
-    const float height = PointElevation(
-      Ogre::Vector2(x, y), walkmesh_.GetA(triangle), walkmesh_.GetB(triangle),
-      walkmesh_.GetC(triangle)
-    );
-    return std::isfinite(height) ? height : fallback;
-}
-
-float EntityManager::PointElevation(
-  const Ogre::Vector2& point, const Ogre::Vector3& a, const Ogre::Vector3& b, const Ogre::Vector3& c
-){
-    float _a = a.z * (b.y - c.y) + b.z * (c.y - a.y) + c.z * (a.y - b.y);
-    float _b = a.y * (b.x - c.x) + b.y * (c.x - a.x) + c.y * (a.x - b.x);
-    float _c = a.x * (b.z - c.z) + b.x * (c.z - a.z) + c.x * (a.z - b.z);
-    float _d
-      = a.x * (b.z * c.y - c.z * b.y) + b.x * (c.z * a.y - a.z * c.y)
-        + c.x * (a.z * b.y - b.z * a.y);
-    return (_d - _c * point.y - _a * point.x) / _b;
-}
-
-float EntityManager::SideOfVector(
-  const Ogre::Vector2& point, const Ogre::Vector2& p1, const Ogre::Vector2& p2
-){
-    Ogre::Vector2 AB = p2    - p1;
-    Ogre::Vector2 AP = point - p1;
-    return AB.x * AP.y - AB.y * AP.x;
-}
-
-bool EntityManager::IsWorldPositionBlocked(
-    const Entity* moving_entity, const Ogre::Vector3& position
-) const{
-        if (!IsWorldModule() || moving_entity == nullptr) return false;
-
-        for (const Entity* other : entity_){
-                if (other == moving_entity || !other->IsSolid()) continue;
-
-                const Ogre::Vector3 other_position = other->GetPosition();
-                const Ogre::Real dx = position.x - other_position.x;
-                const Ogre::Real dz = position.z - other_position.z;
-                const Ogre::Real radius = moving_entity->GetSolidRadius() + other->GetSolidRadius();
-                if (dx * dx + dz * dz >= radius * radius) continue;
-
-                const Ogre::Real moving_top = position.y + moving_entity->GetHeight();
-                const Ogre::Real other_top = other_position.y + other->GetHeight();
-                if (position.y < other_top && other_position.y < moving_top) return true;
-        }
-        return false;
-}
-
-bool EntityManager::SetEntityOnWalkmesh(Entity* entity){
-    if (IsBattleModule()){
-        LOG_WARNING("Tried to set entity on the walkmesh, but the EntityManager is in battle mode");
-        return false;
-    }
-    Ogre::Vector3 position3 = entity->GetPosition();
-    Ogre::Vector2 position2;
-    position2.x = position3.x;
-    position2.y = position3.y;
-    std::vector<std::pair<int, float>> triangles;
-    // Search for possible triangles.
-    for (int i = 0; i < walkmesh_.GetNumberOfTriangles(); ++ i){
-        Ogre::Vector3 A3 = walkmesh_.GetA(i);
-        Ogre::Vector3 B3 = walkmesh_.GetB(i);
-        Ogre::Vector3 C3 = walkmesh_.GetC(i);
-        Ogre::Vector2 A2(A3.x, A3.y);
-        Ogre::Vector2 B2(B3.x, B3.y);
-        Ogre::Vector2 C2(C3.x, C3.y);
-        if (Ogre::Math::pointInTri2D(position2, A2, B2, C2) == true){
-            triangles.push_back(std::make_pair(i, PointElevation(
-              position2, walkmesh_.GetA(i), walkmesh_.GetB(i), walkmesh_.GetC(i)
-            )));
-        }
-    }
-    // If the coordinates doesn't match any triangle, exit.
-    if (triangles.size() == 0 && entity == player_entity_){
-        LOG_ERROR(
-          "Can't find any triangle to place entity '" + entity->GetName() + "' on walkmesh."
-        );
-        return false;
-    }
-    // From the possible triangles, select the closest one (on the Z edge).
-    int closest_z_triangle = -1;
-    float closest_z_distance = 9999.0f;
-    float pos_z = position3.z;
-    for (size_t i = 0; i < triangles.size(); ++ i){
-        if (std::abs(pos_z - triangles[i].second) < closest_z_distance){
-            closest_z_triangle = triangles[i].first;
-            closest_z_distance = std::abs(pos_z - triangles[i].second);
-        }
-    }
-    if (closest_z_triangle == -1 && entity == player_entity_){
-        LOG_ERROR(
-          "Can't find nearby triangle to place entity '" + entity->GetName() + "' on walkmesh."
-        );
-        return false;
-    }
-    entity->SetPosition(Ogre::Vector3(position2.x, position2.y, pos_z));
-    entity->SetMoveTriangleId(closest_z_triangle);
-    return true;
-}
-
-bool EntityManager::WalkmeshEdgeBlocks(bool is_player, bool scripted_move){
-    return is_player || !scripted_move;
-}
-
-float EntityManager::ScriptedMoveStep(float distance, float stop_distance, float max_step){
-    return std::min(max_step, std::max(0.0f, distance - stop_distance));
-}
-
-bool EntityManager::PerformWalkmeshMove(Entity* entity, const float speed, const float delta_time){
-    if (IsBattleModule()){
-        LOG_WARNING("Tried to perform a walkmesh move, but the EntityManager is in battle mode");
-        return false;
-    }
-    Ogre::Vector3 start_point = entity->GetPosition();
-    Ogre::Vector3 move_vector = entity->GetMovePosition() - start_point;
-    Ogre::Vector2 direction(move_vector.x, move_vector.y);
-    const float distance_to_target = direction.length();
-    const bool scripted_move = entity->IsScriptedMove();
-    const float stop_distance = entity->GetMoveStopDistance();
-    if (scripted_move && distance_to_target <= stop_distance + 0.0001f){
-        entity->UnsetMove();
-        return false;
-    }
-    direction.normalise();
-    direction *= delta_time;
-    direction *= speed;
-    if (scripted_move && !direction.isZeroLength()){
-        direction.normalise();
-        direction *= ScriptedMoveStep(
-          distance_to_target, stop_distance, speed * delta_time
-        );
-    }
-    // If movement is still needed but speed or time don't allow it, just return for now.
-    if (direction.isZeroLength() == true){
-        if (player_entity_ == entity) CheckTriggers(entity, entity->GetPosition());
-        return false;
-    }
-    int current_triangle = entity->GetMoveTriangleId();
-    // A character that is not on the walkmesh (Jenova of shpin_3, that is placed outside it and
-    // moves with FMOVE) is walked in a straight line, or the scene that waits for it would never go
-    // on.
-    if (current_triangle == -1 && scripted_move && entity != player_entity_){
-        const float step = std::min(direction.length(), distance_to_target);
-        Ogre::Vector2 move = direction;
-        if (!move.isZeroLength()) move.normalise();
-        move *= step;
-        entity->SetPosition(Ogre::Vector3(start_point.x + move.x, start_point.y + move.y, start_point.z));
-        if (distance_to_target - step <= stop_distance + 0.0001f) entity->UnsetMove();
-        return step > 0.0f;
-    }
-    if (current_triangle == -1){
-        // The entities that a scene places later (the soldiers of the parade of junonr4) are asked
-        // to move before it, and wait. Only the player has to be on the walkmesh.
-        if (entity == player_entity_)
-            LOG_ERROR("Entity '" + entity->GetName() + "' not placed on walkmesh and can't move.");
-        return false;
-    }
-    Ogre::Vector3 rotation(0.0f, 0.0f, 0.0f);
-    Ogre::Quaternion q1(0.0f, 0.0f, 0.0f, 1.0f);
-    Ogre::Vector3 end_point(0.0f, 0.0f, 0.0f);
-    Ogre::Vector3 end_point2(0.0f, 0.0f, 0.0f);
-    bool first_triangle_check = false;
-    bool second_triangle_check = false;
-    bool third_triangle_check = false;
-    bool last_triangle_check = false;
-    bool first_entity_check = false;
-    bool second_entity_check = false;
-    bool third_entity_check = false;
-    // Shorten move vector by triangle angle
-    end_point.x = start_point.x + direction.x;
-    end_point.y = start_point.y + direction.y;
-    Ogre::Vector3 A3 = walkmesh_.GetA(current_triangle);
-    Ogre::Vector3 B3 = walkmesh_.GetB(current_triangle);
-    Ogre::Vector3 C3 = walkmesh_.GetC(current_triangle);
-    end_point.z = PointElevation(Ogre::Vector2(end_point.x, end_point.y), A3, B3, C3);
-    Ogre::Vector3 temp = end_point - start_point;
-    temp.normalise();
-    temp = temp * direction.length();
-    direction.x = temp.x;
-    direction.y = temp.y;
-    // Set the direction for the entity if it has to move.
-    if (entity->GetMoveAutoRotation() == true){
-        Ogre::Vector2 up(0.0f, -1.0f);
-        // Angle between vectors
-        Ogre::Degree angle(Ogre::Radian(SafeAcos(
-          direction.dotProduct(up), direction.length() * up.length()
-        )));
-        angle = (direction.x < 0) ? Ogre::Degree(360) - angle : angle;
-        entity->SetRotation(Ogre::Degree(angle));
-    }
-    // A scripted walk (also of the player entity, while a scene has it locked) must end, or the
-    // scene waiting for it would never go on. Several scripts place solid entities next to where
-    // another one has to walk to, so they don't block it: only the walkmesh does. A manual move
-    // of the player is never scripted.
-    // The same goes for the points around the end of the step: they are there for the player and
-    // NPCs to slide along walls, and a destination next to an edge of the walkmesh would never be
-    // reached. The end point itself is still checked.
-    const bool check_probes = !scripted_move;
-    float solid = (entity->IsSolid() == true) ? entity->GetSolidRadius() : 0.01f;
-
-    // For not playable entities, be a bit more lenient with solid collisions.
-    // Don't use the solid radius.
-    if (entity != player_entity_) solid /= 10;
-
-    // Get ending point.
-    end_point.z = start_point.z;
-    for (
-      int i = 0;
-      (entity == player_entity_ && i < 16)
-        || (entity == player_entity_ &&  i < 3)
-        || (entity != player_entity_ && i <= 16);
-      ++ i
-    ){
-        end_point = Ogre::Vector3(
-          start_point.x + direction.x, start_point.y + direction.y, start_point.z
-        );
-        // 1st check.
-        // Rotate move_vector +45.
-        q1.FromAngleAxis(Ogre::Radian(Ogre::Degree(45)), Ogre::Vector3::UNIT_Z);
-        rotation.x = direction.x;
-        rotation.y = direction.y;
-        rotation.z = 0;
-        rotation.normalise();
-        rotation = q1 * rotation;
-        // Multiply move_vector by solid range
-        rotation = rotation * solid;
-        end_point2.x = end_point.x + rotation.x;
-        end_point2.y = end_point.y + rotation.y;
-        // Check_triangle.
-        first_triangle_check = check_probes && WalkmeshBorderCross(entity, end_point2, direction);
-        entity->SetMoveTriangleId(current_triangle);
-        // Model check.
-        first_entity_check = check_probes && CheckSolidCollisions(entity, end_point2);
-
-        // 2nd check.
-        // Rotate move_vector +45.
-        q1.FromAngleAxis(Ogre::Radian(Ogre::Degree(-45)), Ogre::Vector3::UNIT_Z);
-        rotation.x = direction.x;
-        rotation.y = direction.y;
-        rotation.z = 0;
-        rotation.normalise();
-        rotation = q1 * rotation;
-        // Multiply move_vector by solid range.
-        rotation = rotation * solid;
-        end_point2.x = end_point.x + rotation.x;
-        end_point2.y = end_point.y + rotation.y;
-        // Check triangle.
-        second_triangle_check = check_probes && WalkmeshBorderCross(entity, end_point2, direction);
-        entity->SetMoveTriangleId(current_triangle);
-        // Model check.
-        second_entity_check = check_probes && CheckSolidCollisions(entity, end_point2);
-
-        // 3rd check.
-        rotation.x = direction.x;
-        rotation.y = direction.y;
-        rotation.z = 0;
-        rotation.normalise();
-        rotation = rotation * solid;
-        end_point2.x = end_point.x + rotation.x;
-        end_point2.y = end_point.y + rotation.y;
-        // Check triangle.
-        third_triangle_check = check_probes && WalkmeshBorderCross(entity, end_point2, direction);
-        entity->SetMoveTriangleId(current_triangle);
-        // Model check.
-        third_entity_check = check_probes && CheckSolidCollisions(entity, end_point2);
-
-        // Check condition and modify move_vector.
-        if (
-          first_triangle_check != false || second_triangle_check != false
-          || third_triangle_check != false || first_entity_check != false
-          || second_entity_check != false || third_entity_check != false
-        ){
-            // Only for NPC.
-            if (entity != player_entity_){
-                // If the entity collides only directly into a triangle border.
-                if (
-                  first_triangle_check  == false
-                  && second_triangle_check == false
-                  && third_triangle_check != false
-                ){
-                    q1.FromAngleAxis(Ogre::Radian(Ogre::Degree(-7)), Ogre::Vector3::UNIT_Z);
-                    rotation.x = direction.x;
-                    rotation.y = direction.y;
-                    rotation = q1 * rotation;
-                    direction.x = rotation.x;
-                    direction.y = rotation.y;
-                }
-                // Or if the entity only collides into other entity directly.
-                else if (
-                  first_entity_check == false && second_entity_check == false
-                  && third_entity_check != false
-                ){
-                    q1.FromAngleAxis(Ogre::Radian(Ogre::Degree(-11.25f)), Ogre::Vector3::UNIT_Z);
-                    rotation.x = direction.x;
-                    rotation.y = direction.y;
-                    rotation = q1 * rotation;
-                    direction.x = rotation.x;
-                    direction.y = rotation.y;
-                }
-
-                // If not both left and right check failed.
-                if (first_triangle_check == false || second_triangle_check == false){
-                    if (
-                      (first_triangle_check == false && first_entity_check != false)
-                      || (first_triangle_check != false && second_triangle_check == false)
-                    ){
-                        q1.FromAngleAxis(
-                          Ogre::Radian(Ogre::Degree(-11.25f)), Ogre::Vector3::UNIT_Z
-                        );
-                        rotation.x = direction.x;
-                        rotation.y = direction.y;
-                        rotation = q1 * rotation;
-                        direction.x = rotation.x;
-                        direction.y = rotation.y;
-                    }
-
-                    if (
-                      first_triangle_check == false
-                      && first_entity_check == false
-                      && (second_triangle_check != false || second_entity_check != false
-                      )
-                    ){
-                        q1.FromAngleAxis(Ogre::Radian(Ogre::Degree(11.25f)), Ogre::Vector3::UNIT_Z);
-                        rotation.x = direction.x;
-                        rotation.y = direction.y;
-                        rotation = q1 * rotation;
-                        direction.x = rotation.x;
-                        direction.y = rotation.y;
-                    }
-                    continue;
-                }
-                break;
-            }
-
-            // Only for playable character.
-            else{
-                if (
-                  first_entity_check  == false
-                  && second_entity_check == false
-                  && third_entity_check  == false
-                ){
-                    // If not both left and right check failed
-                    if (first_triangle_check == false || second_triangle_check == false){
-                        // With SLIP off the move is not turned along the wall: it stays blocked.
-                        if (!player_slip_) break;
-                        if (first_triangle_check != false && second_triangle_check == false){
-                            q1.FromAngleAxis(
-                              Ogre::Radian(Ogre::Degree(-11.25f)), Ogre::Vector3::UNIT_Z
-                            );
-                            rotation.x = direction.x;
-                            rotation.y = direction.y;
-                            rotation = q1 * rotation;
-                            direction.x = rotation.x;
-                            direction.y = rotation.y;
-                        }
-
-                        if (first_triangle_check == false && second_triangle_check != false){
-                            q1.FromAngleAxis(
-                              Ogre::Radian(Ogre::Degree(11.25f)), Ogre::Vector3::UNIT_Z
-                            );
-                            rotation.x = direction.x;
-                            rotation.y = direction.y;
-                            rotation = q1 * rotation;
-                            direction.x = rotation.x;
-                            direction.y = rotation.y;
-                        }
-                        continue;
-                    }
-                    break;
-                }
-            }
-        }
-    }
-
-    // Set new X, Y and Z
-    last_triangle_check = WalkmeshBorderCross(entity, end_point, direction);
-
-    if (
-      first_triangle_check != false || second_triangle_check != false
-      || third_triangle_check != false || last_triangle_check != false
-      || first_entity_check != false || second_entity_check != false
-      || third_entity_check != false
-    ){
-        // Event if the entity can't move, check for triggers, but use current position.
-        if (player_entity_ == entity) CheckTriggers(entity, entity->GetPosition());
-        return false;
-    }
-
-    // Check triggers before set entity position because move line is checked.
-    if (player_entity_ == entity) CheckTriggers(entity, end_point);
-    entity->SetPosition(end_point);
-
-    // If the entity has come to destination point, finish movement.
-    Ogre::Vector3 final = entity->GetMovePosition() - end_point;
-    const float tolerance = scripted_move ? 0.0001f : speed / 10;
-    if (Ogre::Vector2(final.x, final.y).length() <= stop_distance + tolerance)
-        entity->UnsetMove();
-
-    return true;
-}
-
-bool EntityManager::WalkmeshBorderCross(
-  Entity* entity, Ogre::Vector3& position, const Ogre::Vector2& move_vector
-){
-    if (IsBattleModule()){
-        LOG_WARNING("Tried to check for walkmesh cross, but the EntityManager is in battle mode");
-        return false;
-    }
-    int current_triangle = entity->GetMoveTriangleId();
-    if (current_triangle == -1) return true;
-    // While a scene has the player locked, the scene walks the player like any other character,
-    // and it can lead over the edge of the walkmesh.
-    const bool free_walk = !WalkmeshEdgeBlocks(
-      entity == player_entity_ && !player_lock_, entity->IsScriptedMove()
-    );
-    Ogre::Vector2 pos = Ogre::Vector2(position.x, position.y);
-    bool searched_other_triangle = false;
-    for (;;){
-        Ogre::Vector3 A3 = walkmesh_.GetA(current_triangle);
-        Ogre::Vector3 B3 = walkmesh_.GetB(current_triangle);
-        Ogre::Vector3 C3 = walkmesh_.GetC(current_triangle);
-        Ogre::Vector2 A(A3.x, A3.y);
-        Ogre::Vector2 B(B3.x, B3.y);
-        Ogre::Vector2 C(C3.x, C3.y);
-        float sign1 = SideOfVector(pos, B, A);
-        float sign2 = SideOfVector(pos, C, B);
-        float sign3 = SideOfVector(pos, A, C);
-        int next_triangle = -1;
-        if (sign1 < 0) next_triangle = walkmesh_.GetAccessSide(current_triangle, 0);
-        else if (sign2 < 0) next_triangle = walkmesh_.GetAccessSide(current_triangle, 1);
-        else if (sign3 < 0) next_triangle = walkmesh_.GetAccessSide(current_triangle, 2);
-        else{
-            position.z = PointElevation(pos, A3, B3, C3);
-            entity->SetMoveTriangleId(current_triangle);
-            return false;
-        }
-        if (next_triangle >= 0){
-            bool lock = walkmesh_.IsLocked(next_triangle);
-            if (lock == false || free_walk){
-                current_triangle = next_triangle;
-                continue;
-            }
-        }
-        // A walk of a script goes on over the edge: it keeps the last triangle, unless the point is
-        // inside another one (the triangles apart from the rest, that scenes use to put a character
-        // higher than the floor, are not joined to it: the character would keep that height after
-        // leaving it).
-        if (free_walk && !searched_other_triangle){
-            searched_other_triangle = true;
-            int other_triangle = -1;
-            float other_distance = 9999.0f;
-            for (int i = 0; i < walkmesh_.GetNumberOfTriangles(); ++ i){
-                if (i == current_triangle) continue;
-                const Ogre::Vector3 a = walkmesh_.GetA(i);
-                const Ogre::Vector3 b = walkmesh_.GetB(i);
-                const Ogre::Vector3 c = walkmesh_.GetC(i);
-                if (!Ogre::Math::pointInTri2D(
-                  pos, Ogre::Vector2(a.x, a.y), Ogre::Vector2(b.x, b.y), Ogre::Vector2(c.x, c.y)
-                )) continue;
-                const float distance = std::abs(position.z - PointElevation(pos, a, b, c));
-                if (distance < other_distance){
-                    other_distance = distance;
-                    other_triangle = i;
-                }
-            }
-            if (other_triangle >= 0){
-                current_triangle = other_triangle;
-                continue;
-            }
-        }
-        position.z = PointElevation(pos, A3, B3, C3);
-        entity->SetMoveTriangleId(current_triangle);
-        // A walk of a script goes on over the edge, keeping the last triangle.
-        return !free_walk;
-    }
-}
-
-bool EntityManager::CheckSolidCollisions(Entity* entity, Ogre::Vector3& position){
-    if (IsBattleModule()){
-        LOG_WARNING("Tried to check for solid collisions, but the EntityManager is in battle mode");
-        return false;
-    }
-    if (entity->IsSolid() == false) return false;
-    for (size_t i = 0; i < entity_.size(); ++ i){
-        if (entity_[i]->IsSolid() == false) continue;
-        if (entity_[i] == entity) continue;
-        Ogre::Vector3 pos1 = entity_[i]->GetPosition();
-        float solid_range = entity_[i]->GetSolidRadius();
-        solid_range *= solid_range;
-        float height = (pos1.z < position.z) ? entity_[i]->GetHeight() : entity->GetHeight();
-        if (
-          ((pos1.z - position.z + height) < (height * 2)) && ((pos1.z - position.z + height) >= 0)
-        ){
-            float distance
-              = (pos1.x - position.x) * (pos1.x - position.x)
-              + (pos1.y - position.y) * (pos1.y - position.y);
-            if (distance < solid_range) return true;
-        }
-    }
-    return false;
-}
-
-void EntityManager::SetNextOffsetStep(Entity* entity){
-    // TODO: Allow this while on battle mode?
-    ActionType type = entity->GetOffsetType();
-    float total = entity->GetOffsetSeconds();
-    float current = entity->GetOffsetCurrentSeconds();
-    current += Timer::getSingleton().GetGameTimeDelta();
-    current = (current > total) ? total : current;
-    Ogre::Vector3 start = entity->GetOffsetPositionStart();
-    Ogre::Vector3 end = entity->GetOffsetPositionEnd();
-    // An offset of zero seconds is done at once. Dividing would give NaN.
-    float x = (total > 0.0f) ? current / total : 1.0f;
-    if (std::isnan(x)) x = 0.0f;
-    float smooth_modifier = (type == AT_SMOOTH) ? -2 * x * x * x + 3 * x * x : x;
-    Ogre::Vector3 offset = start + (end - start) * smooth_modifier;
-    entity->SetOffset(offset);
-    if (current == total) entity->UnsetOffset();
-    else entity->SetOffsetCurrentSeconds(current);
-}
-
-void EntityManager::SetNextTurnStep(Entity* entity){
-    // TODO: Allow this while on battle mode?
-    ActionType type = entity->GetTurnType();
-    float total = entity->GetTurnSeconds();
-    float current = entity->GetTurnCurrentSeconds();
-    current += Timer::getSingleton().GetGameTimeDelta();
-    current = (current > total) ? total : current;
-    Ogre::Degree start = entity->GetTurnDirectionStart();
-    Ogre::Degree end = entity->GetTurnDirectionEnd();
-    // A turn of zero seconds is done at once. Dividing would give NaN, and a NaN rotation breaks
-    // the bounding box of the entity.
-    float x = (total > 0.0f) ? current / total : 1.0f;
-    float smooth_modifier = (type == AT_SMOOTH) ? -2 * x * x * x + 3 * x * x : x;
-    Ogre::Degree rotation = start + (end - start) * smooth_modifier;
-    entity->SetRotation(rotation);
-    if (current == total) entity->UnsetTurn();
-    else entity->SetTurnCurrentSeconds(current);
-}
-
-void EntityManager::SetNextLinearStep(Entity* entity){
-    if (IsBattleModule()){
-        LOG_WARNING("Tried to set next linear step, but the EntityManager is in battle mode");
-        return;
-    }
-    bool to_end = true;
-    bool is_move = false;
-    Ogre::Vector3 start = entity->GetLinearStart();
-    Ogre::Vector3 end = entity->GetLinearEnd();
-    Ogre::Vector3 current = entity->GetPosition();
-    float delta = Timer::getSingleton().GetGameTimeDelta();
-    // The player climbs a ladder with the directional keys. While a scene has the player locked
-    // the keys have no effect, and the scene makes the player move on its own, as with any other
-    // entity.
-    if (entity == player_entity_ && !player_lock_){
-        LinearMovement move = entity->GetLinearMovement();
-        if (move == LM_DOWN_TO_UP || move == LM_UP_TO_DOWN){
-            if (player_move_.y > 0){ // move up
-                to_end = (move == LM_DOWN_TO_UP) ? true : false;
-                is_move = true;
-            }
-            else if (player_move_.y < 0){ // move down
-                to_end = (move == LM_DOWN_TO_UP) ? false : true;
-                is_move = true;
-            }
-        }
-        else if (move == LM_LEFT_TO_RIGHT || move == LM_RIGHT_TO_LEFT){
-            if (player_move_.x > 0){ // move right
-                to_end = (move == LM_LEFT_TO_RIGHT) ? true : false;
-                is_move = true;
-            }
-            else if (player_move_.x < 0){ // move left
-                to_end = (move == LM_LEFT_TO_RIGHT) ? false : true;
-                is_move = true;
-            }
-        }
-    }
-    else is_move = true;
-    if (is_move == true && (end - start).length() < 0.0001f){
-        // Start and end are the same place, so there is nothing to walk. Dividing by the time to
-        // cross the line (zero) would give a NaN position. Just finish the move.
-        entity->UnsetLinear();
-        if (to_end == true) entity->SetMoveTriangleId(entity->GetLinearDestTriangle());
-        SetEntityOnWalkmesh(entity);
-        entity->SetPosition(to_end ? end : start);
-    }
-    else if (is_move == true){
-        Ogre::Vector3 position;
-        if (to_end == true){
-            Ogre::Vector3 end_start = end - start;
-            // Move across the whole line by this number of seconds.
-            float time = end_start.length() / 1.2f;
-            position.x = current.x + (end_start.x / time) * delta;
-            position.y = current.y + (end_start.y / time) * delta;
-            position.z = current.z + (end_start.z / time) * delta;
-            position.x = (end_start.x < 0)
-              ? std::max(position.x, end.x) : std::min(position.x, end.x);
-            position.y = (end_start.y < 0)
-              ? std::max(position.y, end.y) : std::min(position.y, end.y);
-            position.z = (end_start.z < 0)
-              ? std::max(position.z, end.z) : std::min(position.z, end.z);
-            // Compared with a tolerance: if the entity starts a bit off the end in one of the
-            // axes (the entry points are written with a few digits only), that axis could move
-            // less than the precision of a float per frame and never be exactly equal.
-            if ((position - end).length() < 0.0001f){
-                position = end;
-                entity->UnsetLinear();
-                entity->SetMoveTriangleId(entity->GetLinearDestTriangle());
-                SetEntityOnWalkmesh(entity);
-            }
-        }
-        else{
-            Ogre::Vector3 end_start = start - end;
-            // Move across the whole line by this number of seconds.
-            float time = end_start.length() / 1.2f;
-            position.x = current.x + (end_start.x / time) * delta;
-            position.y = current.y + (end_start.y / time) * delta;
-            position.z = current.z + (end_start.z / time) * delta;
-            position.x = (end_start.x < 0)
-              ? std::max(position.x, start.x) : std::min(position.x, start.x);
-            position.y = (end_start.y < 0)
-              ? std::max(position.y, start.y) : std::min(position.y, start.y);
-            position.z = (end_start.z < 0)
-              ? std::max(position.z, start.z) : std::min(position.z, start.z);
-            if ((position - start).length() < 0.0001f){
-                position = start;
-                entity->UnsetLinear();
-                SetEntityOnWalkmesh(entity);
-            }
-        }
-        entity->SetPosition(position);
-        entity->UpdateAnimation((to_end == true) ? delta : -delta);
-    }
-}
-
-void EntityManager::SetNextJumpStep(Entity* entity){
-    if (IsBattleModule()){
-        LOG_WARNING("Tried to set next jump step, but the EntityManager is in battle mode");
-        return;
-    }
-    float total = entity->GetJumpSeconds();
-    float current = entity->GetJumpCurrentSeconds();
-    current += Timer::getSingleton().GetGameTimeDelta();
-    // A jump of zero seconds lands at once, without dividing by zero.
-    if (total <= 0.0f) total = 0.0001f;
-    current = (current > total) ? total : current;
-    Ogre::Vector3 start_position = entity->GetJumpStart();
-    Ogre::Vector3 end_position   = entity->GetJumpEnd();
-    Ogre::Vector3 position;
-    position.x = start_position.x + ((end_position.x - start_position.x) / total) * current;
-    position.y = start_position.y + ((end_position.y - start_position.y) / total) * current;
-    position.z = current * current * -1.0f + current
-      * ((end_position.z - start_position.z) / total + total * 1.0f) + start_position.z;
-    entity->SetPosition(position);
-    if (total == current){
-        entity->UnsetJump();
-        entity->SetMoveTriangleId(entity->GetJumpDestTriangle());
-        SetEntityOnWalkmesh(entity);
-        // The scripts set the animation of the jump as the default one (DFANM) and don't set it
-        // back, but the player stands normally after landing in the original game (the scene of
-        // mds6_2 where Cloud jumps down, for example). The scripts that do set it, do it after
-        // the jump, so they aren't affected.
-        if (entity == player_entity_){
-            entity->ScriptSetDefaultAnimation("Idle");
-            entity->PlayAnimationContinue("Idle");
-        }
-    }
-    else entity->SetJumpCurrentSeconds(current);
-}
-
-void EntityManager::SetNextScrollStep(){
-    // TODO: Allow this on battle mode?
-    background_2d_.UpdateScrollTarget();
-    Background2D::SCROLL_TYPE type = background_2d_.GetScrollType();
-    float total = background_2d_.GetScrollSeconds();
-    float current = background_2d_.GetScrollCurrentSeconds();
-    current += Timer::getSingleton().GetGameTimeDelta();
-    current = (current > total) ? total : current;
-    Ogre::Vector2 start = background_2d_.GetScrollPositionStart();
-    Ogre::Vector2 end = background_2d_.GetScrollPositionEnd();
-    float x = (total > 0.0f) ? current / total : 1.0f;
-    float smooth_modifier = (type == Background2D::SMOOTH) ? -2 * x * x * x + 3 * x * x : x;
-    Ogre::Vector2 scroll = start + (end - start) * smooth_modifier;
-    background_2d_.SetScroll(scroll);
-    if (current == total) background_2d_.UnsetScroll();
-    else background_2d_.SetScrollCurrentSeconds(current);
-}

+ 24 - 42
src/engine/entity/EntityManagerPlayer.cpp

@@ -45,25 +45,7 @@ void EntityManager::Input(const VGears::Event& event){
         }
         if (event.type == VGears::ET_KEY_PRESS && event.event == "CONFIRM"){
             CheckEntityInteract();
-            for (unsigned int i = 0; i < entity_triggers_.size(); ++ i){
-                if (
-                  entity_triggers_[i]->IsEnabled() == true
-                  && entity_triggers_[i]->CheckApproached() == true
-                ){
-                    ScriptEntity* scr_entity = ScriptManager::getSingleton().GetScriptEntityByName(
-                      ScriptManager::ENTITY, entity_triggers_[i]->GetName()
-                    );
-                    bool added = ScriptManager::getSingleton().ScriptRequest(
-                      scr_entity, "on_interact", INTERACT_SCRIPT_PRIORITY, "", "", false, false
-                    );
-                    if (added == false){
-                        LOG_WARNING(
-                          "Script 'on_interact' for entity '" + entity_triggers_[i]->GetName()
-                          + "' doesn't exist."
-                        );
-                    }
-                }
-            }
+            triggers_.InteractWithLines(entity_triggers_);
         }
     }
 }
@@ -87,7 +69,7 @@ void EntityManager::ScriptSetPlayerEntity(const char* name){
                     entity_[i]->SetRotation(player_entity_->GetRotation());
                 }
             }
-            if (entity_[i]->GetMoveTriangleId() == -1) SetEntityOnWalkmesh(entity_[i]);
+            if (entity_[i]->GetMoveTriangleId() == -1) movement_.PlaceOnWalkmesh(entity_[i]);
             LOG_TRIVIAL("Player entity set to '" + std::string(name) + "'.");
             // The camera that follows the player keeps following it when another entity takes over
             // (Cloud and the dressed Cloud, for example); a camera that follows some other entity
@@ -109,31 +91,31 @@ void EntityManager::ScriptSetPlayerEntity(const char* name){
 }
 
 void EntityManager::ScriptPlacePlayerAtFieldEntry(
-    const float x, const float y, const int triangle_id, const float direction
+  const float x, const float y, const int triangle_id, const float direction
 ){
-        if (player_entity_ == nullptr || walkmesh_.GetNumberOfTriangles() <= 0) return;
+    if (player_entity_ == nullptr || walkmesh_.GetNumberOfTriangles() <= 0) return;
 
-        int safe_triangle_id = triangle_id;
-        if (safe_triangle_id < 0 || safe_triangle_id >= walkmesh_.GetNumberOfTriangles()){
-                LOG_WARNING("World-map field entry has an invalid walkmesh triangle; using triangle 0.");
-                safe_triangle_id = 0;
-        }
+    int safe_triangle_id = triangle_id;
+    if (safe_triangle_id < 0 || safe_triangle_id >= walkmesh_.GetNumberOfTriangles()){
+        LOG_WARNING("World-map field entry has an invalid walkmesh triangle; using triangle 0.");
+        safe_triangle_id = 0;
+    }
 
-        player_entity_->SetPosition(Ogre::Vector3(
-            x, y, walkmesh_.GetA(static_cast<unsigned int>(safe_triangle_id)).z
-        ));
-        player_entity_->SetRotation(Ogre::Degree(direction));
-        player_entity_->SetMoveTriangleId(safe_triangle_id);
-        // In the WALKMESH state the entity walks to its move position: without this one it walks to
-        // whatever it had (the origin of the field), and the player enters the town walking.
-        player_entity_->SetMovePosition(player_entity_->GetPosition());
-        player_entity_->SetState(Entity::WALKMESH);
-        // The player starts standing still: no move or run from the world map, and the held keys
-        // don't count until they are released.
-        player_move_ = Ogre::Vector3::ZERO;
-        player_run_ = false;
-        ignore_held_walk_ = true;
-        player_entity_->PlayAnimationContinue(player_entity_->GetDefaultAnimationName());
+    player_entity_->SetPosition(Ogre::Vector3(
+      x, y, walkmesh_.GetA(static_cast<unsigned int>(safe_triangle_id)).z
+    ));
+    player_entity_->SetRotation(Ogre::Degree(direction));
+    player_entity_->SetMoveTriangleId(safe_triangle_id);
+    // In the WALKMESH state the entity walks to its move position: without this one it walks to
+    // whatever it had (the origin of the field), and the player enters the town walking.
+    player_entity_->SetMovePosition(player_entity_->GetPosition());
+    player_entity_->SetState(Entity::WALKMESH);
+    // The player starts standing still: no move or run from the world map, and the held keys
+    // don't count until they are released.
+    player_move_ = Ogre::Vector3::ZERO;
+    player_run_ = false;
+    ignore_held_walk_ = true;
+    player_entity_->PlayAnimationContinue(player_entity_->GetDefaultAnimationName());
 }
 
 Entity* EntityManager::ScriptGetPlayerEntity() const{

+ 138 - 145
src/engine/entity/EntityManagerTriggers.cpp → src/engine/entity/EntityTriggers.cpp

@@ -15,13 +15,15 @@
 
 #include <cmath>
 #include <limits>
-#include "engine/entity/EntityManager.h"
 #include "common/Logger.h"
+#include "engine/entity/Entity.h"
+#include "engine/entity/EntityTrigger.h"
+#include "engine/entity/EntityTriggers.h"
 #include "engine/script/ScriptManager.h"
 
-const int EntityManager::INTERACT_SCRIPT_PRIORITY = 4;
+const int EntityTriggers::INTERACT_SCRIPT_PRIORITY = 4;
 
-float EntityManager::SquareDistanceToLine(
+float EntityTriggers::SquareDistanceToLine(
   const Ogre::Vector3& point, const Ogre::Vector3& point_a, const Ogre::Vector3& point_b,
   Ogre::Vector3& proj
 ){
@@ -47,10 +49,9 @@ float EntityManager::SquareDistanceToLine(
     return -1;
 }
 
-Ogre::Degree EntityManager::GetDirectionToPoint(
+Ogre::Degree EntityTriggers::GetDirectionToPoint(
   const Ogre::Vector3& current_point, const Ogre::Vector3& direction_point
 ){
-    // TODO: Declare function in header file.
     Ogre::Vector2 up(0.0f, -1.0f);
     Ogre::Vector2 dir(direction_point.x - current_point.x, direction_point.y - current_point.y);
     // Angle between vectors
@@ -58,28 +59,13 @@ Ogre::Degree EntityManager::GetDirectionToPoint(
     return (dir.x < 0) ? Ogre::Degree(360) - angle : angle;
 }
 
-void EntityManager::AddEntityTrigger(
-  const Ogre::String& name,
-  const Ogre::Vector3& point1, const Ogre::Vector3& point2, const bool enabled
-){
-    if (IsBattleModule()){
-        LOG_WARNING("Tried to add an entity trigger but the EntityManager is in battle mode.");
-        return;
-    }
-    EntityTrigger* trigger = new EntityTrigger(name);
-    trigger->SetPoints(point1, point2);
-    trigger->SetEnabled(enabled);
-    entity_triggers_.push_back(trigger);
-    ScriptManager::getSingleton().AddEntity(ScriptManager::ENTITY, trigger->GetName(), nullptr);
-}
-
-float EntityManager::TriggerReach(float solid_radius){
+float EntityTriggers::Reach(float solid_radius){
     // The radius an entity has when a script doesn't change it.
     const float default_radius = 0.21f;
     return solid_radius < 0.01f ? default_radius : solid_radius;
 }
 
-bool EntityManager::IsBetterInteractionTarget(
+bool EntityTriggers::IsBetterInteractionTarget(
   float angle, float distance, float best_angle, float best_distance
 ){
     const float same_angle = 0.001f;
@@ -87,15 +73,11 @@ bool EntityManager::IsBetterInteractionTarget(
     return std::fabs(angle - best_angle) <= same_angle && distance < best_distance;
 }
 
-void EntityManager::CheckTriggers(Entity* entity, const Ogre::Vector3& position){
-    if (IsBattleModule()){
-        LOG_WARNING("Tried to check for triggers, but the EntityManager is in battle mode");
-        return;
-    }
-    if (entity->IsSolid() == false) return;
-    if (player_entity_ != entity) return;
-    if (player_entity_->IsSolid() == false) return;
-    if (player_lock_) return;
+void EntityTriggers::ClearContacts(){contacts_.clear();}
+
+void EntityTriggers::CheckLines(
+  Entity* entity, const Ogre::Vector3& position, const std::vector<EntityTrigger*>& lines
+){
     bool is_moving = true;
     if (
       std::fabs(entity->GetPosition().x - position.x) < 0.005f
@@ -105,20 +87,20 @@ void EntityManager::CheckTriggers(Entity* entity, const Ogre::Vector3& position)
         is_moving = false;
     }
 
-    for (unsigned int i = 0; i < entity_triggers_.size(); ++ i){
+    for (unsigned int i = 0; i < lines.size(); ++ i){
         ScriptEntity* trigger = ScriptManager::getSingleton().GetScriptEntityByName(
-          ScriptManager::ENTITY, entity_triggers_[i]->GetName()
+          ScriptManager::ENTITY, lines[i]->GetName()
         );
 
-        if (trigger != nullptr && entity_triggers_[i]->IsEnabled() == true){
-            Ogre::Vector3 point_a = entity_triggers_[i]->GetPoint1();
-            Ogre::Vector3 point_b = entity_triggers_[i]->GetPoint2();
+        if (trigger != nullptr && lines[i]->IsEnabled() == true){
+            Ogre::Vector3 point_a = lines[i]->GetPoint1();
+            Ogre::Vector3 point_b = lines[i]->GetPoint2();
             Ogre::Vector3 entity_position = entity->GetPosition();
             Ogre::Vector3 proj;
 
             // Calculate distance
             float square_dist = SquareDistanceToLine(entity_position, point_a, point_b, proj);
-            float solid_radius = TriggerReach(entity->GetSolidRadius());
+            float solid_radius = Reach(entity->GetSolidRadius());
 
             // Calculate direction.
             const Ogre::Degree direction_to_line = GetDirectionToPoint(entity_position, proj);
@@ -134,12 +116,12 @@ void EntityManager::CheckTriggers(Entity* entity, const Ogre::Vector3& position)
             if (
               square_dist != -1 && square_dist <= solid_radius * solid_radius
               && angle < Ogre::Degree(180) && angle > Ogre::Degree(0)
-              && entity_triggers_[i]->CheckApproached() == false
+              && lines[i]->CheckApproached() == false
               && is_moving
             ){
-                entity_triggers_[i]->SetApproached(true);
+                lines[i]->SetApproached(true);
                 //std::cout << "    [TRIGGER] " << entity->GetName() << " on_approach "
-                //  << entity_triggers_[i]->GetName() << std::endl;
+                //  << lines[i]->GetName() << std::endl;
                 ScriptManager::getSingleton().ScriptRequest(
                   trigger, "on_approach", 1, entity->GetName(), "", false, false
                 );
@@ -150,12 +132,12 @@ void EntityManager::CheckTriggers(Entity* entity, const Ogre::Vector3& position)
             // previously entered the line.
             if (
               square_dist != -1 && square_dist < 1
-              && entity_triggers_[i]->CheckCrossed() == false
-              && entity_triggers_[i]->CheckApproached() == true
+              && lines[i]->CheckCrossed() == false
+              && lines[i]->CheckApproached() == true
             ){
-                entity_triggers_[i]->SetCrossed(true);
+                lines[i]->SetCrossed(true);
                 //std::cout << "    [TRIGGER] " << entity->GetName() << " on_cross "
-                //  << entity_triggers_[i]->GetName() << std::endl;
+                //  << lines[i]->GetName() << std::endl;
                 ScriptManager::getSingleton().ScriptRequest(
                   trigger, "on_cross", 1, entity->GetName(), "", false, false
                 );
@@ -166,33 +148,33 @@ void EntityManager::CheckTriggers(Entity* entity, const Ogre::Vector3& position)
             // the entity has previously entered the line.
             if (
               square_dist != -1 && square_dist <= solid_radius * solid_radius
-              && entity_triggers_[i]->CheckApproached() == true
+              && lines[i]->CheckApproached() == true
             ){
                 // TODO: Fix this hack.
                 // After the on_near script is run, set a cooltime of 5 frames before running
                 // it again. This is because most of the time this trigger checks for a key, and
                 // if its pressed, is run multiple times.
-                if (entity_triggers_[i]->GetNearEventCooldown() == 0){
+                if (lines[i]->GetNearEventCooldown() == 0){
                     //std::cout << "    [TRIGGER] " << entity->GetName()
-                    //  << " on_near " << entity_triggers_[i]->GetName() << std::endl;
+                    //  << " on_near " << lines[i]->GetName() << std::endl;
                     ScriptManager::getSingleton().ScriptRequest(
                       trigger, "on_near", 1, entity->GetName(), "", true, true
                     );
-                    entity_triggers_[i]->ResetNearEventCooldown();
+                    lines[i]->ResetNearEventCooldown();
                 }
-                else entity_triggers_[i]->DecreaseNearEventCooldown();
+                else lines[i]->DecreaseNearEventCooldown();
             }
 
             // Check on cross line once.
             // The same as on cross line, but only once.
             if (
               square_dist != -1 && square_dist < solid_radius * solid_radius
-              && entity_triggers_[i]->CheckNearSingleEventTriggered() == false
-              && entity_triggers_[i]->CheckApproached() == true
+              && lines[i]->CheckNearSingleEventTriggered() == false
+              && lines[i]->CheckApproached() == true
             ){
-                entity_triggers_[i]->SetNearSingleEventTriggered(true);
+                lines[i]->SetNearSingleEventTriggered(true);
                 //std::cout << "    [TRIGGER] " << entity->GetName()
-                //  << " on_near_once " << entity_triggers_[i]->GetName() << std::endl;
+                //  << " on_near_once " << lines[i]->GetName() << std::endl;
                 ScriptManager::getSingleton().ScriptRequest(
                   trigger, "on_near_once", 1, entity->GetName(), "", false, false
                 );
@@ -204,10 +186,10 @@ void EntityManager::CheckTriggers(Entity* entity, const Ogre::Vector3& position)
             // on enter script has been triggered previously.
             if (
               square_dist != -1 && square_dist > solid_radius * solid_radius
-              && entity_triggers_[i]->CheckApproached()
+              && lines[i]->CheckApproached()
             ){
                 //std::cout << "    [TRIGGER] " << entity->GetName() << " on_leave "
-                //  << entity_triggers_[i]->GetName() << std::endl;
+                //  << lines[i]->GetName() << std::endl;
                 ScriptManager::getSingleton().ScriptRequest(
                   trigger, "on_leave", 1, entity->GetName(), "", false, false
                 );
@@ -215,52 +197,41 @@ void EntityManager::CheckTriggers(Entity* entity, const Ogre::Vector3& position)
 
             // If the entity is far enough from the line, mark every trigger as inactive
             if (square_dist == -1 || square_dist > solid_radius * solid_radius){
-                entity_triggers_[i]->Clear();
+                lines[i]->Clear();
                 //std::cout << "    [TRIGGER] " << entity->GetName() << " clear of "
-                //  << entity_triggers_[i]->GetName() << std::endl;
+                //  << lines[i]->GetName() << std::endl;
             }
 
         }
     }
 }
 
-void EntityManager::ScriptSetLine(
-  const char* name, const float x1, const float y1, const float z1, const float x2, const float y2,
-  const float z2
+void EntityTriggers::CheckContacts(
+  Entity* player, const bool player_locked, const std::vector<Entity*>& entities
 ){
-    for (EntityTrigger* trigger : entity_triggers_){
-        if (trigger->GetName() == name){
-            trigger->SetPoints(Ogre::Vector3(x1, y1, z1), Ogre::Vector3(x2, y2, z2));
-            return;
-        }
-    }
-}
-
-void EntityManager::CheckEntityContacts(){
-    if (IsBattleModule() || !IsFieldModule()) return;
-    if (player_entity_ == nullptr || player_lock_ || !player_entity_->IsSolid()){
-        entities_in_contact_.clear();
+    if (player == nullptr || player_locked || !player->IsSolid()){
+        contacts_.clear();
         return;
     }
-    const Ogre::Vector3 player_position = player_entity_->GetPosition();
-    for (Entity* entity : entity_){
-        if (entity == player_entity_ || entity->IsLine() || !entity->IsSolid()) continue;
+    const Ogre::Vector3 player_position = player->GetPosition();
+    for (Entity* entity : entities){
+        if (entity == player || entity->IsLine() || !entity->IsSolid()) continue;
         const Ogre::Vector3 position = entity->GetPosition();
         const float height = (position.z < player_position.z)
-          ? entity->GetHeight() : player_entity_->GetHeight();
+          ? entity->GetHeight() : player->GetHeight();
         const float distance_z = position.z - player_position.z + height;
         bool touching = false;
         if (distance_z < height * 2 && distance_z >= 0){
-            const float reach = player_entity_->GetSolidRadius() + entity->GetSolidRadius() + 0.05f;
+            const float reach = player->GetSolidRadius() + entity->GetSolidRadius() + 0.05f;
             const float dx = position.x - player_position.x;
             const float dy = position.y - player_position.y;
             touching = dx * dx + dy * dy < reach * reach;
         }
         if (!touching){
-            entities_in_contact_.erase(entity);
+            contacts_.erase(entity);
             continue;
         }
-        if (!entities_in_contact_.insert(entity).second) continue;
+        if (!contacts_.insert(entity).second) continue;
         ScriptEntity* script_entity = ScriptManager::getSingleton().GetScriptEntityByName(
           ScriptManager::ENTITY, entity->GetName()
         );
@@ -273,72 +244,12 @@ void EntityManager::CheckEntityContacts(){
     }
 }
 
-void EntityManager::CheckEntityInteract(){
-    if (IsBattleModule()){
-        LOG_WARNING(
-          "Tried to check for entity interaction, but the EntityManager is in battle mode"
-        );
-        return;
-    }
-    if (player_entity_ == NULL || player_lock_ == true || player_entity_->IsSolid() == false)
-        return;
-    Ogre::Degree angle_pc = player_entity_->GetRotation();
-    Entity* entity_to_interact = NULL;
-    Ogre::Degree less_angle(90);
-    float best_distance = std::numeric_limits<float>::max();
-    Ogre::Real nearest_worldmap_distance = -1.0f;
-    for (unsigned int i = 0; i < entity_.size(); ++ i){
-        if (entity_[i]->IsTalkable() == false) continue;
-        if (entity_[i] == player_entity_) continue;
-        Ogre::Vector3 pos1 =  entity_[i]->GetPosition();
-        float interact_range =  entity_[i]->GetTalkRadius();
-        Ogre::Vector3 pos2 = player_entity_->GetPosition();
-        float solid_range = player_entity_->GetSolidRadius();
-                if (IsWorldModule()){
-                        const Ogre::Real target_bottom = pos1.y;
-                        const Ogre::Real player_bottom = pos2.y;
-                                                const Ogre::Real talk_range
-                                                    = interact_range + solid_range + 0.05f;
-                        const Ogre::Real distance
-                            = (pos1.x - pos2.x) * (pos1.x - pos2.x)
-                                + (pos1.z - pos2.z) * (pos1.z - pos2.z);
-                        const bool height_overlap
-                            = player_bottom <= target_bottom + entity_[i]->GetHeight()
-                                && player_bottom + player_entity_->GetHeight() >= target_bottom;
-                        if (
-                                height_overlap && distance <= talk_range * talk_range
-                                && (nearest_worldmap_distance < 0 || distance < nearest_worldmap_distance)
-                        ){
-                                entity_to_interact = entity_[i];
-                                nearest_worldmap_distance = distance;
-                        }
-                        continue;
-                }
-        int height = (pos1.z < pos2.z) ? entity_[i]->GetHeight() : player_entity_->GetHeight();
-        if (((pos1.z - pos2.z + height) < (height * 2)) && ((pos1.z - pos2.z + height) >= 0)){
-            interact_range = (interact_range + solid_range) * (interact_range + solid_range);
-            float distance
-              = (pos1.x - pos2.x) * (pos1.x - pos2.x) + (pos1.y - pos2.y) * (pos1.y - pos2.y);
-            if (distance < interact_range + solid_range){
-                Ogre::Degree angle_to_model = GetDirectionToPoint(pos2, pos1);
-                Ogre::Degree angle = angle_pc - angle_to_model;
-                angle = (angle < Ogre::Degree(0)) ? -angle : angle;
-                angle = (angle >= Ogre::Degree(180)) ? Ogre::Degree(360) - angle : angle;
-                // With several entities in range, interact with the one the player faces most.
-                // Nobody 90 degrees or more away from where the player faces is considered.
-                if (
-                  angle < Ogre::Degree(90) && IsBetterInteractionTarget(
-                    angle.valueDegrees(), distance, less_angle.valueDegrees(), best_distance
-                  )
-                ){
-                    less_angle = angle;
-                    best_distance = distance;
-                    entity_to_interact = entity_[i];
-                }
-            }
-        }
-    }
-    if (entity_to_interact != NULL && entity_to_interact->IsLine() == false){
+void EntityTriggers::Interact(
+  Entity* player, const std::vector<Entity*>& entities, const bool world_map
+){
+    Entity* entity_to_interact = world_map
+      ? FindWorldMapTarget(player, entities) : FindFieldTarget(player, entities);
+    if (entity_to_interact != nullptr && entity_to_interact->IsLine() == false){
         Ogre::String name = entity_to_interact->GetName();
         ScriptEntity* scr_entity = ScriptManager::getSingleton().GetScriptEntityByName(
           ScriptManager::ENTITY, name
@@ -351,3 +262,85 @@ void EntityManager::CheckEntityInteract(){
         }
     }
 }
+
+void EntityTriggers::InteractWithLines(const std::vector<EntityTrigger*>& lines){
+    for (EntityTrigger* line : lines){
+        if (line->IsEnabled() == true && line->CheckApproached() == true){
+            ScriptEntity* script_entity = ScriptManager::getSingleton().GetScriptEntityByName(
+              ScriptManager::ENTITY, line->GetName()
+            );
+            const bool added = ScriptManager::getSingleton().ScriptRequest(
+              script_entity, "on_interact", INTERACT_SCRIPT_PRIORITY, "", "", false, false
+            );
+            if (added == false){
+                LOG_WARNING(
+                  "Script 'on_interact' for entity '" + line->GetName() + "' doesn't exist."
+                );
+            }
+        }
+    }
+}
+
+Entity* EntityTriggers::FindWorldMapTarget(Entity* player, const std::vector<Entity*>& entities){
+    Entity* target = nullptr;
+    Ogre::Real nearest_distance = -1.0f;
+    const Ogre::Vector3 player_position = player->GetPosition();
+    for (Entity* entity : entities){
+        if (entity->IsTalkable() == false || entity == player) continue;
+        const Ogre::Vector3 position = entity->GetPosition();
+        const Ogre::Real talk_range = entity->GetTalkRadius() + player->GetSolidRadius() + 0.05f;
+        // The world map has the height in the Y axis.
+        const Ogre::Real distance
+          = (position.x - player_position.x) * (position.x - player_position.x)
+          + (position.z - player_position.z) * (position.z - player_position.z);
+        const bool height_overlap
+          = player_position.y <= position.y + entity->GetHeight()
+          && player_position.y + player->GetHeight() >= position.y;
+        if (
+          height_overlap && distance <= talk_range * talk_range
+          && (nearest_distance < 0 || distance < nearest_distance)
+        ){
+            target = entity;
+            nearest_distance = distance;
+        }
+    }
+    return target;
+}
+
+Entity* EntityTriggers::FindFieldTarget(Entity* player, const std::vector<Entity*>& entities){
+    Entity* target = nullptr;
+    Ogre::Degree less_angle(90);
+    float best_distance = std::numeric_limits<float>::max();
+    const Ogre::Degree player_angle = player->GetRotation();
+    const Ogre::Vector3 player_position = player->GetPosition();
+    const float solid_range = player->GetSolidRadius();
+    for (Entity* entity : entities){
+        if (entity->IsTalkable() == false || entity == player) continue;
+        const Ogre::Vector3 position = entity->GetPosition();
+        const int height = (position.z < player_position.z)
+          ? entity->GetHeight() : player->GetHeight();
+        const float distance_z = position.z - player_position.z + height;
+        if (!((distance_z < (height * 2)) && (distance_z >= 0))) continue;
+        float interact_range = entity->GetTalkRadius();
+        interact_range = (interact_range + solid_range) * (interact_range + solid_range);
+        const float distance
+          = (position.x - player_position.x) * (position.x - player_position.x)
+          + (position.y - player_position.y) * (position.y - player_position.y);
+        if (!(distance < interact_range + solid_range)) continue;
+        Ogre::Degree angle = player_angle - GetDirectionToPoint(player_position, position);
+        angle = (angle < Ogre::Degree(0)) ? -angle : angle;
+        angle = (angle >= Ogre::Degree(180)) ? Ogre::Degree(360) - angle : angle;
+        // With several entities in range, interact with the one the player faces most. Nobody 90
+        // degrees or more away from where the player faces is considered.
+        if (
+          angle < Ogre::Degree(90) && IsBetterInteractionTarget(
+            angle.valueDegrees(), distance, less_angle.valueDegrees(), best_distance
+          )
+        ){
+            less_angle = angle;
+            best_distance = distance;
+            target = entity;
+        }
+    }
+    return target;
+}

+ 179 - 0
src/engine/entity/EntityTriggers.h

@@ -0,0 +1,179 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#pragma once
+
+#include <set>
+#include <vector>
+#include <Ogre.h>
+
+class Entity;
+class EntityTrigger;
+
+/**
+ * Runs the scripts that the player starts by being somewhere: crossing lines, touching entities,
+ * and pressing the OK button in front of them.
+ */
+class EntityTriggers{
+
+    public:
+
+        /**
+         * Retrieves how close to a line an entity has to be to trigger it.
+         *
+         * It's the solid radius of the entity, unless a script has made it too small, as scripts
+         * do while a scene is playing. Lines couldn't be triggered at all then.
+         *
+         * @param[in] solid_radius Solid radius of the entity.
+         * @return The distance to the line from which it triggers.
+         */
+        static float Reach(float solid_radius);
+
+        /**
+         * Decides whether an entity is a better target to interact with than the best one so far.
+         *
+         * The one the player faces more directly wins. If the angles are the same, the nearest
+         * one does.
+         *
+         * @param[in] angle Angle in degrees between where the player faces and the candidate.
+         * @param[in] distance Squared distance to the candidate.
+         * @param[in] best_angle Angle of the best candidate so far, or the largest one allowed.
+         * @param[in] best_distance Squared distance to the best candidate so far.
+         * @return True if the candidate is better.
+         */
+        static bool IsBetterInteractionTarget(
+          float angle, float distance, float best_angle, float best_distance
+        );
+
+        /**
+         * Forgets which entities the player is touching.
+         */
+        void ClearContacts();
+
+        /**
+         * Runs the scripts of the lines that the player is close to.
+         *
+         * If there are lines, and the conditions are met, the appropriate trigger function is added
+         * to the queue. This must be tested every time the player moves.
+         *
+         * @param[in] player The player entity. It must be solid and not locked.
+         * @param[in] position The position the player is moving to.
+         * @param[in] lines The lines of the map.
+         */
+        void CheckLines(
+          Entity* player, const Ogre::Vector3& position, const std::vector<EntityTrigger*>& lines
+        );
+
+        /**
+         * Runs the contact script (script 2) of the entities that the player touches.
+         *
+         * The script of an entity that the original game runs when the player collides with it
+         * (the old man of condor1 starts his conversation that way, and only after it can be
+         * talked to). It runs once for each touch.
+         *
+         * @param[in] player The player entity, or nullptr if there is none.
+         * @param[in] player_locked True if the player can't be controlled.
+         * @param[in] entities The entities of the field.
+         */
+        void CheckContacts(
+          Entity* player, const bool player_locked, const std::vector<Entity*>& entities
+        );
+
+        /**
+         * Runs the on_interact script of the entity in front of the player.
+         *
+         * It looks for the entities that can be interacted with from the player's position and
+         * orientation, and selects the most appropriate one.
+         *
+         * @param[in] player The player entity. It must be solid and not locked.
+         * @param[in] entities The entities of the map.
+         * @param[in] world_map True in the world map, where the height is in the Y axis and the
+         * direction the player faces doesn't count.
+         */
+        void Interact(Entity* player, const std::vector<Entity*>& entities, const bool world_map);
+
+        /**
+         * Runs the on_interact script of the lines that the player is next to.
+         *
+         * @param[in] lines The lines of the map.
+         */
+        void InteractWithLines(const std::vector<EntityTrigger*>& lines);
+
+    private:
+
+        /**
+         * Priority of the script that runs when the player presses OK in front of an entity.
+         *
+         * It has to run before the scripts that fields leave running on an entity (the loops that
+         * play an animation, requested with priority 5 or 6), or the entity could not be talked to.
+         * But it can't be the highest: a script of the same entity that is requested with a higher
+         * priority (3 or smaller) has to be able to run while the talk script waits for it, as in
+         * the scenes where a talk script asks its own entity to do something and waits for it to
+         * start.
+         */
+        static const int INTERACT_SCRIPT_PRIORITY;
+
+        /**
+         * Calculates the square distance between a point and a line.
+         *
+         * The calculated distance is the vector orthogonal to the line that passes by the point,
+         * i.e. the shortest distance.
+         *
+         * @param[in] point The point.
+         * @param[in] point_a First point of the line.
+         * @param[in] point_b Second point of the line.
+         * @param[out] proj Vector representing the shortest distance.
+         * @return The distance from the point to the line.
+         */
+        static float SquareDistanceToLine(
+          const Ogre::Vector3& point, const Ogre::Vector3& point_a, const Ogre::Vector3& point_b,
+          Ogre::Vector3& proj
+        );
+
+        /**
+         * Calculates the direction degree between to points.
+         *
+         * @param[in] current_point Origin point.
+         * @param[in] direction_point Next point in the direction.
+         * @return Degrees between the two points
+         */
+        static Ogre::Degree GetDirectionToPoint(
+          const Ogre::Vector3& current_point, const Ogre::Vector3& direction_point
+        );
+
+        /**
+         * Finds the entity of the world map that the player can talk to.
+         *
+         * @param[in] player The player entity.
+         * @param[in] entities The entities of the map.
+         * @return The nearest talkable entity in range, or nullptr if there is none.
+         */
+        static Entity* FindWorldMapTarget(Entity* player, const std::vector<Entity*>& entities);
+
+        /**
+         * Finds the entity of a field that the player can talk to.
+         *
+         * @param[in] player The player entity.
+         * @param[in] entities The entities of the field.
+         * @return The talkable entity in range that the player faces most, or nullptr if there is
+         * none.
+         */
+        static Entity* FindFieldTarget(Entity* player, const std::vector<Entity*>& entities);
+
+        /**
+         * Entities that the player is touching.
+         */
+        std::set<const Entity*> contacts_;
+};

+ 47 - 44
src/engine/entity/EntityManagerEncounters.cpp → src/engine/entity/FieldEncounters.cpp

@@ -14,11 +14,12 @@
  */
 
 #include <cstdlib>
-#include "engine/config/ConfigVar.h"
-#include "engine/entity/EntityManager.h"
 #include "common/Logger.h"
-#include "engine/script/ScriptManager.h"
 #include "engine/Timer.h"
+#include "engine/config/ConfigVar.h"
+#include "engine/entity/Entity.h"
+#include "engine/entity/FieldEncounters.h"
+#include "engine/script/ScriptManager.h"
 
 ConfigVar cv_encounter_multiplier(
   "encounter_multiplier", "Multiplier of the random encounter rate (0 disables them)", "1"
@@ -39,38 +40,38 @@ static const float ENCOUNTER_CHECK_FRAMES = 8.0f;
  */
 static const float ENCOUNTER_STEP_VALUE = 5.0f;
 
-float EntityManager::GetEncounterMultiplier() const{return cv_encounter_multiplier.GetF();}
+float FieldEncounters::GetMultiplier(){return cv_encounter_multiplier.GetF();}
 
-bool EntityManager::IsDebugEncounters() const{return cv_debug_encounters.GetB();}
+bool FieldEncounters::IsDebug(){return cv_debug_encounters.GetB();}
 
-void EntityManager::SetRandomEncounters(bool active){random_encounters_ = active;}
+void FieldEncounters::SetActive(bool active){active_ = active;}
 
-void EntityManager::ClearEncounterTables(){
-    encounter_tables_.clear();
-    encounter_table_ = 1;
-    encounter_distance_ = 0.0f;
-    encounter_last_position_valid_ = false;
-    encounter_accumulator_ = 0;
-    encounter_last_battle_ = -1;
+void FieldEncounters::Clear(){
+    tables_.clear();
+    table_ = 1;
+    distance_ = 0.0f;
+    last_position_valid_ = false;
+    accumulator_ = 0;
+    last_battle_ = -1;
 }
 
-void EntityManager::AddEncounterTable(
+void FieldEncounters::AddTable(
   const int id, const int rate, const std::vector<std::pair<int, int>>& battles,
   const std::vector<std::pair<int, int>>& specials
 ){
-    EncounterTable table;
+    Table table;
     table.rate = rate;
     table.battles = battles;
     table.specials = specials;
-    encounter_tables_[id] = table;
+    tables_[id] = table;
 }
 
-void EntityManager::ScriptSetEncounterTable(const int id){encounter_table_ = id;}
+void FieldEncounters::SetTable(const int id){table_ = id;}
 
-int EntityManager::ScriptRollEncounterBattle() const{
-    auto found = encounter_tables_.find(encounter_table_);
-    if (found == encounter_tables_.end()) return -1;
-    const EncounterTable& table = found->second;
+int FieldEncounters::RollBattle() const{
+    auto found = tables_.find(table_);
+    if (found == tables_.end()) return -1;
+    const Table& table = found->second;
     // Like the original game: a roll out of 64 is checked against the special battles one after
     // the other (each one adds its probability). If none is hit, a new roll chooses a standard
     // battle, the last one being the default.
@@ -90,21 +91,21 @@ int EntityManager::ScriptRollEncounterBattle() const{
     return table.battles.back().first;
 }
 
-void EntityManager::UpdateEncounters(const bool walked){
-    if (player_entity_ == nullptr){
-        encounter_last_position_valid_ = false;
+void FieldEncounters::Update(const Entity* player, const bool player_locked, const bool walked){
+    if (player == nullptr){
+        last_position_valid_ = false;
         return;
     }
-    const Ogre::Vector3 position = player_entity_->GetPosition();
+    const Ogre::Vector3 position = player->GetPosition();
     const float distance
-      = encounter_last_position_valid_ ? (position - encounter_last_position_).length() : 0.0f;
-    encounter_last_position_ = position;
-    encounter_last_position_valid_ = true;
+      = last_position_valid_ ? (position - last_position_).length() : 0.0f;
+    last_position_ = position;
+    last_position_valid_ = true;
     // Only walking counts: not scripted movements, and not jumps to another place.
-    if (!walked || player_lock_ || distance > 2.0f) return;
-    if (!random_encounters_ || encounter_tables_.empty()) return;
-    auto found = encounter_tables_.find(encounter_table_);
-    if (found == encounter_tables_.end()) return;
+    if (!walked || player_locked || distance > 2.0f) return;
+    if (!active_ || tables_.empty()) return;
+    auto found = tables_.find(table_);
+    if (found == tables_.end()) return;
     const float multiplier = cv_encounter_multiplier.GetF();
     if (multiplier <= 0.0f) return;
     // Same as the original game. Every few frames of walking the accumulator grows by a value
@@ -112,29 +113,31 @@ void EntityManager::UpdateEncounters(const bool walked){
     // starts if a random number is lower than the accumulator.
     const int rate = found->second.rate;
     if (rate <= 0) return;
-    encounter_distance_ += Timer::getSingleton().GetGameTimeDelta() * 30.0f;
-    while (encounter_distance_ >= ENCOUNTER_CHECK_FRAMES){
-        encounter_distance_ -= ENCOUNTER_CHECK_FRAMES;
-        // Enemy Away and Enemy Lure materia change the rate of the party (see Party.get_encounter_modifier).
+    distance_ += Timer::getSingleton().GetGameTimeDelta() * 30.0f;
+    while (distance_ >= ENCOUNTER_CHECK_FRAMES){
+        distance_ -= ENCOUNTER_CHECK_FRAMES;
+        // Enemy Away and Enemy Lure materia change the rate of the party (see
+        // Party.get_encounter_modifier).
         const float materia_multiplier
           = ScriptManager::getSingleton().EvaluateNumber("Party.get_encounter_modifier()", 1.0f);
-        encounter_accumulator_ += static_cast<int>(ENCOUNTER_STEP_VALUE * multiplier * materia_multiplier * 256.0f) / rate;
+        accumulator_
+          += static_cast<int>(ENCOUNTER_STEP_VALUE * multiplier * materia_multiplier * 256.0f) / rate;
         const int roll = std::rand() % 256 * 256;
         if (cv_debug_encounters.GetB()){
             LOG_TRIVIAL(
               "Encounter check: rate " + std::to_string(rate) + ", accumulator "
-              + std::to_string(encounter_accumulator_ / 256.0f) + "/256, roll "
+              + std::to_string(accumulator_ / 256.0f) + "/256, roll "
               + std::to_string(roll / 256)
             );
         }
-        if (roll >= encounter_accumulator_) continue;
-        int battle = ScriptRollEncounterBattle();
+        if (roll >= accumulator_) continue;
+        int battle = RollBattle();
         // The same battle is not repeated: it's rolled again once.
-        if (battle == encounter_last_battle_) battle = ScriptRollEncounterBattle();
+        if (battle == last_battle_) battle = RollBattle();
         if (battle < 0) return;
-        encounter_distance_ = 0.0f;
-        encounter_accumulator_ = 0;
-        encounter_last_battle_ = battle;
+        distance_ = 0.0f;
+        accumulator_ = 0;
+        last_battle_ = battle;
         LOG_TRIVIAL("Random encounter: battle " + std::to_string(battle));
         // The battle is started by a script, as it has to change the module of every manager.
         ScriptManager::getSingleton().RunString("Encounter.start(" + std::to_string(battle) + ")");

+ 159 - 0
src/engine/entity/FieldEncounters.h

@@ -0,0 +1,159 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#pragma once
+
+#include <map>
+#include <utility>
+#include <vector>
+#include <OgreVector3.h>
+
+class Entity;
+
+/**
+ * The random battles of a field: its encounter tables, and the count of the steps of the player
+ * that starts them.
+ */
+class FieldEncounters{
+
+    public:
+
+        /**
+         * Gets the multiplier of the random encounter rate (the encounter_multiplier cvar).
+         *
+         * @return The multiplier. 0 prevents random encounters.
+         */
+        static float GetMultiplier();
+
+        /**
+         * Checks if the random encounter checks are logged (the debug_encounters cvar).
+         *
+         * @return True if they are logged.
+         */
+        static bool IsDebug();
+
+        /**
+         * Enables or disables random encounters in the field.
+         *
+         * @param[in] active True to enable encounters, false to deactivate them.
+         */
+        void SetActive(bool active);
+
+        /**
+         * Removes the random encounter tables of the field, and forgets the walked distance.
+         */
+        void Clear();
+
+        /**
+         * Adds a random encounter table to the field.
+         *
+         * @param[in] id Table ID (1 or 2).
+         * @param[in] rate Encounter rate, as in the original game (24 is very low, 240 is high).
+         * @param[in] battles Standard encounters, pairs of battle ID and probability (out of 64).
+         * @param[in] specials Special encounters, with the same format.
+         */
+        void AddTable(
+          const int id, const int rate, const std::vector<std::pair<int, int>>& battles,
+          const std::vector<std::pair<int, int>>& specials
+        );
+
+        /**
+         * Selects the encounter table to use.
+         *
+         * @param[in] id Table ID (1 or 2). If it doesn't exist, no encounters happen.
+         */
+        void SetTable(const int id);
+
+        /**
+         * Picks the battle of a random encounter from the current encounter table.
+         *
+         * @return The battle ID, -1 if the field has no encounters.
+         */
+        int RollBattle() const;
+
+        /**
+         * Counts the steps of the player and starts random encounters.
+         *
+         * It has to be called once per frame.
+         *
+         * @param[in] player The player entity, or nullptr if there is none.
+         * @param[in] player_locked True if the player can't be controlled.
+         * @param[in] walked True if the player was moved by the player's input in this frame.
+         */
+        void Update(const Entity* player, const bool player_locked, const bool walked);
+
+    private:
+
+        /**
+         * Random encounter table of a field.
+         */
+        struct Table{
+
+            /**
+             * Encounter rate, as in the original game.
+             */
+            int rate;
+
+            /**
+             * Standard encounters: battle ID and probability (out of 64).
+             */
+            std::vector<std::pair<int, int>> battles;
+
+            /**
+             * Special encounters: battle ID and probability (out of 64).
+             */
+            std::vector<std::pair<int, int>> specials;
+        };
+
+        /**
+         * Indicates if random encounters happen in the map.
+         */
+        bool active_ = false;
+
+        /**
+         * Random encounter tables of the field, by ID.
+         */
+        std::map<int, Table> tables_;
+
+        /**
+         * ID of the encounter table in use.
+         */
+        int table_ = 1;
+
+        /**
+         * Frames walked by the player since the last encounter check.
+         */
+        float distance_ = 0.0f;
+
+        /**
+         * Position of the player in the last frame, to know how much it has walked.
+         */
+        Ogre::Vector3 last_position_ = Ogre::Vector3::ZERO;
+
+        /**
+         * Indicates if {@see last_position_} is valid.
+         */
+        bool last_position_valid_ = false;
+
+        /**
+         * Accumulated chance of a random encounter, out of 256 * 256. It grows while walking.
+         */
+        int accumulator_ = 0;
+
+        /**
+         * Last random battle, which is not repeated twice in a row. -1 if none.
+         */
+        int last_battle_ = -1;
+};

+ 580 - 0
src/engine/entity/WalkmeshMovement.cpp

@@ -0,0 +1,580 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <algorithm>
+#include <cmath>
+#include <OgreMath.h>
+#include "common/Logger.h"
+#include "engine/Manager.h"
+#include "engine/Timer.h"
+#include "engine/entity/Entity.h"
+#include "engine/entity/Walkmesh.h"
+#include "engine/entity/WalkmeshMovement.h"
+
+WalkmeshMovement::WalkmeshMovement(
+  const Manager& manager, const Walkmesh& walkmesh, const std::vector<Entity*>& entities,
+  Entity* const& player, const bool& player_locked, const bool& player_slip,
+  const Ogre::Vector3& player_move, const LineCheck& check_lines
+):
+  manager_(manager),
+  walkmesh_(walkmesh),
+  entities_(entities),
+  player_(player),
+  player_locked_(player_locked),
+  player_slip_(player_slip),
+  player_move_(player_move),
+  check_lines_(check_lines)
+{}
+
+float WalkmeshMovement::GetTriangleHeight(int triangle, float x, float y, float fallback) const{
+    if (manager_.IsBattleModule() || triangle < 0 || triangle >= walkmesh_.GetNumberOfTriangles())
+        return fallback;
+    const float height = PointElevation(
+      Ogre::Vector2(x, y), walkmesh_.GetA(triangle), walkmesh_.GetB(triangle),
+      walkmesh_.GetC(triangle)
+    );
+    return std::isfinite(height) ? height : fallback;
+}
+
+float WalkmeshMovement::PointElevation(
+  const Ogre::Vector2& point, const Ogre::Vector3& a, const Ogre::Vector3& b, const Ogre::Vector3& c
+){
+    float _a = a.z * (b.y - c.y) + b.z * (c.y - a.y) + c.z * (a.y - b.y);
+    float _b = a.y * (b.x - c.x) + b.y * (c.x - a.x) + c.y * (a.x - b.x);
+    float _c = a.x * (b.z - c.z) + b.x * (c.z - a.z) + c.x * (a.z - b.z);
+    float _d
+      = a.x * (b.z * c.y - c.z * b.y) + b.x * (c.z * a.y - a.z * c.y)
+        + c.x * (a.z * b.y - b.z * a.y);
+    return (_d - _c * point.y - _a * point.x) / _b;
+}
+
+float WalkmeshMovement::SideOfVector(
+  const Ogre::Vector2& point, const Ogre::Vector2& p1, const Ogre::Vector2& p2
+){
+    Ogre::Vector2 AB = p2    - p1;
+    Ogre::Vector2 AP = point - p1;
+    return AB.x * AP.y - AB.y * AP.x;
+}
+
+bool WalkmeshMovement::IsInCurrentTriangle(const Entity& entity) const{
+    const int triangle = entity.GetMoveTriangleId();
+    if (triangle < 0 || triangle >= walkmesh_.GetNumberOfTriangles()) return false;
+    const Ogre::Vector3 position = entity.GetPosition();
+    const Ogre::Vector3 a = walkmesh_.GetA(triangle);
+    const Ogre::Vector3 b = walkmesh_.GetB(triangle);
+    const Ogre::Vector3 c = walkmesh_.GetC(triangle);
+    return Ogre::Math::pointInTri2D(
+      Ogre::Vector2(position.x, position.y), Ogre::Vector2(a.x, a.y),
+      Ogre::Vector2(b.x, b.y), Ogre::Vector2(c.x, c.y)
+    );
+}
+
+bool WalkmeshMovement::PlaceOnWalkmesh(Entity* entity){
+    if (manager_.IsBattleModule()){
+        LOG_WARNING("Tried to set entity on the walkmesh, but the EntityManager is in battle mode");
+        return false;
+    }
+    Ogre::Vector3 position3 = entity->GetPosition();
+    Ogre::Vector2 position2;
+    position2.x = position3.x;
+    position2.y = position3.y;
+    std::vector<std::pair<int, float>> triangles;
+    // Search for possible triangles.
+    for (int i = 0; i < walkmesh_.GetNumberOfTriangles(); ++ i){
+        Ogre::Vector3 A3 = walkmesh_.GetA(i);
+        Ogre::Vector3 B3 = walkmesh_.GetB(i);
+        Ogre::Vector3 C3 = walkmesh_.GetC(i);
+        Ogre::Vector2 A2(A3.x, A3.y);
+        Ogre::Vector2 B2(B3.x, B3.y);
+        Ogre::Vector2 C2(C3.x, C3.y);
+        if (Ogre::Math::pointInTri2D(position2, A2, B2, C2) == true){
+            triangles.push_back(std::make_pair(i, PointElevation(
+              position2, walkmesh_.GetA(i), walkmesh_.GetB(i), walkmesh_.GetC(i)
+            )));
+        }
+    }
+    // If the coordinates doesn't match any triangle, exit.
+    if (triangles.size() == 0 && entity == player_){
+        LOG_ERROR(
+          "Can't find any triangle to place entity '" + entity->GetName() + "' on walkmesh."
+        );
+        return false;
+    }
+    // From the possible triangles, select the closest one (on the Z edge).
+    int closest_z_triangle = -1;
+    float closest_z_distance = 9999.0f;
+    float pos_z = position3.z;
+    for (size_t i = 0; i < triangles.size(); ++ i){
+        if (std::abs(pos_z - triangles[i].second) < closest_z_distance){
+            closest_z_triangle = triangles[i].first;
+            closest_z_distance = std::abs(pos_z - triangles[i].second);
+        }
+    }
+    if (closest_z_triangle == -1 && entity == player_){
+        LOG_ERROR(
+          "Can't find nearby triangle to place entity '" + entity->GetName() + "' on walkmesh."
+        );
+        return false;
+    }
+    entity->SetPosition(Ogre::Vector3(position2.x, position2.y, pos_z));
+    entity->SetMoveTriangleId(closest_z_triangle);
+    return true;
+}
+
+bool WalkmeshMovement::EdgeBlocks(bool is_player, bool scripted_move){
+    return is_player || !scripted_move;
+}
+
+float WalkmeshMovement::ScriptedStep(float distance, float stop_distance, float max_step){
+    return std::min(max_step, std::max(0.0f, distance - stop_distance));
+}
+
+bool WalkmeshMovement::Obstacles::Any() const{
+    return left_wall || right_wall || ahead_wall || left_entity || right_entity || ahead_entity;
+}
+
+bool WalkmeshMovement::Walk(Entity* entity, const float speed, const float delta_time){
+    if (manager_.IsBattleModule()){
+        LOG_WARNING("Tried to perform a walkmesh move, but the EntityManager is in battle mode");
+        return false;
+    }
+    const Ogre::Vector3 start_point = entity->GetPosition();
+    const Ogre::Vector3 move_vector = entity->GetMovePosition() - start_point;
+    Ogre::Vector2 direction(move_vector.x, move_vector.y);
+    const float distance_to_target = direction.length();
+    const bool scripted_move = entity->IsScriptedMove();
+    const float stop_distance = entity->GetMoveStopDistance();
+    if (scripted_move && distance_to_target <= stop_distance + 0.0001f){
+        entity->UnsetMove();
+        return false;
+    }
+    // The step of this frame.
+    direction.normalise();
+    direction *= delta_time;
+    direction *= speed;
+    if (scripted_move && !direction.isZeroLength()){
+        direction.normalise();
+        direction *= ScriptedStep(distance_to_target, stop_distance, speed * delta_time);
+    }
+    // If movement is still needed but speed or time don't allow it, just return for now.
+    if (direction.isZeroLength() == true){
+        if (player_ == entity) check_lines_(entity, entity->GetPosition());
+        return false;
+    }
+    const int triangle = entity->GetMoveTriangleId();
+    if (triangle == -1){
+        // A character that is not on the walkmesh (Jenova of shpin_3, that is placed outside it
+        // and moves with FMOVE) is walked in a straight line, or the scene that waits for it would
+        // never go on.
+        if (scripted_move && entity != player_) return WalkOffWalkmesh(entity, direction);
+        // The entities that a scene places later (the soldiers of the parade of junonr4) are asked
+        // to move before it, and wait. Only the player has to be on the walkmesh.
+        if (entity == player_)
+            LOG_ERROR("Entity '" + entity->GetName() + "' not placed on walkmesh and can't move.");
+        return false;
+    }
+    FollowSlope(triangle, start_point, direction);
+    // Set the direction for the entity if it has to move.
+    if (entity->GetMoveAutoRotation() == true) FaceDirection(entity, direction);
+
+    Obstacles obstacles;
+    Ogre::Vector3 end_point = FindWay(entity, triangle, direction, obstacles);
+    // This also stores in the entity the triangle of the end point, even if it can't move there.
+    const bool off_walkmesh = CrossBorder(entity, end_point);
+    if (obstacles.Any() || off_walkmesh){
+        // Event if the entity can't move, check for triggers, but use current position.
+        if (player_ == entity) check_lines_(entity, entity->GetPosition());
+        return false;
+    }
+
+    // Check triggers before set entity position because move line is checked.
+    if (player_ == entity) check_lines_(entity, end_point);
+    entity->SetPosition(end_point);
+
+    // If the entity has come to destination point, finish movement.
+    const Ogre::Vector3 remaining = entity->GetMovePosition() - end_point;
+    const float tolerance = scripted_move ? 0.0001f : speed / 10;
+    if (Ogre::Vector2(remaining.x, remaining.y).length() <= stop_distance + tolerance)
+        entity->UnsetMove();
+    return true;
+}
+
+bool WalkmeshMovement::WalkOffWalkmesh(Entity* entity, const Ogre::Vector2& direction){
+    const Ogre::Vector3 start_point = entity->GetPosition();
+    const Ogre::Vector3 move_vector = entity->GetMovePosition() - start_point;
+    const float distance_to_target = Ogre::Vector2(move_vector.x, move_vector.y).length();
+    const float step = std::min(direction.length(), distance_to_target);
+    Ogre::Vector2 move = direction;
+    if (!move.isZeroLength()) move.normalise();
+    move *= step;
+    entity->SetPosition(
+      Ogre::Vector3(start_point.x + move.x, start_point.y + move.y, start_point.z)
+    );
+    if (distance_to_target - step <= entity->GetMoveStopDistance() + 0.0001f) entity->UnsetMove();
+    return step > 0.0f;
+}
+
+void WalkmeshMovement::FollowSlope(
+  const int triangle, const Ogre::Vector3& start_point, Ogre::Vector2& direction
+) const{
+    Ogre::Vector3 end_point(start_point.x + direction.x, start_point.y + direction.y, 0.0f);
+    end_point.z = PointElevation(
+      Ogre::Vector2(end_point.x, end_point.y), walkmesh_.GetA(triangle),
+      walkmesh_.GetB(triangle), walkmesh_.GetC(triangle)
+    );
+    Ogre::Vector3 slope_step = end_point - start_point;
+    slope_step.normalise();
+    slope_step = slope_step * direction.length();
+    direction.x = slope_step.x;
+    direction.y = slope_step.y;
+}
+
+void WalkmeshMovement::FaceDirection(Entity* entity, const Ogre::Vector2& direction){
+    const Ogre::Vector2 up(0.0f, -1.0f);
+    // Angle between vectors
+    Ogre::Degree angle(Ogre::Radian(SafeAcos(
+      direction.dotProduct(up), direction.length() * up.length()
+    )));
+    angle = (direction.x < 0) ? Ogre::Degree(360) - angle : angle;
+    entity->SetRotation(Ogre::Degree(angle));
+}
+
+Ogre::Vector3 WalkmeshMovement::FindWay(
+  Entity* entity, const int triangle, Ogre::Vector2 direction, Obstacles& obstacles
+){
+    const Ogre::Vector3 start_point = entity->GetPosition();
+    const bool is_player = entity == player_;
+    // A scripted walk (also of the player entity, while a scene has it locked) must end, or the
+    // scene waiting for it would never go on. Several scripts place solid entities next to where
+    // another one has to walk to, so they don't block it: only the walkmesh does. A manual move
+    // of the player is never scripted.
+    // The same goes for the points around the end of the step: they are there for the player and
+    // NPCs to slide along walls, and a destination next to an edge of the walkmesh would never be
+    // reached. The end point itself is still checked by the caller.
+    const bool check_probes = !entity->IsScriptedMove();
+    float radius = (entity->IsSolid() == true) ? entity->GetSolidRadius() : 0.01f;
+    // For not playable entities, be a bit more lenient with solid collisions.
+    // Don't use the solid radius.
+    if (!is_player) radius /= 10;
+
+    const int attempts = is_player ? 16 : 17;
+    Ogre::Vector3 end_point;
+    for (int i = 0; i < attempts; ++ i){
+        end_point = Ogre::Vector3(
+          start_point.x + direction.x, start_point.y + direction.y, start_point.z
+        );
+        if (!check_probes) break;
+        obstacles = ProbeAround(entity, triangle, end_point, direction, radius);
+        if (!obstacles.Any() || !Steer(is_player, player_slip_, obstacles, direction)) break;
+    }
+    return end_point;
+}
+
+WalkmeshMovement::Obstacles WalkmeshMovement::ProbeAround(
+  Entity* entity, const int triangle, const Ogre::Vector3& end_point,
+  const Ogre::Vector2& direction, const float radius
+){
+    Ogre::Vector3 ahead(direction.x, direction.y, 0.0f);
+    ahead.normalise();
+    Ogre::Quaternion turn;
+    turn.FromAngleAxis(Ogre::Radian(Ogre::Degree(45)), Ogre::Vector3::UNIT_Z);
+    const Ogre::Vector3 left = turn * ahead;
+    turn.FromAngleAxis(Ogre::Radian(Ogre::Degree(-45)), Ogre::Vector3::UNIT_Z);
+    const Ogre::Vector3 right = turn * ahead;
+
+    Obstacles found;
+    // Checks the point at the solid radius from the end of the step, in a direction.
+    const auto probe = [&](const Ogre::Vector3& towards, bool& wall, bool& other_entity){
+        const Ogre::Vector3 offset = towards * radius;
+        Ogre::Vector3 point(end_point.x + offset.x, end_point.y + offset.y, 0.0f);
+        // It sets the height of the point, needed to check the entities.
+        wall = CrossBorder(entity, point);
+        entity->SetMoveTriangleId(triangle);
+        other_entity = CheckSolidCollisions(entity, point);
+    };
+    probe(left, found.left_wall, found.left_entity);
+    probe(right, found.right_wall, found.right_entity);
+    probe(ahead, found.ahead_wall, found.ahead_entity);
+    return found;
+}
+
+bool WalkmeshMovement::Steer(
+  const bool is_player, const bool slip, const Obstacles& obstacles, Ogre::Vector2& direction
+){
+    const bool sides_blocked = obstacles.left_wall && obstacles.right_wall;
+    if (is_player){
+        // The player only slides along walls, never around other entities.
+        if (obstacles.left_entity || obstacles.right_entity || obstacles.ahead_entity)
+            return false;
+        // With SLIP off the move is not turned along the wall: it stays blocked.
+        if (sides_blocked || !slip) return false;
+        if (obstacles.left_wall) Turn(direction, -11.25f);
+        else if (obstacles.right_wall) Turn(direction, 11.25f);
+        return true;
+    }
+    // If the entity collides only directly into a triangle border.
+    if (!obstacles.left_wall && !obstacles.right_wall && obstacles.ahead_wall)
+        Turn(direction, -7.0f);
+    // Or if the entity only collides into other entity directly.
+    else if (!obstacles.left_entity && !obstacles.right_entity && obstacles.ahead_entity)
+        Turn(direction, -11.25f);
+    if (sides_blocked) return false;
+    if (
+      (!obstacles.left_wall && obstacles.left_entity)
+      || (obstacles.left_wall && !obstacles.right_wall)
+    ) Turn(direction, -11.25f);
+    if (
+      !obstacles.left_wall && !obstacles.left_entity
+      && (obstacles.right_wall || obstacles.right_entity)
+    ) Turn(direction, 11.25f);
+    return true;
+}
+
+void WalkmeshMovement::Turn(Ogre::Vector2& direction, const float degrees){
+    Ogre::Quaternion turn;
+    turn.FromAngleAxis(Ogre::Radian(Ogre::Degree(degrees)), Ogre::Vector3::UNIT_Z);
+    const Ogre::Vector3 turned = turn * Ogre::Vector3(direction.x, direction.y, 0.0f);
+    direction.x = turned.x;
+    direction.y = turned.y;
+}
+
+bool WalkmeshMovement::CrossBorder(Entity* entity, Ogre::Vector3& position){
+    if (manager_.IsBattleModule()){
+        LOG_WARNING("Tried to check for walkmesh cross, but the EntityManager is in battle mode");
+        return false;
+    }
+    int current_triangle = entity->GetMoveTriangleId();
+    if (current_triangle == -1) return true;
+    // While a scene has the player locked, the scene walks the player like any other character,
+    // and it can lead over the edge of the walkmesh.
+    const bool free_walk = !EdgeBlocks(
+      entity == player_ && !player_locked_, entity->IsScriptedMove()
+    );
+    Ogre::Vector2 pos = Ogre::Vector2(position.x, position.y);
+    bool searched_other_triangle = false;
+    for (;;){
+        Ogre::Vector3 A3 = walkmesh_.GetA(current_triangle);
+        Ogre::Vector3 B3 = walkmesh_.GetB(current_triangle);
+        Ogre::Vector3 C3 = walkmesh_.GetC(current_triangle);
+        Ogre::Vector2 A(A3.x, A3.y);
+        Ogre::Vector2 B(B3.x, B3.y);
+        Ogre::Vector2 C(C3.x, C3.y);
+        float sign1 = SideOfVector(pos, B, A);
+        float sign2 = SideOfVector(pos, C, B);
+        float sign3 = SideOfVector(pos, A, C);
+        int next_triangle = -1;
+        if (sign1 < 0) next_triangle = walkmesh_.GetAccessSide(current_triangle, 0);
+        else if (sign2 < 0) next_triangle = walkmesh_.GetAccessSide(current_triangle, 1);
+        else if (sign3 < 0) next_triangle = walkmesh_.GetAccessSide(current_triangle, 2);
+        else{
+            position.z = PointElevation(pos, A3, B3, C3);
+            entity->SetMoveTriangleId(current_triangle);
+            return false;
+        }
+        if (next_triangle >= 0){
+            bool lock = walkmesh_.IsLocked(next_triangle);
+            if (lock == false || free_walk){
+                current_triangle = next_triangle;
+                continue;
+            }
+        }
+        // A walk of a script goes on over the edge: it keeps the last triangle, unless the point is
+        // inside another one (the triangles apart from the rest, that scenes use to put a character
+        // higher than the floor, are not joined to it: the character would keep that height after
+        // leaving it).
+        if (free_walk && !searched_other_triangle){
+            searched_other_triangle = true;
+            int other_triangle = -1;
+            float other_distance = 9999.0f;
+            for (int i = 0; i < walkmesh_.GetNumberOfTriangles(); ++ i){
+                if (i == current_triangle) continue;
+                const Ogre::Vector3 a = walkmesh_.GetA(i);
+                const Ogre::Vector3 b = walkmesh_.GetB(i);
+                const Ogre::Vector3 c = walkmesh_.GetC(i);
+                if (!Ogre::Math::pointInTri2D(
+                  pos, Ogre::Vector2(a.x, a.y), Ogre::Vector2(b.x, b.y), Ogre::Vector2(c.x, c.y)
+                )) continue;
+                const float distance = std::abs(position.z - PointElevation(pos, a, b, c));
+                if (distance < other_distance){
+                    other_distance = distance;
+                    other_triangle = i;
+                }
+            }
+            if (other_triangle >= 0){
+                current_triangle = other_triangle;
+                continue;
+            }
+        }
+        position.z = PointElevation(pos, A3, B3, C3);
+        entity->SetMoveTriangleId(current_triangle);
+        // A walk of a script goes on over the edge, keeping the last triangle.
+        return !free_walk;
+    }
+}
+
+bool WalkmeshMovement::CheckSolidCollisions(Entity* entity, Ogre::Vector3& position){
+    if (manager_.IsBattleModule()){
+        LOG_WARNING("Tried to check for solid collisions, but the EntityManager is in battle mode");
+        return false;
+    }
+    if (entity->IsSolid() == false) return false;
+    for (size_t i = 0; i < entities_.size(); ++ i){
+        if (entities_[i]->IsSolid() == false) continue;
+        if (entities_[i] == entity) continue;
+        Ogre::Vector3 pos1 = entities_[i]->GetPosition();
+        float solid_range = entities_[i]->GetSolidRadius();
+        solid_range *= solid_range;
+        float height = (pos1.z < position.z) ? entities_[i]->GetHeight() : entity->GetHeight();
+        if (
+          ((pos1.z - position.z + height) < (height * 2)) && ((pos1.z - position.z + height) >= 0)
+        ){
+            float distance
+              = (pos1.x - position.x) * (pos1.x - position.x)
+              + (pos1.y - position.y) * (pos1.y - position.y);
+            if (distance < solid_range) return true;
+        }
+    }
+    return false;
+}
+
+void WalkmeshMovement::LinearStep(Entity* entity){
+    if (manager_.IsBattleModule()){
+        LOG_WARNING("Tried to set next linear step, but the EntityManager is in battle mode");
+        return;
+    }
+    bool to_end = true;
+    bool is_move = false;
+    Ogre::Vector3 start = entity->GetLinearStart();
+    Ogre::Vector3 end = entity->GetLinearEnd();
+    Ogre::Vector3 current = entity->GetPosition();
+    float delta = Timer::getSingleton().GetGameTimeDelta();
+    // The player climbs a ladder with the directional keys. While a scene has the player locked
+    // the keys have no effect, and the scene makes the player move on its own, as with any other
+    // entity.
+    if (entity == player_ && !player_locked_){
+        LinearMovement move = entity->GetLinearMovement();
+        if (move == LM_DOWN_TO_UP || move == LM_UP_TO_DOWN){
+            if (player_move_.y > 0){ // move up
+                to_end = (move == LM_DOWN_TO_UP) ? true : false;
+                is_move = true;
+            }
+            else if (player_move_.y < 0){ // move down
+                to_end = (move == LM_DOWN_TO_UP) ? false : true;
+                is_move = true;
+            }
+        }
+        else if (move == LM_LEFT_TO_RIGHT || move == LM_RIGHT_TO_LEFT){
+            if (player_move_.x > 0){ // move right
+                to_end = (move == LM_LEFT_TO_RIGHT) ? true : false;
+                is_move = true;
+            }
+            else if (player_move_.x < 0){ // move left
+                to_end = (move == LM_LEFT_TO_RIGHT) ? false : true;
+                is_move = true;
+            }
+        }
+    }
+    else is_move = true;
+    if (is_move == true && (end - start).length() < 0.0001f){
+        // Start and end are the same place, so there is nothing to walk. Dividing by the time to
+        // cross the line (zero) would give a NaN position. Just finish the move.
+        entity->UnsetLinear();
+        if (to_end == true) entity->SetMoveTriangleId(entity->GetLinearDestTriangle());
+        PlaceOnWalkmesh(entity);
+        entity->SetPosition(to_end ? end : start);
+    }
+    else if (is_move == true){
+        Ogre::Vector3 position;
+        if (to_end == true){
+            Ogre::Vector3 end_start = end - start;
+            // Move across the whole line by this number of seconds.
+            float time = end_start.length() / 1.2f;
+            position.x = current.x + (end_start.x / time) * delta;
+            position.y = current.y + (end_start.y / time) * delta;
+            position.z = current.z + (end_start.z / time) * delta;
+            position.x = (end_start.x < 0)
+              ? std::max(position.x, end.x) : std::min(position.x, end.x);
+            position.y = (end_start.y < 0)
+              ? std::max(position.y, end.y) : std::min(position.y, end.y);
+            position.z = (end_start.z < 0)
+              ? std::max(position.z, end.z) : std::min(position.z, end.z);
+            // Compared with a tolerance: if the entity starts a bit off the end in one of the
+            // axes (the entry points are written with a few digits only), that axis could move
+            // less than the precision of a float per frame and never be exactly equal.
+            if ((position - end).length() < 0.0001f){
+                position = end;
+                entity->UnsetLinear();
+                entity->SetMoveTriangleId(entity->GetLinearDestTriangle());
+                PlaceOnWalkmesh(entity);
+            }
+        }
+        else{
+            Ogre::Vector3 end_start = start - end;
+            // Move across the whole line by this number of seconds.
+            float time = end_start.length() / 1.2f;
+            position.x = current.x + (end_start.x / time) * delta;
+            position.y = current.y + (end_start.y / time) * delta;
+            position.z = current.z + (end_start.z / time) * delta;
+            position.x = (end_start.x < 0)
+              ? std::max(position.x, start.x) : std::min(position.x, start.x);
+            position.y = (end_start.y < 0)
+              ? std::max(position.y, start.y) : std::min(position.y, start.y);
+            position.z = (end_start.z < 0)
+              ? std::max(position.z, start.z) : std::min(position.z, start.z);
+            if ((position - start).length() < 0.0001f){
+                position = start;
+                entity->UnsetLinear();
+                PlaceOnWalkmesh(entity);
+            }
+        }
+        entity->SetPosition(position);
+        entity->UpdateAnimation((to_end == true) ? delta : -delta);
+    }
+}
+
+void WalkmeshMovement::JumpStep(Entity* entity){
+    if (manager_.IsBattleModule()){
+        LOG_WARNING("Tried to set next jump step, but the EntityManager is in battle mode");
+        return;
+    }
+    float total = entity->GetJumpSeconds();
+    float current = entity->GetJumpCurrentSeconds();
+    current += Timer::getSingleton().GetGameTimeDelta();
+    // A jump of zero seconds lands at once, without dividing by zero.
+    if (total <= 0.0f) total = 0.0001f;
+    current = (current > total) ? total : current;
+    Ogre::Vector3 start_position = entity->GetJumpStart();
+    Ogre::Vector3 end_position   = entity->GetJumpEnd();
+    Ogre::Vector3 position;
+    position.x = start_position.x + ((end_position.x - start_position.x) / total) * current;
+    position.y = start_position.y + ((end_position.y - start_position.y) / total) * current;
+    position.z = current * current * -1.0f + current
+      * ((end_position.z - start_position.z) / total + total * 1.0f) + start_position.z;
+    entity->SetPosition(position);
+    if (total == current){
+        entity->UnsetJump();
+        entity->SetMoveTriangleId(entity->GetJumpDestTriangle());
+        PlaceOnWalkmesh(entity);
+        // The scripts set the animation of the jump as the default one (DFANM) and don't set it
+        // back, but the player stands normally after landing in the original game (the scene of
+        // mds6_2 where Cloud jumps down, for example). The scripts that do set it, do it after
+        // the jump, so they aren't affected.
+        if (entity == player_){
+            entity->ScriptSetDefaultAnimation("Idle");
+            entity->PlayAnimationContinue("Idle");
+        }
+    }
+    else entity->SetJumpCurrentSeconds(current);
+}

+ 332 - 0
src/engine/entity/WalkmeshMovement.h

@@ -0,0 +1,332 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#pragma once
+
+#include <functional>
+#include <vector>
+#include <Ogre.h>
+
+class Entity;
+class Manager;
+class Walkmesh;
+
+/**
+ * Moves the entities of a field on its walkmesh: walking, climbing ladders and jumping.
+ */
+class WalkmeshMovement{
+
+    public:
+
+        /**
+         * Function called when the player moves, with the position it moves to, to check the lines.
+         */
+        typedef std::function<void(Entity*, const Ogre::Vector3&)> LineCheck;
+
+        /**
+         * Constructor.
+         *
+         * The references are kept, and have to be valid while the object is used.
+         *
+         * @param[in] manager The manager of the entities, to know if a battle is taking place.
+         * @param[in] walkmesh The walkmesh of the field.
+         * @param[in] entities The entities of the field.
+         * @param[in] player The player entity, nullptr if there is none.
+         * @param[in] player_locked True if the player can't be controlled.
+         * @param[in] player_slip True if the player slides along the walls.
+         * @param[in] player_move The direction the player is pressing.
+         * @param[in] check_lines Function that checks the lines of the field.
+         */
+        WalkmeshMovement(
+          const Manager& manager, const Walkmesh& walkmesh, const std::vector<Entity*>& entities,
+          Entity* const& player, const bool& player_locked, const bool& player_slip,
+          const Ogre::Vector3& player_move, const LineCheck& check_lines
+        );
+
+        /**
+         * Limits a scripted movement step to its remaining distance.
+         *
+         * @param[in] distance Distance to the target.
+         * @param[in] stop_distance Desired distance from the target.
+         * @param[in] max_step Maximum distance to move this frame.
+         * @return Distance to move this frame.
+         */
+        static float ScriptedStep(float distance, float stop_distance, float max_step);
+
+        /**
+         * Checks if the edge of the walkmesh stops an entity.
+         *
+         * It stops the player and the characters that wander. The characters that a script walks
+         * to a position are not stopped: the original game lets them walk off the walkmesh.
+         *
+         * @param[in] is_player Whether the entity is the player.
+         * @param[in] scripted_move Whether a script asked the entity to walk to a position.
+         * @return True if the edge of the walkmesh blocks the entity.
+         */
+        static bool EdgeBlocks(bool is_player, bool scripted_move);
+
+        /**
+         * Calculates the point elevation over a plane.
+         *
+         * @param[in] point Point to calculate the elevation of.
+         * @param[in] a First point of the plane.
+         * @param[in] b Second point of the plane.
+         * @param[in] c Third  point of the plane.
+         * @return The elevation of the point.
+         */
+        static float PointElevation(
+          const Ogre::Vector2& point,
+          const Ogre::Vector3& a, const Ogre::Vector3& b, const Ogre::Vector3& c
+        );
+
+        /**
+         * Determines at which side of a line a point is.
+         *
+         * @param[in] point The point to evaluate.
+         * @param[in] p1 The first point of the line.
+         * @param[in] p2 The second point of the line.
+         * @return A negative value if the point is on the "left" of the line vector, a positive
+         * value if the point is on the "right" of the vector line, or 0 if the point is part of
+         * the line. "Left" and "right" are determined by going from p1 to p2.
+         */
+        static float SideOfVector(
+          const Ogre::Vector2& point, const Ogre::Vector2& p1, const Ogre::Vector2& p2
+        );
+
+        /**
+         * Retrieves the height of a point of a walkmesh triangle.
+         *
+         * @param[in] triangle The triangle.
+         * @param[in] x X coordinate of the point.
+         * @param[in] y Y coordinate of the point.
+         * @param[in] fallback Value returned if there is no such triangle.
+         * @return The height of the triangle at the point.
+         */
+        float GetTriangleHeight(int triangle, float x, float y, float fallback) const;
+
+        /**
+         * Checks if an entity is over the walkmesh triangle that it is attached to.
+         *
+         * @param[in] entity The entity.
+         * @return False if it's not over it, or if it's not attached to any triangle.
+         */
+        bool IsInCurrentTriangle(const Entity& entity) const;
+
+        /**
+         * Attaches an entity to the walkmesh.
+         *
+         * It sets the triangle from the entity position coordinates. To account for multiple
+         * triangles on different levels, it uses only the X and Y coordinates, and automatically
+         * sets the Z one to the closest triangle. If the manager is in battle mode, it will do
+         * nothing.
+         *
+         * @param[in] entity Entity to attach.
+         * @return True if the entity was assigned to a walkmesh triangle, false if the entity is
+         * not in a triangle or if the manager is in battle mode.
+         */
+        bool PlaceOnWalkmesh(Entity* entity);
+
+        /**
+         * Moves an entity in the walkmesh.
+         *
+         * If the manager is in battle mode, it will do nothing.
+         *
+         * @param[in] entity Entity to move.
+         * @param[in] speed Movement speed.
+         * @param[in] delta_time Time elapsed for this movement step.
+         * @return True if the movement was possible and the entity was moved, false otherwise.
+         * If the manager is in battle mode, it will always return false.
+         */
+        bool Walk(Entity* entity, const float speed, const float delta_time);
+
+        /**
+         * Calculates and sets the next position during a linear movement.
+         *
+         * If the manager is in battle mode, it will do nothing
+         *
+         * @param[in] entity The moving entity.
+         */
+        void LinearStep(Entity* entity);
+
+        /**
+         * Calculates and sets the next position during a jump.
+         *
+         * If the manager is in battle mode, it will do nothing
+         *
+         * @param[in] entity The jump entity.
+         */
+        void JumpStep(Entity* entity);
+
+        /**
+         * What is next to the end of a step: walls (the edge of the walkmesh) and other entities,
+         * ahead of the entity, and 45 degrees to each side.
+         */
+        struct Obstacles{
+            bool left_wall = false;
+            bool right_wall = false;
+            bool ahead_wall = false;
+            bool left_entity = false;
+            bool right_entity = false;
+            bool ahead_entity = false;
+
+            /**
+             * Checks if there is any obstacle.
+             *
+             * @return True if there is one.
+             */
+            bool Any() const;
+        };
+
+        /**
+         * Changes the direction of a step that finds obstacles, to go around them.
+         *
+         * @param[in] is_player Whether the entity that moves is the player.
+         * @param[in] slip Whether the player slides along the walls.
+         * @param[in] obstacles What the step finds. At least one of them is expected.
+         * @param[in,out] direction The step.
+         * @return True to try again with the new direction, false if the entity is blocked.
+         */
+        static bool Steer(
+          const bool is_player, const bool slip, const Obstacles& obstacles,
+          Ogre::Vector2& direction
+        );
+
+    private:
+
+        /**
+         * Rotates a step around the vertical axis.
+         *
+         * @param[in,out] direction The step.
+         * @param[in] degrees Angle to rotate it.
+         */
+        static void Turn(Ogre::Vector2& direction, const float degrees);
+
+        /**
+         * Turns an entity to face the direction it walks to.
+         *
+         * @param[in] entity The entity.
+         * @param[in] direction The direction.
+         */
+        static void FaceDirection(Entity* entity, const Ogre::Vector2& direction);
+
+        /**
+         * Finds the triangle of a position an entity moves to, going through the borders of the
+         * triangles from the one the entity is in. The triangle is stored in the entity.
+         *
+         * @param[in] entity Entity to check.
+         * @param[in,out] position The position. Its height is set to the one of the walkmesh.
+         * @return True if the edge of the walkmesh blocks the move, false otherwise. In battle
+         * mode, always false.
+         */
+        bool CrossBorder(Entity* entity, Ogre::Vector3& position);
+
+        /**
+         * Checks for collisions of the entity with other entities.
+         *
+         * @param[in] entity Entity to check for collisions.
+         * @param[in] position Position of the entity.
+         * @return True if the entity is colliding with another, false otherwise. If the entity is
+         * not solid, always false. If the manager is in battle mode, it will always return false.
+         */
+        bool CheckSolidCollisions(Entity* entity, Ogre::Vector3& position);
+
+        /**
+         * Walks an entity that is not on the walkmesh in a straight line to its destination.
+         *
+         * @param[in] entity The entity.
+         * @param[in] direction The step of this frame.
+         * @return True if the entity moved.
+         */
+        bool WalkOffWalkmesh(Entity* entity, const Ogre::Vector2& direction);
+
+        /**
+         * Shortens a step according to the slope of the triangle it starts in.
+         *
+         * @param[in] triangle The triangle.
+         * @param[in] start_point Start of the step.
+         * @param[in,out] direction The step.
+         */
+        void FollowSlope(
+          const int triangle, const Ogre::Vector3& start_point, Ogre::Vector2& direction
+        ) const;
+
+        /**
+         * Finds where a step ends, turning it to go around obstacles if needed.
+         *
+         * @param[in] entity The entity that moves.
+         * @param[in] triangle The triangle the entity is in.
+         * @param[in] direction The step.
+         * @param[out] obstacles The obstacles that block the entity. None if it can move.
+         * @return The end point of the step, with the height of the start point.
+         */
+        Ogre::Vector3 FindWay(
+          Entity* entity, const int triangle, Ogre::Vector2 direction, Obstacles& obstacles
+        );
+
+        /**
+         * Looks for obstacles around the end of a step.
+         *
+         * @param[in] entity The entity that moves.
+         * @param[in] triangle The triangle the entity is in.
+         * @param[in] end_point End of the step.
+         * @param[in] direction The step.
+         * @param[in] radius Distance from the end point to look for obstacles.
+         * @return The obstacles found.
+         */
+        Obstacles ProbeAround(
+          Entity* entity, const int triangle, const Ogre::Vector3& end_point,
+          const Ogre::Vector2& direction, const float radius
+        );
+
+        /**
+         * The manager of the entities.
+         */
+        const Manager& manager_;
+
+        /**
+         * The walkmesh of the field.
+         */
+        const Walkmesh& walkmesh_;
+
+        /**
+         * The entities of the field.
+         */
+        const std::vector<Entity*>& entities_;
+
+        /**
+         * The player entity.
+         */
+        Entity* const& player_;
+
+        /**
+         * Indicates if player control is locked.
+         */
+        const bool& player_locked_;
+
+        /**
+         * Indicates if the player slides along the walls.
+         */
+        const bool& player_slip_;
+
+        /**
+         * The direction the player is pressing.
+         */
+        const Ogre::Vector3& player_move_;
+
+        /**
+         * Function that checks the lines of the field.
+         */
+        LineCheck check_lines_;
+};

+ 2 - 1
test/engine/entity/CMakeLists.txt

@@ -1,5 +1,6 @@
 # Tests of this folder (see vgears_tests and vgears_installer_tests in test/CMakeLists.txt).
 vgears_tests(
-    EntityManager.cpp
     EntityPoint.cpp
+    EntityTriggers.cpp
+    WalkmeshMovement.cpp
 )

+ 0 - 86
test/engine/entity/EntityManager.cpp

@@ -1,86 +0,0 @@
-/*
- * Copyright (C) 2022 The V-Gears Team
- *
- * This file is part of V-Gears
- *
- * V-Gears is free software: you can redistribute it and/or modify it under
- * terms of the GNU General Public License as published by the Free Software
- * Foundation, version 3.0 (GPLv3) of the License.
- *
- * V-Gears is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- */
-
-#include <boost/test/unit_test.hpp>
-#include "engine/entity/EntityManager.h"
-
-BOOST_AUTO_TEST_CASE(TestEntityManagerInteractionPicksTheEntityTheCharacterFaces){
-    // The maximum angle is 90 degrees, and no candidate yet.
-    const float max_angle = 90.0f;
-    const float no_distance = 1000.0f;
-    BOOST_CHECK(EntityManager::IsBetterInteractionTarget(30.0f, 1.0f, max_angle, no_distance));
-    // Facing the character more directly is better, whatever the order.
-    BOOST_CHECK(EntityManager::IsBetterInteractionTarget(5.0f, 1.0f, 30.0f, 1.0f));
-    BOOST_CHECK(!EntityManager::IsBetterInteractionTarget(30.0f, 1.0f, 5.0f, 1.0f));
-    // A candidate further from the front than the best one is not better.
-    BOOST_CHECK(!EntityManager::IsBetterInteractionTarget(120.0f, 1.0f, max_angle, no_distance));
-    // The same angle: the nearest wins, and the first one is kept on a tie.
-    BOOST_CHECK(EntityManager::IsBetterInteractionTarget(10.0f, 0.5f, 10.0f, 1.0f));
-    BOOST_CHECK(!EntityManager::IsBetterInteractionTarget(10.0f, 1.0f, 10.0f, 0.5f));
-    BOOST_CHECK(!EntityManager::IsBetterInteractionTarget(10.0f, 1.0f, 10.0f, 1.0f));
-
-    // Two characters side by side, in the list order Jessie then Wedge: facing Jessie must
-    // choose Jessie, and facing Wedge must choose Wedge.
-    const float jessie_angle_facing_jessie = 4.0f;
-    const float wedge_angle_facing_jessie = 40.0f;
-    float best_angle = max_angle;
-    float best_distance = no_distance;
-    int chosen = -1;
-    const float angles[] = {jessie_angle_facing_jessie, wedge_angle_facing_jessie};
-    for (int i = 0; i < 2; ++i){
-        if (EntityManager::IsBetterInteractionTarget(angles[i], 0.2f, best_angle, best_distance)){
-            best_angle = angles[i];
-            best_distance = 0.2f;
-            chosen = i;
-        }
-    }
-    BOOST_CHECK_EQUAL(chosen, 0);
-}
-
-BOOST_AUTO_TEST_CASE(TestEntityManagerLinesTriggerEvenIfAScriptZeroedTheRadius){
-    // A script sets the radius of the player to zero while a scene plays: lines must still work.
-    BOOST_CHECK_CLOSE(EntityManager::TriggerReach(0.0f), 0.21f, 0.01f);
-    BOOST_CHECK_CLOSE(EntityManager::TriggerReach(0.005f), 0.21f, 0.01f);
-    // A radius that a script chose is respected.
-    BOOST_CHECK_CLOSE(EntityManager::TriggerReach(0.265625f), 0.265625f, 0.01f);
-    BOOST_CHECK_CLOSE(EntityManager::TriggerReach(0.078125f), 0.078125f, 0.01f);
-}
-
-BOOST_AUTO_TEST_CASE(TestEntityManagerScriptedWalksAreNotStoppedByTheWalkmeshEdge){
-    // The player and the characters that wander are stopped.
-    BOOST_CHECK(EntityManager::WalkmeshEdgeBlocks(true, false));
-    BOOST_CHECK(EntityManager::WalkmeshEdgeBlocks(false, false));
-    // Even if a script moves the player, the player stays on the walkmesh.
-    BOOST_CHECK(EntityManager::WalkmeshEdgeBlocks(true, true));
-    // A character a script walks to a position is not.
-    BOOST_CHECK(!EntityManager::WalkmeshEdgeBlocks(false, true));
-}
-
-BOOST_AUTO_TEST_CASE(TestEntityManager){
-    BOOST_CHECK_CLOSE(EntityManager::ScriptedMoveStep(0.5f, 0.0f, 0.1f), 0.1f, 0.01f);
-    BOOST_CHECK_CLOSE(EntityManager::ScriptedMoveStep(0.05f, 0.0f, 0.1f), 0.05f, 0.01f);
-    BOOST_CHECK_CLOSE(EntityManager::ScriptedMoveStep(0.55f, 0.5f, 0.1f), 0.05f, 0.01f);
-    BOOST_CHECK_EQUAL(EntityManager::ScriptedMoveStep(0.4f, 0.5f, 0.1f), 0.0f);
-    BOOST_CHECK_EQUAL(EntityManager::ScriptedMoveStep(1.0f, 0.0f, 0.0f), 0.0f);
-
-    for (float frame_time : {1.0f / 120.0f, 1.0f / 60.0f, 1.0f / 30.0f}){
-        float distance = 2.0f;
-        for (int step = 0; step < 1000 && distance > 0.0001f; ++step){
-            distance -= EntityManager::ScriptedMoveStep(distance, 0.0f, 6.0f * frame_time);
-        }
-        BOOST_CHECK_SMALL(distance, 0.0001f);
-    }
-}
-

+ 59 - 0
test/engine/entity/EntityTriggers.cpp

@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <boost/test/unit_test.hpp>
+#include "engine/entity/EntityTriggers.h"
+
+BOOST_AUTO_TEST_CASE(TestEntityTriggersInteractionPicksTheEntityTheCharacterFaces){
+    // The maximum angle is 90 degrees, and no candidate yet.
+    const float max_angle = 90.0f;
+    const float no_distance = 1000.0f;
+    BOOST_CHECK(EntityTriggers::IsBetterInteractionTarget(30.0f, 1.0f, max_angle, no_distance));
+    // Facing the character more directly is better, whatever the order.
+    BOOST_CHECK(EntityTriggers::IsBetterInteractionTarget(5.0f, 1.0f, 30.0f, 1.0f));
+    BOOST_CHECK(!EntityTriggers::IsBetterInteractionTarget(30.0f, 1.0f, 5.0f, 1.0f));
+    // A candidate further from the front than the best one is not better.
+    BOOST_CHECK(!EntityTriggers::IsBetterInteractionTarget(120.0f, 1.0f, max_angle, no_distance));
+    // The same angle: the nearest wins, and the first one is kept on a tie.
+    BOOST_CHECK(EntityTriggers::IsBetterInteractionTarget(10.0f, 0.5f, 10.0f, 1.0f));
+    BOOST_CHECK(!EntityTriggers::IsBetterInteractionTarget(10.0f, 1.0f, 10.0f, 0.5f));
+    BOOST_CHECK(!EntityTriggers::IsBetterInteractionTarget(10.0f, 1.0f, 10.0f, 1.0f));
+
+    // Two characters side by side, in the list order Jessie then Wedge: facing Jessie must
+    // choose Jessie, and facing Wedge must choose Wedge.
+    const float jessie_angle_facing_jessie = 4.0f;
+    const float wedge_angle_facing_jessie = 40.0f;
+    float best_angle = max_angle;
+    float best_distance = no_distance;
+    int chosen = -1;
+    const float angles[] = {jessie_angle_facing_jessie, wedge_angle_facing_jessie};
+    for (int i = 0; i < 2; ++i){
+        if (EntityTriggers::IsBetterInteractionTarget(angles[i], 0.2f, best_angle, best_distance)){
+            best_angle = angles[i];
+            best_distance = 0.2f;
+            chosen = i;
+        }
+    }
+    BOOST_CHECK_EQUAL(chosen, 0);
+}
+
+BOOST_AUTO_TEST_CASE(TestEntityTriggersLinesTriggerEvenIfAScriptZeroedTheRadius){
+    // A script sets the radius of the player to zero while a scene plays: lines must still work.
+    BOOST_CHECK_CLOSE(EntityTriggers::Reach(0.0f), 0.21f, 0.01f);
+    BOOST_CHECK_CLOSE(EntityTriggers::Reach(0.005f), 0.21f, 0.01f);
+    // A radius that a script chose is respected.
+    BOOST_CHECK_CLOSE(EntityTriggers::Reach(0.265625f), 0.265625f, 0.01f);
+    BOOST_CHECK_CLOSE(EntityTriggers::Reach(0.078125f), 0.078125f, 0.01f);
+}

+ 118 - 0
test/engine/entity/WalkmeshMovement.cpp

@@ -0,0 +1,118 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <boost/test/unit_test.hpp>
+#include "engine/entity/WalkmeshMovement.h"
+
+BOOST_AUTO_TEST_CASE(TestWalkmeshMovementScriptedWalksAreNotStoppedByTheWalkmeshEdge){
+    // The player and the characters that wander are stopped.
+    BOOST_CHECK(WalkmeshMovement::EdgeBlocks(true, false));
+    BOOST_CHECK(WalkmeshMovement::EdgeBlocks(false, false));
+    // Even if a script moves the player, the player stays on the walkmesh.
+    BOOST_CHECK(WalkmeshMovement::EdgeBlocks(true, true));
+    // A character a script walks to a position is not.
+    BOOST_CHECK(!WalkmeshMovement::EdgeBlocks(false, true));
+}
+
+BOOST_AUTO_TEST_CASE(TestWalkmeshMovementScriptedSteps){
+    BOOST_CHECK_CLOSE(WalkmeshMovement::ScriptedStep(0.5f, 0.0f, 0.1f), 0.1f, 0.01f);
+    BOOST_CHECK_CLOSE(WalkmeshMovement::ScriptedStep(0.05f, 0.0f, 0.1f), 0.05f, 0.01f);
+    BOOST_CHECK_CLOSE(WalkmeshMovement::ScriptedStep(0.55f, 0.5f, 0.1f), 0.05f, 0.01f);
+    BOOST_CHECK_EQUAL(WalkmeshMovement::ScriptedStep(0.4f, 0.5f, 0.1f), 0.0f);
+    BOOST_CHECK_EQUAL(WalkmeshMovement::ScriptedStep(1.0f, 0.0f, 0.0f), 0.0f);
+
+    for (float frame_time : {1.0f / 120.0f, 1.0f / 60.0f, 1.0f / 30.0f}){
+        float distance = 2.0f;
+        for (int step = 0; step < 1000 && distance > 0.0001f; ++step){
+            distance -= WalkmeshMovement::ScriptedStep(distance, 0.0f, 6.0f * frame_time);
+        }
+        BOOST_CHECK_SMALL(distance, 0.0001f);
+    }
+}
+
+BOOST_AUTO_TEST_CASE(TestWalkmeshMovementHeightOfAPointOfATriangle){
+    // A slope that goes up one unit for each two units along X.
+    const Ogre::Vector3 a(0.0f, 0.0f, 0.0f);
+    const Ogre::Vector3 b(2.0f, 0.0f, 1.0f);
+    const Ogre::Vector3 c(0.0f, 2.0f, 0.0f);
+    BOOST_CHECK_CLOSE(
+      WalkmeshMovement::PointElevation(Ogre::Vector2(1.0f, 0.5f), a, b, c), 0.5f, 0.01f
+    );
+    BOOST_CHECK_CLOSE(
+      WalkmeshMovement::PointElevation(Ogre::Vector2(2.0f, 0.0f), a, b, c), 1.0f, 0.01f
+    );
+}
+
+BOOST_AUTO_TEST_CASE(TestWalkmeshMovementSideOfALine){
+    const Ogre::Vector2 start(0.0f, 0.0f);
+    const Ogre::Vector2 end(1.0f, 0.0f);
+    BOOST_CHECK(WalkmeshMovement::SideOfVector(Ogre::Vector2(0.5f, 1.0f), start, end) > 0.0f);
+    BOOST_CHECK(WalkmeshMovement::SideOfVector(Ogre::Vector2(0.5f, -1.0f), start, end) < 0.0f);
+    BOOST_CHECK_EQUAL(
+      WalkmeshMovement::SideOfVector(Ogre::Vector2(3.0f, 0.0f), start, end), 0.0f
+    );
+}
+
+/**
+ * Steers a step that goes along X.
+ *
+ * @return The angle in degrees that the step has been turned, or 1000 if the entity is blocked.
+ */
+static float SteerAngle(
+  const bool is_player, const bool slip, const WalkmeshMovement::Obstacles& obstacles
+){
+    Ogre::Vector2 direction(1.0f, 0.0f);
+    if (!WalkmeshMovement::Steer(is_player, slip, obstacles, direction)) return 1000.0f;
+    return Ogre::Math::ATan2(direction.y, direction.x).valueDegrees();
+}
+
+BOOST_AUTO_TEST_CASE(TestWalkmeshMovementThePlayerSlidesAlongWalls){
+    WalkmeshMovement::Obstacles left;
+    left.left_wall = true;
+    BOOST_CHECK_CLOSE(SteerAngle(true, true, left), -11.25f, 0.01f);
+    WalkmeshMovement::Obstacles right;
+    right.right_wall = true;
+    BOOST_CHECK_CLOSE(SteerAngle(true, true, right), 11.25f, 0.01f);
+    // Not with SLIP off, nor in a corner.
+    BOOST_CHECK_EQUAL(SteerAngle(true, false, left), 1000.0f);
+    WalkmeshMovement::Obstacles corner = left;
+    corner.right_wall = true;
+    BOOST_CHECK_EQUAL(SteerAngle(true, true, corner), 1000.0f);
+    // The player doesn't go around other entities.
+    WalkmeshMovement::Obstacles somebody = left;
+    somebody.ahead_entity = true;
+    BOOST_CHECK_EQUAL(SteerAngle(true, true, somebody), 1000.0f);
+}
+
+BOOST_AUTO_TEST_CASE(TestWalkmeshMovementCharactersGoAroundObstacles){
+    WalkmeshMovement::Obstacles wall_ahead;
+    wall_ahead.ahead_wall = true;
+    BOOST_CHECK_CLOSE(SteerAngle(false, true, wall_ahead), -7.0f, 0.01f);
+    // Somebody ahead: it turns to one side. Somebody to the left or right too.
+    WalkmeshMovement::Obstacles ahead;
+    ahead.ahead_entity = true;
+    BOOST_CHECK_CLOSE(SteerAngle(false, true, ahead), -11.25f, 0.01f);
+    WalkmeshMovement::Obstacles left;
+    left.left_entity = true;
+    BOOST_CHECK_CLOSE(SteerAngle(false, true, left), -11.25f, 0.01f);
+    WalkmeshMovement::Obstacles right;
+    right.right_entity = true;
+    BOOST_CHECK_CLOSE(SteerAngle(false, true, right), 11.25f, 0.01f);
+    // Walls on both sides block it.
+    WalkmeshMovement::Obstacles corner;
+    corner.left_wall = true;
+    corner.right_wall = true;
+    BOOST_CHECK_EQUAL(SteerAngle(false, true, corner), 1000.0f);
+}