Explorar o código

Split the world map module into several files

- The module is divided by subject: data tables, textures, terrain, entities, vehicles, submarine, encounters and snow. The functions are unchanged.
- Removed WorldMapManager, which nothing used.
Iñigo Valentin hai 1 día
pai
achega
4bdbc674a2

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

@@ -1,6 +1,13 @@
 # Sources of this folder (see vgears_sources in src/CMakeLists.txt).
 vgears_sources(
-    WorldMapManager.cpp
     WorldmapBinds.cpp
+    WorldmapData.cpp
+    WorldmapEncounters.cpp
+    WorldmapEntities.cpp
     WorldmapModule.cpp
+    WorldmapSnow.cpp
+    WorldmapSubmarine.cpp
+    WorldmapTerrain.cpp
+    WorldmapTextures.cpp
+    WorldmapVehicles.cpp
 )

+ 0 - 74
src/modules/worldmap/WorldMapManager.cpp

@@ -1,74 +0,0 @@
-/*
- * Copyright (C) 2022 The V-Gears Team
- *
- * This file is part of V-Gears
- *
- * V-Gears is free software: you can redistribute it and/or modify it under
- * terms of the GNU General Public License as published by the Free Software
- * Foundation, version 3.0 (GPLv3) of the License.
- *
- * V-Gears is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- */
-
-#include <algorithm>
-#include <iostream>
-#include <cmath>
-#include <OgreEntity.h>
-#include <OgreRoot.h>
-#include <OgreViewport.h>
-#include "common/FF7Character.h"
-#include "engine/audio/AudioManager.h"
-#include "modules/worldmap/WorldMapManager.h"
-#include "modules/worldmap/WorldMapManager.h"
-#include "engine/graphics/CameraManager.h"
-#include "engine/ui/Console.h"
-#include "engine/ui/DialogsManager.h"
-#include "engine/entity/EntityManager.h"
-#include "engine/config/ConfigVar.h"
-#include "engine/input/InputManager.h"
-#include "common/Logger.h"
-#include "engine/script/ScriptManager.h"
-#include "engine/ui/TextHandler.h"
-#include "engine/ui/UiManager.h"
-
-/**
- * World Map manager singleton.
- */
-template<>WorldMapManager *Ogre::Singleton<WorldMapManager>::msSingleton = nullptr;
-
-WorldMapManager::WorldMapManager(){
-    LOG_TRIVIAL("WorldMapManager created.");
-    scene_node_ = Ogre::Root::getSingleton().getSceneManager("Scene")
-      ->getRootSceneNode()->createChildSceneNode("WorldMapManager");
-}
-
-WorldMapManager::~WorldMapManager(){
-    Clear();
-    Ogre::Root::getSingleton().getSceneManager("Scene")->getRootSceneNode()->removeAndDestroyChild(
-      "WorldMapManager"
-    );
-    LOG_TRIVIAL("WorldMapManager destroyed.");
-}
-
-void WorldMapManager::Input(const VGears::Event& event){}
-
-void WorldMapManager::UpdateDebug(){}
-
-void WorldMapManager::OnResize(){}
-
-void WorldMapManager::ClearField(){}
-
-void WorldMapManager::ClearBattle(){}
-
-void WorldMapManager::ClearWorld(){
-    // TODO
-}
-
-void WorldMapManager::UpdateField(){}
-
-void WorldMapManager::UpdateBattle(){}
-
-void WorldMapManager::UpdateWorld(){}

+ 0 - 103
src/modules/worldmap/WorldMapManager.h

@@ -1,103 +0,0 @@
-/*
- * Copyright (C) 2022 The V-Gears Team
- *
- * This file is part of V-Gears
- *
- * V-Gears is free software: you can redistribute it and/or modify it under
- * terms of the GNU General Public License as published by the Free Software
- * Foundation, version 3.0 (GPLv3) of the License.
- *
- * V-Gears is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- */
-
-#pragma once
-
-#include <OgreSingleton.h>
-#include "engine/Event.h"
-#include "engine/Manager.h"
-
-/**
- * The world map manager.
- */
-class WorldMapManager : public Manager, public Ogre::Singleton<WorldMapManager>{
-
-    public:
-
-        /**
-         * Constructor.
-         */
-        WorldMapManager();
-
-        /**
-         * Destructor.
-         */
-        virtual ~WorldMapManager();
-
-        /**
-         * Handles an input event.
-         *
-         * @param[in] event Event to handle.
-         */
-        void Input(const VGears::Event& event) override;
-
-        /**
-         * Updates the world map manager  with debug information.
-         *
-         * It's automatically called from {@see Update}.
-         */
-        void UpdateDebug() override;
-
-        /**
-         * Handles resizing events
-         */
-        void OnResize() override;
-
-        /**
-         * Clears all field information in the field manager.
-         *
-         * Does nothing.
-         */
-        void ClearField() override;
-
-        /**
-         * Clears all battle information in the battle manager.
-         *
-         * Does nothing
-         */
-        void ClearBattle() override;
-
-        /**
-         * Clears all world map information in the world map manager.
-         */
-        void ClearWorld() override;
-
-    private:
-
-        /**
-         * Updates the manager while in the field.
-         *
-         * It does nothing
-         */
-        void UpdateField() override;
-
-        /**
-         * Updates the manager during a battle.
-         */
-        void UpdateBattle() override;
-
-        /**
-         * Updates manager while in the world map.
-         *
-         * It does nothing
-         */
-        void UpdateWorld() override;
-
-        /**
-         * The scene node.
-         */
-        Ogre::SceneNode* scene_node_;
-
-};

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

@@ -0,0 +1,51 @@
+/*
+ * 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
+
+
+
+namespace VGears {
+
+    /// Rotation speed of the camera with L1 and R1, in radians per second.
+    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.
+    static const float FLIGHT_MIN_CLEARANCE = 0.1f;
+
+    /**
+     * Highest terrain height the submarine can reach in WM2. The terrain above it is the top
+     * layer. The submarine can move over all terrain types below this height.
+     *
+     * @todo The value was chosen from the height distribution of the WM2 triangles, and not
+     * verified against the original game.
+     */
+    static const float UNDERWATER_MAX_HEIGHT = -0.3f;
+
+    /**
+     * Enables the submarine height limit of WM2.
+     *
+     * The submarine can't go over terrain that is closer than FLIGHT_MIN_CLEARANCE to the
+     * ceiling.
+     */
+    static const bool UNDERWATER_HEIGHT_LIMIT_ENABLED = true;
+}

+ 469 - 0
src/modules/worldmap/WorldmapData.cpp

