Просмотр исходного кода

Moved the terrain, the encounters and the snow of the world map to their own classes

- WorldmapTerrain, WorldmapEncounters and WorldmapSnow own their data, which was in the module.
- The frame update of the module is divided in steps, and uses a single function to get the name of the vehicle.
Iñigo Valentin 1 день назад
Родитель
Сommit
f425b5163c

+ 1 - 0
src/modules/worldmap/CMakeLists.txt

@@ -9,5 +9,6 @@ vgears_sources(
     WorldmapSubmarine.cpp
     WorldmapSubmarine.cpp
     WorldmapTerrain.cpp
     WorldmapTerrain.cpp
     WorldmapTextures.cpp
     WorldmapTextures.cpp
+    WorldmapTriggers.cpp
     WorldmapVehicles.cpp
     WorldmapVehicles.cpp
 )
 )

+ 0 - 7
src/modules/worldmap/WorldmapConstants.h

@@ -22,13 +22,6 @@ namespace VGears {
     /// Rotation speed of the camera with L1 and R1, in radians per second.
     /// Rotation speed of the camera with L1 and R1, in radians per second.
     static const float CAMERA_ROTATION_SPEED = 1.5f;
     static const float CAMERA_ROTATION_SPEED = 1.5f;
 
 
-    /// Snow map (WM3): the camera turns by itself after this many seconds (random in the range) ...
-    static const float SNOW_CAMERA_MIN_WAIT = 6.0f;
-    static const float SNOW_CAMERA_MAX_WAIT = 12.0f;
-    /// ... by this many degrees (random in the range, to any side), at the speed of the manual rotation.
-    static const float SNOW_CAMERA_MIN_DEGREES = 30.0f;
-    static const float SNOW_CAMERA_MAX_DEGREES = 160.0f;
-
     /// Closest distance of the flying vehicles to the ground.
     /// Closest distance of the flying vehicles to the ground.
     static const float FLIGHT_MIN_CLEARANCE = 0.1f;
     static const float FLIGHT_MIN_CLEARANCE = 0.1f;
 
 

+ 13 - 8
src/modules/worldmap/WorldmapEncounters.cpp

@@ -13,7 +13,7 @@
  * GNU General Public License for more details.
  * GNU General Public License for more details.
  */
  */
 
 
-#include "modules/worldmap/WorldmapModule.h"
+#include "modules/worldmap/WorldmapEncounters.h"
 #include <algorithm>
 #include <algorithm>
 #include <cstdlib>
 #include <cstdlib>
 #include <sstream>
 #include <sstream>
@@ -21,10 +21,11 @@
 #include "common/Logger.h"
 #include "common/Logger.h"
 #include "engine/entity/EntityManager.h"
 #include "engine/entity/EntityManager.h"
 #include "engine/script/ScriptManager.h"
 #include "engine/script/ScriptManager.h"
+#include "modules/worldmap/WorldmapTerrain.h"
 
 
 namespace VGears {
 namespace VGears {
 
 
-    void WorldmapModule::LoadEncounters(){
+    void WorldmapEncounters::Load(){
         encounter_records_.clear();
         encounter_records_.clear();
         TiXmlDocument document("./game/world/world_encounters.xml");
         TiXmlDocument document("./game/world/world_encounters.xml");
         if (!document.LoadFile()){
         if (!document.LoadFile()){
@@ -37,7 +38,7 @@ namespace VGears {
             .FirstChildElement("record").ToElement();
             .FirstChildElement("record").ToElement();
           record != nullptr; record = record->NextSiblingElement("record")
           record != nullptr; record = record->NextSiblingElement("record")
         ){
         ){
-            EncounterRecord data;
+            Record data;
             int enabled = 0;
             int enabled = 0;
             data.rate = 0;
             data.rate = 0;
             data.terrain = 0;
             data.terrain = 0;
@@ -57,7 +58,7 @@ namespace VGears {
         LOG_TRIVIAL("World map encounters loaded: " + std::to_string(encounter_records_.size()));
         LOG_TRIVIAL("World map encounters loaded: " + std::to_string(encounter_records_.size()));
     }
     }
 
 
-    int WorldmapModule::RollEncounterBattle(const EncounterRecord& record) const{
+    int WorldmapEncounters::RollBattle(const Record& record) const{
         // Same order as the original game: the special battles first, then the standard ones. The
         // Same order as the original game: the special battles first, then the standard ones. The
         // chance of a word is its probability out of 64, as the roll is a 16 bit value and the
         // chance of a word is its probability out of 64, as the roll is a 16 bit value and the
         // probability sits in the 6 highest bits.
         // probability sits in the 6 highest bits.
@@ -93,7 +94,7 @@ namespace VGears {
         return battle;
         return battle;
     }
     }
 
 
-    void WorldmapModule::UpdateEncounters(const float delta_time, const TerrainTriangle& triangle){
+    void WorldmapEncounters::Update(const float delta_time, const TerrainTriangle& triangle){
         if (encounters_locked_ || encounter_records_.size() < 64) return;
         if (encounters_locked_ || encounter_records_.size() < 64) return;
         // The original game checks every 16 frames of walking, at 30 frames per second.
         // The original game checks every 16 frames of walking, at 30 frames per second.
         encounter_frames_ += delta_time * 30.0f;
         encounter_frames_ += delta_time * 30.0f;
@@ -112,7 +113,7 @@ namespace VGears {
                 break;
                 break;
             }
             }
         }
         }
-        const EncounterRecord& record = encounter_records_[region * 4 + group];
+        const Record& record = encounter_records_[region * 4 + group];
 
 
         // The accumulator grows on every check, so the chance gets higher until a battle starts.
         // The accumulator grows on every check, so the chance gets higher until a battle starts.
         const float multiplier = EntityManager::getSingleton().GetEncounterMultiplier();
         const float multiplier = EntityManager::getSingleton().GetEncounterMultiplier();
@@ -130,13 +131,17 @@ namespace VGears {
         }
         }
         if (check >= (encounter_accumulator_ >> 8) || !record.enabled) return;
         if (check >= (encounter_accumulator_ >> 8) || !record.enabled) return;
         encounter_accumulator_ = 0;
         encounter_accumulator_ = 0;
-        const int battle = RollEncounterBattle(record);
+        const int battle = RollBattle(record);
         if (battle < 0) return;
         if (battle < 0) return;
         encounter_last_battle_ = battle;
         encounter_last_battle_ = battle;
         LOG_TRIVIAL("World random encounter: battle " + std::to_string(battle));
         LOG_TRIVIAL("World random encounter: battle " + std::to_string(battle));
         ScriptManager::getSingleton().RunString("Encounter.start(" + std::to_string(battle) + ")");
         ScriptManager::getSingleton().RunString("Encounter.start(" + std::to_string(battle) + ")");
     }
     }
 
 
-    void WorldmapModule::SetEncountersLocked(const bool locked){encounters_locked_ = locked;}
+    void WorldmapEncounters::Clear(){encounter_records_.clear();}
+
+    void WorldmapEncounters::SetLocked(const bool locked){encounters_locked_ = locked;}
+
+    void WorldmapEncounters::ResetTimer(){encounter_frames_ = 0;}
 
 
 } // namespace VGears
 } // namespace VGears

+ 91 - 0
src/modules/worldmap/WorldmapEncounters.h

@@ -0,0 +1,91 @@
+/*
+ * 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 <vector>
+#include "common/TypeDefine.h"
+
+namespace VGears {
+
+    struct TerrainTriangle;
+
+    /**
+     * The random battles of the world map.
+     */
+    class WorldmapEncounters{
+
+        public:
+
+            /**
+             * Loads the encounters of the world map. Without them there are no random battles.
+             */
+            void Load();
+
+            /**
+             * Forgets the loaded encounters.
+             */
+            void Clear();
+
+            /**
+             * Counts the time walked, and starts a battle when the chance says so.
+             *
+             * @param[in] delta_time Seconds walked since the last call.
+             * @param[in] triangle Triangle where the player is.
+             */
+            void Update(const float delta_time, const TerrainTriangle& triangle);
+
+            /**
+             * Prevents or allows random encounters.
+             *
+             * @param[in] locked True to prevent them.
+             */
+            void SetLocked(const bool locked);
+
+            /**
+             * Starts counting the time to the next check again.
+             */
+            void ResetTimer();
+
+        private:
+
+            /**
+             * Random encounters of a region and terrain group, from ENC_W.BIN.
+             */
+            struct Record{
+                bool enabled;
+                /// Lower values mean more frequent encounters.
+                int rate;
+                /// Walkability type that selects this record.
+                int terrain;
+                /// Words 1-15 of the record: battle ID (10 bits) and probability (6 bits).
+                uint16 words[15];
+            };
+
+            /**
+             * Chooses the battle of an encounter.
+             *
+             * @param[in] record Encounters of the terrain.
+             * @return The battle ID, or -1 if none.
+             */
+            int RollBattle(const Record& record) const;
+
+            std::vector<Record> encounter_records_;
+            float encounter_frames_ = 0;
+            int encounter_accumulator_ = 0;
+            int encounter_last_battle_ = -1;
+            bool encounters_locked_ = false;
+    };
+}

+ 11 - 6
src/modules/worldmap/WorldmapEntities.cpp

@@ -70,17 +70,13 @@ namespace VGears {
         else{
         else{
             // Spawn points of the other maps are unknown: use the walkable triangle closest to the
             // Spawn points of the other maps are unknown: use the walkable triangle closest to the
             // center of the map, or to the position where the submarine dived.
             // center of the map, or to the position where the submarine dived.
-            const Ogre::Real space = From16BitFixedPoint(8182);
-            const Ogre::Vector3 center = dive_requested_ ? dive_position_ : Ogre::Vector3(
-              space * (origin_x_ * 4.0f + grid_width_ * 2.0f), 0.0f,
-              space * (origin_y_ * 4.0f + grid_height_ * 2.0f)
-            );
+            const Ogre::Vector3 center = dive_requested_ ? dive_position_ : terrain_.GetCenter();
             Ogre::Real best_distance = std::numeric_limits<Ogre::Real>::max();
             Ogre::Real best_distance = std::numeric_limits<Ogre::Real>::max();
             // The exact position of the dive, if the submarine can be there.
             // The exact position of the dive, if the submarine can be there.
             const bool exact_dive_position = dive_requested_
             const bool exact_dive_position = dive_requested_
               && FindWalkableSurface(dive_position_, spawn_position, false, true);
               && FindWalkableSurface(dive_position_, spawn_position, false, true);
             if (exact_dive_position) best_distance = 0;
             if (exact_dive_position) best_distance = 0;
-            else for (const TerrainTriangle& triangle : terrain_triangles_){
+            else for (const TerrainTriangle& triangle : terrain_.GetTriangles()){
                 const Ogre::Vector3 centroid
                 const Ogre::Vector3 centroid
                   = (triangle.vertices[0] + triangle.vertices[1] + triangle.vertices[2]) / 3.0f;
                   = (triangle.vertices[0] + triangle.vertices[1] + triangle.vertices[2]) / 3.0f;
                 if (map_id_ == 1 ? (UNDERWATER_HEIGHT_LIMIT_ENABLED
                 if (map_id_ == 1 ? (UNDERWATER_HEIGHT_LIMIT_ENABLED
@@ -439,4 +435,13 @@ namespace VGears {
         return static_cast<int>(std::floor(turns * 256.0f + 0.5f)) & 255;
         return static_cast<int>(std::floor(turns * 256.0f + 0.5f)) & 255;
     }
     }
 
 
+    void WorldmapModule::PlaceSnowPole(){
+        if (player_entity_ == nullptr) return;
+        const Ogre::Vector3 position = player_entity_->GetPosition();
+        snow_.PlacePole([this, position](const std::string& name){
+            // The model and scale of the snow poles of the game (WorldMapModels: djc, 0x300).
+            AddWorldModelFromScript(name.c_str(), "djc", position.x, position.z, 0x300, 0, 0.0f, 0.0f, 0.0f);
+        });
+    }
+
 } // namespace VGears
 } // namespace VGears

+ 152 - 197
src/modules/worldmap/WorldmapModule.cpp

@@ -29,7 +29,6 @@
 #include "engine/ui/DialogsManager.h"
 #include "engine/ui/DialogsManager.h"
 #include "modules/worldmap/WorldmapConstants.h"
 #include "modules/worldmap/WorldmapConstants.h"
 #include "modules/worldmap/WorldmapData.h"
 #include "modules/worldmap/WorldmapData.h"
-#include "modules/worldmap/WorldmapSnow.h"
 #include "modules/worldmap/WorldmapTextures.h"
 #include "modules/worldmap/WorldmapTextures.h"
 
 
 /**
 /**
@@ -46,8 +45,6 @@ namespace VGears {
     static const float UNDERWATER_FOG_END = 6.0f;
     static const float UNDERWATER_FOG_END = 6.0f;
 
 
     WorldmapModule::WorldmapModule():
     WorldmapModule::WorldmapModule():
-      scene_manager_(nullptr),
-      world_map_node_(nullptr),
       player_entity_(nullptr),
       player_entity_(nullptr),
       highwind_entity_(nullptr),
       highwind_entity_(nullptr),
       buggy_entity_(nullptr),
       buggy_entity_(nullptr),
@@ -56,15 +53,11 @@ namespace VGears {
       tiny_bronco_entity_(nullptr),
       tiny_bronco_entity_(nullptr),
       current_vehicle_(VehicleType::ON_FOOT),
       current_vehicle_(VehicleType::ON_FOOT),
       map_id_(-1),
       map_id_(-1),
-      grid_width_(9),
-      grid_height_(7),
       camera_yaw_(0),
       camera_yaw_(0),
       flight_active_(false),
       flight_active_(false),
       flight_entity_(nullptr),
       flight_entity_(nullptr),
       flight_heading_(0),
       flight_heading_(0),
       flight_y_(0),
       flight_y_(0),
-      origin_x_(0),
-      origin_y_(0),
       player_height_offset_(0),
       player_height_offset_(0),
       active_function_mesh_index_(-1),
       active_function_mesh_index_(-1),
       active_function_id_(-1),
       active_function_id_(-1),
@@ -83,82 +76,89 @@ namespace VGears {
       dive_requested_(false),
       dive_requested_(false),
       dive_position_(Ogre::Vector3::ZERO),
       dive_position_(Ogre::Vector3::ZERO),
       dive_heading_(0),
       dive_heading_(0),
-      encounter_frames_(0),
-      encounter_accumulator_(0),
-      encounter_last_battle_(-1),
-      encounters_locked_(false),
       paused_for_battle_(false)
       paused_for_battle_(false)
     {}
     {}
 
 
     WorldmapModule::~WorldmapModule(){
     WorldmapModule::~WorldmapModule(){
       if (frame_listener_attached_) Root::getSingleton().removeFrameListener(this);
       if (frame_listener_attached_) Root::getSingleton().removeFrameListener(this);
-      if (scene_manager_ != nullptr && world_map_node_ != nullptr){
-        scene_manager_->getRootSceneNode()->removeAndDestroyChild("WorldMapTerrain");
-      }
     }
     }
 
 
     bool WorldmapModule::frameStarted(const Ogre::FrameEvent& event){
     bool WorldmapModule::frameStarted(const Ogre::FrameEvent& event){
-      if (!initialized_ || player_entity_ == nullptr || paused_for_battle_) return true;
-      AnimateWorldMapTextures(event.timeSinceLastFrame);
-
-      // Diving or surfacing: the submarine moves by itself and the screen fades.
-      if (transition_stage_ != TransitionStage::NONE){
-        UpdateTransition(event.timeSinceLastFrame);
-        if (initialized_ && player_entity_ != nullptr){
-          UpdateVehicleAnimations(false);
-          UpdateCamera(event.timeSinceLastFrame, false);
+        if (!initialized_ || player_entity_ == nullptr || paused_for_battle_) return true;
+        const Ogre::Real delta_time = event.timeSinceLastFrame;
+        AnimateWorldMapTextures(delta_time);
+
+        // Diving or surfacing: the submarine moves by itself and the screen fades.
+        if (transition_stage_ != TransitionStage::NONE){
+            UpdateTransition(delta_time);
+            if (initialized_ && player_entity_ != nullptr){
+                UpdateVehicleAnimations(false);
+                UpdateCamera(delta_time, false);
+            }
+            return true;
         }
         }
-        return true;
-      }
 
 
         ::Entity* active_entity = EntityManager::getSingleton().ScriptGetPlayerEntity();
         ::Entity* active_entity = EntityManager::getSingleton().ScriptGetPlayerEntity();
-      if (active_entity == player_entity_){
-        current_vehicle_ = VehicleType::ON_FOOT;
-      }
-      else if (active_entity == chocobo_entity_){
-        current_vehicle_ = VehicleType::CHOCOBO;
-      }
-      else if (active_entity == buggy_entity_){
-        current_vehicle_ = VehicleType::BUGGY;
-      }
-      else if (active_entity == highwind_entity_){
-        current_vehicle_ = VehicleType::HIGHWIND;
-      }
-      else if (active_entity == submarine_entity_){
-        current_vehicle_ = VehicleType::SUBMARINE;
-      }
-      else if (active_entity == tiny_bronco_entity_){
-        current_vehicle_ = VehicleType::TINY_BRONCO;
-      }
-      else{
-        // An entity of a scripted scene (the Warship): the camera follows it and nothing else happens.
-        if (active_entity != nullptr){
-          UpdateCamera(event.timeSinceLastFrame, false);
+        if (!UpdateCurrentVehicle(active_entity)){
+            // An entity of a scripted scene (the Warship): the camera follows it and nothing else happens.
+            if (active_entity != nullptr) UpdateCamera(delta_time, false);
+            return true;
+        }
+        UpdateMusic(delta_time);
+        // The buttons can change the map: the entities are not valid after it.
+        if (HandleActionButtons(active_entity)) return true;
+
+        const bool highwind_active = active_entity == highwind_entity_;
+        EntityModel* active_model = GetActiveModel(active_entity);
+
+        // Flying vehicles (the Highwind, and the submarine of WM2) have their own controls.
+        flight_active_ = highwind_active || (map_id_ == 1 && active_entity == player_entity_);
+        if (flight_active_){
+            UpdateFlight(active_model, delta_time, highwind_active);
+            UpdateVehicleAnimations(false);
+            UpdateCamera(delta_time, false);
+            return true;
+        }
+        flight_entity_ = nullptr;
+
+        UpdateCameraRotation(delta_time);
+        const bool is_walking = UpdateWalking(active_entity, active_model, delta_time);
+
+        // The submarine of WM2 has no walking animations.
+        if (current_vehicle_ == VehicleType::ON_FOOT && map_id_ != 1){
+            player_entity_->PlayAnimationContinue(is_walking ? "Walk" : "Idle");
         }
         }
+
+        UpdateVehicleAnimations(is_walking);
+        UpdateCamera(delta_time, false);
         return true;
         return true;
-      }
+    }
 
 
+    bool WorldmapModule::UpdateCurrentVehicle(const ::Entity* active_entity){
+        if (active_entity == player_entity_) current_vehicle_ = VehicleType::ON_FOOT;
+        else if (active_entity == chocobo_entity_) current_vehicle_ = VehicleType::CHOCOBO;
+        else if (active_entity == buggy_entity_) current_vehicle_ = VehicleType::BUGGY;
+        else if (active_entity == highwind_entity_) current_vehicle_ = VehicleType::HIGHWIND;
+        else if (active_entity == submarine_entity_) current_vehicle_ = VehicleType::SUBMARINE;
+        else if (active_entity == tiny_bronco_entity_) current_vehicle_ = VehicleType::TINY_BRONCO;
+        else return false;
+        return true;
+    }
+
+    void WorldmapModule::UpdateMusic(const Ogre::Real delta_time){
         // The music of the map (WorldMusic in world_music.lua): when the vehicle changes and every half second.
         // The music of the map (WorldMusic in world_music.lua): when the vehicle changes and every half second.
-        music_timer_ += event.timeSinceLastFrame;
-        if (music_timer_ >= 0.5f || music_vehicle_ != current_vehicle_){
-          music_timer_ = 0.0f;
-          music_vehicle_ = current_vehicle_;
-          const char* music_vehicle = "walk";
-          switch (current_vehicle_){
-            case VehicleType::CHOCOBO: music_vehicle = "chocobo"; break;
-            case VehicleType::BUGGY: music_vehicle = "buggy"; break;
-            case VehicleType::HIGHWIND: music_vehicle = "highwind"; break;
-            case VehicleType::SUBMARINE: music_vehicle = "submarine"; break;
-            case VehicleType::TINY_BRONCO: music_vehicle = "tiny_bronco"; break;
-            default: break;
-          }
-          ScriptManager::getSingleton().RunString(
-            "if WorldMusic then WorldMusic.update(" + std::to_string(map_id_) + ", \"" + music_vehicle + "\") end"
-          );
-        }
+        music_timer_ += delta_time;
+        if (music_timer_ < 0.5f && music_vehicle_ == current_vehicle_) return;
+        music_timer_ = 0.0f;
+        music_vehicle_ = current_vehicle_;
+        ScriptManager::getSingleton().RunString(
+          "if WorldMusic then WorldMusic.update(" + std::to_string(map_id_) + ", \""
+          + GetVehicleScriptName(current_vehicle_) + "\") end"
+        );
+    }
 
 
-        const bool highwind_active = active_entity == highwind_entity_;
-      const bool vehicle_active = current_vehicle_ != VehicleType::ON_FOOT;
+    bool WorldmapModule::HandleActionButtons(::Entity* active_entity){
+        const bool vehicle_active = current_vehicle_ != VehicleType::ON_FOOT;
         const bool cancel_pressed = InputManager::getSingleton().IsGameEventPressed("CANCEL");
         const bool cancel_pressed = InputManager::getSingleton().IsGameEventPressed("CANCEL");
         const bool cancel_edge = cancel_pressed && !cancel_was_pressed_;
         const bool cancel_edge = cancel_pressed && !cancel_was_pressed_;
         // The cancel button makes the submarine of WM2 go back to the surface.
         // The cancel button makes the submarine of WM2 go back to the surface.
@@ -167,7 +167,6 @@ namespace VGears {
           && !EntityManager::getSingleton().IsPlayerLocked()
           && !EntityManager::getSingleton().IsPlayerLocked()
         ){
         ){
             cancel_was_pressed_ = true;
             cancel_was_pressed_ = true;
-            // Changes the map: the entities are not valid after it.
             if (SurfaceToOverworld(submarine_entity_)) return true;
             if (SurfaceToOverworld(submarine_entity_)) return true;
         }
         }
         if (vehicle_active && cancel_pressed && !cancel_was_pressed_){
         if (vehicle_active && cancel_pressed && !cancel_was_pressed_){
@@ -176,127 +175,93 @@ namespace VGears {
             );
             );
         }
         }
         cancel_was_pressed_ = cancel_pressed;
         cancel_was_pressed_ = cancel_pressed;
-        // The action button makes the submarine dive from WM0 to WM2.
+        // The action button places a pole in the snow map, and makes the submarine dive from WM0 to WM2.
         const bool confirm_pressed = InputManager::getSingleton().IsGameEventPressed("CONFIRM");
         const bool confirm_pressed = InputManager::getSingleton().IsGameEventPressed("CONFIRM");
-        const bool dive_pressed = confirm_pressed && !confirm_was_pressed_;
+        const bool confirm_edge = confirm_pressed && !confirm_was_pressed_;
         confirm_was_pressed_ = confirm_pressed;
         confirm_was_pressed_ = confirm_pressed;
         if (
         if (
-          dive_pressed && map_id_ == 2 && active_entity == player_entity_
+          confirm_edge && map_id_ == 2 && active_entity == player_entity_
           && !EntityManager::getSingleton().IsPlayerLocked()
           && !EntityManager::getSingleton().IsPlayerLocked()
         ){
         ){
             PlaceSnowPole();
             PlaceSnowPole();
         }
         }
         if (
         if (
-          dive_pressed && map_id_ == 0 && active_entity == submarine_entity_
+          confirm_edge && map_id_ == 0 && active_entity == submarine_entity_
           && !EntityManager::getSingleton().IsPlayerLocked()
           && !EntityManager::getSingleton().IsPlayerLocked()
         ){
         ){
-            // Changes the map: the entities are not valid after it.
             if (DiveToUnderwaterMap(submarine_entity_)) return true;
             if (DiveToUnderwaterMap(submarine_entity_)) return true;
         }
         }
-      EntityModel* active_model = active_entity == player_entity_ ? player_entity_
-        : (current_vehicle_ == VehicleType::CHOCOBO ? chocobo_entity_
-        : (current_vehicle_ == VehicleType::BUGGY ? buggy_entity_
-          : (highwind_active ? highwind_entity_
-            : (current_vehicle_ == VehicleType::SUBMARINE
-              ? submarine_entity_ : tiny_bronco_entity_))));
-
-        // Flying vehicles (the Highwind, and the submarine of WM2) have their own controls.
-        flight_active_ = highwind_active || (map_id_ == 1 && active_entity == player_entity_);
-        if (flight_active_){
-            UpdateFlight(active_model, event.timeSinceLastFrame, highwind_active);
-            UpdateVehicleAnimations(false);
-            UpdateCamera(event.timeSinceLastFrame, false);
-            return true;
-        }
-        flight_entity_ = nullptr;
+        return false;
+    }
 
 
-        // L1 and R1 rotate the camera around the active entity.
-        {
-            InputManager& camera_input = InputManager::getSingleton();
-            // The camera of the snow map (WM3) can't be moved by hand: it turns by itself.
-            if (map_id_ == 2) UpdateSnowCamera(event.timeSinceLastFrame);
-            else{
-                if (camera_input.IsGameEventPressed("L1")) camera_yaw_ -= CAMERA_ROTATION_SPEED * event.timeSinceLastFrame;
-                if (camera_input.IsGameEventPressed("R1")) camera_yaw_ += CAMERA_ROTATION_SPEED * event.timeSinceLastFrame;
-            }
-            if (camera_yaw_ > Ogre::Math::PI) camera_yaw_ -= Ogre::Math::TWO_PI;
-            else if (camera_yaw_ < -Ogre::Math::PI) camera_yaw_ += Ogre::Math::TWO_PI;
+    EntityModel* WorldmapModule::GetActiveModel(const ::Entity* active_entity) const{
+        if (active_entity == player_entity_) return player_entity_;
+        switch (current_vehicle_){
+            case VehicleType::CHOCOBO: return chocobo_entity_;
+            case VehicleType::BUGGY: return buggy_entity_;
+            default: break;
         }
         }
+        if (active_entity == highwind_entity_) return highwind_entity_;
+        if (current_vehicle_ == VehicleType::SUBMARINE) return submarine_entity_;
+        return tiny_bronco_entity_;
+    }
 
 
-        Ogre::Vector3 movement = Ogre::Vector3::ZERO;
-        // Scripts lock the player during events and transitions.
-        if (EntityManager::getSingleton().IsPlayerLocked()){
-            // Nothing: no movement.
-        }
+    void WorldmapModule::UpdateCameraRotation(const Ogre::Real delta_time){
+        // The camera of the snow map (WM3) can't be moved by hand: it turns by itself.
+        if (map_id_ == 2) camera_yaw_ += snow_.UpdateCamera(delta_time);
         else{
         else{
-            // The game events of the movement, so the keys of the controller settings are used.
+            // L1 and R1 rotate the camera around the active entity.
             InputManager& input = InputManager::getSingleton();
             InputManager& input = InputManager::getSingleton();
-            if (input.IsGameEventPressed("walk_left")) movement.x -= 1.0f;
-            if (input.IsGameEventPressed("walk_right")) movement.x += 1.0f;
-            if (input.IsGameEventPressed("walk_up")) movement.z -= 1.0f;
-            if (input.IsGameEventPressed("walk_down")) movement.z += 1.0f;
-        }
-        bool is_walking = false;
-        if (!movement.isZeroLength()){
-          movement.normalise();
-          // The movement is relative to the camera.
-          movement = Ogre::Quaternion(Ogre::Radian(camera_yaw_), Ogre::Vector3::UNIT_Y) * movement;
-            const Ogre::Vector3 current_position = active_entity->GetPosition();
-          const char* speed_name = "walk";
-          switch (current_vehicle_){
-            case VehicleType::CHOCOBO: speed_name = "chocobo"; break;
-            case VehicleType::BUGGY: speed_name = "buggy"; break;
-            case VehicleType::HIGHWIND: speed_name = "highwind"; break;
-            case VehicleType::SUBMARINE: speed_name = "submarine"; break;
-            case VehicleType::TINY_BRONCO: speed_name = "tiny_bronco"; break;
-            default: break;
-          }
-          const Ogre::Real speed = GetSpeed(
-            speed_name, From16BitFixedPoint(8182) * 0.45f * (vehicle_active ? 2.0f : 1.0f)
-          );
-          Ogre::Vector3 requested_position = current_position
-            + movement * speed * event.timeSinceLastFrame;
-          Ogre::Vector3 surface;
-          size_t triangle_index = 0;
-          if (FindWalkableSurface(requested_position, surface, false, true, nullptr,
-              &triangle_index)){
-                if (highwind_active){
-                    Ogre::Vector3 current_surface;
-                    if (FindWalkableSurface(current_position, current_surface, false, false)){
-                        surface.y += current_position.y - current_surface.y;
-                    }
-                }
-                else if (active_entity == player_entity_){
-                  surface.y += player_height_offset_;
-                }
-                if (!EntityManager::getSingleton().IsWorldPositionBlocked(
-                  active_entity, surface
-                )){
-                    active_entity->SetPosition(surface);
-                    const TerrainTriangle& triangle = terrain_triangles_[triangle_index];
-                    EnterTriangle(triangle);
-                    // There are no encounters underwater.
-                    if (current_vehicle_ == VehicleType::ON_FOOT && map_id_ != 1){
-                        UpdateEncounters(event.timeSinceLastFrame, triangle);
-                    }
-                    const Ogre::Vector3 model_forward(0.0f, 0.0f, 1.0f);
-                    const Ogre::Vector3 move_direction(movement.x, 0.0f, movement.z);
-                    const Ogre::Quaternion heading
-                      = model_forward.getRotationTo(move_direction, Ogre::Vector3::UNIT_Y);
-                    active_model->GetModel()->getParentSceneNode()
-                      ->getParentSceneNode()->setOrientation(heading);
-                    is_walking = true;
-                }
-          }
+            if (input.IsGameEventPressed("L1")) camera_yaw_ -= CAMERA_ROTATION_SPEED * delta_time;
+            if (input.IsGameEventPressed("R1")) camera_yaw_ += CAMERA_ROTATION_SPEED * delta_time;
         }
         }
+        if (camera_yaw_ > Ogre::Math::PI) camera_yaw_ -= Ogre::Math::TWO_PI;
+        else if (camera_yaw_ < -Ogre::Math::PI) camera_yaw_ += Ogre::Math::TWO_PI;
+    }
 
 
-        // The submarine of WM2 has no walking animations.
-        if (!vehicle_active && map_id_ != 1){
-            player_entity_->PlayAnimationContinue(is_walking ? "Walk" : "Idle");
-        }
+    bool WorldmapModule::UpdateWalking(
+      ::Entity* active_entity, EntityModel* active_model, const Ogre::Real delta_time
+    ){
+        // Scripts lock the player during events and transitions.
+        if (EntityManager::getSingleton().IsPlayerLocked()) return false;
+        // The game events of the movement, so the keys of the controller settings are used.
+        Ogre::Vector3 movement = Ogre::Vector3::ZERO;
+        InputManager& input = InputManager::getSingleton();
+        if (input.IsGameEventPressed("walk_left")) movement.x -= 1.0f;
+        if (input.IsGameEventPressed("walk_right")) movement.x += 1.0f;
+        if (input.IsGameEventPressed("walk_up")) movement.z -= 1.0f;
+        if (input.IsGameEventPressed("walk_down")) movement.z += 1.0f;
+        if (movement.isZeroLength()) return false;
+        movement.normalise();
+        // The movement is relative to the camera.
+        movement = Ogre::Quaternion(Ogre::Radian(camera_yaw_), Ogre::Vector3::UNIT_Y) * movement;
 
 
-        UpdateVehicleAnimations(is_walking);
-        UpdateCamera(event.timeSinceLastFrame, false);
+        const bool vehicle_active = current_vehicle_ != VehicleType::ON_FOOT;
+        const Ogre::Vector3 current_position = active_entity->GetPosition();
+        const Ogre::Real speed = GetSpeed(
+          GetVehicleScriptName(current_vehicle_), From16BitFixedPoint(8182) * 0.45f * (vehicle_active ? 2.0f : 1.0f)
+        );
+        const Ogre::Vector3 requested_position = current_position + movement * speed * delta_time;
+        Ogre::Vector3 surface;
+        size_t triangle_index = 0;
+        if (!FindWalkableSurface(requested_position, surface, false, true, nullptr, &triangle_index)) return false;
+        if (active_entity == highwind_entity_){
+            Ogre::Vector3 current_surface;
+            if (FindWalkableSurface(current_position, current_surface, false, false)){
+                surface.y += current_position.y - current_surface.y;
+            }
+        }
+        else if (active_entity == player_entity_) surface.y += player_height_offset_;
+        if (EntityManager::getSingleton().IsWorldPositionBlocked(active_entity, surface)) return false;
+        active_entity->SetPosition(surface);
+        const TerrainTriangle& triangle = terrain_.GetTriangles()[triangle_index];
+        EnterTriangle(triangle);
+        // There are no encounters underwater.
+        if (current_vehicle_ == VehicleType::ON_FOOT && map_id_ != 1) encounters_.Update(delta_time, triangle);
+        const Ogre::Vector3 model_forward(0.0f, 0.0f, 1.0f);
+        const Ogre::Vector3 move_direction(movement.x, 0.0f, movement.z);
+        const Ogre::Quaternion heading = model_forward.getRotationTo(move_direction, Ogre::Vector3::UNIT_Y);
+        active_model->GetModel()->getParentSceneNode()->getParentSceneNode()->setOrientation(heading);
         return true;
         return true;
     }
     }
 
 
@@ -343,16 +308,18 @@ namespace VGears {
 
 
     void WorldmapModule::PauseForBattle(){
     void WorldmapModule::PauseForBattle(){
         paused_for_battle_ = true;
         paused_for_battle_ = true;
-        if (world_map_node_ != nullptr) world_map_node_->setVisible(false);
+        terrain_.SetVisible(false);
     }
     }
 
 
+    void WorldmapModule::SetEncountersLocked(const bool locked){encounters_.SetLocked(locked);}
+
     void WorldmapModule::ResumeAfterBattle(){
     void WorldmapModule::ResumeAfterBattle(){
         paused_for_battle_ = false;
         paused_for_battle_ = false;
-        encounter_frames_ = 0;
+        encounters_.ResetTimer();
         // The battle had its own music: the one of the map starts again.
         // The battle had its own music: the one of the map starts again.
         music_timer_ = 1.0f;
         music_timer_ = 1.0f;
         ScriptManager::getSingleton().RunString("if WorldMusic then WorldMusic.reset() end");
         ScriptManager::getSingleton().RunString("if WorldMusic then WorldMusic.reset() end");
-        if (world_map_node_ != nullptr) world_map_node_->setVisible(true);
+        terrain_.SetVisible(true);
         if (player_entity_ != nullptr) UpdateCamera(0, true);
         if (player_entity_ != nullptr) UpdateCamera(0, true);
     }
     }
 
 
@@ -397,16 +364,8 @@ namespace VGears {
       // The overworld is built again when the submarine surfaces: keep where everything was.
       // The overworld is built again when the submarine surfaces: keep where everything was.
       if (map_id_ == 0) SaveOverworldSnapshot();
       if (map_id_ == 0) SaveOverworldSnapshot();
       Suspend();
       Suspend();
-      if (world_map_node_ != nullptr && scene_manager_ != nullptr){
-        // Destroy the surfaces. The node is kept and reused.
-        while (world_map_node_->numAttachedObjects() > 0){
-          Ogre::MovableObject* object = world_map_node_->detachObject(static_cast<unsigned short>(0));
-          scene_manager_->destroyMovableObject(object);
-        }
-      }
-      terrain_triangles_.clear();
-      terrain_grid_.clear();
-      encounter_records_.clear();
+      terrain_.Clear();
+      encounters_.Clear();
       // The entities of the old map (player, vehicles, models and scripts).
       // The entities of the old map (player, vehicles, models and scripts).
       EntityManager::getSingleton().ClearWorld();
       EntityManager::getSingleton().ClearWorld();
       initialized_ = false;
       initialized_ = false;
@@ -433,7 +392,7 @@ namespace VGears {
         if (frame_listener_attached_) return;
         if (frame_listener_attached_) return;
         EntityManager::getSingleton().SetWorldModule();
         EntityManager::getSingleton().SetWorldModule();
         DialogsManager::getSingleton().SetWorldModule();
         DialogsManager::getSingleton().SetWorldModule();
-        world_map_node_->setVisible(true);
+        terrain_.SetVisible(true);
         // The music starts again (a field or a battle had its own).
         // The music starts again (a field or a battle had its own).
         music_timer_ = 1.0f;
         music_timer_ = 1.0f;
         ScriptManager::getSingleton().RunString("if WorldMusic then WorldMusic.reset() end");
         ScriptManager::getSingleton().RunString("if WorldMusic then WorldMusic.reset() end");
@@ -444,14 +403,13 @@ namespace VGears {
       }
       }
       map_id_ = map_id;
       map_id_ = map_id;
       camera_yaw_ = 0;
       camera_yaw_ = 0;
-      const MapLayout layout = GetMapLayout(map_id_);
-      grid_width_ = layout.width;
-      grid_height_ = layout.height;
-      origin_x_ = layout.origin_x;
-      origin_y_ = layout.origin_y;
       EntityManager::getSingleton().SetWorldModule();
       EntityManager::getSingleton().SetWorldModule();
       DialogsManager::getSingleton().SetWorldModule();
       DialogsManager::getSingleton().SetWorldModule();
-      CreateWorldMap(Root::getSingleton().getSceneManager("Scene"));
+      terrain_.Load(Root::getSingleton().getSceneManager("Scene"), map_id_);
+      const Ogre::Vector3 center = terrain_.GetCenter();
+      Ogre::Camera* camera = CameraManager::getSingleton().GetCurrentCamera();
+      camera->setPosition(Ogre::Vector3(center.x, 80.0f, center.z + 90.0f));
+      camera->lookAt(Ogre::Vector3(center.x, 0.0f, center.z));
       // Underwater (WM2): everything fades to black with the distance to the camera.
       // Underwater (WM2): everything fades to black with the distance to the camera.
       if (map_id_ == 1){
       if (map_id_ == 1){
         Root::getSingleton().getSceneManager("Scene")->setFog(
         Root::getSingleton().getSceneManager("Scene")->setFog(
@@ -460,16 +418,13 @@ namespace VGears {
       }
       }
       else Root::getSingleton().getSceneManager("Scene")->setFog(Ogre::FOG_NONE);
       else Root::getSingleton().getSceneManager("Scene")->setFog(Ogre::FOG_NONE);
       // Snow map (WM3): it always snows.
       // Snow map (WM3): it always snows.
-      SetSnowOverlay(map_id_ == 2);
+      snow_.SetVisible(map_id_ == 2);
       // The music of the map starts in the first frame.
       // The music of the map starts in the first frame.
       music_timer_ = 1.0f;
       music_timer_ = 1.0f;
       ScriptManager::getSingleton().RunString("if WorldMusic then WorldMusic.reset() end");
       ScriptManager::getSingleton().RunString("if WorldMusic then WorldMusic.reset() end");
-      snow_poles_.clear();
-      snow_pole_counter_ = 0;
       // The button that was used to get here (a menu, a field) must not count as the first pole.
       // The button that was used to get here (a menu, a field) must not count as the first pole.
       confirm_was_pressed_ = InputManager::getSingleton().IsGameEventPressed("CONFIRM");
       confirm_was_pressed_ = InputManager::getSingleton().IsGameEventPressed("CONFIRM");
-      snow_camera_remaining_ = 0.0f;
-      snow_camera_timer_ = Ogre::Math::RangeRandom(SNOW_CAMERA_MIN_WAIT, SNOW_CAMERA_MAX_WAIT);
+      snow_.Reset();
       ScriptManager::getSingleton().RunFile(
       ScriptManager::getSingleton().RunFile(
         "game/world/scripts/wm" + std::to_string(WORLD_MAP_FILE_NUMBERS[map_id_]) + ".lua"
         "game/world/scripts/wm" + std::to_string(WORLD_MAP_FILE_NUMBERS[map_id_]) + ".lua"
       );
       );
@@ -490,7 +445,7 @@ namespace VGears {
       ScriptManager::getSingleton().RunString(
       ScriptManager::getSingleton().RunString(
         "if WorldVM then WorldVM.place_models(" + std::to_string(map_id_) + ") end"
         "if WorldVM then WorldVM.place_models(" + std::to_string(map_id_) + ") end"
       );
       );
-      LoadEncounters();
+      encounters_.Load();
       initialized_ = true;
       initialized_ = true;
       Root::getSingleton().addFrameListener(this);
       Root::getSingleton().addFrameListener(this);
       frame_listener_attached_ = true;
       frame_listener_attached_ = true;
@@ -500,8 +455,8 @@ namespace VGears {
       if (!frame_listener_attached_) return;
       if (!frame_listener_attached_) return;
       Root::getSingleton().removeFrameListener(this);
       Root::getSingleton().removeFrameListener(this);
       frame_listener_attached_ = false;
       frame_listener_attached_ = false;
-      if (world_map_node_ != nullptr) world_map_node_->setVisible(false);
-      SetSnowOverlay(false);
+      terrain_.SetVisible(false);
+      snow_.SetVisible(false);
       player_entity_ = nullptr;
       player_entity_ = nullptr;
       highwind_entity_ = nullptr;
       highwind_entity_ = nullptr;
       buggy_entity_ = nullptr;
       buggy_entity_ = nullptr;

+ 71 - 74
src/modules/worldmap/WorldmapModule.h

@@ -18,13 +18,16 @@
 #include <OgreFrameListener.h>
 #include <OgreFrameListener.h>
 #include <OgreSingleton.h>
 #include <OgreSingleton.h>
 #include <OgreVector3.h>
 #include <OgreVector3.h>
-#include <deque>
 #include <map>
 #include <map>
 #include <set>
 #include <set>
 #include <vector>
 #include <vector>
 #include "common/TypeDefine.h"
 #include "common/TypeDefine.h"
 #include "engine/WorldMapInterface.h"
 #include "engine/WorldMapInterface.h"
+#include "modules/worldmap/WorldmapEncounters.h"
+#include "modules/worldmap/WorldmapSnow.h"
+#include "modules/worldmap/WorldmapTerrain.h"
 
 
+class Entity;
 class EntityModel;
 class EntityModel;
 
 
 namespace VGears {
 namespace VGears {
@@ -84,16 +87,6 @@ namespace VGears {
              */
              */
             void SetEncountersLocked(const bool locked);
             void SetEncountersLocked(const bool locked);
 
 
-            /**
-             * Sets the orientation of the model of a world map entity, in degrees. It's the
-             * orientation of the model itself, so the heading of the entity is added to it. It is
-             * for finding the right orientation of a model.
-             *
-             * @param[in] entity_name Name of the entity, like "WorldMapHighwind".
-             * @param[in] x Rotation in X.
-             * @param[in] y Rotation in Y.
-             * @param[in] z Rotation in Z.
-             */
             /**
             /**
              * Moves the model of a world map entity up or down, in world units, without moving
              * Moves the model of a world map entity up or down, in world units, without moving
              * the entity. It is for finding the right height of a model.
              * the entity. It is for finding the right height of a model.
@@ -166,6 +159,16 @@ namespace VGears {
               const float rotation_z
               const float rotation_z
             );
             );
 
 
+            /**
+             * Sets the orientation of the model of a world map entity, in degrees. It's the
+             * orientation of the model itself, so the heading of the entity is added to it. It is
+             * for finding the right orientation of a model.
+             *
+             * @param[in] entity_name Name of the entity, like "WorldMapHighwind".
+             * @param[in] x Rotation in X.
+             * @param[in] y Rotation in Y.
+             * @param[in] z Rotation in Z.
+             */
             void SetModelOrientation(const char* entity_name, const float x, const float y, const float z);
             void SetModelOrientation(const char* entity_name, const float x, const float y, const float z);
             /// Turns a model of the scripts to a direction of the game (a full turn is 256).
             /// Turns a model of the scripts to a direction of the game (a full turn is 256).
             void SetModelHeading(const char* entity_name, const float direction);
             void SetModelHeading(const char* entity_name, const float direction);
@@ -174,29 +177,6 @@ namespace VGears {
 
 
         private:
         private:
 
 
-            struct TerrainTriangle{
-                Ogre::Vector3 vertices[3];
-                uint8 walkability_type;
-                uint8 function_id;
-                int mesh_x;
-                int mesh_y;
-                /// Encounter region of the triangle, 0-15.
-                uint8 region;
-            };
-
-            /**
-             * Random encounters of a region and terrain group, from ENC_W.BIN.
-             */
-            struct EncounterRecord{
-                bool enabled;
-                /// Lower values mean more frequent encounters.
-                int rate;
-                /// Walkability type that selects this record.
-                int terrain;
-                /// Words 1-15 of the record: battle ID (10 bits) and probability (6 bits).
-                uint16 words[15];
-            };
-
             void DestroyWorldMap();
             void DestroyWorldMap();
             /**
             /**
              * State of an entity of the overworld, kept while another map is loaded.
              * State of an entity of the overworld, kept while another map is loaded.
@@ -234,7 +214,6 @@ namespace VGears {
             /// Vehicles that the story hasn't given.
             /// Vehicles that the story hasn't given.
             std::set<Ogre::String> hidden_vehicles_;
             std::set<Ogre::String> hidden_vehicles_;
 
 
-            void CreateWorldMap(Ogre::SceneManager* scene_manager);
             void CreatePlayer();
             void CreatePlayer();
                         void CreateCompanionModels();
                         void CreateCompanionModels();
                         void AddWorldModel(
                         void AddWorldModel(
@@ -246,20 +225,63 @@ namespace VGears {
                             Ogre::Real explicit_scale = 0.0f
                             Ogre::Real explicit_scale = 0.0f
                         );
                         );
             void UpdateCamera(Ogre::Real delta_time, bool snap_to_player);
             void UpdateCamera(Ogre::Real delta_time, bool snap_to_player);
-            /// Snow map (WM3): the camera turns by itself every few seconds.
-            void UpdateSnowCamera(Ogre::Real delta_time);
+
+            /**
+             * Sets the current vehicle from the entity that the player controls.
+             *
+             * @param[in] active_entity The entity that the player controls.
+             * @return False if it is not Cloud nor a vehicle (an entity of a scripted scene).
+             */
+            bool UpdateCurrentVehicle(const ::Entity* active_entity);
+
+            /**
+             * Tells the scripts the vehicle, so they play the music of the map.
+             *
+             * @param[in] delta_time Seconds since the last frame.
+             */
+            void UpdateMusic(const Ogre::Real delta_time);
+
+            /**
+             * Does what the cancel and action buttons do: unboard, surface, dive or place a snow pole.
+             *
+             * @param[in] active_entity The entity that the player controls.
+             * @return True if the map changed, so the entities are not valid anymore.
+             */
+            bool HandleActionButtons(::Entity* active_entity);
+
+            /**
+             * Gets the model of the entity that the player controls.
+             *
+             * @param[in] active_entity The entity that the player controls.
+             * @return Its model.
+             */
+            EntityModel* GetActiveModel(const ::Entity* active_entity) const;
+
+            /**
+             * Rotates the camera, with the buttons or by itself in the snow map.
+             *
+             * @param[in] delta_time Seconds since the last frame.
+             */
+            void UpdateCameraRotation(const Ogre::Real delta_time);
+
+            /**
+             * Moves the entity that the player controls over the ground, with the movement keys.
+             *
+             * @param[in] active_entity The entity that the player controls.
+             * @param[in] active_model Its model, which is turned to the direction of the movement.
+             * @param[in] delta_time Seconds since the last frame.
+             * @return True if it moved.
+             */
+            bool UpdateWalking(::Entity* active_entity, EntityModel* active_model, const Ogre::Real delta_time);
+
             /// Snow map (WM3): puts a pole where the player is (only 4 poles exist, the oldest goes away).
             /// Snow map (WM3): puts a pole where the player is (only 4 poles exist, the oldest goes away).
             void PlaceSnowPole();
             void PlaceSnowPole();
             bool FindWalkableSurface(
             bool FindWalkableSurface(
                             const Ogre::Vector3& position, Ogre::Vector3& surface,
                             const Ogre::Vector3& position, Ogre::Vector3& surface,
                             bool grass_only = false, bool require_walkable = true,
                             bool grass_only = false, bool require_walkable = true,
                             uint8* walkability_type = nullptr,
                             uint8* walkability_type = nullptr,
-                            size_t* triangle_index = nullptr,
-                            bool use_index = true
+                            size_t* triangle_index = nullptr
             ) const;
             ) const;
-            /// Groups the triangles of the terrain by the cell of a grid they touch, so the search of the
-            /// triangle under a position only checks a few of them.
-            void BuildTerrainIndex();
             bool IsActiveTerrainAllowed(uint8 walkability_type) const;
             bool IsActiveTerrainAllowed(uint8 walkability_type) const;
             /**
             /**
              * Runs the function of a triangle when it is entered, if it changed.
              * Runs the function of a triangle when it is entered, if it changed.
@@ -339,27 +361,15 @@ namespace VGears {
             static const char* GetVehicleScriptName(const VehicleType vehicle);
             static const char* GetVehicleScriptName(const VehicleType vehicle);
 
 
             void TriggerTriangleFunction(const TerrainTriangle& triangle);
             void TriggerTriangleFunction(const TerrainTriangle& triangle);
-            void LoadEncounters();
-            void UpdateEncounters(const float delta_time, const TerrainTriangle& triangle);
-            int RollEncounterBattle(const EncounterRecord& record) const;
-
-            std::vector<EncounterRecord> encounter_records_;
-            float encounter_frames_;
-            int encounter_accumulator_;
-            int encounter_last_battle_;
-            bool encounters_locked_;
+
+            /// Surfaces of the loaded map.
+            WorldmapTerrain terrain_;
+            /// Random battles.
+            WorldmapEncounters encounters_;
+            /// What is special in the snow map (WM3).
+            WorldmapSnow snow_;
             bool paused_for_battle_;
             bool paused_for_battle_;
 
 
-            std::vector<TerrainTriangle> terrain_triangles_;
-            /// Indices of the triangles (ascending) that touch each cell of the grid, row by row.
-            std::vector<std::vector<uint32>> terrain_grid_;
-            float terrain_grid_min_x_ = 0.0f;
-            float terrain_grid_min_z_ = 0.0f;
-            float terrain_grid_cell_ = 1.0f;
-            int terrain_grid_columns_ = 0;
-            int terrain_grid_rows_ = 0;
-            Ogre::SceneManager* scene_manager_;
-            Ogre::SceneNode* world_map_node_;
             EntityModel* player_entity_;
             EntityModel* player_entity_;
             EntityModel* highwind_entity_;
             EntityModel* highwind_entity_;
             EntityModel* buggy_entity_;
             EntityModel* buggy_entity_;
@@ -373,9 +383,6 @@ namespace VGears {
             int active_function_id_;
             int active_function_id_;
             /// Loaded map ID, -1 if none.
             /// Loaded map ID, -1 if none.
             int map_id_;
             int map_id_;
-            /// Size of the map in blocks.
-            size_t grid_width_;
-            size_t grid_height_;
             /// Rotation of the camera around the active entity, in radians. Positive is to the right.
             /// Rotation of the camera around the active entity, in radians. Positive is to the right.
             float camera_yaw_;
             float camera_yaw_;
             /// True while the active entity is a flying vehicle.
             /// True while the active entity is a flying vehicle.
@@ -386,9 +393,6 @@ namespace VGears {
             float flight_heading_;
             float flight_heading_;
             /// Height of the vehicle.
             /// Height of the vehicle.
             float flight_y_;
             float flight_y_;
-            /// Position of the first block of the map in the 9x7 block grid of the world.
-            size_t origin_x_;
-            size_t origin_y_;
             bool initialized_;
             bool initialized_;
             bool frame_listener_attached_;
             bool frame_listener_attached_;
             bool cancel_was_pressed_;
             bool cancel_was_pressed_;
@@ -409,13 +413,6 @@ namespace VGears {
             };
             };
             /// Cameras set by the scripts, by name (the ones that are not set use the default one).
             /// Cameras set by the scripts, by name (the ones that are not set use the default one).
             std::map<std::string, CameraSettings> camera_settings_;
             std::map<std::string, CameraSettings> camera_settings_;
-            /// Snow map: seconds until the next automatic turn of the camera.
-            float snow_camera_timer_ = 0.0f;
-            /// Snow map: radians left of the turn that is going on, with the sign of its direction.
-            float snow_camera_remaining_ = 0.0f;
-            /// Snow map: the poles that exist (names of the entities), the oldest first.
-            std::deque<std::string> snow_poles_;
-            unsigned int snow_pole_counter_ = 0;
             enum class TransitionStage{
             enum class TransitionStage{
                 /// No animation going on.
                 /// No animation going on.
                 NONE,
                 NONE,

+ 21 - 11
src/modules/worldmap/WorldmapSnow.cpp

@@ -19,6 +19,7 @@
 #include <OgreException.h>
 #include <OgreException.h>
 #include <OgreLogManager.h>
 #include <OgreLogManager.h>
 #include <OgreMaterialManager.h>
 #include <OgreMaterialManager.h>
+#include <OgreMath.h>
 #include <OgreOverlaySystem.h>
 #include <OgreOverlaySystem.h>
 #include <OgreResourceGroupManager.h>
 #include <OgreResourceGroupManager.h>
 #include <OgreRoot.h>
 #include <OgreRoot.h>
@@ -31,8 +32,6 @@
 #include <Overlay/OgrePanelOverlayElement.h>
 #include <Overlay/OgrePanelOverlayElement.h>
 #include "engine/ApplicationInterface.h"
 #include "engine/ApplicationInterface.h"
 #include "engine/entity/EntityManager.h"
 #include "engine/entity/EntityManager.h"
-#include "engine/entity/EntityModel.h"
-#include "modules/worldmap/WorldmapModule.h"
 #include "modules/worldmap/WorldmapConstants.h"
 #include "modules/worldmap/WorldmapConstants.h"
 #include "modules/worldmap/WorldmapTextures.h"
 #include "modules/worldmap/WorldmapTextures.h"
 
 
@@ -40,6 +39,13 @@ namespace VGears {
 
 
     using namespace Ogre;
     using namespace Ogre;
 
 
+    /// Snow map (WM3): the camera turns by itself after this many seconds (random in the range) ...
+    static const float SNOW_CAMERA_MIN_WAIT = 6.0f;
+    static const float SNOW_CAMERA_MAX_WAIT = 12.0f;
+    /// ... by this many degrees (random in the range, to any side), at the speed of the manual rotation.
+    static const float SNOW_CAMERA_MIN_DEGREES = 30.0f;
+    static const float SNOW_CAMERA_MAX_DEGREES = 160.0f;
+
     /// Snow map (WM3): how many poles can exist at the same time.
     /// Snow map (WM3): how many poles can exist at the same time.
     static const size_t SNOW_MAX_POLES = 4;
     static const size_t SNOW_MAX_POLES = 4;
 
 
@@ -64,7 +70,7 @@ namespace VGears {
         // HIDDEN: {"snow5", 0.30f, -0.015f, 0.090f, 1.0f, 0.75f}
         // HIDDEN: {"snow5", 0.30f, -0.015f, 0.090f, 1.0f, 0.75f}
     };
     };
 
 
-    void SetSnowOverlay(const bool visible){
+    void WorldmapSnow::SetVisible(const bool visible){
         Ogre::OverlayManager& manager = Ogre::OverlayManager::getSingleton();
         Ogre::OverlayManager& manager = Ogre::OverlayManager::getSingleton();
         Ogre::Overlay* overlay = manager.getByName("WorldMapSnow");
         Ogre::Overlay* overlay = manager.getByName("WorldMapSnow");
         if (overlay == nullptr){
         if (overlay == nullptr){
@@ -123,10 +129,17 @@ namespace VGears {
         );
         );
     }
     }
 
 
-    void WorldmapModule::UpdateSnowCamera(Ogre::Real delta_time){
+    void WorldmapSnow::Reset(){
+        snow_poles_.clear();
+        snow_pole_counter_ = 0;
+        snow_camera_remaining_ = 0.0f;
+        snow_camera_timer_ = Ogre::Math::RangeRandom(SNOW_CAMERA_MIN_WAIT, SNOW_CAMERA_MAX_WAIT);
+    }
+
+    float WorldmapSnow::UpdateCamera(const float delta_time){
       if (snow_camera_remaining_ == 0.0f){
       if (snow_camera_remaining_ == 0.0f){
         snow_camera_timer_ -= delta_time;
         snow_camera_timer_ -= delta_time;
-        if (snow_camera_timer_ > 0.0f) return;
+        if (snow_camera_timer_ > 0.0f) return 0.0f;
         const float degrees = Ogre::Math::RangeRandom(SNOW_CAMERA_MIN_DEGREES, SNOW_CAMERA_MAX_DEGREES);
         const float degrees = Ogre::Math::RangeRandom(SNOW_CAMERA_MIN_DEGREES, SNOW_CAMERA_MAX_DEGREES);
         const float direction = Ogre::Math::UnitRandom() < 0.5f ? -1.0f : 1.0f;
         const float direction = Ogre::Math::UnitRandom() < 0.5f ? -1.0f : 1.0f;
         snow_camera_remaining_ = direction * Ogre::Math::DegreesToRadians(degrees);
         snow_camera_remaining_ = direction * Ogre::Math::DegreesToRadians(degrees);
@@ -134,22 +147,19 @@ namespace VGears {
       }
       }
       const float step = std::min(std::abs(snow_camera_remaining_), CAMERA_ROTATION_SPEED * delta_time);
       const float step = std::min(std::abs(snow_camera_remaining_), CAMERA_ROTATION_SPEED * delta_time);
       const float signed_step = snow_camera_remaining_ < 0.0f ? -step : step;
       const float signed_step = snow_camera_remaining_ < 0.0f ? -step : step;
-      camera_yaw_ += signed_step;
       snow_camera_remaining_ -= signed_step;
       snow_camera_remaining_ -= signed_step;
       if (std::abs(snow_camera_remaining_) < 0.0001f) snow_camera_remaining_ = 0.0f;
       if (std::abs(snow_camera_remaining_) < 0.0001f) snow_camera_remaining_ = 0.0f;
+      return signed_step;
     }
     }
 
 
-    void WorldmapModule::PlaceSnowPole(){
-      if (player_entity_ == nullptr) return;
+    void WorldmapSnow::PlacePole(const PoleCreator& create){
       // The oldest pole goes away when there is no room for another one.
       // The oldest pole goes away when there is no room for another one.
       while (snow_poles_.size() >= SNOW_MAX_POLES){
       while (snow_poles_.size() >= SNOW_MAX_POLES){
         EntityManager::getSingleton().RemoveWorldMapEntity(snow_poles_.front());
         EntityManager::getSingleton().RemoveWorldMapEntity(snow_poles_.front());
         snow_poles_.pop_front();
         snow_poles_.pop_front();
       }
       }
-      const Ogre::Vector3 position = player_entity_->GetPosition();
       const std::string name = "snowpole_" + std::to_string(snow_pole_counter_++);
       const std::string name = "snowpole_" + std::to_string(snow_pole_counter_++);
-      // The model and scale of the snow poles of the game (WorldMapModels: djc, 0x300).
-      AddWorldModelFromScript(name.c_str(), "djc", position.x, position.z, 0x300, 0, 0.0f, 0.0f, 0.0f);
+      create(name);
       if (EntityManager::getSingleton().GetEntity("WorldMap" + name) != nullptr){
       if (EntityManager::getSingleton().GetEntity("WorldMap" + name) != nullptr){
         snow_poles_.push_back("WorldMap" + name);
         snow_poles_.push_back("WorldMap" + name);
       }
       }

+ 51 - 5
src/modules/worldmap/WorldmapSnow.h

@@ -15,14 +15,60 @@
 
 
 #pragma once
 #pragma once
 
 
-
+#include <deque>
+#include <functional>
+#include <string>
 
 
 namespace VGears {
 namespace VGears {
 
 
     /**
     /**
-     * Shows or hides the blizzard of WM3, which is drawn over the screen. It is created the first time.
-     *
-     * @param[in] visible True to show it.
+     * What is special in the snow map (WM3): the blizzard, the camera that turns by itself and the
+     * poles that the player can place.
      */
      */
-    void SetSnowOverlay(const bool visible);
+    class WorldmapSnow{
+
+        public:
+
+            /**
+             * Creates the model of a pole. It receives the name of the entity, without the prefix "WorldMap".
+             */
+            typedef std::function<void(const std::string& name)> PoleCreator;
+
+            /**
+             * Shows or hides the blizzard, which is drawn over the screen. It is created the first time.
+             *
+             * @param[in] visible True to show it.
+             */
+            void SetVisible(const bool visible);
+
+            /**
+             * Forgets the poles and starts the wait for the next turn of the camera. For a map that is loaded.
+             */
+            void Reset();
+
+            /**
+             * Turns the camera by itself every few seconds.
+             *
+             * @param[in] delta_time Seconds since the last frame.
+             * @return What the camera turns in this frame, in radians.
+             */
+            float UpdateCamera(const float delta_time);
+
+            /**
+             * Places a pole. Only 4 poles exist, the oldest one goes away.
+             *
+             * @param[in] create Creates the model of the new pole.
+             */
+            void PlacePole(const PoleCreator& create);
+
+        private:
+
+            /// Seconds until the next automatic turn of the camera.
+            float snow_camera_timer_ = 0.0f;
+            /// Radians left of the turn that is going on, with the sign of its direction.
+            float snow_camera_remaining_ = 0.0f;
+            /// The poles that exist (names of the entities), the oldest first.
+            std::deque<std::string> snow_poles_;
+            unsigned int snow_pole_counter_ = 0;
+    };
 }
 }

+ 59 - 132
src/modules/worldmap/WorldmapTerrain.cpp

@@ -13,7 +13,7 @@
  * GNU General Public License for more details.
  * GNU General Public License for more details.
  */
  */
 
 
-#include "modules/worldmap/WorldmapModule.h"
+#include "modules/worldmap/WorldmapTerrain.h"
 #include <algorithm>
 #include <algorithm>
 #include <cmath>
 #include <cmath>
 #include <limits>
 #include <limits>
@@ -22,12 +22,8 @@
 #include <OgreException.h>
 #include <OgreException.h>
 #include <OgreLogManager.h>
 #include <OgreLogManager.h>
 #include <OgreManualObject.h>
 #include <OgreManualObject.h>
-#include <OgreRoot.h>
 #include <OgreSceneManager.h>
 #include <OgreSceneManager.h>
-#include "engine/entity/EntityManager.h"
-#include "engine/graphics/CameraManager.h"
-#include "engine/script/ScriptManager.h"
-#include "modules/worldmap/WorldmapConstants.h"
+#include <OgreSceneNode.h>
 #include "modules/worldmap/WorldmapData.h"
 #include "modules/worldmap/WorldmapData.h"
 #include "modules/worldmap/WorldmapTextures.h"
 #include "modules/worldmap/WorldmapTextures.h"
 
 
@@ -35,13 +31,41 @@ namespace VGears {
 
 
     using namespace Ogre;
     using namespace Ogre;
 
 
-    /**
-     * Width in meshes of the grid that the world map scripts use to index meshes (mesh_y * 36 +
-     * mesh_x). It is the same in every map, regardless of the size of the map.
-     */
-    static const int WORLD_MAP_SCRIPT_MESH_STRIDE = 36;
+    WorldmapTerrain::WorldmapTerrain(){}
 
 
-    void WorldmapModule::CreateWorldMap(SceneManager* scene_manager){
+    WorldmapTerrain::~WorldmapTerrain(){
+        if (scene_manager_ != nullptr && world_map_node_ != nullptr){
+            scene_manager_->getRootSceneNode()->removeAndDestroyChild("WorldMapTerrain");
+        }
+    }
+
+    void WorldmapTerrain::Clear(){
+        if (world_map_node_ != nullptr && scene_manager_ != nullptr){
+            // Destroy the surfaces. The node is kept and reused.
+            while (world_map_node_->numAttachedObjects() > 0){
+                Ogre::MovableObject* object = world_map_node_->detachObject(static_cast<unsigned short>(0));
+                scene_manager_->destroyMovableObject(object);
+            }
+        }
+        triangles_.clear();
+        terrain_grid_.clear();
+    }
+
+    void WorldmapTerrain::SetVisible(const bool visible){
+        if (world_map_node_ != nullptr) world_map_node_->setVisible(visible);
+    }
+
+    const std::vector<TerrainTriangle>& WorldmapTerrain::GetTriangles() const{return triangles_;}
+
+    Ogre::Vector3 WorldmapTerrain::GetCenter() const{
+        const float space = From16BitFixedPoint(8182);
+        return Ogre::Vector3(
+          space * (origin_x_ * 4.0f + grid_width_ * 2.0f), 0.0f,
+          space * (origin_y_ * 4.0f + grid_height_ * 2.0f)
+        );
+    }
+
+    void WorldmapTerrain::Load(SceneManager* scene_manager, const int map_id){
       scene_manager_ = scene_manager;
       scene_manager_ = scene_manager;
       // The node is kept when a map is replaced.
       // The node is kept when a map is replaced.
       if (world_map_node_ == nullptr){
       if (world_map_node_ == nullptr){
@@ -49,16 +73,21 @@ namespace VGears {
           ->createChildSceneNode("WorldMapTerrain");
           ->createChildSceneNode("WorldMapTerrain");
       }
       }
       world_map_node_->setVisible(true);
       world_map_node_->setVisible(true);
+      const MapLayout layout = GetMapLayout(map_id);
+      grid_width_ = layout.width;
+      grid_height_ = layout.height;
+      origin_x_ = layout.origin_x;
+      origin_y_ = layout.origin_y;
         std::vector<VGears::WorldmapFileSerializer::Block> blocks
         std::vector<VGears::WorldmapFileSerializer::Block> blocks
-          = LoadWorldMap("WM" + std::to_string(WORLD_MAP_FILE_NUMBERS[map_id_]) + ".MAP");
-        if (GetTextureIdOffset(map_id_) != 0){
+          = LoadWorldMap("WM" + std::to_string(WORLD_MAP_FILE_NUMBERS[map_id]) + ".MAP");
+        if (GetTextureIdOffset(map_id) != 0){
           for (auto& block : blocks) for (auto& mesh : block.meshes) for (auto& triangle : mesh.triangles){
           for (auto& block : blocks) for (auto& mesh : block.meshes) for (auto& triangle : mesh.triangles){
-            triangle.TextureInfo += GetTextureIdOffset(map_id_);
+            triangle.TextureInfo += GetTextureIdOffset(map_id);
           }
           }
         }
         }
         const size_t texture_count = WORLD_MAP_TEXTURE_COUNT;
         const size_t texture_count = WORLD_MAP_TEXTURE_COUNT;
         // WM0 has extra blocks after the 9x7 grid: the alternate shapes of the story progress.
         // WM0 has extra blocks after the 9x7 grid: the alternate shapes of the story progress.
-        const size_t base_block_count = map_id_ == 0
+        const size_t base_block_count = map_id == 0
           ? std::min(blocks.size(), size_t(63)) : blocks.size();
           ? std::min(blocks.size(), size_t(63)) : blocks.size();
         const float space = From16BitFixedPoint(8182);
         const float space = From16BitFixedPoint(8182);
         std::map<uint16, ManualObject*> texture_objects;
         std::map<uint16, ManualObject*> texture_objects;
@@ -107,7 +136,7 @@ namespace VGears {
                     terrain_triangle.mesh_y = static_cast<int>(map_y * 4 + mesh_y);
                     terrain_triangle.mesh_y = static_cast<int>(map_y * 4 + mesh_y);
                     // The 5 lower bits of the location are the region of the random encounters.
                     // The 5 lower bits of the location are the region of the random encounters.
                     terrain_triangle.region = std::min<int>(triangle.Location & 0x1F, 15);
                     terrain_triangle.region = std::min<int>(triangle.Location & 0x1F, 15);
-                    terrain_triangles_.push_back(terrain_triangle);
+                    triangles_.push_back(terrain_triangle);
 
 
                     if (unavailable_texture_ids.find(triangle.TextureInfo)
                     if (unavailable_texture_ids.find(triangle.TextureInfo)
                       != unavailable_texture_ids.end()){
                       != unavailable_texture_ids.end()){
@@ -189,23 +218,17 @@ namespace VGears {
             world_map_node_->attachObject(texture_object.second);
             world_map_node_->attachObject(texture_object.second);
         }
         }
 
 
-        BuildTerrainIndex();
-
-        const float map_center_x = space * (origin_x_ * 4.0f + grid_width_ * 2.0f);
-        const float map_center_z = space * (origin_y_ * 4.0f + grid_height_ * 2.0f);
-        Ogre::Camera* camera = CameraManager::getSingleton().GetCurrentCamera();
-        camera->setPosition(Ogre::Vector3(map_center_x, 80.0f, map_center_z + 90.0f));
-        camera->lookAt(Ogre::Vector3(map_center_x, 0.0f, map_center_z));
+        BuildIndex();
     }
     }
 
 
-    void WorldmapModule::BuildTerrainIndex(){
+    void WorldmapTerrain::BuildIndex(){
         terrain_grid_.clear();
         terrain_grid_.clear();
         terrain_grid_columns_ = 0;
         terrain_grid_columns_ = 0;
         terrain_grid_rows_ = 0;
         terrain_grid_rows_ = 0;
-        if (terrain_triangles_.empty()) return;
+        if (triangles_.empty()) return;
         float min_x = std::numeric_limits<float>::max(), min_z = min_x;
         float min_x = std::numeric_limits<float>::max(), min_z = min_x;
         float max_x = -min_x, max_z = -min_x;
         float max_x = -min_x, max_z = -min_x;
-        for (const TerrainTriangle& triangle : terrain_triangles_){
+        for (const TerrainTriangle& triangle : triangles_){
             for (const Ogre::Vector3& vertex : triangle.vertices){
             for (const Ogre::Vector3& vertex : triangle.vertices){
                 min_x = std::min(min_x, vertex.x); max_x = std::max(max_x, vertex.x);
                 min_x = std::min(min_x, vertex.x); max_x = std::max(max_x, vertex.x);
                 min_z = std::min(min_z, vertex.z); max_z = std::max(max_z, vertex.z);
                 min_z = std::min(min_z, vertex.z); max_z = std::max(max_z, vertex.z);
@@ -220,8 +243,8 @@ namespace VGears {
         terrain_grid_.resize(static_cast<size_t>(terrain_grid_columns_) * terrain_grid_rows_);
         terrain_grid_.resize(static_cast<size_t>(terrain_grid_columns_) * terrain_grid_rows_);
         // The tolerance of the search (a point a little outside of the edge still counts).
         // The tolerance of the search (a point a little outside of the edge still counts).
         const float margin = 0.01f;
         const float margin = 0.01f;
-        for (size_t i = 0; i < terrain_triangles_.size(); ++i){
-            const TerrainTriangle& triangle = terrain_triangles_[i];
+        for (size_t i = 0; i < triangles_.size(); ++i){
+            const TerrainTriangle& triangle = triangles_[i];
             float t_min_x = triangle.vertices[0].x, t_max_x = t_min_x;
             float t_min_x = triangle.vertices[0].x, t_max_x = t_min_x;
             float t_min_z = triangle.vertices[0].z, t_max_z = t_min_z;
             float t_min_z = triangle.vertices[0].z, t_max_z = t_min_z;
             for (const Ogre::Vector3& vertex : triangle.vertices){
             for (const Ogre::Vector3& vertex : triangle.vertices){
@@ -241,31 +264,31 @@ namespace VGears {
         size_t entries = 0;
         size_t entries = 0;
         for (const auto& cell : terrain_grid_) entries += cell.size();
         for (const auto& cell : terrain_grid_) entries += cell.size();
         LogManager::getSingleton().logMessage(
         LogManager::getSingleton().logMessage(
-          "World map terrain index: " + std::to_string(terrain_triangles_.size()) + " triangles in "
+          "World map terrain index: " + std::to_string(triangles_.size()) + " triangles in "
           + std::to_string(terrain_grid_columns_) + "x" + std::to_string(terrain_grid_rows_) + " cells, "
           + std::to_string(terrain_grid_columns_) + "x" + std::to_string(terrain_grid_rows_) + " cells, "
           + std::to_string(entries) + " entries"
           + std::to_string(entries) + " entries"
         );
         );
     }
     }
 
 
-    bool WorldmapModule::FindWalkableSurface(
+    bool WorldmapTerrain::FindSurface(
       const Ogre::Vector3& position, Ogre::Vector3& surface, bool grass_only,
       const Ogre::Vector3& position, Ogre::Vector3& surface, bool grass_only,
-      bool require_walkable, uint8* walkability_type, size_t* triangle_index, bool use_index
+      const WalkableCheck& check, uint8* walkability_type, size_t* triangle_index
     ) const{
     ) const{
         bool found = false;
         bool found = false;
         Ogre::Real closest_height_distance = std::numeric_limits<Ogre::Real>::max();
         Ogre::Real closest_height_distance = std::numeric_limits<Ogre::Real>::max();
         // Only the triangles of the cell of the position (the index is in ascending order, so the result
         // Only the triangles of the cell of the position (the index is in ascending order, so the result
         // is the same as with all of them).
         // is the same as with all of them).
         const std::vector<uint32>* cell_triangles = nullptr;
         const std::vector<uint32>* cell_triangles = nullptr;
-        if (use_index && !terrain_grid_.empty()){
+        if (!terrain_grid_.empty()){
             const int column = static_cast<int>(std::floor((position.x - terrain_grid_min_x_) / terrain_grid_cell_));
             const int column = static_cast<int>(std::floor((position.x - terrain_grid_min_x_) / terrain_grid_cell_));
             const int row = static_cast<int>(std::floor((position.z - terrain_grid_min_z_) / terrain_grid_cell_));
             const int row = static_cast<int>(std::floor((position.z - terrain_grid_min_z_) / terrain_grid_cell_));
             if (column < 0 || row < 0 || column >= terrain_grid_columns_ || row >= terrain_grid_rows_) return false;
             if (column < 0 || row < 0 || column >= terrain_grid_columns_ || row >= terrain_grid_rows_) return false;
             cell_triangles = &terrain_grid_[static_cast<size_t>(row) * terrain_grid_columns_ + column];
             cell_triangles = &terrain_grid_[static_cast<size_t>(row) * terrain_grid_columns_ + column];
         }
         }
-        const size_t candidate_count = cell_triangles != nullptr ? cell_triangles->size() : terrain_triangles_.size();
+        const size_t candidate_count = cell_triangles != nullptr ? cell_triangles->size() : triangles_.size();
         for (size_t candidate = 0; candidate < candidate_count; ++candidate){
         for (size_t candidate = 0; candidate < candidate_count; ++candidate){
             const size_t i = cell_triangles != nullptr ? (*cell_triangles)[candidate] : candidate;
             const size_t i = cell_triangles != nullptr ? (*cell_triangles)[candidate] : candidate;
-            const TerrainTriangle& triangle = terrain_triangles_[i];
+            const TerrainTriangle& triangle = triangles_[i];
             if (grass_only
             if (grass_only
               && triangle.walkability_type != VGears::WorldmapFileSerializer::GRASS){
               && triangle.walkability_type != VGears::WorldmapFileSerializer::GRASS){
                 continue;
                 continue;
@@ -293,11 +316,7 @@ namespace VGears {
             const Ogre::Real height_distance = Ogre::Math::Abs(height - position.y);
             const Ogre::Real height_distance = Ogre::Math::Abs(height - position.y);
             if (height_distance >= closest_height_distance) continue;
             if (height_distance >= closest_height_distance) continue;
             closest_height_distance = height_distance;
             closest_height_distance = height_distance;
-            found = !require_walkable || (map_id_ == 1
-              // Underwater: every terrain type is allowed, but there is a height limit.
-              ? (!UNDERWATER_HEIGHT_LIMIT_ENABLED
-                || height + FLIGHT_MIN_CLEARANCE <= UNDERWATER_MAX_HEIGHT)
-              : IsActiveTerrainAllowed(triangle.walkability_type));
+            found = !check || check(triangle, height);
             surface = Ogre::Vector3(position.x, height, position.z);
             surface = Ogre::Vector3(position.x, height, position.z);
             if (walkability_type != nullptr) *walkability_type = triangle.walkability_type;
             if (walkability_type != nullptr) *walkability_type = triangle.walkability_type;
             if (triangle_index != nullptr) *triangle_index = i;
             if (triangle_index != nullptr) *triangle_index = i;
@@ -305,96 +324,4 @@ namespace VGears {
         return found;
         return found;
     }
     }
 
 
-    void WorldmapModule::ClearVehicleTerrains(){
-        active_vehicle_terrain_types_.clear();
-    }
-
-    void WorldmapModule::AddVehicleTerrain(const char* terrain_name){
-        if (terrain_name == nullptr) return;
-        const auto terrain = GetWorldMapTerrainTypes().find(terrain_name);
-        if (terrain == GetWorldMapTerrainTypes().end()){
-            LogManager::getSingleton().logMessage(
-              "Unknown world-map vehicle terrain '" + Ogre::String(terrain_name) + "'."
-            );
-            return;
-        }
-        if (std::find(
-              active_vehicle_terrain_types_.begin(), active_vehicle_terrain_types_.end(),
-              terrain->second
-            ) == active_vehicle_terrain_types_.end()){
-            active_vehicle_terrain_types_.push_back(terrain->second);
-        }
-    }
-
-    bool WorldmapModule::IsActiveTerrainAllowed(uint8 walkability_type) const{
-        if (current_vehicle_ == VehicleType::ON_FOOT){
-            return IsFootWalkable(walkability_type);
-        }
-        return std::find(
-          active_vehicle_terrain_types_.begin(), active_vehicle_terrain_types_.end(),
-          walkability_type
-        ) != active_vehicle_terrain_types_.end();
-    }
-
-    void WorldmapModule::EnterTriangle(const TerrainTriangle& triangle){
-        const int mesh_index = triangle.mesh_y * WORLD_MAP_SCRIPT_MESH_STRIDE + triangle.mesh_x;
-        if (triangle.function_id >= 3){
-            if (mesh_index != active_function_mesh_index_
-              || triangle.function_id != active_function_id_){
-                TriggerTriangleFunction(triangle);
-            }
-            active_function_mesh_index_ = mesh_index;
-            active_function_id_ = triangle.function_id;
-        }
-        else{
-            active_function_mesh_index_ = -1;
-            active_function_id_ = -1;
-        }
-    }
-
-    void WorldmapModule::TriggerTriangleFunction(const TerrainTriangle& triangle){
-        ScriptEntity* world_map_script
-          = ScriptManager::getSingleton().GetScriptEntityByName(
-              ScriptManager::SYSTEM, "WorldMap"
-            );
-        if (world_map_script == nullptr) return;
-
-        const int mesh_index = triangle.mesh_y * WORLD_MAP_SCRIPT_MESH_STRIDE + triangle.mesh_x;
-        // What the function can know about who entered the triangle (see WorldVM.can_enter).
-        ScriptManager::getSingleton().RunString(
-          std::string("System.WorldMap.vehicle = \"") + GetVehicleScriptName(current_vehicle_)
-          + "\"; System.WorldMap.landing = " + (landing_trigger_ ? "true" : "false")
-        );
-        ScriptManager::getSingleton().ScriptRequest(
-          world_map_script, "on_triangle_enter", 1,
-          std::to_string(mesh_index), std::to_string(triangle.function_id - 3), false, false
-        );
-    }
-
-      Ogre::String WorldmapModule::GetTerrainTypeUnderEntity(const char* entity_name) const{
-        if (entity_name == nullptr) return "";
-        const ::Entity* entity = EntityManager::getSingleton().GetEntity(entity_name);
-        if (entity == nullptr) return "";
-
-        Ogre::Vector3 surface;
-        uint8 walkability_type = 0;
-        if (!FindWalkableSurface(entity->GetPosition(), surface, false, false, &walkability_type)){
-          return "";
-        }
-        return GetWorldMapTerrainName(walkability_type);
-      }
-
-      int WorldmapModule::GetTerrainTriangleUnderEntity(const char* entity_name) const{
-        if (entity_name == nullptr) return -1;
-        const ::Entity* entity = EntityManager::getSingleton().GetEntity(entity_name);
-        if (entity == nullptr) return -1;
-
-        Ogre::Vector3 surface;
-        size_t triangle_index = 0;
-        if (!FindWalkableSurface(entity->GetPosition(), surface, false, false, nullptr, &triangle_index)){
-          return -1;
-        }
-        return static_cast<int>(triangle_index);
-      }
-
 } // namespace VGears
 } // namespace VGears

+ 144 - 0
src/modules/worldmap/WorldmapTerrain.h

@@ -0,0 +1,144 @@
+/*
+ * 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 <OgreVector3.h>
+#include "common/TypeDefine.h"
+#include "formats/worldmap/WorldmapFileSerializer.h"
+
+namespace Ogre{
+    class SceneManager;
+    class SceneNode;
+}
+
+namespace VGears {
+
+    /**
+     * A triangle of the terrain of a world map.
+     */
+    struct TerrainTriangle{
+        /// Corners of the triangle, in world units.
+        Ogre::Vector3 vertices[3];
+        /// Type of the terrain.
+        uint8 walkability_type;
+        /// Function of the world map script that runs when the triangle is entered, if 3 or more.
+        uint8 function_id;
+        /// Column of its mesh in the 9x7 block grid of the world.
+        int mesh_x;
+        /// Row of its mesh in the 9x7 block grid of the world.
+        int mesh_y;
+        /// Encounter region of the triangle, 0-15.
+        uint8 region;
+    };
+
+    /**
+     * The terrain of the loaded world map: its surfaces in the scene, and the search of the ground
+     * under a position.
+     */
+    class WorldmapTerrain{
+
+        public:
+
+            /**
+             * Tells if a triangle can be walked, at the height of the searched position.
+             */
+            typedef std::function<bool(const TerrainTriangle& triangle, Ogre::Real height)> WalkableCheck;
+
+            /**
+             * Constructor.
+             */
+            WorldmapTerrain();
+
+            /**
+             * Destructor. Removes the terrain from the scene.
+             */
+            ~WorldmapTerrain();
+
+            /**
+             * Loads the terrain of a map and shows it. {@see Clear} must be called before loading another one.
+             *
+             * @param[in] scene_manager Scene where the terrain is added.
+             * @param[in] map_id 0 is WM0, 1 WM2 and 2 WM3.
+             */
+            void Load(Ogre::SceneManager* scene_manager, const int map_id);
+
+            /**
+             * Removes the surfaces and the triangles of the loaded map.
+             */
+            void Clear();
+
+            /**
+             * Shows or hides the terrain.
+             *
+             * @param[in] visible True to show it.
+             */
+            void SetVisible(const bool visible);
+
+            /**
+             * Searches the ground under a position: of the triangles over or under it, the one with the closest
+             * height.
+             *
+             * @param[in] position Position to search at.
+             * @param[out] surface The position on the ground. Only set if there is a triangle.
+             * @param[in] grass_only True to only search grass.
+             * @param[in] check Tells if the triangle can be walked. If empty, any triangle can.
+             * @param[out] walkability_type Type of the terrain found. Can be nullptr.
+             * @param[out] triangle_index Index of the triangle found. Can be nullptr.
+             * @return True if the closest triangle can be walked.
+             */
+            bool FindSurface(
+              const Ogre::Vector3& position, Ogre::Vector3& surface, bool grass_only,
+              const WalkableCheck& check, uint8* walkability_type, size_t* triangle_index
+            ) const;
+
+            /**
+             * Gets the triangles of the loaded map.
+             */
+            const std::vector<TerrainTriangle>& GetTriangles() const;
+
+            /**
+             * Gets the center of the loaded map, at height 0.
+             */
+            Ogre::Vector3 GetCenter() const;
+
+        private:
+
+            /**
+             * Groups the triangles by the cell of a grid they touch, so the search of the triangle under a
+             * position only checks a few of them.
+             */
+            void BuildIndex();
+
+            std::vector<TerrainTriangle> triangles_;
+            /// Indices of the triangles (ascending) that touch each cell of the grid, row by row.
+            std::vector<std::vector<uint32>> terrain_grid_;
+            float terrain_grid_min_x_ = 0.0f;
+            float terrain_grid_min_z_ = 0.0f;
+            float terrain_grid_cell_ = 1.0f;
+            int terrain_grid_columns_ = 0;
+            int terrain_grid_rows_ = 0;
+            Ogre::SceneManager* scene_manager_ = nullptr;
+            Ogre::SceneNode* world_map_node_ = nullptr;
+            /// Size of the map in blocks.
+            size_t grid_width_ = 9;
+            size_t grid_height_ = 7;
+            /// Position of the first block of the map in the 9x7 block grid of the world.
+            size_t origin_x_ = 0;
+            size_t origin_y_ = 0;
+    };
+}

+ 110 - 0
src/modules/worldmap/WorldmapTriggers.cpp

@@ -0,0 +1,110 @@
+/*
+ * 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 "modules/worldmap/WorldmapModule.h"
+#include <OgreVector3.h>
+#include "engine/entity/EntityManager.h"
+#include "engine/script/ScriptManager.h"
+#include "modules/worldmap/WorldmapConstants.h"
+#include "modules/worldmap/WorldmapData.h"
+
+namespace VGears {
+
+    /**
+     * Width in meshes of the grid that the world map scripts use to index meshes (mesh_y * 36 +
+     * mesh_x). It is the same in every map, regardless of the size of the map.
+     */
+    static const int WORLD_MAP_SCRIPT_MESH_STRIDE = 36;
+
+    bool WorldmapModule::FindWalkableSurface(
+      const Ogre::Vector3& position, Ogre::Vector3& surface, bool grass_only,
+      bool require_walkable, uint8* walkability_type, size_t* triangle_index
+    ) const{
+        WorldmapTerrain::WalkableCheck check;
+        if (require_walkable){
+            check = [this](const TerrainTriangle& triangle, const Ogre::Real height){
+                // Underwater: every terrain type is allowed, but there is a height limit.
+                if (map_id_ == 1){
+                    return !UNDERWATER_HEIGHT_LIMIT_ENABLED
+                      || height + FLIGHT_MIN_CLEARANCE <= UNDERWATER_MAX_HEIGHT;
+                }
+                return IsActiveTerrainAllowed(triangle.walkability_type);
+            };
+        }
+        return terrain_.FindSurface(position, surface, grass_only, check, walkability_type, triangle_index);
+    }
+
+    void WorldmapModule::EnterTriangle(const TerrainTriangle& triangle){
+        const int mesh_index = triangle.mesh_y * WORLD_MAP_SCRIPT_MESH_STRIDE + triangle.mesh_x;
+        if (triangle.function_id >= 3){
+            if (mesh_index != active_function_mesh_index_
+              || triangle.function_id != active_function_id_){
+                TriggerTriangleFunction(triangle);
+            }
+            active_function_mesh_index_ = mesh_index;
+            active_function_id_ = triangle.function_id;
+        }
+        else{
+            active_function_mesh_index_ = -1;
+            active_function_id_ = -1;
+        }
+    }
+
+    void WorldmapModule::TriggerTriangleFunction(const TerrainTriangle& triangle){
+        ScriptEntity* world_map_script
+          = ScriptManager::getSingleton().GetScriptEntityByName(
+              ScriptManager::SYSTEM, "WorldMap"
+            );
+        if (world_map_script == nullptr) return;
+
+        const int mesh_index = triangle.mesh_y * WORLD_MAP_SCRIPT_MESH_STRIDE + triangle.mesh_x;
+        // What the function can know about who entered the triangle (see WorldVM.can_enter).
+        ScriptManager::getSingleton().RunString(
+          std::string("System.WorldMap.vehicle = \"") + GetVehicleScriptName(current_vehicle_)
+          + "\"; System.WorldMap.landing = " + (landing_trigger_ ? "true" : "false")
+        );
+        ScriptManager::getSingleton().ScriptRequest(
+          world_map_script, "on_triangle_enter", 1,
+          std::to_string(mesh_index), std::to_string(triangle.function_id - 3), false, false
+        );
+    }
+
+      Ogre::String WorldmapModule::GetTerrainTypeUnderEntity(const char* entity_name) const{
+        if (entity_name == nullptr) return "";
+        const ::Entity* entity = EntityManager::getSingleton().GetEntity(entity_name);
+        if (entity == nullptr) return "";
+
+        Ogre::Vector3 surface;
+        uint8 walkability_type = 0;
+        if (!FindWalkableSurface(entity->GetPosition(), surface, false, false, &walkability_type)){
+          return "";
+        }
+        return GetWorldMapTerrainName(walkability_type);
+      }
+
+      int WorldmapModule::GetTerrainTriangleUnderEntity(const char* entity_name) const{
+        if (entity_name == nullptr) return -1;
+        const ::Entity* entity = EntityManager::getSingleton().GetEntity(entity_name);
+        if (entity == nullptr) return -1;
+
+        Ogre::Vector3 surface;
+        size_t triangle_index = 0;
+        if (!FindWalkableSurface(entity->GetPosition(), surface, false, false, nullptr, &triangle_index)){
+          return -1;
+        }
+        return static_cast<int>(triangle_index);
+      }
+
+} // namespace VGears

+ 35 - 3
src/modules/worldmap/WorldmapVehicles.cpp

@@ -15,6 +15,7 @@
 
 
 #include "modules/worldmap/WorldmapModule.h"
 #include "modules/worldmap/WorldmapModule.h"
 #include <algorithm>
 #include <algorithm>
+#include <OgreLogManager.h>
 #include <OgreEntity.h>
 #include <OgreEntity.h>
 #include <OgreSceneNode.h>
 #include <OgreSceneNode.h>
 #include "engine/entity/EntityManager.h"
 #include "engine/entity/EntityManager.h"
@@ -27,6 +28,37 @@ namespace VGears {
 
 
     using namespace Ogre;
     using namespace Ogre;
 
 
+    void WorldmapModule::ClearVehicleTerrains(){
+        active_vehicle_terrain_types_.clear();
+    }
+
+    void WorldmapModule::AddVehicleTerrain(const char* terrain_name){
+        if (terrain_name == nullptr) return;
+        const auto terrain = GetWorldMapTerrainTypes().find(terrain_name);
+        if (terrain == GetWorldMapTerrainTypes().end()){
+            LogManager::getSingleton().logMessage(
+              "Unknown world-map vehicle terrain '" + Ogre::String(terrain_name) + "'."
+            );
+            return;
+        }
+        if (std::find(
+              active_vehicle_terrain_types_.begin(), active_vehicle_terrain_types_.end(),
+              terrain->second
+            ) == active_vehicle_terrain_types_.end()){
+            active_vehicle_terrain_types_.push_back(terrain->second);
+        }
+    }
+
+    bool WorldmapModule::IsActiveTerrainAllowed(uint8 walkability_type) const{
+        if (current_vehicle_ == VehicleType::ON_FOOT){
+            return IsFootWalkable(walkability_type);
+        }
+        return std::find(
+          active_vehicle_terrain_types_.begin(), active_vehicle_terrain_types_.end(),
+          walkability_type
+        ) != active_vehicle_terrain_types_.end();
+    }
+
     /// Turning speed of the flying vehicles, in radians per second.
     /// Turning speed of the flying vehicles, in radians per second.
     static const float FLIGHT_TURN_SPEED = 1.5f;
     static const float FLIGHT_TURN_SPEED = 1.5f;
 
 
@@ -156,7 +188,7 @@ namespace VGears {
         if (EntityManager::getSingleton().IsWorldPositionBlocked(entity, new_position)) return;
         if (EntityManager::getSingleton().IsWorldPositionBlocked(entity, new_position)) return;
         flight_y_ = new_y;
         flight_y_ = new_y;
         entity->SetPosition(new_position);
         entity->SetPosition(new_position);
-        if (forward) EnterTriangle(terrain_triangles_[triangle_index]);
+        if (forward) EnterTriangle(terrain_.GetTriangles()[triangle_index]);
     }
     }
 
 
     /// Name of a vehicle in the scripts (WorldMapSettings).
     /// Name of a vehicle in the scripts (WorldMapSettings).
@@ -220,8 +252,8 @@ namespace VGears {
             size_t landing_triangle = 0;
             size_t landing_triangle = 0;
             if (FindWalkableSurface(vehicle_position, ground, false, false, &landing_terrain, &landing_triangle)
             if (FindWalkableSurface(vehicle_position, ground, false, false, &landing_terrain, &landing_triangle)
               && landing_terrain == VGears::WorldmapFileSerializer::NORTHERND_CAVE
               && landing_terrain == VGears::WorldmapFileSerializer::NORTHERND_CAVE
-              && terrain_triangles_[landing_triangle].function_id >= 3){
-              landing_after_unboard_ = &terrain_triangles_[landing_triangle];
+              && terrain_.GetTriangles()[landing_triangle].function_id >= 3){
+              landing_after_unboard_ = &terrain_.GetTriangles()[landing_triangle];
             }
             }
           }
           }
           player_entity_->SetPosition(surface);
           player_entity_->SetPosition(surface);