Răsfoiți Sursa

Add world map settings, music rules, town entry rules and WM2/WM3 visuals

Settings
- Add world_settings.lua with per-vehicle speed and camera (distance and pitch), walking speed, music tracks and overrides, and town entry rules.

Music
- Add music to different worlds, based onvehicle and story preogress

Town entry
- Implemented per-vehicle entry conditions for towns.

Visuals and mechanics
- Animate the water textures of WM0.
- Add fog to WM2, and fix the WM2/WM3 texture mapping using the texture table.
- WM3: snow overlay, camera mechanicas, and poles.
- Cliff terrain is not walkable on foot.

Fixes
- Place the player at the exit point from the field script.
- Reload vehicles.lua when returning from a field.

Performance
- Add a spatial grid for the terrain triangle lookup,
Iñigo Valentin 2 zile în urmă
părinte
comite
1ab5a78450

+ 2 - 0
data/data/scripts/_scripts.xml

@@ -31,6 +31,8 @@
     <script file="scripts/worldmap/triangle_triggers.lua" />
     <script file="scripts/worldmap/vehicles.lua" />
     <script file="scripts/worldmap/world_model_table.lua" />
+    <script file="scripts/worldmap/world_settings.lua" />
+    <script file="scripts/worldmap/world_music.lua" />
     <script file="scripts/worldmap/world_vm.lua" />
     <script file="scripts/worldmap/script_stubs.lua" />
     <script file="scripts/battle_ai.lua" />

+ 5 - 0
data/data/scripts/worldmap/triangle_triggers.lua