@@ -0,0 +1,469 @@
+/*
+ * 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/WorldmapData.h"
+#include <OgreLogManager.h>
+#include <OgreResourceGroupManager.h>
+#include "formats/worldmap/WorldmapFile.h"
+
+namespace VGears {
+
+    using namespace Ogre;
+
+    /**
+     * World map hardcoded textures
+     */
+    const HarcodedTextureInfo WORLD_MAP_TEXTURES[] ={
+        {0, "pond", 32, 32, 0, 352},
+        {1, "riv_m2", 32, 32, 128, 64},
+        {2, "was_gs", 64, 64, 64, 192},
+        {3, "wpcltr", 32, 128, 0, 256},
+        {4, "wpcltr2", 32, 32, 160, 64},
+        {5, "bzdun", 64, 64, 192, 192},
+        {6, "bone", 32, 32, 224, 384},
+        {7, "bone2", 32, 32, 224, 416},
+        {8, "bornwd", 64, 64, 160, 320},
+        {9, "bridge", 32, 64, 192, 0},
+        {10, "bridge2", 32, 32, 224, 0},
+        {11, "cave", 32, 32, 224, 448},
+        {12, "cave2", 32, 32, 224, 320},
+        {13, "cave_s", 32, 32, 160, 224},
+        {14, "cdl_cl2", 64, 32, 96, 96},
+        {15, "cf01", 64, 32, 192, 288},
+        {16, "clf_bgs", 64, 32, 192, 384},
+        {17, "clf_ggl", 64, 64, 128, 256},
+        {18, "clf_ggs", 64, 32, 192, 352},
+        {19, "clf_l", 64, 64, 0, 0},
+        {20, "clf_ld", 64, 64, 64, 0},
+        {21, "clf_lf", 64, 64, 128, 0},
+        {22, "clf_lg", 32, 64, 0, 96},
+        {23, "clf_lr", 32, 64, 128, 0},
+        {24, "clf_lsg", 32, 64, 64, 64},
+        {25, "clf_r", 32, 32, 0, 96},
+        {26, "clf_s", 64, 32, 192, 0},
+        {27, "clf_sd", 64, 32, 192, 32},
+        {28, "clf_sf", 64, 32, 0, 64},
+        {29, "clf_sg", 32, 32, 32, 96},
+        {30, "clf_sg2", 32, 32, 0, 160},
+        {31, "clf_sr", 32, 32, 32, 96},
+        {32, "clf_ss", 32, 32, 32, 128},
+        {33, "clf_ssd", 32, 32, 0, 224},
+        {34, "clf_ssw", 32, 32, 224, 32},
+        {35, "clf_sw", 32, 32, 192, 32},
+        {36, "clf_w02", 64, 64, 128, 64},
+        {37, "clf_w03", 64, 64, 192, 64},
+        {38, "clf_was", 64, 32, 64, 64},
+        {39, "clfeg", 32, 32, 192, 320},
+        {40, "clfegd", 32, 32, 0, 320},
+        {41, "clftop", 64, 32, 192, 64},
+        {42, "clftop2", 32, 32, 128, 64},
+        {43, "cndl_cl", 64, 32, 96, 128},
+        {44, "cndlf", 64, 64, 160, 64},
+        {45, "cndlf02", 64, 64, 208, 64},
+        {46, "comtr", 16, 32, 144, 96},
+        {47, "cosinn", 32, 32, 224, 416},
+        {48, "cosinn2", 32, 32, 192, 448},
+        {49, "csmk", 32, 32, 64, 64},
+        {50, "csmk2", 32, 32, 96, 64},
+        {51, "cstds01", 32, 32, 224, 160},
+        {52, "cstds02", 64, 64, 0, 448},
+        {53, "des01", 32, 32, 160, 320},
+        {54, "desert", 64, 64, 128, 128},
+        {55, "desor", 64, 32, 160, 64},
+        {56, "ds1", 32, 32, 0, 256},
+        {57, "ds_s1", 32, 32, 192, 288},
+        {58, "dsee1", 32, 32, 96, 288},
+        {59, "dsrt_d", 32, 32, 224, 0},
+        {60, "dsrt_e", 64, 128, 64, 128},
+        {61, "edes01", 32, 32, 224, 320},
+        {62, "elm01", 32, 32, 160, 0},
+        {63, "elm02", 32, 32, 64, 96},
+        {64, "elm_gro", 64, 64, 0, 96},
+        {65, "elm_r", 32, 32, 192, 0},
+        {66, "elm_r2", 32, 32, 224, 0},
+        {67, "fall1", 32, 32, 128, 256},
+        {68, "farm01", 32, 32, 160, 32},
+        {69, "farm02", 32, 32, 192, 32},
+        {70, "farm_g", 32, 32, 128, 64},
+        {71, "farm_r", 32, 16, 128, 48},
+        {72, "fld", 64, 64, 64, 96},
+        {73, "fld_02", 64, 64, 0, 64},
+        {74, "fld_s", 64, 64, 0, 160},
+        {75, "fld_s2", 32, 32, 224, 256},
+        {76, "fld_sw", 64, 64, 128, 192},
+        {77, "fld_v", 128, 128, 0, 128},
+        {78, "fld_vd", 32, 64, 96, 128},
+        {79, "fld_vd2", 32, 64, 192, 416},
+        {80, "fvedge", 32, 64, 0, 0},
+        {81, "gclf_d", 128, 64, 128, 128},
+        {82, "gclf_g", 32, 64, 224, 128},
+        {83, "gclfwa", 128, 64, 64, 320},
+        {84, "gclfwa2", 32, 64, 160, 320},
+        {85, "gclfwag", 32, 64, 32, 320},
+        {86, "gg_gro", 64, 64, 64, 448},
+        {87, "gg_mts", 64, 128, 0, 128},
+        {88, "ggmk", 64, 64, 128, 448},
+        {89, "ggmt", 128, 128, 0, 0},
+        {90, "ggmt_e", 128, 32, 0, 96},
+        {91, "ggmt_ed", 128, 32, 128, 96},
+        {92, "ggmt_eg", 32, 32, 96, 224},
+        {93, "ggmtd", 128, 128, 128, 0},
+        {94, "ggs_g", 32, 32, 32, 64},
+        {95, "ggshr", 32, 32, 192, 96},
+        {96, "ggshrg", 32, 32, 224, 96},
+        {97, "gia", 64, 32, 64, 224},
+        {98, "gia2", 64, 32, 0, 224},
+        {99, "gia_d", 64, 32, 128, 224},
+        {100, "gia_d2", 64, 32, 64, 224},
+        {101, "gia_g", 32, 32, 192, 224},
+        {102, "gia_g2", 32, 32, 128, 224},
+        {103, "gmt_eda", 32, 32, 0, 352},
+        {104, "gonclf", 128, 64, 96, 64},
+        {105, "gredge", 32, 32, 192, 192},
+        {106, "hyouga", 64, 64, 192, 64},
+        {107, "iceclf", 64, 32, 64, 96},
+        {108, "iceclfd", 64, 32, 128, 96},
+        {109, "iceclfg", 32, 32, 32, 224},
+        {110, "jun", 64, 64, 192, 192},
+        {111, "jun_d", 64, 64, 128, 192},
+        {112, "jun_e", 64, 16, 0, 240},
+        {113, "jun_gro", 64, 64, 0, 64},
+        {114, "junmk", 32, 32, 0, 96},
+        {115, "junn01", 32, 32, 160, 112},
+        {116, "junn02", 32, 32, 192, 112},
+        {117, "junn03", 32, 32, 224, 112},
+        {118, "junn04", 32, 32, 64, 128},
+        {119, "jutmpl01", 64, 64, 128, 192},
+        {120, "lake-e", 32, 32, 96, 192},
+        {121, "lake_ef", 32, 32, 128, 224},
+        {122, "lake_fl", 128, 32, 160, 224},
+        {123, "lostclf", 32, 64, 128, 384},
+        {124, "lostmt", 128, 32, 128, 448},
+        {125, "lostmtd", 128, 32, 128, 480},
+        {126, "lostmts", 64, 32, 160, 384},
+        {127, "lostwd_e", 32, 32, 64, 480},
+        {128, "lostwod", 64, 64, 0, 448},
+        {129, "lst1", 32, 32, 192, 256},
+        {130, "lstwd_e2", 32, 32, 96, 480},
+        {131, "mzes", 32, 32, 224, 128},
+        {132, "mzmt_e", 128, 64, 128, 64},
+        {133, "mzmt_ed", 128, 32, 128, 128},
+        {134, "mzmt_edw", 128, 32, 128, 160},
+        {135, "mzmt_ew", 128, 32, 0, 128},
+        {136, "mzmt_o", 128, 32, 64, 416},
+        {137, "mzmt_od", 128, 32, 64, 448},
+        {138, "mzmt_s", 128, 32, 0, 192},
+        {139, "mzmt_sd", 128, 32, 0, 160},
+        {140, "md01", 32, 32, 96, 16},
+        {141, "md02", 128, 128, 0, 0},
+        {142, "md03", 16, 16, 112, 64},
+        {143, "md04", 32, 32, 128, 16},
+        {144, "md05", 64, 16, 96, 0},
+        {145, "md06", 16, 32, 96, 48},
+        {146, "md07", 16, 16, 112, 48},
+        {147, "md_mt", 128, 128, 128, 0},
+        {148, "md_mtd", 128, 128, 0, 0},
+        {149, "md_mts", 64, 128, 64, 160},
+        {150, "md_snow", 128, 32, 128, 0},
+        {151, "md_snw2", 128, 32, 128, 32},
+        {152, "md_snwd", 128, 64, 0, 128},
+        {153, "md_snwe", 64, 64, 96, 320},
+        {154, "md_snws", 64, 64, 128, 128},
+        {155, "md_snwt", 128, 32, 0, 192},
+        {156, "md_snww", 32, 32, 224, 224},
+        {157, "md_sw_s", 128, 128, 0, 0},
+        {158, "md_swd2", 32, 32, 192, 256},
+        {159, "md_swnp", 128, 128, 0, 96},
+        {160, "mdsrt_e", 128, 32, 128, 192},
+        {161, "mdsrt_ed", 128, 32, 128, 224},
+        {162, "mdsrt_eg", 32, 32, 64, 224},
+        {163, "midil", 32, 32, 32, 192},
+        {164, "midild", 32, 32, 224, 192},
+        {165, "mt_ewg", 32, 32, 64, 96},
+        {166, "mt_road", 64, 64, 192, 128},
+        {167, "mt_se", 32, 32, 160, 416},
+        {168, "mt_se2", 64, 64, 128, 256},
+        {169, "mt_sg01", 32, 32, 0, 224},
+        {170, "mt_sg02", 32, 32, 32, 224},
+        {171, "mt_sg03", 32, 32, 0, 192},
+        {172, "mt_sg04", 32, 32, 160, 384},
+        {173, "mtcoin", 64, 64, 0, 256},
+        {174, "mtwas_e", 128, 32, 0, 224},
+        {175, "mtwas_ed", 128, 32, 0, 224},
+        {176, "ncol_gro", 64, 64, 64, 384},
+        {177, "ncole01", 32, 32, 224, 384},
+        {178, "ncole02", 32, 32, 192, 416},
+        {179, "nivl_gro", 64, 64, 128, 384},
+        {180, "nivl_mt", 128, 64, 0, 0},
+        {181, "nivl_top", 32, 32, 0, 64},
+        {182, "nivlr", 32, 32, 192, 384},
+        {183, "port", 32, 32, 96, 224},
+        {184, "port_d", 32, 32, 160, 0},
+        {185, "rzclf02", 64, 64, 128, 128},
+        {186, "rct_gro", 64, 128, 0, 416},
+        {187, "riv_cls", 64, 64, 64, 0},
+        {188, "riv_l1", 32, 32, 96, 320},
+        {189, "riv_m", 32, 32, 0, 224},
+        {190, "rivr", 32, 32, 64, 224},
+        {191, "rivrclf", 64, 64, 128, 192},
+        {192, "rivs1", 32, 32, 128, 320},
+        {193, "rivshr", 64, 64, 192, 192},
+        {194, "rivssr", 64, 32, 192, 224},
+        {195, "rivstrt", 32, 32, 192, 160},
+        {196, "rm1", 32, 32, 32, 288},
+        {197, "rocet", 32, 32, 128, 160},
+        {198, "rs_ss", 32, 32, 96, 224},
+        {199, "sango", 32, 32, 224, 320},
+        {200, "sango2", 32, 32, 224, 352},
+        {201, "sango3", 32, 32, 128, 384},
+        {202, "sango4", 64, 64, 0, 384},
+        {203, "sdun", 64, 64, 0, 160},
+        {204, "sdun02", 64, 64, 64, 160},
+        {205, "sh1", 32, 32, 32, 256},
+        {206, "sh_s1", 32, 32, 224, 288},
+        {207, "shedge", 32, 64, 160, 160},
+        {208, "shlm_1", 32, 32, 192, 320},
+        {209, "shol", 128, 128, 128, 96},
+        {210, "shol_s", 64, 64, 192, 192},
+        {211, "shor", 128, 128, 0, 0},
+        {212, "shor_s", 64, 64, 128, 192},
+        {213, "shor_s2", 32, 32, 224, 416},
+        {214, "shor_v", 32, 32, 192, 0},
+        {215, "silo", 32, 32, 224, 32},
+        {216, "slope", 128, 32, 0, 384},
+        {217, "snow_es", 32, 32, 192, 480},
+        {218, "snow_es2", 32, 32, 224, 480},
+        {219, "snow_es3", 32, 32, 224, 448},
+        {220, "snw_mt", 128, 128, 0, 0},
+        {221, "snw_mtd", 128, 128, 128, 0},
+        {222, "snw_mte", 64, 32, 0, 96},
+        {223, "snw_mted", 64, 32, 64, 96},
+        {224, "snw_mts", 64, 128, 64, 0},
+        {225, "snw_mts2", 64, 32, 128, 192},
+        {226, "snwfld", 64, 64, 0, 64},
+        {227, "snwfld_s", 64, 32, 128, 128},
+        {228, "snwgra", 64, 64, 192, 192},
+        {229, "snwhm01", 32, 32, 32, 0},
+        {230, "snwhm02", 32, 32, 32, 32},
+        {231, "snwods", 32, 32, 224, 192},
+        {232, "snwood", 64, 64, 192, 128},
+        {233, "snwtrk", 32, 64, 96, 256},
+        {234, "sse_s1", 32, 32, 32, 320},
+        {235, "ssee1", 32, 32, 64, 288},
+        {236, "sst1", 32, 32, 224, 256},
+        {237, "stown_r", 32, 32, 192, 256},
+        {238, "stw_gro", 64, 64, 0, 384},
+        {239, "subrg2", 32, 32, 224, 160},
+        {240, "susbrg", 64, 64, 192, 96},
+        {241, "sw_se", 64, 64, 0, 0},
+        {242, "swclf_l", 64, 64, 64, 128},
+        {243, "swclf_ld", 64, 64, 192, 128},
+        {244, "swclf_lg", 32, 64, 0, 192},
+        {245, "swclf_s", 64, 32, 128, 96},
+        {246, "swclf_sd", 64, 32, 192, 96},
+        {247, "swclf_sg", 32, 32, 32, 192},
+        {248, "swclf_wg", 32, 32, 192, 192},
+        {249, "swfld_s2", 64, 32, 128, 160},
+        {250, "swfld_s3", 32, 32, 160, 192},
+        {251, "swmd_cg", 32, 32, 128, 192},
+        {252, "swmd_clf", 64, 32, 64, 192},
+        {253, "swp1", 32, 32, 0, 288},
+        {254, "trk", 64, 64, 128, 0},
+        {255, "tyo_f", 128, 128, 128, 128},
+        {256, "tyosnw", 64, 128, 64, 384},
+        {257, "uf1", 32, 32, 160, 256},
+        {258, "utai01", 32, 32, 32, 96},
+        {259, "utai02", 32, 32, 224, 64},
+        {260, "utai_gro", 64, 64, 128, 96},
+        {261, "utaimt", 32, 32, 0, 128},
+        {262, "utaimtd", 32, 32, 96, 96},
+        {263, "utaimtg", 32, 32, 96, 128},
+        {264, "wa1", 32, 32, 192, 320},
+        {265, "wzs1", 32, 32, 128, 288},
+        {266, "wzshr", 32, 32, 160, 32},
+        {267, "wzshr2", 32, 32, 32, 128},
+        {268, "wzshrs", 32, 32, 32, 160},
+        {269, "was", 128, 128, 0, 96},
+        {270, "was_d", 64, 32, 0, 224},
+        {271, "was_g", 64, 64, 0, 192},
+        {272, "was_s", 128, 128, 128, 0},
+        {273, "wasfld", 64, 64, 64, 256},
+        {274, "wdedge", 64, 64, 64, 160},
+        {275, "we1", 32, 32, 96, 256},
+        {276, "we_s1", 32, 32, 160, 288},
+        {277, "wedged", 32, 64, 128, 160},
+        {278, "wod-e2", 32, 32, 64, 224},
+        {279, "wood", 64, 64, 192, 0},
+        {280, "wood_d", 64, 64, 192, 160},
+        {281, "wtrk", 32, 64, 64, 96},
+        // The ids 282-293 (ff7.exe table of u, v at 0x95b9f0) are the ones that WM2 uses (its ids + 282).
+        {282, "cltr", 128, 128, 0, 0},
+        {283, "lake_a", 128, 256, 0, 0},
+        {284, "rock", 256, 256, 0, 0},
+        {285, "scave", 256, 256, 0, 0},
+        {286, "ssand", 256, 256, 0, 0},
+        {287, "swall02", 256, 256, 0, 0},
+        {288, "sng01", 128, 128, 128, 0},
+        {289, "sng02", 128, 128, 128, 0},
+        {290, "hokola01", 64, 64, 0, 0},
+        {291, "hokola02", 64, 64, 0, 128},
+        {292, "snwfldl", 64, 64, 0, 64},
+        {293, "snwfld2", 64, 64, 0, 192}
+    };
+
+    const size_t WORLD_MAP_TEXTURE_COUNT = sizeof(WORLD_MAP_TEXTURES) / sizeof(WORLD_MAP_TEXTURES[0]);
+
+    /**
+     * The ids of the textures of WM2 and WM3 start after the ones of WM0 in the table of the game:
+     * WM2 uses 0-7 as 282-289 and WM3 0-3 as 290-293 (checked with the ranges of their UVs).
+     */
+    uint16 GetTextureIdOffset(const uint8 map_id){
+        return map_id == 1 ? 282 : (map_id == 2 ? 290 : 0);
+    }
+
+    bool IsFootWalkable(uint8 walkability_type){
+      using WalkType = VGears::WorldmapFileSerializer::TriangleWalkMapTypes;
+      switch (walkability_type){
+        case WalkType::GRASS:
+        case WalkType::FOREST:
+        case WalkType::SWAMP:
+        case WalkType::DESERT:
+        case WalkType::WASTELAND:
+        case WalkType::SNOW:
+        case WalkType::RIVERSIDE:
+        case WalkType::COREL_BRIDGE:
+        case WalkType::WUTAI_BRIDGE:
+        case WalkType::HILL_SIDE:
+        case WalkType::BEACH:
+        case WalkType::CANYON:
+        case WalkType::MOUNTAIN_PASS:
+        case WalkType::GOLD_SAUCER_DESERT:
+        case WalkType::JUNGLE:
+        case WalkType::NORTHERND_CAVE:
+        case WalkType::GOLD_SAUCER_DESERT_BORDER:
+        case WalkType::BRIDGE_HEAD:
+        case WalkType::BACK_ENTRANCE:
+          return true;
+        default:
+          return false;
+      }
+    }
+
+    const std::map<Ogre::String, uint8>& GetWorldMapTerrainTypes(){
+      using WalkType = VGears::WorldmapFileSerializer::TriangleWalkMapTypes;
+      static const std::map<Ogre::String, uint8> terrain_types = {
+        {"GRASS", static_cast<uint8>(WalkType::GRASS)},
+        {"FOREST", static_cast<uint8>(WalkType::FOREST)},
+        {"MOUNTAIN", static_cast<uint8>(WalkType::MOUNTAIN)},
+        {"SEA_DEEP_WATER", static_cast<uint8>(WalkType::SEA_DEEP_WATER)},
+        {"RIVER_CROSSING", static_cast<uint8>(WalkType::RIVER_CROSSING)},
+        {"RIVER", static_cast<uint8>(WalkType::RIVER)},
+        {"WATER", static_cast<uint8>(WalkType::WATER)},
+        {"SWAMP", static_cast<uint8>(WalkType::SWAMP)},
+        {"DESERT", static_cast<uint8>(WalkType::DESERT)},
+        {"WASTELAND", static_cast<uint8>(WalkType::WASTELAND)},
+        {"SNOW", static_cast<uint8>(WalkType::SNOW)},
+        {"RIVERSIDE", static_cast<uint8>(WalkType::RIVERSIDE)},
+        {"CLIFF", static_cast<uint8>(WalkType::CLIFF)},
+        {"COREL_BRIDGE", static_cast<uint8>(WalkType::COREL_BRIDGE)},
+        {"WUTAI_BRIDGE", static_cast<uint8>(WalkType::WUTAI_BRIDGE)},
+        {"UNUSED_1", static_cast<uint8>(WalkType::UNUSED_1)},
+        {"HILL_SIDE", static_cast<uint8>(WalkType::HILL_SIDE)},
+        {"BEACH", static_cast<uint8>(WalkType::BEACH)},
+        {"SUBMARINE_PEN", static_cast<uint8>(WalkType::SUBMARINE_PEN)},
+        {"CANYON", static_cast<uint8>(WalkType::CANYON)},
+        {"MOUNTAIN_PASS", static_cast<uint8>(WalkType::MOUNTAIN_PASS)},
+        {"UNKNOWN_1", static_cast<uint8>(WalkType::UNKNOWN_1)},
+        {"WATERFALL", static_cast<uint8>(WalkType::WATERFALL)},
+        {"UNUSED_2", static_cast<uint8>(WalkType::UNUSED_2)},
+        {"GOLD_SAUCER_DESERT", static_cast<uint8>(WalkType::GOLD_SAUCER_DESERT)},
+        {"JUNGLE", static_cast<uint8>(WalkType::JUNGLE)},
+        {"SEA", static_cast<uint8>(WalkType::SEA)},
+        {"NORTHERND_CAVE", static_cast<uint8>(WalkType::NORTHERND_CAVE)},
+        {"GOLD_SAUCER_DESERT_BORDER", static_cast<uint8>(WalkType::GOLD_SAUCER_DESERT_BORDER)},
+        {"BRIDGE_HEAD", static_cast<uint8>(WalkType::BRIDGE_HEAD)},
+        {"BACK_ENTRANCE", static_cast<uint8>(WalkType::BACK_ENTRANCE)},
+        {"UNUSED_3", static_cast<uint8>(WalkType::UNUSED_3)}
+      };
+      return terrain_types;
+    }
+
+      Ogre::String GetWorldMapTerrainName(const uint8 walkability_type){
+        for (const auto& terrain : GetWorldMapTerrainTypes()){
+          if (terrain.second == walkability_type) return terrain.first;
+        }
+        return "";
+      }
+
+    MapLayout GetMapLayout(const int map_id){
+        switch (map_id){
+            case 1: return {3, 4, 3, 2};
+            case 2: return {2, 2, 0, 0};
+            default: return {9, 7, 0, 0};
+        }
+    }
+
+    /**
+     * Gets if a position of the world is inside the blocks of a map.
+     */
+    bool IsInsideMap(const int map_id, const float x, const float z){
+        const MapLayout layout = GetMapLayout(map_id);
+        const float block_size = (8182.0f / 4096.0f) * 4.0f;
+        const float bx = x / block_size - layout.origin_x;
+        const float bz = z / block_size - layout.origin_y;
+        return bx >= 0 && bz >= 0 && bx < layout.width && bz < layout.height;
+    }
+
+    /**
+     * Loads and parses an installed world map file.
+     *
+     * @param[in] file_name Name of the MAP file, like "WM0.MAP".
+     * @return The map blocks.
+     */
+    std::vector<VGears::WorldmapFileSerializer::Block> LoadWorldMap(
+      const Ogre::String& file_name
+    ){
+        /**
+       * The serializer retains its parsed blocks; the resource argument is
+       * currently unused by the MAP serializer.
+         */
+        class TestFile : public VGears::WorldmapFile{
+
+            public:
+
+                TestFile() : VGears::WorldmapFile(nullptr, "", 0, "") {}
+        };
+
+        Ogre::DataStreamPtr stream
+          = Ogre::ResourceGroupManager::getSingleton().openResource(
+              file_name, WORLD_MAP_RESOURCE_GROUP, nullptr, true
+            );
+        TestFile file;
+        VGears::WorldmapFileSerializer serializer;
+        serializer.ImportWorldmapFile(stream, file);
+
+        Ogre::LogManager::getSingleton().logMessage(
+          "Loaded " + file_name + " with " + std::to_string(serializer.blocks.size())
+            + " blocks."
+        );
+        return serializer.blocks;
+    }
+
+    float From16BitFixedPoint(VGears::sint16 coord){
+        // return float(coord);
+        return (float(coord) / 4096.0f);
+    }
+
+} // namespace VGears

+ 163 - 0
src/modules/worldmap/WorldmapData.h

@@ -0,0 +1,163 @@
+/*
+ * 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 <cstddef>
+#include <map>
+#include <vector>
+#include <OgreString.h>
+#include "common/TypeDefine.h"
+#include "formats/worldmap/WorldmapFileSerializer.h"
+
+namespace VGears {
+
+    /**
+     * Resource group of the world map files.
+     */
+    static const char* const WORLD_MAP_RESOURCE_GROUP = "WORLD_MAP";
+
+    /**
+     * World map hardcoded texture information.
+     */
+    struct HarcodedTextureInfo{
+
+        /**
+         * Texture id.
+         */
+        uint32 id;
+
+        /**
+         * Texture name.
+         */
+        const char* name;
+
+        /**
+         * Texture width.
+         */
+        uint32 width;
+
+        /**
+         * Texture height.
+         */
+        uint32 height;
+
+        /**
+         * Texture U component.
+         */
+        uint32 u;
+
+        /**
+         * Texture V component
+         */
+        uint32 v;
+    };
+
+    /**
+     * World map hardcoded textures.
+     */
+    extern const HarcodedTextureInfo WORLD_MAP_TEXTURES[];
+
+    /**
+     * Number of textures in {@see WORLD_MAP_TEXTURES}.
+     */
+    extern const size_t WORLD_MAP_TEXTURE_COUNT;
+
+    /**
+     * Gets what has to be added to the texture ids of a map to get its textures in the table.
+     *
+     * @param[in] map_id The map.
+     * @return The offset.
+     */
+    uint16 GetTextureIdOffset(const uint8 map_id);
+
+    /**
+     * Tells if a terrain can be walked on foot.
+     *
+     * @param[in] walkability_type Type of the terrain.
+     * @return True if it can be walked.
+     */
+    bool IsFootWalkable(uint8 walkability_type);
+
+    /**
+     * Gets the types of terrain, by name.
+     */
+    const std::map<Ogre::String, uint8>& GetWorldMapTerrainTypes();
+
+    /**
+     * Gets the name of a type of terrain.
+     *
+     * @param[in] walkability_type Type of the terrain.
+     * @return The name, or an empty string if it is unknown.
+     */
+    Ogre::String GetWorldMapTerrainName(const uint8 walkability_type);
+
+    /**
+     * World map IDs and the files of the original game they load. The original game has no WM1.
+     * 0 is the overworld, 1 is WM2 and 2 is WM3.
+     */
+    static const int WORLD_MAP_FILE_NUMBERS[] = {0, 2, 3};
+    static const int WORLD_MAP_COUNT = sizeof(WORLD_MAP_FILE_NUMBERS) / sizeof(int);
+
+    /**
+     * Size and position of a map in blocks. The blocks of a MAP file are stored in order, row by
+     * row. The maps are placed in the 9x7 block grid of the world, since the scripts index the
+     * meshes with the position in that grid, and the maps share coordinates: the underwater map
+     * WM2 is a part of the world of WM0, so a position of WM0 inside it is the same in WM2.
+     *
+     * The layout of WM2 was deduced from the edges of its blocks and the mesh coordinates in its
+     * script. The one of WM3 is a guess.
+     */
+    struct MapLayout{
+        int width;
+        int height;
+        int origin_x;
+        int origin_y;
+    };
+
+    /**
+     * Gets the size and position of a map.
+     *
+     * @param[in] map_id The map.
+     * @return Its layout.
+     */
+    MapLayout GetMapLayout(const int map_id);
+
+    /**
+     * Gets if a position of the world is inside the blocks of a map.
+     *
+     * @param[in] map_id The map.
+     * @param[in] x Position in X.
+     * @param[in] z Position in Z.
+     * @return True if it is inside.
+     */
+    bool IsInsideMap(const int map_id, const float x, const float z);
+
+    /**
+     * Loads and parses an installed world map file.
+     *
+     * @param[in] file_name Name of the MAP file, like "WM0.MAP".
+     * @return The map blocks.
+     */
+    std::vector<VGears::WorldmapFileSerializer::Block> LoadWorldMap(const Ogre::String& file_name);
+
+    /**
+     * Creates a 16 bit point from coordinates.
+     *
+     * @param[in] coord The coordinates.
+     * @return Coordinate point.
+     */
+    float From16BitFixedPoint(VGears::sint16 coord);
+}

+ 142 - 0
src/modules/worldmap/WorldmapEncounters.cpp