@@ -61,6 +61,11 @@ System.WorldMap = {
         local world_function = function_index
           and self["world_function_" .. tostring(function_index)]
         if world_function then
+            -- A place can only be entered by the vehicles that the settings say (WorldMapSettings.entry).
+            local record = WorldVM and WorldVM.find_field_entry(world_function)
+            if record and not WorldVM.can_enter(record, self.vehicle, self.landing) then
+                return
+            end
             world_function(self)
         else
             print(

+ 64 - 0
data/data/scripts/worldmap/world_music.lua

@@ -0,0 +1,64 @@
+--[[
+Music of the world map. The data (tracks, overrides and conditions) is in world_settings.lua
+(WorldMapSettings.music); this has the logic that picks the track and plays it.
+
+WorldMusic.update is called by the module when a map starts, when the vehicle changes, and every half
+second (the story can change the music while the map is on).
+]]
+
+WorldMusic = WorldMusic or {current = nil}
+
+--- Calls a function of the settings that can fail without stopping the game.
+local function safe(func, ...)
+    if type(func) ~= "function" then return nil end
+    local ok, result = pcall(func, ...)
+    if ok then return result end
+    return nil
+end
+
+--- Gets the track of a map and a vehicle.
+-- @param map_id 0 for WM0, 1 for WM2 (underwater), 2 for WM3 (snow).
+-- @param vehicle walk, chocobo, buggy, tiny_bronco, highwind or submarine.
+-- @return The track or nil.
+WorldMusic.choose = function(map_id, vehicle)
+    local music = WorldMapSettings and WorldMapSettings.music
+    if not music then return nil end
+    if map_id == 1 then return music.underwater end
+    if map_id == 2 then return music.snow end
+
+    -- The Chocobo always has priority.
+    if vehicle == "chocobo" and music.chocobo then return music.chocobo end
+
+    -- Overrides of the story: the vehicles don't change them.
+    for _, override in ipairs(music.overrides or {}) do
+        if safe(override.when) then return override.track end
+    end
+
+    -- The vehicles with their own track.
+    if vehicle == "highwind" and music.highwind and not safe(music.cloud_away) then
+        return music.highwind
+    end
+    if vehicle ~= "walk" and vehicle ~= "highwind" and vehicle ~= "chocobo" and music[vehicle] then
+        return music[vehicle]
+    end
+
+    -- The default one of the story.
+    local from_story = music.danger_from_story
+    if music.danger and from_story and ReadWord(0) >= from_story then return music.danger end
+    return music.default
+end
+
+--- Plays the track of the moment if it is not the one that is playing.
+-- @param map_id Map of the module.
+-- @param vehicle Name of the vehicle.
+WorldMusic.update = function(map_id, vehicle)
+    local track = WorldMusic.choose(map_id, vehicle)
+    if track == nil or track == WorldMusic.current then return end
+    WorldMusic.current = track
+    audio_manager:play_music(tostring(track))
+end
+
+--- Forgets the track that was playing (the next update plays it again).
+WorldMusic.reset = function()
+    WorldMusic.current = nil
+end

+ 113 - 0
data/data/scripts/worldmap/world_settings.lua

@@ -0,0 +1,113 @@
+-- Settings of the world map that are meant to be edited.
+
+local BLOCK = 8182 / 4096 -- units of a mesh block (a map block is 2 of them)
+local BASE = BLOCK * 0.45 -- the speed that the game has by default for walking
+
+--- Movement speeds, in world units per second (about 0.9 is the default walking speed).
+-- A name that is removed uses the default of the module (walking 0.9, the vehicles twice that).
+local speed = {
+    walk = BASE,
+    chocobo = BASE * 1.5,
+    buggy = BASE * 1.2,
+    tiny_bronco = BASE * 1.2,
+    -- The Highwind and the submarine (in WM2 and when diving) when they move forward.
+    highwind = BASE * 2,
+    submarine = BASE * 1.2,
+}
+
+-- The camera that the module had: 2.7 units from the vehicle, 33.7 degrees over the ground (the offset
+-- 1.5 up and 2.25 back). It is the distance that was good for the fastest vehicle.
+local DISTANCE = 2.0
+local PITCH = 33.7
+-- A bit more parallel to the ground, for the vehicles that fly.
+local FLIGHT_PITCH = 20
+WorldMapSettings = {
+    speed = speed,
+
+    --- Camera: distance to the vehicle (world units) and angle over the ground (degrees), by vehicle.
+    -- submarine_underwater is the submarine in WM2 and submarine the one that floats in WM0.
+    camera = {
+        walk = {distance = 1.35, pitch = PITCH},
+        chocobo = {distance = DISTANCE, pitch = PITCH},
+        buggy = {distance = DISTANCE, pitch = PITCH},
+        tiny_bronco = {distance = DISTANCE, pitch = PITCH},
+        highwind = {distance = DISTANCE, pitch = FLIGHT_PITCH},
+        submarine = {distance = DISTANCE, pitch = PITCH},
+        submarine_underwater = {distance = DISTANCE, pitch = FLIGHT_PITCH},
+    },
+
+    --- Music of the world map (the logic is in world_music.lua). Numbers are the tracks of audio/musics.
+    -- Written from the description of the game by the user, and from the scripts of the world (wm0.lua);
+    -- the pieces that are not known yet are marked TODO and are the ones to fix.
+    music = {
+        -- On foot (and the vehicles that have no music of their own).
+        default = 13, -- world_map
+        -- TODO: the track that replaces the default after some point of disc two (70, world_map_danger),
+        -- and the value of the story counter (ReadWord(0)) where it starts. nil means it never starts.
+        danger = 70,
+        danger_from_story = nil,
+
+        -- The Chocobo always has its own track (assumed, not checked).
+        chocobo = 50, -- chocobo_ride
+        -- The Highwind (WM0) has its own track, except when the music is an override of the story or
+        -- when cloud_away() is true.
+        highwind = 46, -- airship
+        -- TODO: the Buggy, the Tiny Bronco and the submarine of WM0 have no known music: they use
+        -- the default one. Put the track here when it is known (nil = the default).
+        buggy = nil,
+        tiny_bronco = nil,
+        submarine = nil,
+
+        -- WM2 (underwater) and WM3 (snow): one track that never changes.
+        -- TODO: 84 and 76 are from memory (84 is the "submarine" track of the installer), check them.
+        underwater = 84,
+        snow = 76,
+
+        --- Overrides of the story, in order of priority. The first one whose when() is true gives the
+        -- track, and the vehicles (except the Chocobo) don't change it.
+        overrides = {
+            -- While the Diamond Weapon is around. The conditions are the ones of the world script that
+            -- calls Unknown_AKAO(6) (bit 6803 set, 7212 set, 7209 not set); that 6 is guessed to mean 69.
+            -- TODO: check that the music ends with the Diamond Weapon (what ends it, when 7209 is set?).
+            {name = "diamond_weapon", track = 69, when = function()
+                return ReadBit(6803) ~= 0 and ReadBit(7212) ~= 0 and ReadBit(7209) == 0
+            end},
+            -- Before the last visit to Midgar. The script calls Unknown_AKAO(7) when the story counter is
+            -- exactly 1596; that 7 is guessed to mean 71.
+            -- TODO: the real range of the story counter (it may last more than that value).
+            {name = "before_last_midgar", track = 71, when = function()
+                return ReadWord(0) == 1596
+            end},
+        },
+
+        --- True while Cloud is not in the party: the Highwind doesn't change the music then.
+        -- TODO: find out when (the story counter range, or a flag). For now it is never.
+        cloud_away = function()
+            return false
+        end,
+    },
+
+    --- Which vehicles can enter the places of the map (towns, caves...). The numbers are the FIELD.TBL
+    -- records, the first parameter of EnterFieldScene (1 Midgar, 2 Kalm, 3 the chocobo farm, 7 Junon, 15 North
+    -- Corel, 18 Costa del Sol, 59 the northern cave...). On foot everything can be entered.
+    entry = {
+        --- Records that any vehicle can enter. The scripted events and the submarine station are here
+        -- so that nothing gets stuck.
+        -- TODO: check the list (50-52 are the ship fields, 56 the submarine station): add the other
+        -- records that are story events and not places, if some vehicle must be able to trigger them.
+        exempt = {[50] = true, [51] = true, [52] = true, [56] = true},
+
+        --- Exceptions to "only on foot", by vehicle: records that it can enter.
+        allowed = {
+            chocobo = {[3] = true}, -- the chocobo farm
+            -- Corel, Junon and Costa del Sol.
+            -- TODO: check the records of Corel: 15 is North Corel (ncorel), 14 Mt. Corel (mtcrl_0) and 16
+            -- the Corel desert (desert2) could be it too.
+            buggy = {[7] = true, [15] = true, [18] = true},
+        },
+
+        --- Records that the Highwind enters when it lands on the NORTHERND_CAVE terrain (it cannot enter
+        -- anything else, and it never enters while it is flying).
+        highwind_landing = {[59] = true}, -- the northern cave (las0_1)
+    },
+}

+ 45 - 0
data/data/scripts/worldmap/world_vm.lua

@@ -156,6 +156,41 @@ WorldVM.get_spawn = function(model_type)
     }
 end
 
+--- Which field a function of a trigger enters (EnterFieldScene), without doing anything else of what it
+-- does: it runs it as something that only looks (it undoes the writes to the variables).
+-- @param script_function The function (world_function_N).
+-- @return The FIELD.TBL record that it enters, nil if it doesn't enter one.
+WorldVM.find_field_entry = function(script_function)
+    local previous = EnterFieldScene
+    local record = nil
+    EnterFieldScene = function(field_table_id)
+        record = record or tonumber(field_table_id)
+        return 0
+    end
+    WorldVM.run_sandboxed(function()
+        pcall(script_function, System.WorldMap)
+    end)
+    EnterFieldScene = previous
+    return record
+end
+
+--- If a vehicle can enter a place (WorldMapSettings.entry).
+-- @param record FIELD.TBL record of the place.
+-- @param vehicle walk, chocobo, buggy, tiny_bronco, highwind or submarine.
+-- @param landing True if the Highwind has just landed.
+-- @return True if it can.
+WorldVM.can_enter = function(record, vehicle, landing)
+    if vehicle == nil or vehicle == "walk" then return true end
+    local entry = WorldMapSettings and WorldMapSettings.entry
+    if not entry then return true end
+    if entry.exempt and entry.exempt[record] then return true end
+    if vehicle == "highwind" then
+        return landing == true and entry.highwind_landing ~= nil and entry.highwind_landing[record] == true
+    end
+    local allowed = entry.allowed and entry.allowed[vehicle]
+    return allowed ~= nil and allowed[record] == true
+end
+
 --- Creates the models that the scripts place in a map.
 -- @param map_id Map of the module (0 WM0, 1 WM2, 2 WM3).
 WorldVM.place_models = function(map_id)
@@ -252,6 +287,16 @@ end
 -- @param map_id Map of the module (0 WM0, 1 WM2, 2 WM3).
 WorldVM.prepare = function(map_id)
     WorldVM.apply_debug_variables()
+    -- The speeds of walking and of each vehicle (world_settings.lua).
+    if WorldMapSettings and WorldMapSettings.speed then
+        for name, speed in pairs(WorldMapSettings.speed) do world_map_module:set_speed(name, speed) end
+    end
+    -- The distance and the angle of the camera for walking and for each vehicle.
+    if WorldMapSettings and WorldMapSettings.camera then
+        for name, camera in pairs(WorldMapSettings.camera) do
+            world_map_module:set_camera(name, camera.distance, camera.pitch)
+        end
+    end
     System.WorldMap.specials = {}
     -- The arrival of a real field exit has priority over the spawn points of the debug data.
     local real_arrival = System.WorldMap.arrival

+ 14 - 0
doc/TODO.md

@@ -32,3 +32,17 @@ Not done yet (kernel data in ff7.exe, ids 170-176, see `get_special_limit` in `b
   interactive piece and the random effects of the reels.
 - Vincent's transformations (additional effect 3 with modifiers 0 to 3): they change the model, the
   stats and the commands during the battle.
+
+## World map: culling of the terrain geometry
+
+The terrain of WM0 is built as one `ManualObject` per texture for the whole map (`CreateWorldMap`), so
+its bounding box is the whole map and Ogre never culls it: every frame draws all of its ~142,000
+triangles in ~320 batches, however little of it the camera sees. With the entity debug off it runs at
+about 110-140 fps in the tests. The search of the triangle under a position was the bigger problem and
+is solved (spatial grid, `BuildTerrainIndex`).
+
+Not planned for now. If it is needed: build the geometry per block or mesh (one object per mesh and
+texture), so the frustum culling skips the ones that are out of view, and measure the number of batches
+afterwards, because it can grow. Loading and unloading blocks around the player is the next step after
+that, but the whole map fits in memory, so it should only be for the load time. The 6 alternate blocks of
+WM0 (story shapes) are not loaded now and would have to be handled.

+ 5 - 0
src/common/VGearsApplication.h

@@ -79,6 +79,11 @@ namespace VGears{
              */
             Ogre::RenderWindow* getRenderWindow(void);
 
+            /**
+             * The overlay system (it must be added to a scene manager as a render queue listener to draw overlays).
+             */
+            Ogre::OverlaySystem* GetOverlaySystem(){return _overlay_system.get();}
+
             /**
              * Retrieves the Ogre resources file name.
              *

+ 15 - 0
src/core/EntityManager.cpp

@@ -495,6 +495,21 @@ void EntityManager::RemoveBattleEntity(const Ogre::String& name){
     }
 }
 
+void EntityManager::RemoveWorldMapEntity(const Ogre::String& name){
+    if (!IsWorldModule()) return;
+    for (auto it = entity_.begin(); it != entity_.end(); ++ it){
+        Entity* entity = *it;
+        if (entity->GetName() != name) continue;
+        if (entity == player_entity_) return;
+        ScriptManager::getSingleton().RemoveEntity(ScriptManager::ENTITY, name);
+        entity_.erase(it);
+        // The destructor of the model destroys it.
+        delete entity;
+        scene_node_->removeAndDestroyChild("Model_" + name);
+        return;
+    }
+}
+
 Entity* EntityManager::GetBackground3D() const{
     if (IsFieldModule()){
         LOG_WARNING("Tried to retrieve a 3D background while the EntityManager is in field mode.");

+ 9 - 0
src/core/EntityManager.h

@@ -140,6 +140,15 @@ class EntityManager : public Manager, public Ogre::Singleton<EntityManager>{
          */
         void RemoveBattleEntity(const Ogre::String& name);
 
+        /**
+         * Removes a world map entity (like a pole that was added while playing).
+         *
+         * If the manager is not in the world module, or the entity doesn't exist, it will do nothing.
+         *
+         * @param[in] name Entity name.
+         */
+        void RemoveWorldMapEntity(const Ogre::String& name);
+
         /**
          * Clears all world map information in the entity manager.
          *

+ 2 - 0
src/core/ScriptManagerBinds.h

@@ -645,6 +645,8 @@ void ScriptManager::InitBinds(){
       "set_entity_altitude", &VGears::WorldmapModule::SetEntityAltitude,
       "enter", &VGears::WorldmapModule::Enter,
       "set_spawn", &VGears::WorldmapModule::SetSpawn,
+      "set_speed", &VGears::WorldmapModule::SetSpeed,
+      "set_camera", &VGears::WorldmapModule::SetCamera,
       "set_vehicle_hidden", &VGears::WorldmapModule::SetVehicleHidden,
       "add_world_model", &VGears::WorldmapModule::AddWorldModelFromScript
     );

+ 410 - 16
src/modules/worldmap/WorldmapModule.cpp

@@ -40,6 +40,11 @@
 #include <OgreHardwarePixelBuffer.h>
 #include <OgreLogManager.h>
 #include <OgreTextureManager.h>
+#include "common/VGearsApplication.h"
+#include <Overlay/OgreOverlay.h>
+#include <Overlay/OgreOverlayContainer.h>
+#include <Overlay/OgreOverlayManager.h>
+#include <Overlay/OgrePanelOverlayElement.h>
 #include <OgreMaterialManager.h>
 #include <OgreResourceGroupManager.h>
 #include "data/VGearsTexFile.h"
@@ -386,9 +391,30 @@ namespace VGears {
         {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}
+        {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}
     };
 
+    /**
+     * 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).
+     */
+    static uint16 GetTextureIdOffset(const uint8 map_id){
+        return map_id == 1 ? 282 : (map_id == 2 ? 290 : 0);
+    }
+
     static const char* WORLD_MAP_RESOURCE_GROUP = "WORLD_MAP";
 
     static bool IsFootWalkable(uint8 walkability_type){
@@ -401,7 +427,6 @@ namespace VGears {
         case WalkType::WASTELAND:
         case WalkType::SNOW:
         case WalkType::RIVERSIDE:
-        case WalkType::CLIFF:
         case WalkType::COREL_BRIDGE:
         case WalkType::WUTAI_BRIDGE:
         case WalkType::HILL_SIDE:
@@ -511,6 +536,19 @@ 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;
+    /// Snow map (WM3): how many poles can exist at the same time.
+    static const size_t SNOW_MAX_POLES = 4;
+
+    /** Distances (from the camera, 1 map block = 2 units) where the black fog of WM2 starts and is total. */
+    static const float UNDERWATER_FOG_START = 2.0f;
+    static const float UNDERWATER_FOG_END = 6.0f;
+
     /// Turning speed of the flying vehicles, in radians per second.
     static const float FLIGHT_TURN_SPEED = 1.5f;
 
@@ -670,9 +708,8 @@ namespace VGears {
       }
     };
 
-    static TexturePtr LoadWorldMapTexture(uint16 texture_id){
-        const std::string texture_name
-          = std::string(textures[texture_id].name) + ".tex";
+    static 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
@@ -685,7 +722,7 @@ namespace VGears {
           tex_file.GetImageData()
         );
         TexturePtr texture = Ogre::TextureManager::getSingleton().createManual(
-          std::string("WorldMapTex_") + textures[texture_id].name,
+          std::string("WorldMapTex_") + name,
           ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, TEX_TYPE_2D,
           image_data->width, image_data->height, 0, image_data->format, TU_STATIC
         );
@@ -696,6 +733,135 @@ namespace VGears {
         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;
+
+    static 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&){}
+        }
+    }
+
+
+    /**
+     * 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}
+    };
+
+    static 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::Application::getSingleton().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())
+        );
+    }
+
+
     static MaterialPtr LoadTextureMaterial(uint16 texture_id){
         const std::string material_name
           = std::string("WorldMap_") + textures[texture_id].name;
@@ -703,7 +869,7 @@ namespace VGears {
           = 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(texture_id);
+            TexturePtr texture = LoadWorldMapTexture(textures[texture_id].name);
             material = Ogre::MaterialManager::getSingleton().create(
               material_name, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME
             );
@@ -837,8 +1003,13 @@ namespace VGears {
           ->createChildSceneNode("WorldMapTerrain");
       }
       world_map_node_->setVisible(true);
-        const std::vector<VGears::WorldmapFileSerializer::Block> blocks
+        std::vector<VGears::WorldmapFileSerializer::Block> blocks
           = LoadWorldMap("WM" + std::to_string(WORLD_MAP_FILE_NUMBERS[map_id_]) + ".MAP");
+        if (GetTextureIdOffset(map_id_) != 0){
+          for (auto& block : blocks) for (auto& mesh : block.meshes) for (auto& triangle : mesh.triangles){
+            triangle.TextureInfo += GetTextureIdOffset(map_id_);
+          }
+        }
         const size_t texture_count = sizeof(textures) / sizeof(textures[0]);
         // WM0 has extra blocks after the 9x7 grid: the alternate shapes of the story progress.
         const size_t base_block_count = map_id_ == 0
@@ -972,6 +1143,8 @@ namespace VGears {
             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();
@@ -1255,13 +1428,73 @@ namespace VGears {
         }
     }
 
+    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 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();
-        for (size_t i = 0; i < terrain_triangles_.size(); ++i){
+        // 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){
@@ -1540,6 +1773,19 @@ namespace VGears {
         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);
@@ -1673,7 +1919,9 @@ namespace VGears {
               Ogre::Math::Sin(Ogre::Radian(flight_heading_)), 0.0f,
               Ogre::Math::Cos(Ogre::Radian(flight_heading_))
             );
-            requested_position += direction * From16BitFixedPoint(8182) * 0.45f * 2.0f * delta_time;
+            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.
@@ -1699,6 +1947,18 @@ namespace VGears {
         if (forward) EnterTriangle(terrain_triangles_[triangle_index]);
     }
 
+    /// Name of a vehicle in the scripts (WorldMapSettings).
+    static const char* GetVehicleScriptName(const WorldmapModule::VehicleType vehicle){
+        switch (vehicle){
+            case WorldmapModule::VehicleType::CHOCOBO: return "chocobo";
+            case WorldmapModule::VehicleType::BUGGY: return "buggy";
+            case WorldmapModule::VehicleType::HIGHWIND: return "highwind";
+            case WorldmapModule::VehicleType::SUBMARINE: return "submarine";
+            case WorldmapModule::VehicleType::TINY_BRONCO: return "tiny_bronco";
+            default: return "walk";
+        }
+    }
+
     void WorldmapModule::TriggerTriangleFunction(const TerrainTriangle& triangle){
         ScriptEntity* world_map_script
           = ScriptManager::getSingleton().GetScriptEntityByName(
@@ -1707,6 +1967,11 @@ namespace VGears {
         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
@@ -1783,6 +2048,14 @@ namespace VGears {
             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.
@@ -1791,6 +2064,14 @@ namespace VGears {
           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;
         }
@@ -1799,6 +2080,7 @@ namespace VGears {
 
     bool WorldmapModule::frameStarted(const Ogre::FrameEvent& event){
       if (!initialized_ || player_entity_ == nullptr || paused_for_battle_) return true;
+      AnimateWorldMapTextures(event.timeSinceLastFrame);
 
       // Diving or surfacing: the submarine moves by itself and the screen fades.
       if (transition_stage_ != TransitionStage::NONE){
@@ -1833,6 +2115,25 @@ namespace VGears {
         return true;
       }
 
+        // The music of the map (WorldMusic in world_music.lua): when the vehicle changes and every half second.
+        music_timer_ += event.timeSinceLastFrame;
+        if (music_timer_ >= 0.5f || music_vehicle_ != current_vehicle_){
+          music_timer_ = 0.0f;
+          music_vehicle_ = current_vehicle_;
+          const char* music_vehicle = "walk";
+          switch (current_vehicle_){
+            case VehicleType::CHOCOBO: music_vehicle = "chocobo"; break;
+            case VehicleType::BUGGY: music_vehicle = "buggy"; break;
+            case VehicleType::HIGHWIND: music_vehicle = "highwind"; break;
+            case VehicleType::SUBMARINE: music_vehicle = "submarine"; break;
+            case VehicleType::TINY_BRONCO: music_vehicle = "tiny_bronco"; break;
+            default: break;
+          }
+          ScriptManager::getSingleton().RunString(
+            "if WorldMusic then WorldMusic.update(" + std::to_string(map_id_) + ", \"" + music_vehicle + "\") end"
+          );
+        }
+
         const bool highwind_active = active_entity == highwind_entity_;
       const bool vehicle_active = current_vehicle_ != VehicleType::ON_FOOT;
         const bool cancel_pressed = InputManager::getSingleton().IsGameEventPressed("CANCEL");
@@ -1856,6 +2157,12 @@ namespace VGears {
         const bool confirm_pressed = InputManager::getSingleton().IsGameEventPressed("CONFIRM");
         const bool dive_pressed = confirm_pressed && !confirm_was_pressed_;
         confirm_was_pressed_ = confirm_pressed;
+        if (
+          dive_pressed && map_id_ == 2 && active_entity == player_entity_
+          && !EntityManager::getSingleton().IsPlayerLocked()
+        ){
+            PlaceSnowPole();
+        }
         if (
           dive_pressed && map_id_ == 0 && active_entity == submarine_entity_
           && !EntityManager::getSingleton().IsPlayerLocked()
@@ -1883,8 +2190,12 @@ namespace VGears {
         // L1 and R1 rotate the camera around the active entity.
         {
             InputManager& camera_input = InputManager::getSingleton();
-            if (camera_input.IsGameEventPressed("L1")) camera_yaw_ -= CAMERA_ROTATION_SPEED * event.timeSinceLastFrame;
-            if (camera_input.IsGameEventPressed("R1")) camera_yaw_ += CAMERA_ROTATION_SPEED * event.timeSinceLastFrame;
+            // The camera of the snow map (WM3) can't be moved by hand: it turns by itself.
+            if (map_id_ == 2) UpdateSnowCamera(event.timeSinceLastFrame);
+            else{
+                if (camera_input.IsGameEventPressed("L1")) camera_yaw_ -= CAMERA_ROTATION_SPEED * event.timeSinceLastFrame;
+                if (camera_input.IsGameEventPressed("R1")) camera_yaw_ += CAMERA_ROTATION_SPEED * event.timeSinceLastFrame;
+            }
             if (camera_yaw_ > Ogre::Math::PI) camera_yaw_ -= Ogre::Math::TWO_PI;
             else if (camera_yaw_ < -Ogre::Math::PI) camera_yaw_ += Ogre::Math::TWO_PI;
         }
@@ -1908,8 +2219,18 @@ namespace VGears {
           // The movement is relative to the camera.
           movement = Ogre::Quaternion(Ogre::Radian(camera_yaw_), Ogre::Vector3::UNIT_Y) * movement;
             const Ogre::Vector3 current_position = active_entity->GetPosition();
-          const Ogre::Real speed = From16BitFixedPoint(8182) * 0.45f
-            * (vehicle_active ? 2.0f : 1.0f);
+          const char* speed_name = "walk";
+          switch (current_vehicle_){
+            case VehicleType::CHOCOBO: speed_name = "chocobo"; break;
+            case VehicleType::BUGGY: speed_name = "buggy"; break;
+            case VehicleType::HIGHWIND: speed_name = "highwind"; break;
+            case VehicleType::SUBMARINE: speed_name = "submarine"; break;
+            case VehicleType::TINY_BRONCO: speed_name = "tiny_bronco"; break;
+            default: break;
+          }
+          const Ogre::Real speed = GetSpeed(
+            speed_name, From16BitFixedPoint(8182) * 0.45f * (vehicle_active ? 2.0f : 1.0f)
+          );
           Ogre::Vector3 requested_position = current_position
             + movement * speed * event.timeSinceLastFrame;
           Ogre::Vector3 surface;
@@ -1963,9 +2284,24 @@ namespace VGears {
           = active_entity->GetPosition() + Ogre::Vector3(0, active_entity->GetHeight() * 0.5f, 0);
         // The camera of a flying vehicle stays behind it. L1 and R1 rotate it from there.
         const float yaw = camera_yaw_ + (flight_active_ ? flight_heading_ + Ogre::Math::PI : 0.0f);
+        // The camera of the entity: distance and angle over the ground (the default one is the offset 1.5, 2.25).
+        const char* camera_name = "walk";
+        if (map_id_ == 1) camera_name = "submarine_underwater";
+        else if (active_entity == chocobo_entity_) camera_name = "chocobo";
+        else if (active_entity == buggy_entity_) camera_name = "buggy";
+        else if (active_entity == highwind_entity_) camera_name = "highwind";
+        else if (active_entity == submarine_entity_) camera_name = "submarine";
+        else if (active_entity == tiny_bronco_entity_) camera_name = "tiny_bronco";
+        float distance = std::sqrt(1.5f * 1.5f + 2.25f * 2.25f);
+        float pitch = std::atan2(1.5f, 2.25f);
+        const auto camera_settings = camera_settings_.find(camera_name);
+        if (camera_settings != camera_settings_.end()){
+          distance = camera_settings->second.distance;
+          pitch = Ogre::Math::DegreesToRadians(camera_settings->second.pitch_degrees);
+        }
         const Ogre::Vector3 camera_offset
           = Ogre::Quaternion(Ogre::Radian(yaw), Ogre::Vector3::UNIT_Y)
-            * Ogre::Vector3(0.0f, 1.5f, 2.25f);
+            * Ogre::Vector3(0.0f, distance * std::sin(pitch), distance * std::cos(pitch));
         Ogre::Camera* camera = CameraManager::getSingleton().GetCurrentCamera();
         const Ogre::Vector3 desired_position = target + camera_offset;
         if (snap_to_player){
@@ -2102,6 +2438,9 @@ namespace VGears {
     void WorldmapModule::ResumeAfterBattle(){
         paused_for_battle_ = false;
         encounter_frames_ = 0;
+        // The battle had its own music: the one of the map starts again.
+        music_timer_ = 1.0f;
+        ScriptManager::getSingleton().RunString("if WorldMusic then WorldMusic.reset() end");
         if (world_map_node_ != nullptr) world_map_node_->setVisible(true);
         if (player_entity_ != nullptr) UpdateCamera(0, true);
     }
@@ -2157,6 +2496,7 @@ namespace VGears {
         }
       }
       terrain_triangles_.clear();
+      terrain_grid_.clear();
       encounter_records_.clear();
       // The entities of the old map (player, vehicles, models and scripts).
       EntityManager::getSingleton().ClearWorld();
@@ -2185,6 +2525,9 @@ namespace VGears {
         EntityManager::getSingleton().SetWorldModule();
         DialogsManager::getSingleton().SetWorldModule();
         world_map_node_->setVisible(true);
+        // The music starts again (a field or a battle had its own).
+        music_timer_ = 1.0f;
+        ScriptManager::getSingleton().RunString("if WorldMusic then WorldMusic.reset() end");
         CreatePlayer();
         Root::getSingleton().addFrameListener(this);
         frame_listener_attached_ = true;
@@ -2200,6 +2543,24 @@ namespace VGears {
       EntityManager::getSingleton().SetWorldModule();
       DialogsManager::getSingleton().SetWorldModule();
       CreateWorldMap(Root::getSingleton().getSceneManager("Scene"));
+      // Underwater (WM2): everything fades to black with the distance to the camera.
+      if (map_id_ == 1){
+        Root::getSingleton().getSceneManager("Scene")->setFog(
+          Ogre::FOG_LINEAR, Ogre::ColourValue::Black, 0.0f, UNDERWATER_FOG_START, UNDERWATER_FOG_END
+        );
+      }
+      else Root::getSingleton().getSceneManager("Scene")->setFog(Ogre::FOG_NONE);
+      // Snow map (WM3): it always snows.
+      SetSnowOverlay(map_id_ == 2);
+      // The music of the map starts in the first frame.
+      music_timer_ = 1.0f;
+      ScriptManager::getSingleton().RunString("if WorldMusic then WorldMusic.reset() end");
+      snow_poles_.clear();
+      snow_pole_counter_ = 0;
+      // The button that was used to get here (a menu, a field) must not count as the first pole.
+      confirm_was_pressed_ = InputManager::getSingleton().IsGameEventPressed("CONFIRM");
+      snow_camera_remaining_ = 0.0f;
+      snow_camera_timer_ = Ogre::Math::RangeRandom(SNOW_CAMERA_MIN_WAIT, SNOW_CAMERA_MAX_WAIT);
       ScriptManager::getSingleton().RunFile(
         "scripts/worldmap/wm" + std::to_string(WORLD_MAP_FILE_NUMBERS[map_id_]) + ".lua"
       );
@@ -2226,11 +2587,44 @@ namespace VGears {
       frame_listener_attached_ = true;
     }
 
+    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);
+      }
+    }
+
     void WorldmapModule::Suspend(){
       if (!frame_listener_attached_) return;
       Root::getSingleton().removeFrameListener(this);
       frame_listener_attached_ = false;
       if (world_map_node_ != nullptr) world_map_node_->setVisible(false);
+      SetSnowOverlay(false);
       player_entity_ = nullptr;
       highwind_entity_ = nullptr;
       buggy_entity_ = nullptr;

+ 47 - 1
src/modules/worldmap/WorldmapModule.h

@@ -18,6 +18,7 @@
 #include <OgreFrameListener.h>
 #include <OgreSingleton.h>
 #include <OgreVector3.h>
+#include <deque>
 #include <map>
 #include <set>
 #include <vector>
@@ -119,6 +120,13 @@ namespace VGears {
              * @param[in] z Position in Z, in world units.
              */
             void SetSpawn(const char* entity_name, const float x, const float z);
+            /// Sets a movement speed (world units per second) by name: walk, chocobo, buggy, tiny_bronco,
+            /// highwind or submarine (WorldMapSettings.speed in world_settings.lua).
+            void SetSpeed(const char* name, const float speed);
+            /// Sets the camera of a vehicle by name (the ones of the speeds, and submarine_underwater for the
+            /// submarine of WM2): distance to the vehicle in world units and angle over the ground in degrees
+            /// (WorldMapSettings.camera in world_settings.lua).
+            void SetCamera(const char* name, const float distance, const float pitch_degrees);
 
             /**
              * Hides a vehicle of the overworld that the story hasn't given yet: it is not visible,
@@ -233,12 +241,20 @@ namespace VGears {
                             Ogre::Real explicit_scale = 0.0f
                         );
             void UpdateCamera(Ogre::Real delta_time, bool snap_to_player);
+            /// Snow map (WM3): the camera turns by itself every few seconds.
+            void UpdateSnowCamera(Ogre::Real delta_time);
+            /// Snow map (WM3): puts a pole where the player is (only 4 poles exist, the oldest goes away).
+            void PlaceSnowPole();
             bool FindWalkableSurface(
                             const Ogre::Vector3& position, Ogre::Vector3& surface,
                             bool grass_only = false, bool require_walkable = true,
                             uint8* walkability_type = nullptr,
-                            size_t* triangle_index = nullptr
+                            size_t* triangle_index = nullptr,
+                            bool use_index = true
             ) const;
+            /// Groups the triangles of the terrain by the cell of a grid they touch, so the search of the
+            /// triangle under a position only checks a few of them.
+            void BuildTerrainIndex();
             bool IsActiveTerrainAllowed(uint8 walkability_type) const;
             /**
              * Runs the function of a triangle when it is entered, if it changed.
@@ -322,6 +338,13 @@ namespace VGears {
             bool paused_for_battle_;
 
             std::vector<TerrainTriangle> terrain_triangles_;
+            /// Indices of the triangles (ascending) that touch each cell of the grid, row by row.
+            std::vector<std::vector<uint32>> terrain_grid_;
+            float terrain_grid_min_x_ = 0.0f;
+            float terrain_grid_min_z_ = 0.0f;
+            float terrain_grid_cell_ = 1.0f;
+            int terrain_grid_columns_ = 0;
+            int terrain_grid_rows_ = 0;
             Ogre::SceneManager* scene_manager_;
             Ogre::SceneNode* world_map_node_;
             EntityModel* player_entity_;
@@ -357,6 +380,29 @@ namespace VGears {
             bool frame_listener_attached_;
             bool cancel_was_pressed_;
             bool confirm_was_pressed_;
+            /// True while the function of a triangle is triggered by the landing of the Highwind.
+            bool landing_trigger_ = false;
+            /// Triangle of the northern cave that the Highwind has just landed on (a trigger waiting).
+            const TerrainTriangle* landing_after_unboard_ = nullptr;
+            /// Seconds since the music was checked, and the vehicle it was checked with.
+            float music_timer_ = 1.0f;
+            VehicleType music_vehicle_ = VehicleType::ON_FOOT;
+            /// Speeds set by the scripts, by name (the ones that are not set use the default ones).
+            std::map<std::string, float> speeds_;
+            float GetSpeed(const char* name, float default_speed) const;
+            struct CameraSettings{
+                float distance;
+                float pitch_degrees;
+            };
+            /// Cameras set by the scripts, by name (the ones that are not set use the default one).
+            std::map<std::string, CameraSettings> camera_settings_;
+            /// Snow map: seconds until the next automatic turn of the camera.
+            float snow_camera_timer_ = 0.0f;
+            /// Snow map: radians left of the turn that is going on, with the sign of its direction.
+            float snow_camera_remaining_ = 0.0f;
+            /// Snow map: the poles that exist (names of the entities), the oldest first.
+            std::deque<std::string> snow_poles_;
+            unsigned int snow_pole_counter_ = 0;
             enum class TransitionStage{
                 /// No animation going on.
                 NONE,