@@ -0,0 +1,142 @@
+/*
+ * 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 <algorithm>
+#include <cstdlib>
+#include <sstream>
+#include <tinyxml.h>
+#include "common/Logger.h"
+#include "engine/entity/EntityManager.h"
+#include "engine/script/ScriptManager.h"
+
+namespace VGears {
+
+    void WorldmapModule::LoadEncounters(){
+        encounter_records_.clear();
+        TiXmlDocument document("./game/world/world_encounters.xml");
+        if (!document.LoadFile()){
+            LOG_WARNING("World map encounters were not found. There will be no random battles.");
+            return;
+        }
+        TiXmlHandle handle(&document);
+        for (
+          TiXmlElement* record = handle.FirstChildElement("world_encounters")
+            .FirstChildElement("record").ToElement();
+          record != nullptr; record = record->NextSiblingElement("record")
+        ){
+            EncounterRecord data;
+            int enabled = 0;
+            data.rate = 0;
+            data.terrain = 0;
+            record->QueryIntAttribute("enabled", &enabled);
+            record->QueryIntAttribute("rate", &data.rate);
+            record->QueryIntAttribute("terrain", &data.terrain);
+            data.enabled = enabled != 0;
+            for (unsigned int i = 0; i < 15; ++ i) data.words[i] = 0;
+            std::istringstream words(record->Attribute("words") ? record->Attribute("words") : "");
+            for (unsigned int i = 0; i < 15; ++ i){
+                unsigned int word = 0;
+                if (!(words >> word)) break;
+                data.words[i] = static_cast<uint16>(word);
+            }
+            encounter_records_.push_back(data);
+        }
+        LOG_TRIVIAL("World map encounters loaded: " + std::to_string(encounter_records_.size()));
+    }
+
+    int WorldmapModule::RollEncounterBattle(const EncounterRecord& record) const{
+        // 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
+        // probability sits in the 6 highest bits.
+        const uint16* w = record.words;
+        int battle = -1;
+        int roll = (std::rand() % 256) << 8;
+        // Words 7 and 8 (indices 6 and 7): back attacks.
+        if (w[6] > roll) battle = w[6] & 0x3FF;
+        else if (w[6] + w[7] > roll) battle = w[7] & 0x3FF;
+        // Word 9: side attack. Needs a party of more than one member.
+        if (battle < 0){
+            roll = (std::rand() % 256) << 8;
+            if (w[8] > roll) battle = w[8] & 0x3FF;
+        }
+        // Word 10: pincer attack.
+        if (battle < 0){
+            roll = (std::rand() % 256) << 8;
+            if (w[9] > roll) battle = w[9] & 0x3FF;
+        }
+        // Words 1-6: standard battles. The last battle is not repeated (one reroll).
+        for (unsigned int attempt = 0; battle < 0 && attempt < 2; ++ attempt){
+            roll = (std::rand() % 256) << 8;
+            int sum = 0;
+            for (unsigned int i = 0; i < 6; ++ i){
+                sum += w[i];
+                if (sum > roll){
+                    battle = w[i] & 0x3FF;
+                    break;
+                }
+            }
+            if (battle == encounter_last_battle_ && attempt == 0) battle = -1;
+        }
+        return battle;
+    }
+
+    void WorldmapModule::UpdateEncounters(const float delta_time, const TerrainTriangle& triangle){
+        if (encounters_locked_ || encounter_records_.size() < 64) return;
+        // The original game checks every 16 frames of walking, at 30 frames per second.
+        encounter_frames_ += delta_time * 30.0f;
+        if (encounter_frames_ < 16.0f) return;
+        encounter_frames_ -= 16.0f;
+
+        // Region and terrain group. The terrain types 0x10 and 0x18 count as 0 and 8.
+        const int region = std::min<int>(triangle.region, 15);
+        int terrain = triangle.walkability_type;
+        if (terrain == 0x10) terrain = 0;
+        else if (terrain == 0x18) terrain = 8;
+        int group = 0;
+        for (int i = 0; i < 4; ++ i){
+            if (encounter_records_[region * 4 + i].terrain == terrain){
+                group = i;
+                break;
+            }
+        }
+        const EncounterRecord& record = encounter_records_[region * 4 + group];
+
+        // The accumulator grows on every check, so the chance gets higher until a battle starts.
+        const float multiplier = EntityManager::getSingleton().GetEncounterMultiplier();
+        if (multiplier <= 0.0f) return;
+        const int speed = static_cast<int>(16 * multiplier);
+        encounter_accumulator_ += (record.rate != 0) ? (speed << 10) / record.rate : 0x7FFF;
+        const int check = std::rand() % 256;
+        if (EntityManager::getSingleton().IsDebugEncounters()){
+            LOG_TRIVIAL(
+              "World encounter check: region " + std::to_string(region) + ", terrain "
+              + std::to_string(terrain) + ", group " + std::to_string(group) + ", rate "
+              + std::to_string(record.rate) + ", chance " + std::to_string(encounter_accumulator_ >> 8)
+              + "/256, roll " + std::to_string(check)
+            );
+        }
+        if (check >= (encounter_accumulator_ >> 8) || !record.enabled) return;
+        encounter_accumulator_ = 0;
+        const int battle = RollEncounterBattle(record);
+        if (battle < 0) return;
+        encounter_last_battle_ = battle;
+        LOG_TRIVIAL("World random encounter: battle " + std::to_string(battle));
+        ScriptManager::getSingleton().RunString("Encounter.start(" + std::to_string(battle) + ")");
+    }
+
+    void WorldmapModule::SetEncountersLocked(const bool locked){encounters_locked_ = locked;}
+
+} // namespace VGears

+ 442 - 0
src/modules/worldmap/WorldmapEntities.cpp

@@ -0,0 +1,442 @@
+/*
+ * 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 <algorithm>
+#include <cmath>
+#include <limits>
+#include <OgreEntity.h>
+#include <OgreException.h>
+#include <OgreLogManager.h>
+#include <OgreSceneNode.h>
+#include "engine/entity/EntityManager.h"
+#include "engine/entity/EntityModel.h"
+#include "modules/worldmap/WorldmapConstants.h"
+#include "modules/worldmap/WorldmapData.h"
+
+namespace VGears {
+
+    using namespace Ogre;
+
+    /// How much the model of the submarine is under the surface of the water in WM0, in world
+    /// units. Found by looking at it.
+    static const float SUBMARINE_SUBMERGED_DEPTH = 0.09f;
+
+    /**
+     * Moves the model of an entity up or down, without moving the entity.
+     *
+     * The model is scaled to the size of the world, so the offset has to be divided by that scale
+     * to be in world units.
+     *
+     * @param[in] entity The entity.
+     * @param[in] offset Distance in world units. Negative is down.
+     */
+    static void SetModelHeightOffset(EntityModel* entity, const float offset){
+        Ogre::SceneNode* model_node = entity->GetModel()->getParentSceneNode();
+        float scale = 1.0f;
+        if (model_node->getParentSceneNode() != nullptr){
+            scale = model_node->getParentSceneNode()->_getDerivedScale().y;
+        }
+        if (scale <= 0.0f) scale = 1.0f;
+        model_node->setPosition(Ogre::Vector3(0.0f, offset / scale, 0.0f));
+    }
+
+    /// Height over the ground where the submarine starts, so it floats.
+    static const float SUBMARINE_START_CLEARANCE = 0.3f;
+
+    void WorldmapModule::CreatePlayer(){
+        Ogre::Vector3 requested_spawn = GetSpawn("Cloud", Ogre::Vector3(42.0f, 0.0f, 36.5f));
+        Ogre::Vector3 spawn_position;
+        bool spawn_found;
+        if (map_id_ == 0){
+            // A given spawn point (from a field exit) can be on any terrain, like a town or a forest.
+            const bool given_spawn = spawn_overrides_.find("Cloud") != spawn_overrides_.end();
+            spawn_found = given_spawn
+              ? FindWalkableSurface(requested_spawn, spawn_position, false, false)
+              : FindWalkableSurface(requested_spawn, spawn_position, true);
+        }
+        else{
+            // 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.
+            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)
+            );
+            Ogre::Real best_distance = std::numeric_limits<Ogre::Real>::max();
+            // The exact position of the dive, if the submarine can be there.
+            const bool exact_dive_position = dive_requested_
+              && FindWalkableSurface(dive_position_, spawn_position, false, true);
+            if (exact_dive_position) best_distance = 0;
+            else for (const TerrainTriangle& triangle : terrain_triangles_){
+                const Ogre::Vector3 centroid
+                  = (triangle.vertices[0] + triangle.vertices[1] + triangle.vertices[2]) / 3.0f;
+                if (map_id_ == 1 ? (UNDERWATER_HEIGHT_LIMIT_ENABLED
+                  && centroid.y + FLIGHT_MIN_CLEARANCE > UNDERWATER_MAX_HEIGHT)
+                  : !IsActiveTerrainAllowed(triangle.walkability_type)) continue;
+                const Ogre::Real distance = Ogre::Vector2(
+                  centroid.x - center.x, centroid.z - center.z
+                ).squaredLength();
+                if (distance < best_distance){
+                    best_distance = distance;
+                    requested_spawn = centroid;
+                }
+            }
+            spawn_found = exact_dive_position || (
+              best_distance < std::numeric_limits<Ogre::Real>::max()
+              && FindWalkableSurface(requested_spawn, spawn_position, false)
+            );
+        }
+        if (!spawn_found){
+            LogManager::getSingleton().logMessage(
+              "World map " + std::to_string(map_id_) + " has no walkable surface for Cloud's spawn."
+            );
+            return;
+        }
+
+        if (map_id_ == 1){
+            // The underwater map is played with the submarine only.
+            AddWorldModel(
+              "Submarine", "ddd.mesh", spawn_position, From16BitFixedPoint(8182) * 0.1125f,
+              Ogre::Quaternion::IDENTITY, 1.0f, false
+            );
+            submarine_entity_ = static_cast<EntityModel*>(
+              EntityManager::getSingleton().GetEntity("WorldMapSubmarine")
+            );
+            if (submarine_entity_ == nullptr) return;
+            player_entity_ = submarine_entity_;
+            player_height_offset_ = 0;
+            if (dive_requested_){
+              // Same heading as in WM0.
+              submarine_entity_->GetModel()->getParentSceneNode()->getParentSceneNode()
+                ->setOrientation(Ogre::Quaternion(Ogre::Radian(dive_heading_), Ogre::Vector3::UNIT_Y));
+              dive_requested_ = false;
+            }
+            // It floats over the seabed.
+            submarine_entity_->SetPosition(
+              submarine_entity_->GetPosition() + Ogre::Vector3(0, SUBMARINE_START_CLEARANCE, 0)
+            );
+            EntityManager::getSingleton().ScriptSetPlayerEntity("WorldMapSubmarine");
+            UpdateCamera(0, true);
+            return;
+        }
+
+        LogManager::getSingleton().logMessage(
+          "Spawning Cloud at "
+            + Ogre::StringConverter::toString(spawn_position.x) + ", "
+            + Ogre::StringConverter::toString(spawn_position.z)
+        );
+
+        player_entity_ = EntityManager::getSingleton().AddWorldMapEntity(
+          "WorldMapCloud", "cloud.mesh", spawn_position, Ogre::Degree(0),
+          Ogre::Vector3::UNIT_SCALE, "FIELD_MODELS"
+        );
+        if (player_entity_ == nullptr) return;
+
+        // Cloud's bounds without animations. The bounds in the mesh can't be used for sizing: the
+        // installer enlarges them with the animations' movement, so the model is not culled.
+        const Ogre::AxisAlignedBox bounds(
+          -8.7473f, -8.1671f, -4.1878f, 7.8685f, 5.6837f, 22.8135f
+        );
+        const Ogre::Vector3 model_size = bounds.getSize();
+        const Ogre::Real model_height = model_size.y;
+        if (model_height > 0){
+            const Ogre::Real scale = From16BitFixedPoint(8182) * 0.45f * 0.25f * 0.25f
+              / model_height;
+            player_entity_->setScale(Ogre::Vector3::UNIT_SCALE * scale);
+            player_entity_->SetHeight(model_height * scale);
+            player_entity_->SetSolidRadius(
+              std::max(model_size.x, model_size.z) * scale * 0.5f
+            );
+            player_entity_->SetCollisionDebugOrientation(
+              Ogre::Quaternion(Ogre::Degree(-90), Ogre::Vector3::UNIT_X)
+            );
+            // Only solid entities can interact with the vehicles.
+            player_entity_->SetSolid(true);
+            player_height_offset_ = -bounds.getMinimum().y * scale;
+            spawn_position.y += player_height_offset_;
+            player_entity_->SetPosition(spawn_position);
+            Ogre::AnimationStateSet* animations
+              = player_entity_->GetModel()->getAllAnimationStates();
+            if (animations == nullptr || !animations->hasAnimationState("Walk")){
+                LogManager::getSingleton().logMessage(
+                  "Cloud model has no Walk animation state."
+                );
+            }
+            EntityManager::getSingleton().ScriptSetPlayerEntity("WorldMapCloud");
+            player_entity_->PlayAnimationContinue("Idle");
+            // Vehicles and companions are only placed in the overworld.
+            if (map_id_ == 0){
+                CreateCompanionModels();
+                // Coming back from WM2: everything is where it was, except for the submarine.
+                if (surface_requested_){
+                    RestoreOverworldSnapshot();
+                    PlaceSurfacedSubmarine();
+                }
+                overworld_snapshot_.clear();
+            }
+            UpdateCamera(0, true);
+        }
+    }
+
+    void WorldmapModule::AddWorldModel(
+      const Ogre::String& name, const Ogre::String& mesh_name,
+      const Ogre::Vector3& desired_position, Ogre::Real target_size,
+      const Ogre::Quaternion& orientation, Ogre::Real collision_radius_scale,
+      bool talkable, Ogre::Real explicit_scale
+    ){
+        Ogre::Vector3 surface_position;
+        if (!FindWalkableSurface(desired_position, surface_position, false, false)){
+            LogManager::getSingleton().logMessage(
+              "No terrain surface found for world-map model '" + name + "'."
+            );
+            return;
+        }
+
+        EntityModel* entity = nullptr;
+        try{
+            entity = EntityManager::getSingleton().AddWorldMapEntity(
+              "WorldMap" + name, mesh_name, surface_position,
+              Ogre::Degree(0), Ogre::Vector3::UNIT_SCALE, "WORLD_MODELS"
+            );
+        }
+        catch (const Ogre::Exception& exception){
+            LogManager::getSingleton().logMessage(
+              "Failed to load world-map model '" + mesh_name + "': "
+                + exception.getDescription()
+            );
+            return;
+        }
+        if (entity == nullptr) return;
+
+        const Ogre::Vector3 bounds_size = entity->GetModel()->getBoundingBox().getSize();
+        const Ogre::Real largest_dimension = std::max(
+          bounds_size.x, std::max(bounds_size.y, bounds_size.z)
+        );
+        if (largest_dimension <= 0){
+            LogManager::getSingleton().logMessage(
+              "World-map model '" + mesh_name + "' has empty bounds."
+            );
+            return;
+        }
+
+        // The scale of the model: the size of its largest dimension, or the one that is given.
+        const Ogre::Real model_scale = explicit_scale > 0 ? explicit_scale
+          : target_size / largest_dimension;
+        const Ogre::Vector3 oriented_x = orientation * Ogre::Vector3::UNIT_X;
+        const Ogre::Vector3 oriented_y = orientation * Ogre::Vector3::UNIT_Y;
+        const Ogre::Vector3 oriented_z = orientation * Ogre::Vector3::UNIT_Z;
+        const Ogre::Real world_width =
+          Ogre::Math::Abs(oriented_x.x) * bounds_size.x
+          + Ogre::Math::Abs(oriented_y.x) * bounds_size.y
+          + Ogre::Math::Abs(oriented_z.x) * bounds_size.z;
+        const Ogre::Real world_height =
+          Ogre::Math::Abs(oriented_x.y) * bounds_size.x
+          + Ogre::Math::Abs(oriented_y.y) * bounds_size.y
+          + Ogre::Math::Abs(oriented_z.y) * bounds_size.z;
+        const Ogre::Real world_depth =
+          Ogre::Math::Abs(oriented_x.z) * bounds_size.x
+          + Ogre::Math::Abs(oriented_y.z) * bounds_size.y
+          + Ogre::Math::Abs(oriented_z.z) * bounds_size.z;
+        entity->setRootOrientation(orientation);
+        entity->setScale(Ogre::Vector3::UNIT_SCALE * model_scale);
+        entity->SetSolid(true);
+        entity->SetHeight(world_height * model_scale);
+        entity->SetSolidRadius(
+          std::max(world_width, world_depth) * model_scale * 0.5f
+            * collision_radius_scale
+        );
+        entity->SetTalkable(talkable);
+        if (talkable) entity->SetTalkRadius(entity->GetSolidRadius());
+        // The submarine of the overworld is partially under the surface of the water. Only the
+        // model is lowered, so its position and collision are the same.
+        if (map_id_ == 0 && name == "Submarine"){
+            SetModelHeightOffset(entity, -SUBMARINE_SUBMERGED_DEPTH);
+        }
+        entity->SetCollisionDebugOrientation(
+          Ogre::Quaternion(Ogre::Degree(-90), Ogre::Vector3::UNIT_X)
+        );
+        LogManager::getSingleton().logMessage(
+          "Placed world-map model '" + name + "' at "
+            + Ogre::StringConverter::toString(surface_position.x) + ", "
+            + Ogre::StringConverter::toString(surface_position.z)
+        );
+    }
+
+    void WorldmapModule::CreateCompanionModels(){
+        // These models and their spawn points are now hardcoded, they mmust be
+        // loaded according to the story point and save game data.
+        const Ogre::Real space = From16BitFixedPoint(8182);
+        AddWorldModel(
+          "Chocobo", "aja.mesh",
+          GetSpawn("Chocobo", Ogre::Vector3(42.5f, 0.0f, 37.5f)),
+          space * 0.14f,
+          // The animations of the model (asc) already have it the right way up.
+          Ogre::Quaternion::IDENTITY, 1.0f, true
+        );
+        AddWorldModel(
+          "Highwind", "cgd.mesh",
+          GetSpawn("Highwind", Ogre::Vector3(43.0f, 0.0f, 36.5f)),
+          space * 0.25f,
+          // The animation of the model (cic) already has it the right way up.
+          Ogre::Quaternion::IDENTITY, 0.5f, true
+        );
+        AddWorldModel(
+          "Buggy", "aba.mesh",
+          GetSpawn("Buggy", Ogre::Vector3(42.0f, 0.0f, 36.0f)),
+          space * 0.3f, Ogre::Quaternion::IDENTITY, 0.5f, true
+        );
+        AddWorldModel(
+          "Submarine", "ddd.mesh",
+          GetSpawn("Submarine", Ogre::Vector3(41.5f, 0.0f, 36.5f)),
+          space * 0.1125f, Ogre::Quaternion::IDENTITY, 1.0f, true
+        );
+        AddWorldModel(
+          "TinyBronco", "dva.mesh",
+          GetSpawn("TinyBronco", Ogre::Vector3(42.0f, 0.0f, 37.37f)),
+          space * 0.15f, Ogre::Quaternion::IDENTITY, 0.75f, true
+        );
+        highwind_entity_ = static_cast<EntityModel*>(
+          EntityManager::getSingleton().GetEntity("WorldMapHighwind")
+        );
+        buggy_entity_ = static_cast<EntityModel*>(
+          EntityManager::getSingleton().GetEntity("WorldMapBuggy")
+        );
+        chocobo_entity_ = static_cast<EntityModel*>(
+          EntityManager::getSingleton().GetEntity("WorldMapChocobo")
+        );
+        submarine_entity_ = static_cast<EntityModel*>(
+          EntityManager::getSingleton().GetEntity("WorldMapSubmarine")
+        );
+        tiny_bronco_entity_ = static_cast<EntityModel*>(
+          EntityManager::getSingleton().GetEntity("WorldMapTinyBronco")
+        );
+        for (const Ogre::String& name : hidden_vehicles_){
+            ::Entity* entity = EntityManager::getSingleton().GetEntity("WorldMap" + name);
+            if (entity == nullptr) continue;
+            entity->SetVisible(false);
+            entity->SetSolid(false);
+            entity->SetTalkable(false);
+        }
+    }
+
+    void WorldmapModule::AddWorldModelFromScript(
+      const char* name, const char* hrc, const float x, const float z, const int raw_scale,
+      const int direction, const float rotation_x, const float rotation_y, const float rotation_z
+    ){
+        if (name == nullptr || hrc == nullptr) return;
+        // The game scale is for coordinates of 4096 units per world unit, and 0x200 is 1 (15.2).
+        // The 1.1 is what the models that were adjusted by looking at them have more.
+        const Ogre::Real scale = (static_cast<Ogre::Real>(raw_scale) / 512.0f) * 15.2f / 4096.0f * 1.1f;
+        AddWorldModel(
+          name, Ogre::String(hrc) + ".mesh", Ogre::Vector3(x, 0.0f, z), 1.0f,
+          Ogre::Quaternion::IDENTITY, 1.0f, false, scale
+        );
+        ::Entity* entity = EntityManager::getSingleton().GetEntity(Ogre::String("WorldMap") + name);
+        if (entity == nullptr) return;
+        entity->SetSolid(false);
+        // The rotation of the model itself.
+        entity->setRootOrientation(
+          Ogre::Quaternion(Ogre::Degree(rotation_x), Ogre::Vector3::UNIT_X)
+            * Ogre::Quaternion(Ogre::Degree(rotation_y), Ogre::Vector3::UNIT_Y)
+            * Ogre::Quaternion(Ogre::Degree(rotation_z), Ogre::Vector3::UNIT_Z)
+        );
+        // The direction of the script is a full turn in 256: 0 faces +Z (south), 64 east (+X), 128 north and
+        // 192 west. Checked with the sea around Junon in the scene of the Warship, which sails at 192.
+        const Ogre::Radian heading(Ogre::Degree(direction * 360.0f / 256.0f));
+        static_cast<EntityModel*>(entity)->GetModel()->getParentSceneNode()->getParentSceneNode()
+          ->setOrientation(Ogre::Quaternion(heading, Ogre::Vector3::UNIT_Y));
+    }
+
+    void WorldmapModule::SetVehicleHidden(const char* entity_name){
+        if (entity_name != nullptr) hidden_vehicles_.insert(entity_name);
+    }
+
+    void WorldmapModule::SetSpeed(const char* name, const float speed){
+        if (name != nullptr && speed > 0.0f) speeds_[name] = speed;
+    }
+
+    void WorldmapModule::SetCamera(const char* name, const float distance, const float pitch_degrees){
+        if (name != nullptr && distance > 0.0f) camera_settings_[name] = {distance, pitch_degrees};
+    }
+
+    float WorldmapModule::GetSpeed(const char* name, const float default_speed) const{
+        const auto speed = speeds_.find(name);
+        return speed == speeds_.end() ? default_speed : speed->second;
+    }
+
+    void WorldmapModule::SetSpawn(const char* entity_name, const float x, const float z){
+        if (entity_name == nullptr) return;
+        spawn_overrides_[entity_name] = Ogre::Vector2(x, z);
+    }
+
+    Ogre::Vector3 WorldmapModule::GetSpawn(
+      const Ogre::String& entity_name, const Ogre::Vector3& default_spawn
+    ) const{
+        const auto spawn = spawn_overrides_.find(entity_name);
+        if (spawn == spawn_overrides_.end()) return default_spawn;
+        return Ogre::Vector3(spawn->second.x, 0.0f, spawn->second.y);
+    }
+
+    void WorldmapModule::SetModelOffset(const char* entity_name, const float y){
+        if (entity_name == nullptr) return;
+        ::Entity* entity = EntityManager::getSingleton().GetEntity(entity_name);
+        if (entity == nullptr) return;
+        SetModelHeightOffset(static_cast<EntityModel*>(entity), y);
+    }
+
+    void WorldmapModule::SetEntityAltitude(const char* entity_name, const float y){
+        if (entity_name == nullptr) return;
+        ::Entity* entity = EntityManager::getSingleton().GetEntity(entity_name);
+        if (entity == nullptr) return;
+        const Ogre::Vector3 position = entity->GetPosition();
+        entity->SetPosition(Ogre::Vector3(position.x, y, position.z));
+    }
+
+    void WorldmapModule::SetModelOrientation(
+      const char* entity_name, const float x, const float y, const float z
+    ){
+        if (entity_name == nullptr) return;
+        ::Entity* entity = EntityManager::getSingleton().GetEntity(entity_name);
+        if (entity == nullptr) return;
+        entity->setRootOrientation(
+          Ogre::Quaternion(Ogre::Degree(x), Ogre::Vector3::UNIT_X)
+            * Ogre::Quaternion(Ogre::Degree(y), Ogre::Vector3::UNIT_Y)
+            * Ogre::Quaternion(Ogre::Degree(z), Ogre::Vector3::UNIT_Z)
+        );
+    }
+
+    void WorldmapModule::SetModelHeading(const char* entity_name, const float direction){
+        if (entity_name == nullptr) return;
+        ::Entity* entity = EntityManager::getSingleton().GetEntity(entity_name);
+        if (entity == nullptr) return;
+        // The same heading as AddWorldModelFromScript.
+        const Ogre::Radian heading(Ogre::Degree(direction * 360.0f / 256.0f));
+        static_cast<EntityModel*>(entity)->GetModel()->getParentSceneNode()->getParentSceneNode()
+          ->setOrientation(Ogre::Quaternion(heading, Ogre::Vector3::UNIT_Y));
+    }
+
+    int WorldmapModule::GetModelHeading(const char* entity_name){
+        if (entity_name == nullptr) return 0;
+        ::Entity* entity = EntityManager::getSingleton().GetEntity(entity_name);
+        if (entity == nullptr) return 0;
+        const Ogre::Quaternion orientation = static_cast<EntityModel*>(entity)->GetModel()
+          ->getParentSceneNode()->getParentSceneNode()->getOrientation();
+        const Ogre::Vector3 forward = orientation * Ogre::Vector3(0.0f, 0.0f, 1.0f);
+        const float turns = std::atan2(forward.x, forward.z) / Ogre::Math::TWO_PI;
+        return static_cast<int>(std::floor(turns * 256.0f + 0.5f)) & 255;
+    }
+
+} // namespace VGears

A diferenza do arquivo foi suprimida porque é demasiado grande
+ 13 - 2012
src/modules/worldmap/WorldmapModule.cpp


+ 8 - 0
src/modules/worldmap/WorldmapModule.h

@@ -330,6 +330,14 @@ namespace VGears {
              */
             void UpdateFlight(EntityModel* entity, const Ogre::Real delta_time, const bool highwind);
 
+            /**
+             * Gets the name of a vehicle in the scripts (WorldMapSettings).
+             *
+             * @param[in] vehicle The vehicle.
+             * @return Its name, "walk" on foot.
+             */
+            static const char* GetVehicleScriptName(const VehicleType vehicle);
+
             void TriggerTriangleFunction(const TerrainTriangle& triangle);
             void LoadEncounters();
             void UpdateEncounters(const float delta_time, const TerrainTriangle& triangle);

+ 158 - 0
src/modules/worldmap/WorldmapSnow.cpp

@@ -0,0 +1,158 @@
+/*
+ * 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/WorldmapSnow.h"
+#include <algorithm>
+#include <cmath>
+#include <OgreException.h>
+#include <OgreLogManager.h>
+#include <OgreMaterialManager.h>
+#include <OgreOverlaySystem.h>
+#include <OgreResourceGroupManager.h>
+#include <OgreRoot.h>
+#include <OgreSceneManager.h>
+#include <OgreTechnique.h>
+#include <OgreTextureManager.h>
+#include <Overlay/OgreOverlay.h>
+#include <Overlay/OgreOverlayContainer.h>
+#include <Overlay/OgreOverlayManager.h>
+#include <Overlay/OgrePanelOverlayElement.h>
+#include "engine/ApplicationInterface.h"
+#include "engine/entity/EntityManager.h"
+#include "engine/entity/EntityModel.h"
+#include "modules/worldmap/WorldmapModule.h"
+#include "modules/worldmap/WorldmapConstants.h"
+#include "modules/worldmap/WorldmapTextures.h"
+
+namespace VGears {
+
+    using namespace Ogre;
+
+    /// Snow map (WM3): how many poles can exist at the same time.
+    static const size_t SNOW_MAX_POLES = 4;
+
+    /**
+     * The blizzard of WM3: two layers of the unused textures snow4 (cloud mist) and snow5 (dark blotches)
+     * drift over the screen at different speeds. How the original draws it is not known.
+     */
+    struct SnowLayer{
+        const char* texture;
+        float alpha;
+        float scroll_u;
+        float scroll_v;
+        float tiles_x;
+        float tiles_y;
+    };
+
+    static const SnowLayer SNOW_LAYERS[] = {
+        // The same texture three times, with other size, speed and direction (the opacities add up).
+        {"snow4", 0.28f, 0.030f, 0.150f, 0.6f, 0.45f},
+        {"snow4", 0.22f, -0.070f, 0.240f, 0.5f, 0.4f},
+        {"snow4", 0.18f, 0.105f, 0.345f, 0.8f, 0.6f}
+        // HIDDEN: {"snow5", 0.30f, -0.015f, 0.090f, 1.0f, 0.75f}
+    };
+
+    void SetSnowOverlay(const bool visible){
+        Ogre::OverlayManager& manager = Ogre::OverlayManager::getSingleton();
+        Ogre::Overlay* overlay = manager.getByName("WorldMapSnow");
+        if (overlay == nullptr){
+            if (!visible) return;
+            // The engine doesn't draw the overlays of Ogre unless its system listens to the scene.
+            Ogre::OverlaySystem* overlay_system = VGears::ApplicationInterface::Get()->GetOverlaySystem();
+            if (overlay_system != nullptr){
+                Root::getSingleton().getSceneManager("Scene")->addRenderQueueListener(overlay_system);
+            }
+            overlay = manager.create("WorldMapSnow");
+            overlay->setZOrder(100);
+            int index = 0;
+            for (const SnowLayer& layer : SNOW_LAYERS){
+                // The same texture can be in several layers: the materials and panels are by index.
+                const std::string name = std::string("WorldMapSnow_") + std::to_string(index) + "_" + layer.texture;
+                try{
+                    if (!Ogre::TextureManager::getSingleton().resourceExists(std::string("WorldMapTex_") + layer.texture)){
+                        LoadWorldMapTexture(layer.texture);
+                    }
+                }
+                catch (const Ogre::Exception& exception){
+                    LogManager::getSingleton().logMessage(
+                      "Failed to load the snow texture " + std::string(layer.texture) + ": " + exception.getDescription()
+                    );
+                    continue;
+                }
+                MaterialPtr material = Ogre::MaterialManager::getSingleton().create(
+                  name, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME
+                );
+                Pass* pass = material->getTechnique(0)->getPass(0);
+                pass->setLightingEnabled(false);
+                pass->setDepthCheckEnabled(false);
+                pass->setDepthWriteEnabled(false);
+                pass->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA);
+                Ogre::TextureUnitState* unit = pass->createTextureUnitState(std::string("WorldMapTex_") + layer.texture);
+                unit->setTextureAddressingMode(Ogre::TextureUnitState::TAM_WRAP);
+                unit->setAlphaOperation(Ogre::LBX_MODULATE, Ogre::LBS_TEXTURE, Ogre::LBS_MANUAL, 1.0f, layer.alpha);
+                unit->setScrollAnimation(layer.scroll_u, layer.scroll_v);
+                Ogre::PanelOverlayElement* panel = static_cast<Ogre::PanelOverlayElement*>(
+                  manager.createOverlayElement("Panel", name + "_panel")
+                );
+                panel->setMetricsMode(Ogre::GMM_RELATIVE);
+                panel->setPosition(0.0f, 0.0f);
+                panel->setDimensions(1.0f, 1.0f);
+                panel->setMaterialName(name);
+                panel->setTiling(layer.tiles_x, layer.tiles_y);
+                overlay->add2D(panel);
+                ++index;
+            }
+        }
+        if (visible) overlay->show();
+        else overlay->hide();
+        LogManager::getSingleton().logMessage(
+          std::string("World map snow overlay ") + (visible ? "shown" : "hidden") + ", layers: "
+          + std::to_string(overlay->get2DElements().size())
+        );
+    }
+
+    void WorldmapModule::UpdateSnowCamera(Ogre::Real delta_time){
+      if (snow_camera_remaining_ == 0.0f){
+        snow_camera_timer_ -= delta_time;
+        if (snow_camera_timer_ > 0.0f) return;
+        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;
+        snow_camera_remaining_ = direction * Ogre::Math::DegreesToRadians(degrees);
+        snow_camera_timer_ = Ogre::Math::RangeRandom(SNOW_CAMERA_MIN_WAIT, SNOW_CAMERA_MAX_WAIT);
+      }
+      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;
+      camera_yaw_ += signed_step;
+      snow_camera_remaining_ -= signed_step;
+      if (std::abs(snow_camera_remaining_) < 0.0001f) snow_camera_remaining_ = 0.0f;
+    }
+
+    void WorldmapModule::PlaceSnowPole(){
+      if (player_entity_ == nullptr) return;
+      // The oldest pole goes away when there is no room for another one.
+      while (snow_poles_.size() >= SNOW_MAX_POLES){
+        EntityManager::getSingleton().RemoveWorldMapEntity(snow_poles_.front());
+        snow_poles_.pop_front();
+      }
+      const Ogre::Vector3 position = player_entity_->GetPosition();
+      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);
+      if (EntityManager::getSingleton().GetEntity("WorldMap" + name) != nullptr){
+        snow_poles_.push_back("WorldMap" + name);
+      }
+    }
+
+} // namespace VGears

+ 28 - 0
src/modules/worldmap/WorldmapSnow.h

@@ -0,0 +1,28 @@
+/*
+ * 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
+
+
+
+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.
+     */
+    void SetSnowOverlay(const bool visible);
+}

+ 265 - 0
src/modules/worldmap/WorldmapSubmarine.cpp

@@ -0,0 +1,265 @@
+/*
+ * 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 <algorithm>
+#include <vector>
+#include <OgreEntity.h>
+#include <OgreLogManager.h>
+#include <OgreSceneNode.h>
+#include "engine/entity/EntityManager.h"
+#include "engine/entity/EntityModel.h"
+#include "engine/ui/UiManager.h"
+#include "engine/ui/UiWidget.h"
+#include "modules/worldmap/WorldmapData.h"
+
+namespace VGears {
+
+    using namespace Ogre;
+
+    /// How deep the submarine goes under the surface of WM0 when diving, in world units.
+    static const float DIVE_SINK_DEPTH = 0.5f;
+
+    /// Time the submarine takes to go under the surface of WM0, or to come up to it.
+    static const float DIVE_SINK_TIME = 1.0f;
+
+    /// Height where the submarine appears in WM2 when diving, and where it goes when surfacing.
+    /// It's over the top layer of the map.
+    static const float DIVE_HIGH_HEIGHT = 1.0f;
+
+    /// Time the submarine takes to go down from, or up to, the height above.
+    static const float DIVE_HIGH_TIME = 1.5f;
+
+    /// Time of the fade to black before the map changes.
+    static const float DIVE_FADE_OUT_TIME = 0.5f;
+
+    /**
+     * Gets if a position of the overworld (WM0) is over deep water. Used when the submarine
+     * comes back from WM2, when WM0 is not loaded. Only the part of the world that WM2 covers is
+     * read, and it's done once.
+     */
+    static bool IsOverworldDeepWater(const float x, const float z){
+        struct Triangle{
+            float x[3];
+            float z[3];
+        };
+        static std::vector<Triangle> triangles;
+        static bool loaded = false;
+        if (!loaded){
+            loaded = true;
+            const MapLayout overworld = GetMapLayout(0);
+            const MapLayout underwater = GetMapLayout(1);
+            const float space = From16BitFixedPoint(8182);
+            const std::vector<VGears::WorldmapFileSerializer::Block> blocks = LoadWorldMap("WM0.MAP");
+            for (size_t block_index = 0; block_index < std::min(blocks.size(), size_t(63)); ++block_index){
+                const int map_x = block_index % overworld.width;
+                const int map_y = block_index / overworld.width;
+                if (map_x < underwater.origin_x || map_x >= underwater.origin_x + underwater.width
+                  || map_y < underwater.origin_y || map_y >= underwater.origin_y + underwater.height){
+                    continue;
+                }
+                const VGears::WorldmapFileSerializer::Block& block = blocks[block_index];
+                for (size_t mesh_index = 0; mesh_index < block.meshes.size(); ++mesh_index){
+                    const VGears::WorldmapFileSerializer::BlockPart& part = block.meshes[mesh_index];
+                    const float pos_x = ((mesh_index % 4) + map_x * 4) * space;
+                    const float pos_z = ((mesh_index / 4) + map_y * 4) * space;
+                    for (const VGears::WorldmapFileSerializer::BlockTriangle& triangle : part.triangles){
+                        if (triangle.walkability_info_ != VGears::WorldmapFileSerializer::SEA_DEEP_WATER){
+                            continue;
+                        }
+                        const size_t indices[3] = {
+                          triangle.vertex_0_index, triangle.vertex_1_index, triangle.vertex_2_index
+                        };
+                        Triangle result;
+                        for (int i = 0; i < 3; ++i){
+                            const VGears::WorldmapFileSerializer::Vertex& vertex = part.vertices.at(indices[i]);
+                            result.x[i] = From16BitFixedPoint(vertex.x) + pos_x;
+                            result.z[i] = From16BitFixedPoint(vertex.z) + pos_z;
+                        }
+                        triangles.push_back(result);
+                    }
+                }
+            }
+        }
+        for (const Triangle& t : triangles){
+            const float denominator
+              = (t.z[1] - t.z[2]) * (t.x[0] - t.x[2]) + (t.x[2] - t.x[1]) * (t.z[0] - t.z[2]);
+            if (Ogre::Math::Abs(denominator) < 1e-6f) continue;
+            const float a = ((t.z[1] - t.z[2]) * (x - t.x[2]) + (t.x[2] - t.x[1]) * (z - t.z[2]))
+              / denominator;
+            const float b = ((t.z[2] - t.z[0]) * (x - t.x[2]) + (t.x[0] - t.x[2]) * (z - t.z[2]))
+              / denominator;
+            const float c = 1.0f - a - b;
+            if (a >= -1e-4f && b >= -1e-4f && c >= -1e-4f) return true;
+        }
+        return false;
+    }
+
+    bool WorldmapModule::DiveToUnderwaterMap(EntityModel* submarine){
+        const Ogre::Vector3 position = submarine->GetPosition();
+        Ogre::Vector3 surface;
+        uint8 walkability_type = 0;
+        if (!FindWalkableSurface(position, surface, false, false, &walkability_type)
+          || walkability_type != VGears::WorldmapFileSerializer::SEA_DEEP_WATER){
+            return false;
+        }
+        // WM2 only covers a part of the world.
+        if (!IsInsideMap(1, position.x, position.z)){
+            LogManager::getSingleton().logMessage(
+              "The submarine can't dive here: it's outside the underwater map."
+            );
+            return false;
+        }
+        dive_requested_ = true;
+        dive_position_ = position;
+        dive_heading_ = submarine->GetModel()->getParentSceneNode()->getParentSceneNode()
+          ->getOrientation().getYaw().valueRadians();
+        BeginTransition(true, submarine);
+        return true;
+    }
+
+    /**
+     * Sets how opaque the black cover of the screen is.
+     *
+     * @param[in] alpha 0 shows the world map, 1 is all black.
+     */
+    static void SetScreenCover(const float alpha){
+        UiWidget* cover = UiManager::getSingleton().GetWidget("Fade.Screen");
+        if (cover == nullptr) return;
+        cover->SetColour(0, 0, 0);
+        cover->SetAlpha(std::max(0.0f, std::min(1.0f, alpha)));
+    }
+
+    /// Eases a progress from 0 to 1.
+    static float Smooth(const float t){
+        const float clamped = std::max(0.0f, std::min(1.0f, t));
+        return clamped * clamped * (3.0f - 2.0f * clamped);
+    }
+
+    void WorldmapModule::BeginTransition(const bool dive, EntityModel* submarine){
+        transition_stage_ = TransitionStage::LEAVING;
+        transition_dive_ = dive;
+        transition_timer_ = 0;
+        transition_start_y_ = submarine->GetPosition().y;
+        // Diving: it sinks under the surface. Surfacing: it goes up, out of the map.
+        transition_target_y_ = dive ? transition_start_y_ - DIVE_SINK_DEPTH : DIVE_HIGH_HEIGHT;
+        EntityManager::getSingleton().ScriptPlayerLock(true);
+    }
+
+    void WorldmapModule::EndTransition(){
+        transition_stage_ = TransitionStage::NONE;
+        SetScreenCover(0);
+        EntityManager::getSingleton().ScriptPlayerLock(false);
+    }
+
+    void WorldmapModule::UpdateTransition(const Ogre::Real delta_time){
+        transition_timer_ += delta_time;
+        ::Entity* submarine = EntityManager::getSingleton().ScriptGetPlayerEntity();
+        if (submarine == nullptr){
+            EndTransition();
+            return;
+        }
+        const auto set_height = [submarine](const float y){
+            Ogre::Vector3 position = submarine->GetPosition();
+            position.y = y;
+            submarine->SetPosition(position);
+        };
+
+        if (transition_stage_ == TransitionStage::LEAVING){
+            const float duration = transition_dive_ ? DIVE_SINK_TIME : DIVE_HIGH_TIME;
+            set_height(
+              transition_start_y_
+              + (transition_target_y_ - transition_start_y_) * Smooth(transition_timer_ / duration)
+            );
+            if (transition_timer_ >= duration){
+                transition_stage_ = TransitionStage::FADING_OUT;
+                transition_timer_ = 0;
+            }
+        }
+        else if (transition_stage_ == TransitionStage::FADING_OUT){
+            SetScreenCover(transition_timer_ / DIVE_FADE_OUT_TIME);
+            if (transition_timer_ >= DIVE_FADE_OUT_TIME){
+                // The map changes under the black screen. The entities are not valid after it.
+                Init(transition_dive_ ? 1 : 0);
+                ::Entity* arrived = EntityManager::getSingleton().GetEntity("WorldMapSubmarine");
+                if (arrived == nullptr){
+                    EndTransition();
+                    return;
+                }
+                transition_target_y_ = arrived->GetPosition().y;
+                // Diving: it comes from high up. Surfacing: it comes from under the surface.
+                transition_start_y_ = transition_dive_
+                  ? DIVE_HIGH_HEIGHT : transition_target_y_ - DIVE_SINK_DEPTH;
+                Ogre::Vector3 position = arrived->GetPosition();
+                position.y = transition_start_y_;
+                arrived->SetPosition(position);
+                transition_stage_ = TransitionStage::ARRIVING;
+                transition_timer_ = 0;
+                EntityManager::getSingleton().ScriptPlayerLock(true);
+                UpdateCamera(0, true);
+            }
+        }
+        else if (transition_stage_ == TransitionStage::ARRIVING){
+            const float duration = transition_dive_ ? DIVE_HIGH_TIME : DIVE_SINK_TIME;
+            set_height(
+              transition_start_y_
+              + (transition_target_y_ - transition_start_y_) * Smooth(transition_timer_ / duration)
+            );
+            // The screen is shown again by the time the submarine is at its height.
+            SetScreenCover(1.0f - transition_timer_ / duration);
+            if (transition_timer_ >= duration){
+                set_height(transition_target_y_);
+                EndTransition();
+            }
+        }
+    }
+
+    bool WorldmapModule::SurfaceToOverworld(EntityModel* submarine){
+        const Ogre::Vector3 position = submarine->GetPosition();
+        // The same position of WM0 has to be deep water.
+        if (!IsOverworldDeepWater(position.x, position.z)){
+            LogManager::getSingleton().logMessage(
+              "The submarine can't surface here: it's not deep water in the overworld."
+            );
+            return false;
+        }
+        surface_requested_ = true;
+        surface_position_ = position;
+        surface_heading_ = submarine->GetModel()->getParentSceneNode()->getParentSceneNode()
+          ->getOrientation().getYaw().valueRadians();
+        BeginTransition(false, submarine);
+        return true;
+    }
+
+    void WorldmapModule::PlaceSurfacedSubmarine(){
+        surface_requested_ = false;
+        if (submarine_entity_ == nullptr) return;
+        Ogre::Vector3 surface;
+        if (!FindWalkableSurface(surface_position_, surface, false, false)) return;
+        submarine_entity_->SetPosition(surface);
+        submarine_entity_->GetModel()->getParentSceneNode()->getParentSceneNode()->setOrientation(
+          Ogre::Quaternion(Ogre::Radian(surface_heading_), Ogre::Vector3::UNIT_Y)
+        );
+        // Cloud boards the submarine, like the boarding script does.
+        player_entity_->SetVisible(false);
+        player_entity_->SetSolid(false);
+        player_entity_->SetTalkable(false);
+        ClearVehicleTerrains();
+        for (const char* terrain : {"SEA_DEEP_WATER", "SEA", "SUBMARINE_PEN"}) AddVehicleTerrain(terrain);
+        EntityManager::getSingleton().ScriptSetPlayerEntity("WorldMapSubmarine");
+        UpdateCamera(0, true);
+    }
+
+} // namespace VGears

+ 400 - 0
src/modules/worldmap/WorldmapTerrain.cpp

@@ -0,0 +1,400 @@
+/*
+ * 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 <algorithm>
+#include <cmath>
+#include <limits>
+#include <map>
+#include <set>
+#include <OgreException.h>
+#include <OgreLogManager.h>
+#include <OgreManualObject.h>
+#include <OgreRoot.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 "modules/worldmap/WorldmapData.h"
+#include "modules/worldmap/WorldmapTextures.h"
+
+namespace VGears {
+
+    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;
+
+    void WorldmapModule::CreateWorldMap(SceneManager* scene_manager){
+      scene_manager_ = scene_manager;
+      // The node is kept when a map is replaced.
+      if (world_map_node_ == nullptr){
+        world_map_node_ = scene_manager_->getRootSceneNode()
+          ->createChildSceneNode("WorldMapTerrain");
+      }
+      world_map_node_->setVisible(true);
+        std::vector<VGears::WorldmapFileSerializer::Block> blocks
+          = 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){
+            triangle.TextureInfo += GetTextureIdOffset(map_id_);
+          }
+        }
+        const size_t texture_count = WORLD_MAP_TEXTURE_COUNT;
+        // WM0 has extra blocks after the 9x7 grid: the alternate shapes of the story progress.
+        const size_t base_block_count = map_id_ == 0
+          ? std::min(blocks.size(), size_t(63)) : blocks.size();
+        const float space = From16BitFixedPoint(8182);
+        std::map<uint16, ManualObject*> texture_objects;
+        std::set<uint16> unavailable_texture_ids;
+        unsigned int manual_index = 0;
+
+        for (size_t block_index = 0; block_index < base_block_count; ++block_index){
+            const VGears::WorldmapFileSerializer::Block& block = blocks[block_index];
+            const size_t map_x = origin_x_ + block_index % grid_width_;
+            const size_t map_y = origin_y_ + block_index / grid_width_;
+            for (size_t mesh_index = 0; mesh_index < block.meshes.size(); ++mesh_index){
+                const VGears::WorldmapFileSerializer::BlockPart& part
+                  = block.meshes[mesh_index];
+                const size_t mesh_x = mesh_index % 4;
+                const size_t mesh_y = mesh_index / 4;
+                const float pos_x = (mesh_x * space) + (map_x * space * 4);
+                const float pos_z = (mesh_y * space) + (map_y * space * 4);
+
+                for (const VGears::WorldmapFileSerializer::BlockTriangle& triangle
+                  : part.triangles){
+                    const VGears::WorldmapFileSerializer::Vertex& vertex_0
+                      = part.vertices.at(triangle.vertex_0_index);
+                    const VGears::WorldmapFileSerializer::Vertex& vertex_1
+                      = part.vertices.at(triangle.vertex_1_index);
+                    const VGears::WorldmapFileSerializer::Vertex& vertex_2
+                      = part.vertices.at(triangle.vertex_2_index);
+                    TerrainTriangle terrain_triangle;
+                    terrain_triangle.vertices[0] = Ogre::Vector3(
+                      From16BitFixedPoint(vertex_0.x) + pos_x,
+                      From16BitFixedPoint(vertex_0.y),
+                      From16BitFixedPoint(vertex_0.z) + pos_z
+                    );
+                    terrain_triangle.vertices[1] = Ogre::Vector3(
+                      From16BitFixedPoint(vertex_1.x) + pos_x,
+                      From16BitFixedPoint(vertex_1.y),
+                      From16BitFixedPoint(vertex_1.z) + pos_z
+                    );
+                    terrain_triangle.vertices[2] = Ogre::Vector3(
+                      From16BitFixedPoint(vertex_2.x) + pos_x,
+                      From16BitFixedPoint(vertex_2.y),
+                      From16BitFixedPoint(vertex_2.z) + pos_z
+                    );
+                    terrain_triangle.walkability_type = triangle.walkability_info_;
+                    terrain_triangle.function_id = triangle.function_id;
+                    terrain_triangle.mesh_x = static_cast<int>(map_x * 4 + mesh_x);
+                    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.
+                    terrain_triangle.region = std::min<int>(triangle.Location & 0x1F, 15);
+                    terrain_triangles_.push_back(terrain_triangle);
+
+                    if (unavailable_texture_ids.find(triangle.TextureInfo)
+                      != unavailable_texture_ids.end()){
+                        continue;
+                    }
+                    if (triangle.TextureInfo >= texture_count){
+                        if (unavailable_texture_ids.insert(triangle.TextureInfo).second){
+                            LogManager::getSingleton().logMessage(
+                              "Skipping world-map texture ID "
+                                + std::to_string(triangle.TextureInfo)
+                                + ": no PC texture mapping is available."
+                            );
+                        }
+                        continue;
+                    }
+
+                    ManualObject* manual = nullptr;
+                    auto object = texture_objects.find(triangle.TextureInfo);
+                    if (object == texture_objects.end()){
+                        MaterialPtr material;
+                        try{
+                            material = LoadTextureMaterial(triangle.TextureInfo);
+                        }
+                        catch (const Ogre::Exception& exception){
+                            unavailable_texture_ids.insert(triangle.TextureInfo);
+                            LogManager::getSingleton().logMessage(
+                              "Failed to load world-map texture "
+                                + std::string(WORLD_MAP_TEXTURES[triangle.TextureInfo].name)
+                                + ": " + exception.getDescription()
+                            );
+                            continue;
+                        }
+
+                        manual = scene_manager->createManualObject(
+                          "world_map_surface_" + std::to_string(++manual_index)
+                        );
+                        manual->begin(material->getName(), RenderOperation::OT_TRIANGLE_LIST);
+                        manual->setDebugDisplayEnabled(false);
+                        manual->setDynamic(false);
+                        texture_objects[triangle.TextureInfo] = manual;
+                    }
+                    else manual = object->second;
+
+                    manual->position(
+                      terrain_triangle.vertices[2].x,
+                      terrain_triangle.vertices[2].y,
+                      terrain_triangle.vertices[2].z
+                    );
+                    manual->textureCoord(
+                      ToTextureCoordU(triangle.vertex_2_u, triangle.TextureInfo),
+                      ToTextureCoordV(triangle.vertex_2_v, triangle.TextureInfo)
+                    );
+
+                    manual->position(
+                      terrain_triangle.vertices[1].x,
+                      terrain_triangle.vertices[1].y,
+                      terrain_triangle.vertices[1].z
+                    );
+                    manual->textureCoord(
+                      ToTextureCoordU(triangle.vertex_1_u, triangle.TextureInfo),
+                      ToTextureCoordV(triangle.vertex_1_v, triangle.TextureInfo)
+                    );
+
+                    manual->position(
+                      terrain_triangle.vertices[0].x,
+                      terrain_triangle.vertices[0].y,
+                      terrain_triangle.vertices[0].z
+                    );
+                    manual->textureCoord(
+                      ToTextureCoordU(triangle.vertex_0_u, triangle.TextureInfo),
+                      ToTextureCoordV(triangle.vertex_0_v, triangle.TextureInfo)
+                    );
+                }
+            }
+        }
+
+        for (const auto& texture_object : texture_objects){
+            texture_object.second->end();
+            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));
+    }
+
+    void WorldmapModule::BuildTerrainIndex(){
+        terrain_grid_.clear();
+        terrain_grid_columns_ = 0;
+        terrain_grid_rows_ = 0;
+        if (terrain_triangles_.empty()) return;
+        float min_x = std::numeric_limits<float>::max(), min_z = min_x;
+        float max_x = -min_x, max_z = -min_x;
+        for (const TerrainTriangle& triangle : terrain_triangles_){
+            for (const Ogre::Vector3& vertex : triangle.vertices){
+                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);
+            }
+        }
+        // A cell is as big as a mesh of the map (a triangle almost always touches only one).
+        terrain_grid_cell_ = From16BitFixedPoint(8182);
+        terrain_grid_min_x_ = min_x;
+        terrain_grid_min_z_ = min_z;
+        terrain_grid_columns_ = static_cast<int>((max_x - min_x) / terrain_grid_cell_) + 1;
+        terrain_grid_rows_ = static_cast<int>((max_z - min_z) / terrain_grid_cell_) + 1;
+        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).
+        const float margin = 0.01f;
+        for (size_t i = 0; i < terrain_triangles_.size(); ++i){
+            const TerrainTriangle& triangle = terrain_triangles_[i];
+            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;
+            for (const Ogre::Vector3& vertex : triangle.vertices){
+                t_min_x = std::min(t_min_x, vertex.x); t_max_x = std::max(t_max_x, vertex.x);
+                t_min_z = std::min(t_min_z, vertex.z); t_max_z = std::max(t_max_z, vertex.z);
+            }
+            const int column_0 = std::max(0, static_cast<int>(std::floor((t_min_x - margin - min_x) / terrain_grid_cell_)));
+            const int column_1 = std::min(terrain_grid_columns_ - 1, static_cast<int>(std::floor((t_max_x + margin - min_x) / terrain_grid_cell_)));
+            const int row_0 = std::max(0, static_cast<int>(std::floor((t_min_z - margin - min_z) / terrain_grid_cell_)));
+            const int row_1 = std::min(terrain_grid_rows_ - 1, static_cast<int>(std::floor((t_max_z + margin - min_z) / terrain_grid_cell_)));
+            for (int row = row_0; row <= row_1; ++row){
+                for (int column = column_0; column <= column_1; ++column){
+                    terrain_grid_[static_cast<size_t>(row) * terrain_grid_columns_ + column].push_back(static_cast<uint32>(i));
+                }
+            }
+        }
+        size_t entries = 0;
+        for (const auto& cell : terrain_grid_) entries += cell.size();
+        LogManager::getSingleton().logMessage(
+          "World map terrain index: " + std::to_string(terrain_triangles_.size()) + " triangles in "
+          + std::to_string(terrain_grid_columns_) + "x" + std::to_string(terrain_grid_rows_) + " cells, "
+          + std::to_string(entries) + " entries"
+        );
+    }
+
+    bool WorldmapModule::FindWalkableSurface(
+      const Ogre::Vector3& position, Ogre::Vector3& surface, bool grass_only,
+      bool require_walkable, uint8* walkability_type, size_t* triangle_index, bool use_index
+    ) const{
+        bool found = false;
+        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
+        // is the same as with all of them).
+        const std::vector<uint32>* cell_triangles = nullptr;
+        if (use_index && !terrain_grid_.empty()){
+            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_));
+            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];
+        }
+        const size_t candidate_count = cell_triangles != nullptr ? cell_triangles->size() : terrain_triangles_.size();
+        for (size_t candidate = 0; candidate < candidate_count; ++candidate){
+            const size_t i = cell_triangles != nullptr ? (*cell_triangles)[candidate] : candidate;
+            const TerrainTriangle& triangle = terrain_triangles_[i];
+            if (grass_only
+              && triangle.walkability_type != VGears::WorldmapFileSerializer::GRASS){
+                continue;
+            }
+            const Ogre::Vector3& a = triangle.vertices[0];
+            const Ogre::Vector3& b = triangle.vertices[1];
+            const Ogre::Vector3& c = triangle.vertices[2];
+            const Ogre::Real denominator
+              = (b.z - c.z) * (a.x - c.x) + (c.x - b.x) * (a.z - c.z);
+            if (Ogre::Math::Abs(denominator) < 1e-6f) continue;
+
+            const Ogre::Real weight_a
+              = ((b.z - c.z) * (position.x - c.x)
+                + (c.x - b.x) * (position.z - c.z)) / denominator;
+            const Ogre::Real weight_b
+              = ((c.z - a.z) * (position.x - c.x)
+                + (a.x - c.x) * (position.z - c.z)) / denominator;
+            const Ogre::Real weight_c = 1.0f - weight_a - weight_b;
+            if (weight_a < -1e-4f || weight_b < -1e-4f || weight_c < -1e-4f){
+                continue;
+            }
+
+            const Ogre::Real height
+              = weight_a * a.y + weight_b * b.y + weight_c * c.y;
+            const Ogre::Real height_distance = Ogre::Math::Abs(height - position.y);
+            if (height_distance >= closest_height_distance) continue;
+            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));
+            surface = Ogre::Vector3(position.x, height, position.z);
+            if (walkability_type != nullptr) *walkability_type = triangle.walkability_type;
+            if (triangle_index != nullptr) *triangle_index = i;
+        }
+        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

+ 139 - 0
src/modules/worldmap/WorldmapTextures.cpp

@@ -0,0 +1,139 @@
+/*
+ * 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/WorldmapTextures.h"
+#include <memory>
+#include <OgreException.h>
+#include <OgreHardwarePixelBuffer.h>
+#include <OgreMaterialManager.h>
+#include <OgreResourceGroupManager.h>
+#include <OgreTechnique.h>
+#include <OgreTextureManager.h>
+#include "modules/worldmap/WorldmapData.h"
+#include "formats/texture/TexFile.h"
+
+namespace VGears {
+
+    using namespace Ogre;
+
+    float ToTextureCoordU(uint8 coord, uint16 id){
+        return (float(coord) - float(WORLD_MAP_TEXTURES[id].u)) / float(WORLD_MAP_TEXTURES[id].width);
+        //return (float(WORLD_MAP_TEXTURES[id].u) + float(coord)) / 256.0f;
+    }
+
+    float ToTextureCoordV(uint8 coord, uint16 id){
+        return (float(coord) - float(WORLD_MAP_TEXTURES[id].v)) / float(WORLD_MAP_TEXTURES[id].height);
+        //return (float(WORLD_MAP_TEXTURES[id].v) + float(coord)) / 640.0f;
+    }
+
+    struct ImageDataDeleter{
+
+      void operator()(Ogre::ImageCodec::ImageData* image_data) const{
+        OGRE_DELETE image_data;
+      }
+    };
+
+    TexturePtr LoadWorldMapTexture(const std::string& name){
+        const std::string texture_name = name + ".tex";
+        Ogre::DataStreamPtr stream
+          = ResourceGroupManager::getSingleton().openResource(
+              texture_name, WORLD_MAP_RESOURCE_GROUP, nullptr, true
+            );
+        VGears::TexFile tex_file;
+        tex_file.Read(stream);
+
+        Ogre::MemoryDataStreamPtr pixel_data(tex_file.GetPixelData());
+        std::unique_ptr<Ogre::ImageCodec::ImageData, ImageDataDeleter> image_data(
+          tex_file.GetImageData()
+        );
+        TexturePtr texture = Ogre::TextureManager::getSingleton().createManual(
+          std::string("WorldMapTex_") + name,
+          ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, TEX_TYPE_2D,
+          image_data->width, image_data->height, 0, image_data->format, TU_STATIC
+        );
+        texture->getBuffer()->blitFromMemory(Ogre::PixelBox(
+          image_data->width, image_data->height, 1, image_data->format,
+          pixel_data->getPtr()
+        ));
+        return texture;
+    }
+
+
+    /**
+     * Animated textures (water, shores, rivers, waterfalls, swamps). The original game has sets of
+     * frames named by the first one plus a number (ff7.exe 0x95b880: fall1-8, riv_l1-4, ...). The
+     * triangles use the first frame, and the material of it shows the frames in turn.
+     */
+    struct AnimatedTextureSet{
+        const char* prefix;
+        int frames;
+    };
+
+    static const AnimatedTextureSet ANIMATED_TEXTURES[] = {
+        {"we_s", 8}, {"fall", 8}, {"uf", 4}, {"lst", 4}, {"sst", 4}, {"rm", 4}, {"ds", 4}, {"sh", 4},
+        {"ssee", 4}, {"riv_l", 4}, {"ds_s", 4}, {"sh_s", 4}, {"sse_s", 4}, {"swp", 4}, {"dsee", 4},
+        {"shlm_", 4}, {"des0", 4}, {"edes0", 4}, {"rivs", 4}
+    };
+
+    /** Seconds that each frame of the animated textures lasts (the original timing is not known). */
+    static const float ANIMATED_TEXTURE_FRAME_SECONDS = 0.125f;
+
+    void AnimateWorldMapTextures(const float delta_time){
+        static float elapsed = 0;
+        static long last_step = -1;
+        elapsed += delta_time;
+        const long step = static_cast<long>(elapsed / ANIMATED_TEXTURE_FRAME_SECONDS);
+        if (step == last_step) return;
+        last_step = step;
+        for (const AnimatedTextureSet& set : ANIMATED_TEXTURES){
+            MaterialPtr material = Ogre::MaterialManager::getSingleton().getByName(
+              std::string("WorldMap_") + set.prefix + "1"
+            );
+            if (material.isNull()) continue;
+            const std::string frame_name = std::string(set.prefix) + std::to_string(step % set.frames + 1);
+            const std::string texture_name = std::string("WorldMapTex_") + frame_name;
+            try{
+                if (!Ogre::TextureManager::getSingleton().resourceExists(texture_name)){
+                    if (!ResourceGroupManager::getSingleton().resourceExists(
+                      WORLD_MAP_RESOURCE_GROUP, frame_name + ".tex"
+                    )) continue;
+                    LoadWorldMapTexture(frame_name);
+                }
+                material->getTechnique(0)->getPass(0)->getTextureUnitState(0)->setTextureName(texture_name);
+            }
+            catch (const Ogre::Exception&){}
+        }
+    }
+
+    MaterialPtr LoadTextureMaterial(uint16 texture_id){
+        const std::string material_name
+          = std::string("WorldMap_") + WORLD_MAP_TEXTURES[texture_id].name;
+        MaterialPtr material
+          = Ogre::MaterialManager::getSingleton().getByName(material_name);
+        // The textures and materials are kept when a map is replaced, and the maps share them.
+        if (material.isNull()){
+            TexturePtr texture = LoadWorldMapTexture(WORLD_MAP_TEXTURES[texture_id].name);
+            material = Ogre::MaterialManager::getSingleton().create(
+              material_name, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME
+            );
+            Pass* pass = material->getTechnique(0)->getPass(0);
+            pass->createTextureUnitState(texture->getName());
+            pass->setTextureFiltering(TFO_NONE);
+            pass->setLightingEnabled(false);
+        }
+        return material;
+    }
+
+} // namespace VGears

+ 67 - 0
src/modules/worldmap/WorldmapTextures.h

@@ -0,0 +1,67 @@
+/*
+ * 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 <string>
+#include <OgreMaterial.h>
+#include <OgreTexture.h>
+#include "common/TypeDefine.h"
+
+namespace VGears {
+
+    /**
+     * Converts a coordinate to a texture U component coordinate.
+     *
+     * @param[in] coord The coordinate to convert.
+     * @param[in] id Texture ID.
+     * @return Texture coordinate U component.
+     * @todo Understand and document properly.
+     */
+    float ToTextureCoordU(uint8 coord, uint16 id);
+
+    /**
+     * Converts a coordinate to a texture V component coordinate.
+     *
+     * @param[in] coord The coordinate to convert.
+     * @param[in] id Texture ID.
+     * @return Texture coordinate V component.
+     * @todo Understand and document properly.
+     */
+    float ToTextureCoordV(uint8 coord, uint16 id);
+
+    /**
+     * Loads a texture of the world map.
+     *
+     * @param[in] name Name of the texture file, without extension.
+     * @return The texture, named "WorldMapTex_<name>".
+     */
+    Ogre::TexturePtr LoadWorldMapTexture(const std::string& name);
+
+    /**
+     * Shows the frame that the animated textures (water, waterfalls...) have now.
+     *
+     * @param[in] delta_time Seconds since the last frame.
+     */
+    void AnimateWorldMapTextures(const float delta_time);
+
+    /**
+     * Gets the material of a texture of the terrain, creating it if needed.
+     *
+     * @param[in] texture_id Id of the texture in the table of textures.
+     * @return The material.
+     */
+    Ogre::MaterialPtr LoadTextureMaterial(uint16 texture_id);
+}

+ 248 - 0
src/modules/worldmap/WorldmapVehicles.cpp

@@ -0,0 +1,248 @@
+/*
+ * 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 <algorithm>
+#include <OgreEntity.h>
+#include <OgreSceneNode.h>
+#include "engine/entity/EntityManager.h"
+#include "engine/entity/EntityModel.h"
+#include "engine/input/InputManager.h"
+#include "modules/worldmap/WorldmapConstants.h"
+#include "modules/worldmap/WorldmapData.h"
+
+namespace VGears {
+
+    using namespace Ogre;
+
+    /// Turning speed of the flying vehicles, in radians per second.
+    static const float FLIGHT_TURN_SPEED = 1.5f;
+
+    /// Speed up and down of the flying vehicles, in world units per second.
+    static const float FLIGHT_CLIMB_SPEED = 1.0f;
+
+    /// Highest height over the ground where the Highwind can be unboarded. It lands there.
+    static const float HIGHWIND_MAX_LANDING_HEIGHT = 1.0f;
+
+    /// Highest point the Highwind can reach.
+    static const float HIGHWIND_MAX_HEIGHT = 1.0f;
+
+    /**
+     * Animations of a vehicle in the world map, from the A files of the model: when it's parked,
+     * when it's boarded, and when it's boarded and moving. An empty name is no animation (the
+     * model in its pose). The roles were found by playing them, and for the models with only one
+     * animation it's the one of the model.
+     */
+    struct VehicleAnimations{
+        const char* parked;
+        const char* boarded;
+        const char* moving;
+        /// The parked animation shows its first frame and doesn't move.
+        bool parked_paused;
+    };
+
+    static const VehicleAnimations CHOCOBO_ANIMATIONS = {"asc", "asc", "asd", false};
+    static const VehicleAnimations BUGGY_ANIMATIONS = {"age", "aha", "aha", false};
+    static const VehicleAnimations TINY_BRONCO_ANIMATIONS = {"dya", "dya", "dya", true};
+    static const VehicleAnimations HIGHWIND_ANIMATIONS = {"cic", "cic", "cic", true};
+    static const VehicleAnimations SUBMARINE_ANIMATIONS = {"dfe", "dfe", "dfe", true};
+
+    /**
+     * Plays the animation of a vehicle in its current state.
+     */
+    static void PlayVehicleAnimation(
+      EntityModel* vehicle, const ::Entity* active_entity, const bool moving,
+      const VehicleAnimations& animations
+    ){
+        if (vehicle == nullptr) return;
+        const bool parked = vehicle != active_entity;
+        const char* name = parked ? animations.parked
+          : (moving ? animations.moving : animations.boarded);
+        if (name[0] == '\0'){
+            vehicle->StopAnimation();
+            return;
+        }
+        if (parked && animations.parked_paused){
+            vehicle->PlayAnimationPaused(name);
+            return;
+        }
+        vehicle->UnfreezeAnimation();
+        if (vehicle->HasAnimation(name)) vehicle->PlayAnimationContinue(name);
+    }
+
+    void WorldmapModule::UpdateVehicleAnimations(const bool moving){
+        const ::Entity* active_entity = EntityManager::getSingleton().ScriptGetPlayerEntity();
+        PlayVehicleAnimation(chocobo_entity_, active_entity, moving, CHOCOBO_ANIMATIONS);
+        PlayVehicleAnimation(buggy_entity_, active_entity, moving, BUGGY_ANIMATIONS);
+        PlayVehicleAnimation(tiny_bronco_entity_, active_entity, moving, TINY_BRONCO_ANIMATIONS);
+        PlayVehicleAnimation(highwind_entity_, active_entity, moving, HIGHWIND_ANIMATIONS);
+        PlayVehicleAnimation(submarine_entity_, active_entity, moving, SUBMARINE_ANIMATIONS);
+    }
+
+    void WorldmapModule::UpdateFlight(
+      EntityModel* entity, const Ogre::Real delta_time, const bool highwind
+    ){
+        Ogre::SceneNode* node = entity->GetModel()->getParentSceneNode()->getParentSceneNode();
+        if (flight_entity_ != entity){
+            // Starts flying: continue from the current heading and height.
+            flight_entity_ = entity;
+            flight_heading_ = node->getOrientation().getYaw().valueRadians();
+            flight_y_ = entity->GetPosition().y;
+            camera_yaw_ = 0;
+        }
+
+        float turn = 0;
+        float climb = 0;
+        bool forward = false;
+        // Scripts lock the player during events and transitions.
+        if (!EntityManager::getSingleton().IsPlayerLocked()){
+            InputManager& input = InputManager::getSingleton();
+            // The heading decreases to turn right: the model faces +Z at heading 0 and the
+            // right side of the camera behind it is -X.
+            if (input.IsGameEventPressed("walk_left")) turn += 1.0f;
+            if (input.IsGameEventPressed("walk_right")) turn -= 1.0f;
+            // Inverted, like the controls of a plane: down climbs and up descends.
+            if (input.IsGameEventPressed("walk_up")) climb -= 1.0f;
+            if (input.IsGameEventPressed("walk_down")) climb += 1.0f;
+            forward = input.IsGameEventPressed("CONFIRM");
+        }
+
+        flight_heading_ += turn * FLIGHT_TURN_SPEED * delta_time;
+        if (flight_heading_ > Ogre::Math::PI) flight_heading_ -= Ogre::Math::TWO_PI;
+        else if (flight_heading_ < -Ogre::Math::PI) flight_heading_ += Ogre::Math::TWO_PI;
+        node->setOrientation(Ogre::Quaternion(Ogre::Radian(flight_heading_), Ogre::Vector3::UNIT_Y));
+
+        const Ogre::Vector3 current_position = entity->GetPosition();
+        Ogre::Vector3 requested_position = current_position;
+        if (forward){
+            const Ogre::Vector3 direction(
+              Ogre::Math::Sin(Ogre::Radian(flight_heading_)), 0.0f,
+              Ogre::Math::Cos(Ogre::Radian(flight_heading_))
+            );
+            requested_position += direction * delta_time * GetSpeed(
+              highwind ? "highwind" : "submarine", From16BitFixedPoint(8182) * 0.45f * 2.0f
+            );
+        }
+
+        // The terrain below. If the vehicle can't go there, it stays but can still go up or down.
+        Ogre::Vector3 surface;
+        size_t triangle_index = 0;
+        if (!FindWalkableSurface(requested_position, surface, false, true, nullptr, &triangle_index)){
+            requested_position = current_position;
+            if (!FindWalkableSurface(
+              requested_position, surface, false, false, nullptr, &triangle_index
+            )) return;
+            forward = false;
+        }
+
+        // The ground has priority over the maximum height, so the vehicle never goes through it.
+        const Ogre::Real ceiling = highwind ? HIGHWIND_MAX_HEIGHT : UNDERWATER_MAX_HEIGHT;
+        Ogre::Real new_y = flight_y_ + climb * FLIGHT_CLIMB_SPEED * delta_time;
+        new_y = std::min(new_y, ceiling);
+        new_y = std::max(new_y, surface.y + FLIGHT_MIN_CLEARANCE);
+        const Ogre::Vector3 new_position(requested_position.x, new_y, requested_position.z);
+        if (EntityManager::getSingleton().IsWorldPositionBlocked(entity, new_position)) return;
+        flight_y_ = new_y;
+        entity->SetPosition(new_position);
+        if (forward) EnterTriangle(terrain_triangles_[triangle_index]);
+    }
+
+    /// Name of a vehicle in the scripts (WorldMapSettings).
+    const char* WorldmapModule::GetVehicleScriptName(const VehicleType vehicle){
+        switch (vehicle){
+            case VehicleType::CHOCOBO: return "chocobo";
+            case VehicleType::BUGGY: return "buggy";
+            case VehicleType::HIGHWIND: return "highwind";
+            case VehicleType::SUBMARINE: return "submarine";
+            case VehicleType::TINY_BRONCO: return "tiny_bronco";
+            default: return "walk";
+        }
+    }
+
+      bool WorldmapModule::UnboardVehicle(const char* vehicle_name){
+        if (vehicle_name == nullptr) return false;
+
+        EntityManager& entity_manager = EntityManager::getSingleton();
+        ::Entity* player_entity = entity_manager.ScriptGetPlayerEntity();
+        ::Entity* vehicle_entity = entity_manager.GetEntity(vehicle_name);
+        if (
+          player_entity == nullptr || vehicle_entity == nullptr
+          || player_entity != vehicle_entity || player_entity == player_entity_
+        ){
+          return false;
+        }
+
+        const Ogre::Vector3 vehicle_position = vehicle_entity->GetPosition();
+        const Ogre::Real unboard_distance
+          = vehicle_entity->GetSolidRadius() + player_entity_->GetSolidRadius() + 0.1f;
+        const Ogre::Real diagonal_distance = unboard_distance * 0.70710678f;
+        const Ogre::Vector3 directions[] = {
+          Ogre::Vector3(1, 0, 0), Ogre::Vector3(-1, 0, 0),
+          Ogre::Vector3(0, 0, 1), Ogre::Vector3(0, 0, -1),
+          Ogre::Vector3(1, 0, 1), Ogre::Vector3(-1, 0, 1),
+          Ogre::Vector3(1, 0, -1), Ogre::Vector3(-1, 0, -1)
+        };
+
+        for (size_t i = 0; i < sizeof(directions) / sizeof(directions[0]); ++i){
+          const Ogre::Real distance = i < 4 ? unboard_distance : diagonal_distance;
+          const Ogre::Vector3 requested_position
+            = vehicle_position + directions[i] * distance;
+          Ogre::Vector3 surface;
+          uint8 walkability_type = 0;
+          if (!FindWalkableSurface(
+              requested_position, surface, false, false, &walkability_type
+            ) || !IsFootWalkable(walkability_type)){
+            continue;
+          }
+          surface.y += player_height_offset_;
+          if (entity_manager.IsWorldPositionBlocked(player_entity_, surface)) continue;
+
+          if (vehicle_entity == highwind_entity_){
+            // The Highwind lands. It can't be left higher up, Cloud couldn't board it again.
+            Ogre::Vector3 ground;
+            if (!FindWalkableSurface(vehicle_position, ground, false, false)) return false;
+            if (vehicle_position.y - ground.y > HIGHWIND_MAX_LANDING_HEIGHT) return false;
+            vehicle_entity->SetPosition(Ogre::Vector3(vehicle_position.x, ground.y, vehicle_position.z));
+            // Landing on the terrain of the northern cave enters it (the function of the triangle runs).
+            uint8 landing_terrain = 0;
+            size_t landing_triangle = 0;
+            if (FindWalkableSurface(vehicle_position, ground, false, false, &landing_terrain, &landing_triangle)
+              && landing_terrain == VGears::WorldmapFileSerializer::NORTHERND_CAVE
+              && terrain_triangles_[landing_triangle].function_id >= 3){
+              landing_after_unboard_ = &terrain_triangles_[landing_triangle];
+            }
+          }
+          player_entity_->SetPosition(surface);
+          // The boarding scripts hide Cloud and make him non-solid.
+          player_entity_->SetVisible(true);
+          player_entity_->SetSolid(true);
+          vehicle_entity->SetTalkable(true);
+          entity_manager.ScriptSetPlayerEntity("WorldMapCloud");
+          ClearVehicleTerrains();
+          if (landing_after_unboard_ != nullptr){
+            // The Highwind is what entered (the vehicle of the trigger).
+            current_vehicle_ = VehicleType::HIGHWIND;
+            landing_trigger_ = true;
+            TriggerTriangleFunction(*landing_after_unboard_);
+            landing_trigger_ = false;
+            landing_after_unboard_ = nullptr;
+          }
+          current_vehicle_ = VehicleType::ON_FOOT;
+          return true;
+        }
+        return false;
+      }
+
+} // namespace VGears

Algúns arquivos non se mostraron porque demasiados arquivos cambiaron neste cambio