Browse Source

Split the world data installer and removed its unused output

- The terrain meshes, the map and walkmesh XML files and the terrain materials are no longer written: the game builds the terrain from the original map files.
- There is an installer for the scripts, the encounters and the models, and a class that reads the world map archive. WorldInstaller copies the maps and the textures and passes the other calls on.
- Broke up the generation of the scripts.
- The world model textures were also saved without the model name, and those files were never used.
- Removed WorldMapWalkmesh and the folders that nothing writes to.
- Added tests for the script tables and the encounters.
Iñigo Valentin 4 ngày trước cách đây
mục cha
commit
afbb910022

+ 4 - 0
src/installer/extractors/CMakeLists.txt

@@ -30,5 +30,9 @@ vgears_sources(
     SoundInstaller.cpp
     SpellModelInstaller.cpp
     WindowFonts.cpp
+    WorldArchive.cpp
+    WorldEncounterInstaller.cpp
     WorldInstaller.cpp
+    WorldModelInstaller.cpp
+    WorldScriptInstaller.cpp
 )

+ 46 - 0
src/installer/extractors/WorldArchive.cpp

@@ -0,0 +1,46 @@
+/*
+ * 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 "common/StringUtil.h"
+#include "WorldArchive.h"
+
+WorldArchive::WorldArchive(const std::string& path): file_(path){
+    VGears::LGPArchive archive(path, "LGP");
+    archive.open(path, true);
+    archive.load();
+    entries_ = archive.GetFiles();
+}
+
+const VGears::LGPArchive::FileList& WorldArchive::Entries() const{return entries_;}
+
+bool WorldArchive::Contains(const VGears::LGPArchive::FileEntry& entry) const{
+    return entry.data_offset + entry.data_size <= file_.GetFileSize();
+}
+
+File WorldArchive::Open(const VGears::LGPArchive::FileEntry& entry){
+    return File(&file_, entry.data_offset, entry.data_size);
+}
+
+std::vector<u8> WorldArchive::Read(const VGears::LGPArchive::FileEntry& entry){
+    std::vector<u8> data(entry.data_size);
+    if (!data.empty()) Open(entry).GetFileBuffer(data.data(), 0, entry.data_size);
+    return data;
+}
+
+std::string WorldArchive::LowerName(const VGears::LGPArchive::FileEntry& entry){
+    std::string name = entry.file_name;
+    VGears::StringUtil::toLowerCase(name);
+    return name;
+}

+ 88 - 0
src/installer/extractors/WorldArchive.h

@@ -0,0 +1,88 @@
+/*
+ * 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 <vector>
+#include "common/File.h"
+#include "common/TypeDefine.h"
+#include "formats/lgp/LGPArchive.h"
+
+/**
+ * The archive with the data of the world map (data/wm/world_us.lgp).
+ */
+class WorldArchive{
+
+    public:
+
+        /**
+         * Constructor. Reads the list of files of the archive.
+         *
+         * @param[in] path Path of the archive.
+         */
+        explicit WorldArchive(const std::string& path);
+
+        /**
+         * Retrieves the entries of the files of the archive.
+         *
+         * @return The entries, in the order of the archive.
+         */
+        const VGears::LGPArchive::FileList& Entries() const;
+
+        /**
+         * Checks if the contents of a file are in the archive.
+         *
+         * @param[in] entry Entry of the file.
+         * @return False if the entry goes past the end of the archive.
+         */
+        bool Contains(const VGears::LGPArchive::FileEntry& entry) const;
+
+        /**
+         * Opens a file of the archive.
+         *
+         * @param[in] entry Entry of the file.
+         * @return The file.
+         */
+        File Open(const VGears::LGPArchive::FileEntry& entry);
+
+        /**
+         * Reads a file of the archive.
+         *
+         * @param[in] entry Entry of the file.
+         * @return The contents of the file.
+         */
+        std::vector<u8> Read(const VGears::LGPArchive::FileEntry& entry);
+
+        /**
+         * Retrieves the name of a file in lower case.
+         *
+         * @param[in] entry Entry of the file.
+         * @return The name.
+         */
+        static std::string LowerName(const VGears::LGPArchive::FileEntry& entry);
+
+    private:
+
+        /**
+         * The archive, as a file.
+         */
+        File file_;
+
+        /**
+         * The entries of the archive.
+         */
+        VGears::LGPArchive::FileList entries_;
+};

+ 86 - 0
src/installer/extractors/WorldEncounterInstaller.cpp

@@ -0,0 +1,86 @@
+/*
+ * 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 <iostream>
+#include <boost/filesystem.hpp>
+#include "WorldEncounterInstaller.h"
+
+namespace{
+
+    /**
+     * Size of the data before the records of the encounters.
+     */
+    const unsigned int HEADER_SIZE = 0xA0;
+
+    /**
+     * Number of records of encounters.
+     */
+    const unsigned int RECORD_COUNT = 64;
+
+    /**
+     * Size of a record of encounters.
+     */
+    const unsigned int RECORD_SIZE = 32;
+
+    /**
+     * Walkability types that select each of the 4 terrain groups of every region. This table is
+     * in the executable of the game, not in the data files. The region of a triangle is
+     * (location & 0x1F), and a region over 15 is 15.
+     */
+    const unsigned int TERRAIN_TYPES[16][4] = {
+      {0, 9, 0, 17}, {0, 0, 0, 17}, {0, 9, 1, 17}, {0, 20, 0, 17},
+      {0, 9, 8, 17}, {0, 0, 25, 17}, {0, 9, 19, 17}, {0, 0, 1, 17},
+      {0, 0, 1, 17}, {0, 9, 14, 17}, {0, 9, 25, 17}, {0, 10, 9, 17},
+      {0, 9, 25, 17}, {0, 0, 8, 11}, {0, 0, 8, 0}, {0, 0, 1, 0}
+    };
+}
+
+WorldEncounterInstaller::WorldEncounterInstaller(const std::string& data_dir): data_dir_(data_dir){}
+
+void WorldEncounterInstaller::Install(const std::vector<u8>& data){
+    std::unique_ptr<TiXmlElement> encounters = CreateEncounters(data);
+    if (!encounters){
+        std::cerr << "ENC_W.BIN has an unexpected size." << std::endl;
+        return;
+    }
+    boost::filesystem::create_directories(data_dir_ + "world");
+    TiXmlDocument doc;
+    doc.LinkEndChild(new TiXmlDeclaration("1.0", "", ""));
+    doc.LinkEndChild(encounters.release());
+    doc.SaveFile(data_dir_ + "world/world_encounters.xml");
+}
+
+std::unique_ptr<TiXmlElement> WorldEncounterInstaller::CreateEncounters(const std::vector<u8>& data){
+    if (data.size() < HEADER_SIZE + RECORD_COUNT * RECORD_SIZE) return nullptr;
+    std::unique_ptr<TiXmlElement> root(new TiXmlElement("world_encounters"));
+    for (unsigned int region = 0; region < 16; ++ region){
+        for (unsigned int group = 0; group < 4; ++ group){
+            const unsigned int offset = HEADER_SIZE + (region * 4 + group) * RECORD_SIZE;
+            std::unique_ptr<TiXmlElement> record(new TiXmlElement("record"));
+            record->SetAttribute("region", region);
+            record->SetAttribute("terrain", TERRAIN_TYPES[region][group]);
+            record->SetAttribute("enabled", data[offset] & 0x01);
+            record->SetAttribute("rate", data[offset + 1]);
+            std::string words;
+            for (unsigned int w = 1; w < 16; ++ w){
+                const unsigned int word = data[offset + w * 2] | (data[offset + w * 2 + 1] << 8);
+                words += (w > 1 ? " " : "") + std::to_string(word);
+            }
+            record->SetAttribute("words", words);
+            root->LinkEndChild(record.release());
+        }
+    }
+    return root;
+}

+ 67 - 0
src/installer/extractors/WorldEncounterInstaller.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 <memory>
+#include <string>
+#include <vector>
+#include <tinyxml.h>
+#include "common/TypeDefine.h"
+
+/**
+ * Writes the random encounters of the world map (world/world_encounters.xml).
+ */
+class WorldEncounterInstaller{
+
+    public:
+
+        /**
+         * Constructor.
+         *
+         * @param[in] data_dir The game data folder.
+         */
+        explicit WorldEncounterInstaller(const std::string& data_dir);
+
+        /**
+         * Writes the encounters.
+         *
+         * Nothing is written if the data doesn't have the expected size.
+         *
+         * @param[in] data The contents of ENC_W.BIN.
+         */
+        void Install(const std::vector<u8>& data);
+
+        /**
+         * Creates the element with the encounters.
+         *
+         * ENC_W.BIN has 160 bytes of chocobo encounters and battle data, then 64 records of 16
+         * words. Record = region * 4 + terrain group. Word 0: enabled (low byte bit 0) and rate
+         * (high byte, the lower the more often). Words 1-6: standard battles, 7-10: special
+         * battles (back attack x2, side, pincer) and 11-15: others. A word is a battle ID (10
+         * bits) and a probability out of 64 (6 bits).
+         *
+         * @param[in] data The contents of ENC_W.BIN.
+         * @return The element, or null if the data is too short.
+         */
+        static std::unique_ptr<TiXmlElement> CreateEncounters(const std::vector<u8>& data);
+
+    private:
+
+        /**
+         * The game data folder.
+         */
+        std::string data_dir_;
+};

+ 44 - 1015
src/installer/extractors/WorldInstaller.cpp

@@ -13,1045 +13,74 @@
  * GNU General Public License for more details.
  */
 
-#include <iostream>
-#include <algorithm>
-#include <fstream>
-#include <sstream>
-#include <tinyxml.h>
-#include <OgreRoot.h>
-#include <OgreMesh.h>
-#include <OgreMeshSerializer.h>
 #include <boost/filesystem.hpp>
 #include "WorldInstaller.h"
-#include "installer/tables/ModelMaterials.h"
-#include "installer/formats/TexFile.h"
-#include "installer/formats/Lzs.h"
-#include "formats/FF7NameLookup.h"
-#include "common/StringUtil.h"
-#include "formats/lgp/LGPArchive.h"
-#include "installer/formats/WorldMapWalkmesh.h"
-#include "formats/model/HRCFileManager.h"
-#include "formats/model/AFileManager.h"
-#include "installer/tables/WorldModelTable.h"
-#include "installer/tables/FF7Data.h"
-#include "decompiler/ControlFlow.h"
-#include "decompiler/DecompilerException.h"
-#include "decompiler/world/WorldEngine.h"
-
-std::string WorldInstaller::ELEMENT_MODELS_DIR("world/models/element");
-
-std::string WorldInstaller::TERRAIN_MODELS_DIR("world/models/terrain");
 
 WorldInstaller::WorldInstaller(
-  const DiskImage& disk_image, const std::string output_dir,
-  Ogre::ResourceGroupManager* res_mgr
-): disk_image_(disk_image), output_dir_(output_dir), data_dir_(output_dir + "game/"), res_mgr_(res_mgr) {}
+  const DiskImage& disk_image, const std::string output_dir, Ogre::ResourceGroupManager* res_mgr
+):
+  disk_image_(disk_image), data_dir_(output_dir + "game/"), script_installer_(data_dir_),
+  encounter_installer_(data_dir_), model_installer_(output_dir, data_dir_, res_mgr)
+{}
 
 WorldInstaller::~WorldInstaller(){}
 
-unsigned int WorldInstaller::Initialize(){
-    if (wm_map_.size() > 0) wm_map_.clear();
-    processed_maps_ = 0;
-    wm_map_.push_back(File(*disk_image_.filePath("data/wm/WM0.MAP")));
-    wm_map_.push_back(File(*disk_image_.filePath("data/wm/WM2.MAP")));
-    wm_map_.push_back(File(*disk_image_.filePath("data/wm/WM3.MAP")));
-
-    // The game reads the original map files at runtime (game/world/maps), so install a copy.
-    boost::filesystem::create_directories(data_dir_ + "world/maps/");
-    for (const char* map : {"WM0.MAP", "WM2.MAP", "WM3.MAP"}){
-        boost::filesystem::copy_file(
-          *disk_image_.filePath(std::string("data/wm/") + map), data_dir_ + "world/maps/" + map,
-          boost::filesystem::copy_options::overwrite_existing
-        );
-    }
+void WorldInstaller::InstallMaps(){
+    CopyMaps();
     ExtractTextures();
-    return wm_map_.size();
-}
-
-void WorldInstaller::ExtractTextures(){
-    boost::filesystem::create_directories(data_dir_ + "world/textures/");
-    const auto path = disk_image_.filePath("data/wm/world_us.lgp");
-    File world_file(*path);
-    VGears::LGPArchive world_lgp(*path, "LGP");
-    world_lgp.open(*path, true);
-    world_lgp.load();
-    for (const VGears::LGPArchive::FileEntry& entry : world_lgp.GetFiles()){
-        if (entry.data_offset + entry.data_size > world_file.GetFileSize()) continue;
-        std::string file_name = entry.file_name;
-        VGears::StringUtil::toLowerCase(file_name);
-        if (file_name.size() < 4 || file_name.compare(file_name.size() - 4, 4, ".tex") != 0) continue;
-        File texture(&world_file, entry.data_offset, entry.data_size);
-        texture.WriteFile(data_dir_ + "world/textures/" + file_name);
-    }
-}
-
-void WorldInstaller::GenerateMaterials(){
-    // First, populate the texture list with static data.
-    texture_.push_back({0, "pond", 32, 32, 0, 352});
-    texture_.push_back({1, "riv_m2", 32, 32, 128, 64});
-    texture_.push_back({2, "was_gs", 64, 64, 64, 192});
-    texture_.push_back({3, "wpcltr", 32, 128, 0, 256});
-    texture_.push_back({4, "wpcltr2", 32, 32, 160, 64});
-    texture_.push_back({5, "bzdun", 64, 64, 192, 192});
-    texture_.push_back({6, "bone", 32, 32, 224, 384});
-    texture_.push_back({7, "bone2", 32, 32, 224, 416});
-    texture_.push_back({8, "bornwd", 64, 64, 160, 320});
-    texture_.push_back({9, "bridge", 32, 64, 192, 0});
-    texture_.push_back({10, "bridge2", 32, 32, 224, 0});
-    texture_.push_back({11, "cave", 32, 32, 224, 448});
-    texture_.push_back({12, "cave2", 32, 32, 224, 320});
-    texture_.push_back({13, "cave_s", 32, 32, 160, 224});
-    texture_.push_back({14, "cdl_cl2", 64, 32, 96, 96});
-    texture_.push_back({15, "cf01", 64, 32, 192, 288});
-    texture_.push_back({16, "clf_bgs", 64, 32, 192, 384});
-    texture_.push_back({17, "clf_ggl", 64, 64, 128, 256});
-    texture_.push_back({18, "clf_ggs", 64, 32, 192, 352});
-    texture_.push_back({19, "clf_l", 64, 64, 0, 0});
-    texture_.push_back({20, "clf_ld", 64, 64, 64, 0});
-    texture_.push_back({21, "clf_lf", 64, 64, 128, 0});
-    texture_.push_back({22, "clf_lg", 32, 64, 0, 96});
-    texture_.push_back({23, "clf_lr", 32, 64, 128, 0});
-    texture_.push_back({24, "clf_lsg", 32, 64, 64, 64});
-    texture_.push_back({25, "clf_r", 32, 32, 0, 96});
-    texture_.push_back({26, "clf_s", 64, 32, 192, 0});
-    texture_.push_back({27, "clf_sd", 64, 32, 192, 32});
-    texture_.push_back({28, "clf_sf", 64, 32, 0, 64});
-    texture_.push_back({29, "clf_sg", 32, 32, 32, 96});
-    texture_.push_back({30, "clf_sg2", 32, 32, 0, 160});
-    texture_.push_back({31, "clf_sr", 32, 32, 32, 96});
-    texture_.push_back({32, "clf_ss", 32, 32, 32, 128});
-    texture_.push_back({33, "clf_ssd", 32, 32, 0, 224});
-    texture_.push_back({34, "clf_ssw", 32, 32, 224, 32});
-    texture_.push_back({35, "clf_sw", 32, 32, 192, 32});
-    texture_.push_back({36, "clf_w02", 64, 64, 128, 64});
-    texture_.push_back({37, "clf_w03", 64, 64, 192, 64});
-    texture_.push_back({38, "clf_was", 64, 32, 64, 64});
-    texture_.push_back({39, "clfeg", 32, 32, 192, 320});
-    texture_.push_back({40, "clfegd", 32, 32, 0, 320});
-    texture_.push_back({41, "clftop", 64, 32, 192, 64});
-    texture_.push_back({42, "clftop2", 32, 32, 128, 64});
-    texture_.push_back({43, "cndl_cl", 64, 32, 96, 128});
-    texture_.push_back({44, "cndlf", 64, 64, 160, 64});
-    texture_.push_back({45, "cndlf02", 64, 64, 208, 64});
-    texture_.push_back({46, "comtr", 16, 32, 144, 96});
-    texture_.push_back({47, "cosinn", 32, 32, 224, 416});
-    texture_.push_back({48, "cosinn2", 32, 32, 192, 448});
-    texture_.push_back({49, "csmk", 32, 32, 64, 64});
-    texture_.push_back({50, "csmk2", 32, 32, 96, 64});
-    texture_.push_back({51, "cstds01", 32, 32, 224, 160});
-    texture_.push_back({52, "cstds02", 64, 64, 0, 448});
-    texture_.push_back({53, "des01", 32, 32, 160, 320});
-    texture_.push_back({54, "desert", 64, 64, 128, 128});
-    texture_.push_back({55, "desor", 64, 32, 160, 64});
-    texture_.push_back({56, "ds1", 32, 32, 0, 256});
-    texture_.push_back({57, "ds_s1", 32, 32, 192, 288});
-    texture_.push_back({58, "dsee1", 32, 32, 96, 288});
-    texture_.push_back({59, "dsrt_d", 32, 32, 224, 0});
-    texture_.push_back({60, "dsrt_e", 64, 128, 64, 128});
-    texture_.push_back({61, "edes01", 32, 32, 224, 320});
-    texture_.push_back({62, "elm01", 32, 32, 160, 0});
-    texture_.push_back({63, "elm02", 32, 32, 64, 96});
-    texture_.push_back({64, "elm_gro", 64, 64, 0, 96});
-    texture_.push_back({65, "elm_r", 32, 32, 192, 0});
-    texture_.push_back({66, "elm_r2", 32, 32, 224, 0});
-    texture_.push_back({67, "fall1", 32, 32, 128, 256});
-    texture_.push_back({68, "farm01", 32, 32, 160, 32});
-    texture_.push_back({69, "farm02", 32, 32, 192, 32});
-    texture_.push_back({70, "farm_g", 32, 32, 128, 64});
-    texture_.push_back({71, "farm_r", 32, 16, 128, 48});
-    texture_.push_back({72, "fld", 64, 64, 64, 96});
-    texture_.push_back({73, "fld_02", 64, 64, 0, 64});
-    texture_.push_back({74, "fld_s", 64, 64, 0, 160});
-    texture_.push_back({75, "fld_s2", 32, 32, 224, 256});
-    texture_.push_back({76, "fld_sw", 64, 64, 128, 192});
-    texture_.push_back({77, "fld_v", 128, 128, 0, 128});
-    texture_.push_back({78, "fld_vd", 32, 64, 96, 128});
-    texture_.push_back({79, "fld_vd2", 32, 64, 192, 416});
-    texture_.push_back({80, "fvedge", 32, 64, 0, 0});
-    texture_.push_back({81, "gclf_d", 128, 64, 128, 128});
-    texture_.push_back({82, "gclf_g", 32, 64, 224, 128});
-    texture_.push_back({83, "gclfwa", 128, 64, 64, 320});
-    texture_.push_back({84, "gclfwa2", 32, 64, 160, 320});
-    texture_.push_back({85, "gclfwag", 32, 64, 32, 320});
-    texture_.push_back({86, "gg_gro", 64, 64, 64, 448});
-    texture_.push_back({87, "gg_mts", 64, 128, 0, 128});
-    texture_.push_back({88, "ggmk", 64, 64, 128, 448});
-    texture_.push_back({89, "ggmt", 128, 128, 0, 0});
-    texture_.push_back({90, "ggmt_e", 128, 32, 0, 96});
-    texture_.push_back({91, "ggmt_ed", 128, 32, 128, 96});
-    texture_.push_back({92, "ggmt_eg", 32, 32, 96, 224});
-    texture_.push_back({93, "ggmtd", 128, 128, 128, 0});
-    texture_.push_back({94, "ggs_g", 32, 32, 32, 64});
-    texture_.push_back({95, "ggshr", 32, 32, 192, 96});
-    texture_.push_back({96, "ggshrg", 32, 32, 224, 96});
-    texture_.push_back({97, "gia", 64, 32, 64, 224});
-    texture_.push_back({98, "gia2", 64, 32, 0, 224});
-    texture_.push_back({99, "gia_d", 64, 32, 128, 224});
-    texture_.push_back({100, "gia_d2", 64, 32, 64, 224});
-    texture_.push_back({101, "gia_g", 32, 32, 192, 224});
-    texture_.push_back({102, "gia_g2", 32, 32, 128, 224});
-    texture_.push_back({103, "gmt_eda", 32, 32, 0, 352});
-    texture_.push_back({104, "gonclf", 128, 64, 96, 64});
-    texture_.push_back({105, "gredge", 32, 32, 192, 192});
-    texture_.push_back({106, "hyouga", 64, 64, 192, 64});
-    texture_.push_back({107, "iceclf", 64, 32, 64, 96});
-    texture_.push_back({108, "iceclfd", 64, 32, 128, 96});
-    texture_.push_back({109, "iceclfg", 32, 32, 32, 224});
-    texture_.push_back({110, "jun", 64, 64, 192, 192});
-    texture_.push_back({111, "jun_d", 64, 64, 128, 192});
-    texture_.push_back({112, "jun_e", 64, 16, 0, 240});
-    texture_.push_back({113, "jun_gro", 64, 64, 0, 64});
-    texture_.push_back({114, "junmk", 32, 32, 0, 96});
-    texture_.push_back({115, "junn01", 32, 32, 160, 112});
-    texture_.push_back({116, "junn02", 32, 32, 192, 112});
-    texture_.push_back({117, "junn03", 32, 32, 224, 112});
-    texture_.push_back({118, "junn04", 32, 32, 64, 128});
-    texture_.push_back({119, "jutmpl01", 64, 64, 128, 192});
-    texture_.push_back({120, "lake-e", 32, 32, 96, 192});
-    texture_.push_back({121, "lake_ef", 32, 32, 128, 224});
-    texture_.push_back({122, "lake_fl", 128, 32, 160, 224});
-    texture_.push_back({123, "lostclf", 32, 64, 128, 384});
-    texture_.push_back({124, "lostmt", 128, 32, 128, 448});
-    texture_.push_back({125, "lostmtd", 128, 32, 128, 480});
-    texture_.push_back({126, "lostmts", 64, 32, 160, 384});
-    texture_.push_back({127, "lostwd_e", 32, 32, 64, 480});
-    texture_.push_back({128, "lostwod", 64, 64, 0, 448});
-    texture_.push_back({129, "lst1", 32, 32, 192, 256});
-    texture_.push_back({130, "lstwd_e2", 32, 32, 96, 480});
-    texture_.push_back({131, "mzes", 32, 32, 224, 128});
-    texture_.push_back({132, "mzmt_e", 128, 64, 128, 64});
-    texture_.push_back({133, "mzmt_ed", 128, 32, 128, 128});
-    texture_.push_back({134, "mzmt_edw", 128, 32, 128, 160});
-    texture_.push_back({135, "mzmt_ew", 128, 32, 0, 128});
-    texture_.push_back({136, "mzmt_o", 128, 32, 64, 416});
-    texture_.push_back({137, "mzmt_od", 128, 32, 64, 448});
-    texture_.push_back({138, "mzmt_s", 128, 32, 0, 192});
-    texture_.push_back({139, "mzmt_sd", 128, 32, 0, 160});
-    texture_.push_back({140, "md01", 32, 32, 96, 16});
-    texture_.push_back({141, "md02", 128, 128, 0, 0});
-    texture_.push_back({142, "md03", 16, 16, 112, 64});
-    texture_.push_back({143, "md04", 32, 32, 128, 16});
-    texture_.push_back({144, "md05", 64, 16, 96, 0});
-    texture_.push_back({145, "md06", 16, 32, 96, 48});
-    texture_.push_back({146, "md07", 16, 16, 112, 48});
-    texture_.push_back({147, "md_mt", 128, 128, 128, 0});
-    texture_.push_back({148, "md_mtd", 128, 128, 0, 0});
-    texture_.push_back({149, "md_mts", 64, 128, 64, 160});
-    texture_.push_back({150, "md_snow", 128, 32, 128, 0});
-    texture_.push_back({151, "md_snw2", 128, 32, 128, 32});
-    texture_.push_back({152, "md_snwd", 128, 64, 0, 128});
-    texture_.push_back({153, "md_snwe", 64, 64, 96, 320});
-    texture_.push_back({154, "md_snws", 64, 64, 128, 128});
-    texture_.push_back({155, "md_snwt", 128, 32, 0, 192});
-    texture_.push_back({156, "md_snww", 32, 32, 224, 224});
-    texture_.push_back({157, "md_sw_s", 128, 128, 0, 0});
-    texture_.push_back({158, "md_swd2", 32, 32, 192, 256});
-    texture_.push_back({159, "md_swnp", 128, 128, 0, 96});
-    texture_.push_back({160, "mdsrt_e", 128, 32, 128, 192});
-    texture_.push_back({161, "mdsrt_ed", 128, 32, 128, 224});
-    texture_.push_back({162, "mdsrt_eg", 32, 32, 64, 224});
-    texture_.push_back({163, "midil", 32, 32, 32, 192});
-    texture_.push_back({164, "midild", 32, 32, 224, 192});
-    texture_.push_back({165, "mt_ewg", 32, 32, 64, 96});
-    texture_.push_back({166, "mt_road", 64, 64, 192, 128});
-    texture_.push_back({167, "mt_se", 32, 32, 160, 416});
-    texture_.push_back({168, "mt_se2", 64, 64, 128, 256});
-    texture_.push_back({169, "mt_sg01", 32, 32, 0, 224});
-    texture_.push_back({170, "mt_sg02", 32, 32, 32, 224});
-    texture_.push_back({171, "mt_sg03", 32, 32, 0, 192});
-    texture_.push_back({172, "mt_sg04", 32, 32, 160, 384});
-    texture_.push_back({173, "mtcoin", 64, 64, 0, 256});
-    texture_.push_back({174, "mtwas_e", 128, 32, 0, 224});
-    texture_.push_back({175, "mtwas_ed", 128, 32, 0, 224});
-    texture_.push_back({176, "ncol_gro", 64, 64, 64, 384});
-    texture_.push_back({177, "ncole01", 32, 32, 224, 384});
-    texture_.push_back({178, "ncole02", 32, 32, 192, 416});
-    texture_.push_back({179, "nivl_gro", 64, 64, 128, 384});
-    texture_.push_back({180, "nivl_mt", 128, 64, 0, 0});
-    texture_.push_back({181, "nivl_top", 32, 32, 0, 64});
-    texture_.push_back({182, "nivlr", 32, 32, 192, 384});
-    texture_.push_back({183, "port", 32, 32, 96, 224});
-    texture_.push_back({184, "port_d", 32, 32, 160, 0});
-    texture_.push_back({185, "rzclf02", 64, 64, 128, 128});
-    texture_.push_back({186, "rct_gro", 64, 128, 0, 416});
-    texture_.push_back({187, "riv_cls", 64, 64, 64, 0});
-    texture_.push_back({188, "riv_l1", 32, 32, 96, 320});
-    texture_.push_back({189, "riv_m", 32, 32, 0, 224});
-    texture_.push_back({190, "rivr", 32, 32, 64, 224});
-    texture_.push_back({191, "rivrclf", 64, 64, 128, 192});
-    texture_.push_back({192, "rivs1", 32, 32, 128, 320});
-    texture_.push_back({193, "rivshr", 64, 64, 192, 192});
-    texture_.push_back({194, "rivssr", 64, 32, 192, 224});
-    texture_.push_back({195, "rivstrt", 32, 32, 192, 160});
-    texture_.push_back({196, "rm1", 32, 32, 32, 288});
-    texture_.push_back({197, "rocet", 32, 32, 128, 160});
-    texture_.push_back({198, "rs_ss", 32, 32, 96, 224});
-    texture_.push_back({199, "sango", 32, 32, 224, 320});
-    texture_.push_back({200, "sango2", 32, 32, 224, 352});
-    texture_.push_back({201, "sango3", 32, 32, 128, 384});
-    texture_.push_back({202, "sango4", 64, 64, 0, 384});
-    texture_.push_back({203, "sdun", 64, 64, 0, 160});
-    texture_.push_back({204, "sdun02", 64, 64, 64, 160});
-    texture_.push_back({205, "sh1", 32, 32, 32, 256});
-    texture_.push_back({206, "sh_s1", 32, 32, 224, 288});
-    texture_.push_back({207, "shedge", 32, 64, 160, 160});
-    texture_.push_back({208, "shlm_1", 32, 32, 192, 320});
-    texture_.push_back({209, "shol", 128, 128, 128, 96});
-    texture_.push_back({210, "shol_s", 64, 64, 192, 192});
-    texture_.push_back({211, "shor", 128, 128, 0, 0});
-    texture_.push_back({212, "shor_s", 64, 64, 128, 192});
-    texture_.push_back({213, "shor_s2", 32, 32, 224, 416});
-    texture_.push_back({214, "shor_v", 32, 32, 192, 0});
-    texture_.push_back({215, "silo", 32, 32, 224, 32});
-    texture_.push_back({216, "slope", 128, 32, 0, 384});
-    texture_.push_back({217, "snow_es", 32, 32, 192, 480});
-    texture_.push_back({218, "snow_es2", 32, 32, 224, 480});
-    texture_.push_back({219, "snow_es3", 32, 32, 224, 448});
-    texture_.push_back({220, "snw_mt", 128, 128, 0, 0});
-    texture_.push_back({221, "snw_mtd", 128, 128, 128, 0});
-    texture_.push_back({222, "snw_mte", 64, 32, 0, 96});
-    texture_.push_back({223, "snw_mted", 64, 32, 64, 96});
-    texture_.push_back({224, "snw_mts", 64, 128, 64, 0});
-    texture_.push_back({225, "snw_mts2", 64, 32, 128, 192});
-    texture_.push_back({226, "snwfld", 64, 64, 0, 64});
-    texture_.push_back({227, "snwfld_s", 64, 32, 128, 128});
-    texture_.push_back({228, "snwgra", 64, 64, 192, 192});
-    texture_.push_back({229, "snwhm01", 32, 32, 32, 0});
-    texture_.push_back({230, "snwhm02", 32, 32, 32, 32});
-    texture_.push_back({231, "snwods", 32, 32, 224, 192});
-    texture_.push_back({232, "snwood", 64, 64, 192, 128});
-    texture_.push_back({233, "snwtrk", 32, 64, 96, 256});
-    texture_.push_back({234, "sse_s1", 32, 32, 32, 320});
-    texture_.push_back({235, "ssee1", 32, 32, 64, 288});
-    texture_.push_back({236, "sst1", 32, 32, 224, 256});
-    texture_.push_back({237, "stown_r", 32, 32, 192, 256});
-    texture_.push_back({238, "stw_gro", 64, 64, 0, 384});
-    texture_.push_back({239, "subrg2", 32, 32, 224, 160});
-    texture_.push_back({240, "susbrg", 64, 64, 192, 96});
-    texture_.push_back({241, "sw_se", 64, 64, 0, 0});
-    texture_.push_back({242, "swclf_l", 64, 64, 64, 128});
-    texture_.push_back({243, "swclf_ld", 64, 64, 192, 128});
-    texture_.push_back({244, "swclf_lg", 32, 64, 0, 192});
-    texture_.push_back({245, "swclf_s", 64, 32, 128, 96});
-    texture_.push_back({246, "swclf_sd", 64, 32, 192, 96});
-    texture_.push_back({247, "swclf_sg", 32, 32, 32, 192});
-    texture_.push_back({248, "swclf_wg", 32, 32, 192, 192});
-    texture_.push_back({249, "swfld_s2", 64, 32, 128, 160});
-    texture_.push_back({250, "swfld_s3", 32, 32, 160, 192});
-    texture_.push_back({251, "swmd_cg", 32, 32, 128, 192});
-    texture_.push_back({252, "swmd_clf", 64, 32, 64, 192});
-    texture_.push_back({253, "swp1", 32, 32, 0, 288});
-    texture_.push_back({254, "trk", 64, 64, 128, 0});
-    texture_.push_back({255, "tyo_f", 128, 128, 128, 128});
-    texture_.push_back({256, "tyosnw", 64, 128, 64, 384});
-    texture_.push_back({257, "uf1", 32, 32, 160, 256});
-    texture_.push_back({258, "utai01", 32, 32, 32, 96});
-    texture_.push_back({259, "utai02", 32, 32, 224, 64});
-    texture_.push_back({260, "utai_gro", 64, 64, 128, 96});
-    texture_.push_back({261, "utaimt", 32, 32, 0, 128});
-    texture_.push_back({262, "utaimtd", 32, 32, 96, 96});
-    texture_.push_back({263, "utaimtg", 32, 32, 96, 128});
-    texture_.push_back({264, "wa1", 32, 32, 192, 320});
-    texture_.push_back({265, "wzs1", 32, 32, 128, 288});
-    texture_.push_back({266, "wzshr", 32, 32, 160, 32});
-    texture_.push_back({267, "wzshr2", 32, 32, 32, 128});
-    texture_.push_back({268, "wzshrs", 32, 32, 32, 160});
-    texture_.push_back({269, "was", 128, 128, 0, 96});
-    texture_.push_back({270, "was_d", 64, 32, 0, 224});
-    texture_.push_back({271, "was_g", 64, 64, 0, 192});
-    texture_.push_back({272, "was_s", 128, 128, 128, 0});
-    texture_.push_back({273, "wasfld", 64, 64, 64, 256});
-    texture_.push_back({274, "wdedge", 64, 64, 64, 160});
-    texture_.push_back({275, "we1", 32, 32, 96, 256});
-    texture_.push_back({276, "we_s1", 32, 32, 160, 288});
-    texture_.push_back({277, "wedged", 32, 64, 128, 160});
-    texture_.push_back({278, "wod-e2", 32, 32, 64, 224});
-    texture_.push_back({279, "wood", 64, 64, 192, 0});
-    texture_.push_back({280, "wood_d", 64, 64, 192, 160});
-    texture_.push_back({281, "wtrk", 32, 64, 64, 96});
-    Ogre::MaterialSerializer mSer;
-    for (Texture t : texture_){
-        Ogre::MaterialPtr mat = Ogre::MaterialManager::getSingleton().create(t.name, "General", true);
-        Ogre::Technique* tech = mat->getTechnique(0);
-        Ogre::Pass* pass = tech->getPass(0);
-        pass->setDiffuse(0.7, 0.7, 0.7, 0.7);
-        mSer.exportMaterial(mat, data_dir_ + "world/models/" + t.name + ".material");
-    }
-}
-
-void WorldInstaller::ProcessModels(){
-    // Open world_us.lgp
-    File world_file(*disk_image_.filePath("data/wm/world_us.lgp"));
-    boost::filesystem::create_directories(output_dir_ + "temp/world_models/");
-    boost::filesystem::create_directories(data_dir_ + "world/models/");
-    VGears::LGPArchive world_lgp(*disk_image_.filePath("data/wm/world_us.lgp"), "LGP");
-    world_lgp.open(*disk_image_.filePath("data/wm/world_us.lgp"), true);
-    world_lgp.load();
-    VGears::LGPArchive::FileList file_list = world_lgp.GetFiles();
-    std::vector<std::string> hrc_file_names;
-
-    // First pass: extract all files so HRC sidecar dependencies (.rsd, .p, .tex) exist.
-    for (int i = 0; i < file_list.size(); i ++){
-        VGears::LGPArchive::FileEntry f = file_list.at(i);
-        if (f.data_offset + f.data_size <= world_file.GetFileSize()){
-            File w_lgp_file(&world_file, f.data_offset, f.data_size);
-            std::string file_name = f.file_name;
-            VGears::StringUtil::toLowerCase(file_name);
-            w_lgp_file.WriteFile(output_dir_ + "temp/world_models/" + file_name);
-            if (file_name.size() >= 7 && file_name.substr(4, 3) == "hrc") hrc_file_names.push_back(file_name);
-        }
-    }
-
-    // Second pass: convert HRC models once all dependencies are available on disk.
-    for (int i = 0; i < hrc_file_names.size(); i ++){
-        const std::string& file_name = hrc_file_names.at(i);
-
-        // TODO: Can this be done with declare resource?
-        // TODO: If not, do aloop to save all the hrc files, then call this once, then
-        // another loop to process them.
-        res_mgr_->declareResource(output_dir_ + "temp/world_models/" + file_name, "Skeleton", "FFVII");
-        res_mgr_->removeResourceLocation(output_dir_ + "temp/world_models/", "FFVII");
-        res_mgr_->addResourceLocation(output_dir_ + "temp/world_models/", "FileSystem", "FFVII", true, true);
-
-        try{
-            // TODO: This needs work to assemble all the pieces. Similar to field models.
-            Ogre::ResourcePtr hrc = VGears::HRCFileManager::GetSingleton().load(file_name, "FFVII");
-            Ogre::String hrc_base_name;
-            VGears::StringUtil::splitBase(file_name, hrc_base_name);
-            auto mesh_name = VGears::NameLookup::model(hrc_base_name) + ".mesh";
-            Ogre::MeshPtr mesh(Ogre::MeshManager::getSingleton().load(mesh_name, "FFVII"));
-            Ogre::SkeletonPtr skeleton(mesh->getSkeleton());
-            // The animations of the model, from the tables of ff7.exe (see WorldModelTable.h). Their names
-            // are the ones of the A files, in lower case.
-            for (const WorldModelTable::Model& model : WorldModelTable::MODELS){
-                if (hrc_base_name != model.hrc) continue;
-                for (unsigned int i = 0; i < model.animation_count; ++ i){
-                    const std::string animation_file = std::string(model.animations[i]) + ".a";
-                    try{
-                        VGears::AFilePtr a = VGears::AFileManager::GetSingleton().load(
-                          animation_file, "FFVII"
-                        ).staticCast<VGears::AFile>();
-                        a->AddTo(skeleton, model.animations[i]);
-                    }
-                    catch (const std::exception& ex){
-                        std::cerr << "[ERROR] Exception converting animation " << animation_file << " of world model "
-                          << file_name << ": " << ex.what() << std::endl;
-                    }
-                }
-                break;
-            }
-            ExportMesh(data_dir_ + "world/models/", mesh);
-            // Models can share a skeleton name with different bones (also with field models), so drop this one
-            // (with its skeleton and mesh) before converting the next.
-            VGears::HRCFileManager::GetSingleton().remove(file_name, "FFVII");
-        }
-        catch (const std::exception& ex){
-            std::cerr << "[ERROR] Exception converting world model " << file_name << ": " << ex.what() << std::endl;
-            if (VGears::HRCFileManager::GetSingleton().resourceExists(file_name, "FFVII"))
-                VGears::HRCFileManager::GetSingleton().remove(file_name, "FFVII");
-        }
-    }
-}
-
-bool WorldInstaller::ProcessMap(){
-    if (processed_maps_ >= wm_map_.size()) return true;
-    // Initialize the xml file.
-    TiXmlDocument doc;
-    std::unique_ptr<TiXmlElement> xml(new TiXmlElement("world_map"));
-    // Script.
-    std::unique_ptr<TiXmlElement> xml_script_element(new TiXmlElement("script"));
-    xml_script_element->SetAttribute("file_name", std::to_string(processed_maps_) + "/script.lua");
-    xml->LinkEndChild(xml_script_element.release());
-    // Background.
-    std::unique_ptr<TiXmlElement> xml_background_2d(new TiXmlElement("background2d"));
-    xml_background_2d->SetAttribute("file_name", std::to_string(processed_maps_) + "/bg.xml");
-    xml->LinkEndChild(xml_background_2d.release());
-    // Texts.
-    std::unique_ptr<TiXmlElement> xml_texts(new TiXmlElement("texts"));
-    xml_texts->SetAttribute("file_name", std::to_string(processed_maps_) + "/text.xml");
-    xml->LinkEndChild(xml_texts.release());
-    // Walkmesh.
-    std::unique_ptr<TiXmlElement> xml_walkmesh(new TiXmlElement("walkmesh"));
-    xml_walkmesh->SetAttribute("file_name", std::to_string(processed_maps_) + "/wm.xml");
-    xml->LinkEndChild(xml_walkmesh.release());
-    // Terrain (don't close yet).
-    std::unique_ptr<TiXmlElement> xml_terrain(new TiXmlElement("terrain"));
-    
-    // Initialize the walkmesh data.
-    WorldMapWalkmesh walkmesh(processed_maps_, processed_maps_ == 0 ? true : false);
-
-    // Read WM*.MAP file.
-    Map map;
-    Ogre::MeshSerializer mesh_serializer;
-    boost::filesystem::path p(wm_map_[processed_maps_].GetFileName());
-    std::string map_name = p.stem().native(); // w/o path or extension.
-    for (int b = 0; b < wm_map_[processed_maps_].GetFileSize() / 0xB800; b ++){
-        // Calculate offsets for walkmesh.
-        // WM0 is 9x7 blocks, WM2 probably is too, WM3 no idea?
-        int wm_offset_x = 32 * (b % 9);
-        int wm_offset_y = 32 * (b / 9);
-        Block block;
-        for (int m = 0; m < 16; m ++){
-            // Extract lzss compressed mesh to file.
-            std::vector<unsigned char> lzss;
-            wm_map_[processed_maps_].SetOffset(0xB800 * b + m * 4);
-            u32 mesh_offset = 0xB800 * b + wm_map_[processed_maps_].readU32LE();
-            wm_map_[processed_maps_].SetOffset(mesh_offset);
-            u32 mesh_size = wm_map_[processed_maps_].readU32LE();
-            // Add size to lzss
-            wm_map_[processed_maps_].SetOffset(mesh_offset);
-            for (int d = 0; d < 4; d ++) lzss.push_back(wm_map_[processed_maps_].readU8());
-            for (int d = 0; d < mesh_size ; d ++) lzss.push_back(wm_map_[processed_maps_].readU8());
-            // Extract the lzss file.
-            std::vector<unsigned char> data = Lzs::Decompress(lzss);
-            if (data.size() == 0) continue;
-            std::string dat_name = output_dir_ + "temp/wm/" + map_name + "_"
-              + std::to_string(b) + "_" + std::to_string(m) + ".dat";
-            std::ofstream dat(dat_name, std::ios::out | std::ios::binary);
-            if (!dat){
-                std::cerr << "Cannot create temporary world map file " << dat_name << std::endl;
-                processed_maps_ ++;
-                if (processed_maps_ >= wm_map_.size()) return true;
-                else return false;
-            }
-            for (int d = 0; d < data.size(); d ++) dat.write((char *) &data[d], sizeof(unsigned char));
-            dat.close();
-
-            // Open and read the decompressed file.
-            File mesh_data(dat_name);
-            block.mesh[m].triangle_count = mesh_data.readU16LE();
-            block.mesh[m].vertex_count = mesh_data.readU16LE();
-            for (int tri = 0; tri < block.mesh[m].triangle_count; tri ++){
-                Triangle t;
-                t.vertex_index[0] = mesh_data.readU8();
-                t.vertex_index[1] = mesh_data.readU8();
-                t.vertex_index[2] = mesh_data.readU8();
-                u8 walkability_function = mesh_data.readU8();
-                //t.walkability = walkability_function >> 5; // 5 bits
-                //t.function_id = walkability_function & 0x7; // 3 bits
-                t.walkability =  walkability_function & 0x1F; // Lowest 5 bits
-                t.function_id =  walkability_function >> 3; // 3 bits
-                // FIXME: I think function_id is wrong. It must be 3 bits
-                t.vertex_coord[0].u = mesh_data.readU8();
-                t.vertex_coord[0].v = mesh_data.readU8();
-                t.vertex_coord[1].u = mesh_data.readU8();
-                t.vertex_coord[1].v = mesh_data.readU8();
-                t.vertex_coord[2].u = mesh_data.readU8();
-                t.vertex_coord[2].v = mesh_data.readU8();
-                u16 texture_location = mesh_data.readU16LE();
-                t.texture = texture_location >> 9; // 9 bytes
-                t.location = texture_location & ((1 << 7) - 1); // 7 bytes.
-                block.mesh[m].triangles.push_back(t);
-            }
-            for (int ver = 0; ver < block.mesh[m].vertex_count; ver ++){
-                Vertex v;
-                v.x = mesh_data.readU16LE();
-                v.z = mesh_data.readU16LE();
-                v.y = mesh_data.readU16LE();
-                v.unknown = mesh_data.readU16LE();
-                block.mesh[m].vertices.push_back(v);
-            }
-            for (int nor = 0; nor < block.mesh[m].vertex_count; nor ++){
-                Vertex v;
-                v.x = mesh_data.readU16LE();
-                v.z = mesh_data.readU16LE();
-                v.y = mesh_data.readU16LE();
-                v.unknown = mesh_data.readU16LE();
-                block.mesh[m].normals.push_back(v);
-            }
-
-            // Add data to the walkmesh
-            for (int tri = 0; tri < block.mesh[m].triangle_count; tri ++){
-                Triangle t = block.mesh[m].triangles.at(tri);
-                walkmesh.addTriangle(
-                  Ogre::Vector3(
-                    block.mesh[m].vertices.at(t.vertex_index[0]).x + wm_offset_x,
-                    block.mesh[m].vertices.at(t.vertex_index[0]).y + wm_offset_y,
-                    block.mesh[m].vertices.at(t.vertex_index[0]).z
-                  ), // a
-                  Ogre::Vector3(
-                    block.mesh[m].vertices.at(t.vertex_index[1]).x + wm_offset_x,
-                    block.mesh[m].vertices.at(t.vertex_index[1]).y + wm_offset_y,
-                    block.mesh[m].vertices.at(t.vertex_index[1]).z
-                  ), // b
-                  Ogre::Vector3(
-                    block.mesh[m].vertices.at(t.vertex_index[2]).x + wm_offset_x,
-                    block.mesh[m].vertices.at(t.vertex_index[2]).y + wm_offset_y,
-                    block.mesh[m].vertices.at(t.vertex_index[2]).z
-                  ), // c
-                  t.walkability,
-                  t.function_id
-                );
-            }
-        }
-        map.blocks.push_back(block);
-    }
-    // TODO: Generate material.
-    // Generate manual meshes.
-    for (int b = 0; b < map.blocks.size(); b ++){
-        int wm_offset_x = 32 * (b % 9);
-        int wm_offset_y = 32 * (b / 9);
-        //std::cout << "[MAN] Block " << b << "/" << map.blocks.size() << std::endl;
-
-        std::string name = map_name + "_" + std::to_string(b);
-        std::string mat_name = texture_.at(0).name;
-        Ogre::ManualObject man = Ogre::ManualObject(name);
-        //man.setBoundingBox(Ogre::AxisAlignedBox({-100,-100,0}, {100,100,0})); //TODO;
-          //= Ogre::Root::getSingleton().getSceneManager("Scene")->createManualObject(name);
-        man.begin(mat_name, Ogre::RenderOperation::OT_TRIANGLE_LIST);
-        for (int m = 0; m < 16; m ++){
-            //std::cout << "[MAN]        Mesh " << m << " triangles: "
-            //  << map.blocks[b].mesh[m].triangle_count << "\n";
-            // Add vertices.
-            for (int v = 0; v < map.blocks[b].mesh[m].vertex_count; v ++){
-                man.position(
-                  map.blocks[b].mesh[m].vertices[v].x, map.blocks[b].mesh[m].vertices[v].y,
-                  map.blocks[b].mesh[m].vertices[v].z
-                );
-                man.normal(
-                  map.blocks[b].mesh[m].normals[v].x, map.blocks[b].mesh[m].normals[v].y,
-                  map.blocks[b].mesh[m].normals[v].z
-                );
-                // TODO: How to add texture coordinates at this point?
-                //man->textureCoord(0, 0);
-            }
-            // Conform faces from vertices
-            for (int t = 0; t < map.blocks[b].mesh[m].triangle_count; t ++){
-                //std::cout << "Triangle " << t << " vertizes: "
-                //  << (int) map.blocks[b].mesh[m].triangles[t].vertex_index[0] << ", "
-                //  << (int) map.blocks[b].mesh[m].triangles[t].vertex_index[1] << ", "
-                //  << (int) map.blocks[b].mesh[m].triangles[t].vertex_index[2] << std::endl;
-                // TODO: El index deberia incrementar por triangulo por cada material
-                man.setMaterialName(0, texture_.at(map.blocks[b].mesh[m].triangles[t].texture).name);
-                man.triangle(
-                  map.blocks[b].mesh[m].triangles[t].vertex_index[0],
-                  map.blocks[b].mesh[m].triangles[t].vertex_index[1],
-                  map.blocks[b].mesh[m].triangles[t].vertex_index[2]
-                );
-            }
-        }
-        // Export the mesh.
-        man.end();
-        Ogre::MeshPtr mesh = man.convertToMesh(name);
-        //std::cout << "[WI] Export mesh " << (data_dir_ + "wm/" + mesh->getName() + ".mesh")
-        //  << std::endl;
-        mesh_serializer.exportMesh(
-          mesh.getPointer(),
-          data_dir_ + TERRAIN_MODELS_DIR + "/" + std::to_string(processed_maps_) + "/" + mesh->getName() + ".mesh"
-        );
-        // WM0 is te main worldmap, its shape changes according to the history progress, it has
-        // 68 blocks but only 63 are used at a time
-        if (processed_maps_ > 0 || b < 63){
-            std::unique_ptr<TiXmlElement> xml_block(new TiXmlElement("block"));
-            xml_block->SetAttribute("index", std::to_string(b));
-            xml_block->SetAttribute(
-              "file_name", "terrain/" + std::to_string(processed_maps_) + "/" + mesh->getName() + ".mesh"
-            );
-            xml_block->SetAttribute("position", std::to_string(wm_offset_x) + " " + std::to_string(wm_offset_y) + " 0");
-            if (processed_maps_ == 0){
-                // TODO: Correct history points for each block.
-                switch (b){
-                    case 50: // Block 50 replaced by block 63
-                        xml_block->SetAttribute("alt_file_name", "terrain/0/WM0_63.mesh");
-                        xml_block->SetAttribute("alt_story_change", "1000");
-                        break;
-                    case 41: // Block 41 replaced by block 64
-                        xml_block->SetAttribute("alt_file_name", "terrain/0/WM0_64.mesh");
-                        xml_block->SetAttribute("alt_story_change", "1000");
-                        break;
-                    case 42: // Block 42 replaced by block 65
-                        xml_block->SetAttribute("alt_file_name", "terrain/0/WM0_65.mesh");
-                        xml_block->SetAttribute("alt_story_change", "1000");
-                        break;
-                    case 60: // Block 60 replaced by block 66
-                        xml_block->SetAttribute("alt_file_name", "terrain/0/WM0_66.mesh");
-                        xml_block->SetAttribute("alt_story_change", "1000");
-                        break;
-                    case 47: // Block 50 replaced by block 67
-                        xml_block->SetAttribute("alt_file_name", "terrain/0/WM0_67.mesh");
-                        xml_block->SetAttribute("alt_story_change", "1000");
-                        break;
-                    case 48: // Block 50 replaced by block 68
-                        xml_block->SetAttribute("alt_file_name", "terrain/0/WM0_68.mesh");
-                        xml_block->SetAttribute("alt_story_change", "1000");
-                        break;
-                }
-            }
-            xml_terrain->LinkEndChild(xml_block.release());
-        }
-    }
-    // Add other data to the XML file.
-    // Close and save XML file,
-    xml->LinkEndChild(xml_terrain.release());
-    doc.LinkEndChild(xml.release());
-    // TODO: Add models, entities...
-    doc.SaveFile(
-      data_dir_ + "world/maps/" + std::to_string(processed_maps_) + "/world" + std::to_string(processed_maps_) + ".xml"
-    );
-    // Generate the walkmesh xml file
-    walkmesh.generate(data_dir_ + "world/maps/" + std::to_string(processed_maps_) + "/wm.xml");
-    // TODO: Generate other files: background, script, texts...
-    // Ready for next map or next step.
-    processed_maps_ ++;
-    if (processed_maps_ >= wm_map_.size()) return true;
-    else return false;
-}
-
-void WorldInstaller::ExportEncounters(
-  File& archive_file, const VGears::LGPArchive::FileEntry& entry
-){
-    // ENC_W.BIN: 160 bytes of chocobo encounters and battle data, then 64 records of 16 words.
-    // Record = region * 4 + terrain group. Word 0: enabled (low byte bit 0) and rate (high byte,
-    // the lower the more often). Words 1-6: standard battles, 7-10: special battles
-    // (back attack x2, side, pincer) and 11-15: others. A word is a battle ID (10 bits) and a
-    // probability out of 64 (6 bits).
-    static const unsigned int HEADER_SIZE = 0xA0;
-    static const unsigned int RECORD_COUNT = 64;
-    static const unsigned int RECORD_SIZE = 32;
-    if (entry.data_size < HEADER_SIZE + RECORD_COUNT * RECORD_SIZE){
-        std::cerr << "ENC_W.BIN has an unexpected size." << std::endl;
-        return;
-    }
-    std::vector<u8> data(entry.data_size);
-    File file(&archive_file, entry.data_offset, entry.data_size);
-    file.GetFileBuffer(data.data(), 0, entry.data_size);
-    // Walkability types that select each of the 4 terrain groups of every region. This table is
-    // in the executable of the game, not in the data files. The region of a triangle is
-    // (location & 0x1F), and a region over 15 is 15.
-    static const unsigned int TERRAIN_TYPES[16][4] = {
-      {0, 9, 0, 17}, {0, 0, 0, 17}, {0, 9, 1, 17}, {0, 20, 0, 17},
-      {0, 9, 8, 17}, {0, 0, 25, 17}, {0, 9, 19, 17}, {0, 0, 1, 17},
-      {0, 0, 1, 17}, {0, 9, 14, 17}, {0, 9, 25, 17}, {0, 10, 9, 17},
-      {0, 9, 25, 17}, {0, 0, 8, 11}, {0, 0, 8, 0}, {0, 0, 1, 0}
-    };
-    boost::filesystem::create_directories(data_dir_ + "world");
-    TiXmlDocument doc;
-    std::unique_ptr<TiXmlElement> root(new TiXmlElement("world_encounters"));
-    for (unsigned int region = 0; region < 16; ++ region){
-        for (unsigned int group = 0; group < 4; ++ group){
-            const unsigned int index = region * 4 + group;
-            const unsigned int offset = HEADER_SIZE + index * RECORD_SIZE;
-            std::unique_ptr<TiXmlElement> record(new TiXmlElement("record"));
-            record->SetAttribute("region", region);
-            record->SetAttribute("terrain", TERRAIN_TYPES[region][group]);
-            record->SetAttribute("enabled", data[offset] & 0x01);
-            record->SetAttribute("rate", data[offset + 1]);
-            std::string words;
-            for (unsigned int w = 1; w < 16; ++ w){
-                const unsigned int word = data[offset + w * 2] | (data[offset + w * 2 + 1] << 8);
-                words += (w > 1 ? " " : "") + std::to_string(word);
-            }
-            record->SetAttribute("words", words);
-            root->LinkEndChild(record.release());
-        }
-    }
-    doc.LinkEndChild(new TiXmlDeclaration("1.0", "", ""));
-    doc.LinkEndChild(root.release());
-    doc.SaveFile(data_dir_ + "world/world_encounters.xml");
 }
 
 bool WorldInstaller::GenerateScripts(
-    const std::vector<std::string>& field_names,
-    const std::map<u16, float>& field_scale_factors,
-    const std::vector<std::string>& converted_fields,
-    std::string& error_message
+  const std::vector<std::string>& field_names, const std::map<u16, float>& field_scale_factors,
+  const std::vector<std::string>& converted_fields, std::string& error_message
 ){
     error_message.clear();
-        if (field_names.empty() || converted_fields.empty()){
-                error_message = "Field maps were not installed; enable field map extraction.";
-                return false;
-        }
-    std::unique_ptr<std::string> archive_path
-      = disk_image_.filePath("data/wm/world_us.lgp");
-    if (!archive_path){
-        error_message = "WORLD_US.LGP was not found on the game disc.";
+    if (field_names.empty() || converted_fields.empty()){
+        error_message = "Field maps were not installed; enable field map extraction.";
         return false;
     }
-
-    File archive_file(*archive_path);
-    VGears::LGPArchive archive(*archive_path, "LGP");
-    archive.open(*archive_path, true);
-    archive.load();
-    const VGears::LGPArchive::FileList& archive_entries = archive.GetFiles();
-    std::vector<const VGears::LGPArchive::FileEntry*> event_entries;
-    const VGears::LGPArchive::FileEntry* field_table_entry = nullptr;
-    const VGears::LGPArchive::FileEntry* encounter_entry = nullptr;
-    bool has_wm0 = false;
-    for (const VGears::LGPArchive::FileEntry& entry : archive_entries){
-        std::string lower_name = entry.file_name;
-        VGears::StringUtil::toLowerCase(lower_name);
-        if (
-          lower_name.size() > 5 && lower_name.compare(0, 2, "wm") == 0
-          && lower_name.compare(lower_name.size() - 3, 3, ".ev") == 0
-        ){
-            const std::string map_number
-              = lower_name.substr(2, lower_name.size() - 5);
-            if (!map_number.empty() && std::all_of(
-                  map_number.begin(), map_number.end(), [](char character){
-                      return character >= '0' && character <= '9';
-                  }
-                )){
-                event_entries.push_back(&entry);
-                if (lower_name == "wm0.ev") has_wm0 = true;
-            }
-        }
-        else if (lower_name == "field.tbl"){
-            field_table_entry = &entry;
-        }
-        else if (lower_name == "enc_w.bin"){
-            encounter_entry = &entry;
-        }
-    }
-    if (encounter_entry != nullptr){
-        ExportEncounters(archive_file, *encounter_entry);
-    }
-    if (event_entries.empty() || !has_wm0 || field_table_entry == nullptr){
-        error_message = "WM0.EV, other world event files, or FIELD.TBL were not found inside WORLD_US.LGP.";
+    const std::string path = ArchivePath();
+    if (path.empty()){
+        error_message = "WORLD_US.LGP was not found on the game disc.";
         return false;
     }
-
-    File field_table_file(
-      &archive_file, field_table_entry->data_offset, field_table_entry->data_size
-    );
-    std::vector<u8> field_table_data(field_table_entry->data_size);
-    if (field_table_data.size() != 64 * 24){
-        error_message = "FIELD.TBL has an unexpected size.";
-        return false;
+    WorldArchive archive(path);
+    for (const VGears::LGPArchive::FileEntry& entry : archive.Entries()){
+        if (WorldArchive::LowerName(entry) == "enc_w.bin")
+            encounter_installer_.Install(archive.Read(entry));
     }
-    field_table_file.GetFileBuffer(
-      field_table_data.data(), 0, field_table_entry->data_size
+    return script_installer_.Install(
+      archive, field_names, field_scale_factors, converted_fields, error_message
     );
-
-    const std::string script_directory = data_dir_ + "world/scripts";
-    boost::filesystem::create_directories(script_directory);
-    for (const VGears::LGPArchive::FileEntry* event_entry : event_entries){
-        File event_file(&archive_file, event_entry->data_offset, event_entry->data_size);
-        std::vector<u8> event_data(event_entry->data_size);
-        if (event_data.empty()){
-            error_message = event_entry->file_name + " inside WORLD_US.LGP is empty.";
-            return false;
-        }
-        event_file.GetFileBuffer(event_data.data(), 0, event_entry->data_size);
-
-        std::string map_file_name = event_entry->file_name;
-        VGears::StringUtil::toLowerCase(map_file_name);
-        const std::string map_name = map_file_name.substr(0, map_file_name.size() - 3);
-        std::ofstream script_file(script_directory + "/" + map_name + ".lua");
-        if (!script_file){
-            error_message = "Cannot create script output in " + script_directory + ".";
-            return false;
-        }
-        script_file << "-- Decompiled from the user's " << event_entry->file_name << " data.\n\n";
-
-        std::vector<bool> generated_functions(256, false);
-        unsigned int generated_function_count = 0;
-        for (int script_index = 0; script_index < 256; ++script_index){
-        try{
-            WorldEngine engine(script_index);
-            InstVec instructions;
-            std::unique_ptr<Disassembler> disassembler = engine.GetDisassembler(instructions);
-            disassembler->Open(event_data);
-            disassembler->Disassemble();
-            if (instructions.empty()) continue;
-
-            ControlFlow control_flow(instructions, engine);
-            control_flow.CreateGroups();
-            std::ostringstream generated_script;
-            std::unique_ptr<CodeGenerator> code_generator
-              = engine.GetCodeGenerator(instructions, generated_script);
-            code_generator->Generate(instructions, control_flow.GetGraph());
-            script_file << generated_script.str() << "\n";
-            generated_functions[script_index] = true;
-            ++generated_function_count;
-        }
-        catch (const DecompilerException&){
-            std::cerr << "[WARNING] World function " << script_index << " of " << map_name
-              << " could not be decompiled." << std::endl;
-            script_file << "-- world function " << script_index
-              << " could not be decompiled.\n";
-        }
-        catch (const std::exception& exception){
-            std::cerr << "[WARNING] World function " << script_index << " of " << map_name
-              << " failed: " << exception.what() << std::endl;
-            script_file << "-- world function " << script_index
-              << " failed: " << exception.what() << ".\n";
-        }
-        }
-
-        script_file << "-- " << map_name << " mesh-function call-table mapping.\n";
-        for (size_t function_index = 0; function_index < generated_functions.size(); ++function_index){
-                if (!generated_functions[function_index]) continue;
-
-                const size_t type_offset = function_index * 4;
-            if (type_offset + 1 >= event_data.size()) continue;
-                const uint16 function_type = static_cast<uint16>(event_data[type_offset])
-                    | static_cast<uint16>(event_data[type_offset + 1] << 8);
-                if ((function_type >> 14) != 2) continue;
-
-                const uint16 mesh_index = (function_type >> 4) & 0x03FF;
-                const uint8 mesh_function_id = function_type & 0x0F;
-                if (mesh_index >= 36 * 28 || mesh_function_id > 4) continue;
-
-                script_file << "System.WorldMap.triangle_functions[" << mesh_index << "]"
-                    << " = System.WorldMap.triangle_functions[" << mesh_index << "] or {}\n"
-                    << "System.WorldMap.triangle_functions[" << mesh_index << "]["
-                    << static_cast<unsigned int>(mesh_function_id) << "] = " << function_index << "\n";
-        }
-
-        // The functions that run when an entity of a type is created, and for the other events of the
-        // entities. The type is in the bits 8 to 13 of the type of the function, and the event in the low byte.
-        script_file << "System.WorldMap.entity_functions = {}\n";
-        for (size_t function_index = 0; function_index < generated_functions.size(); ++function_index){
-                if (!generated_functions[function_index]) continue;
-                const size_t type_offset = function_index * 4;
-                if (type_offset + 1 >= event_data.size()) continue;
-                const uint16 function_type = static_cast<uint16>(event_data[type_offset])
-                    | static_cast<uint16>(event_data[type_offset + 1] << 8);
-                if ((function_type >> 14) != 1) continue;
-                const unsigned int entity_type = (function_type >> 8) & 0x3F;
-                const unsigned int event = function_type & 0xFF;
-                script_file << "System.WorldMap.entity_functions[" << entity_type << "] = "
-                    << "System.WorldMap.entity_functions[" << entity_type << "] or {}\n"
-                    << "System.WorldMap.entity_functions[" << entity_type << "][" << event << "] = "
-                    << function_index << "\n";
-        }
-
-        script_file << "System.WorldMap.field_table = {}\n";
-        for (size_t record_index = 0; record_index < 64; ++record_index){
-                for (size_t scenario = 0; scenario < 2; ++scenario){
-                        const size_t offset = record_index * 24 + scenario * 12;
-                        const uint16 raw_x = static_cast<uint16>(field_table_data[offset])
-                            | (static_cast<uint16>(field_table_data[offset + 1]) << 8);
-                        const uint16 raw_y = static_cast<uint16>(field_table_data[offset + 2])
-                            | (static_cast<uint16>(field_table_data[offset + 3]) << 8);
-                        const uint16 raw_triangle = static_cast<uint16>(field_table_data[offset + 4])
-                            | (static_cast<uint16>(field_table_data[offset + 5]) << 8);
-                        const uint16 field_id = static_cast<uint16>(field_table_data[offset + 6])
-                            | (static_cast<uint16>(field_table_data[offset + 7]) << 8);
-                        if (field_id >= field_names.size()) continue;
-                        const std::string& field_name = field_names[field_id];
-                        if (std::find(converted_fields.begin(), converted_fields.end(), field_name)
-                            == converted_fields.end()){
-                                continue;
-                        }
-                        const auto scale_factor = field_scale_factors.find(field_id);
-                        if (scale_factor == field_scale_factors.end() || scale_factor->second <= 0){
-                                continue;
-                        }
-
-                        const float downscale = 128.0f * scale_factor->second;
-                        const float x = static_cast<int16>(raw_x) / downscale;
-                        const float y = static_cast<int16>(raw_y) / downscale;
-                        const int16 triangle = static_cast<int16>(raw_triangle);
-                        const uint8 direction = field_table_data[offset + 8];
-                        const float direction_degrees
-                            = 360.0f * static_cast<float>(direction) / 256.0f;
-                        const size_t table_id = record_index + 1;
-                        script_file << "System.WorldMap.field_table[" << table_id << "]"
-                            << " = System.WorldMap.field_table[" << table_id << "] or {}\n"
-                            << "System.WorldMap.field_table[" << table_id << "][" << scenario << "] = {"
-                            << "field = \"" << field_name << "\", x = " << x << ", y = " << y
-                            << ", triangle = " << triangle << ", direction = "
-                            << direction_degrees << "}\n";
-                }
-        }
-        script_file.flush();
-        if (!script_file){
-            error_message = "Failed while writing " + script_directory + "/" + map_name + ".lua.";
-            return false;
-        }
-        if (generated_function_count == 0){
-            error_message = "No functions in " + event_entry->file_name + " could be decompiled.";
-            return false;
-        }
-    }
-    return true;
 }
 
-void WorldInstaller::ExportMesh(const std::string outdir, const Ogre::MeshPtr &mesh){
-    if (mesh.isNull()){
-        std::cerr << "[ERROR] ExportMesh called with null mesh." << std::endl;
-        return;
-    }
-    boost::filesystem::create_directories(outdir);
+void WorldInstaller::ProcessModels(){
+    WorldArchive archive(ArchivePath());
+    model_installer_.Install(archive);
+}
 
-    // TODO: Share function with pc model exporter
-    VGears::String base_mesh_name;
-    VGears::StringUtil::splitFull(mesh->getName(), base_mesh_name);
-    MakeMaterialsUnique(mesh, base_mesh_name);
-    Ogre::MeshSerializer mesh_serializer;
-    Ogre::SkeletonPtr skeleton(mesh->getSkeleton());
-    if (!skeleton.isNull()){
-        Ogre::SkeletonSerializer skeleton_serializer;
-        skeleton_serializer.exportSkeleton(skeleton.getPointer(), outdir + base_mesh_name + ".skeleton");
-        mesh->setSkeletonName(base_mesh_name + ".skeleton");
+void WorldInstaller::CopyMaps(){
+    boost::filesystem::create_directories(data_dir_ + "world/maps/");
+    for (const char* map : {"WM0.MAP", "WM2.MAP", "WM3.MAP"}){
+        boost::filesystem::copy_file(
+          *disk_image_.filePath(std::string("data/wm/") + map), data_dir_ + "world/maps/" + map,
+          boost::filesystem::copy_options::overwrite_existing
+        );
     }
-    mesh_serializer.exportMesh(mesh.getPointer(), outdir + mesh->getName());
-    Ogre::Mesh::SubMeshIterator it(mesh->getSubMeshIterator());
-    Ogre::MaterialSerializer mat_ser;
-    size_t i(0);
-    std::set<std::string> queued_materials;
-    bool has_queued_materials = false;
-    while (it.hasMoreElements()){
-        Ogre::SubMesh *sub_mesh(it.getNext());
-        Ogre::MaterialPtr mat(Ogre::MaterialManager::getSingleton().getByName(sub_mesh->getMaterialName()));
-        if (mat != nullptr){
-            for (size_t techs = 0; techs < mat->getNumTechniques(); techs ++){
-                Ogre::Technique* tech = mat->getTechnique(techs);
-                if (tech){
-                    for (size_t pass_num = 0; pass_num < tech->getNumPasses(); pass_num ++){
-                        Ogre::Pass* pass = tech->getPass(pass_num);
-                        if (pass){
-                            for (
-                              size_t texture_unit_num = 0;
-                              texture_unit_num < pass->getNumTextureUnitStates();
-                              texture_unit_num ++
-                            ){
-                                Ogre::TextureUnitState* unit = pass->getTextureUnitState(texture_unit_num);
-                                if (unit && unit->getTextureName().empty() == false){
-                                    // Materials are shared by name across all model types, so this one may have
-                                    // already been converted for a field or battle model (its texture is then a png).
-                                    if (!boost::filesystem::exists(output_dir_ + "temp/world_models/" + unit->getTextureName())){
-                                        std::cerr << "[WARNING] Texture " << unit->getTextureName()
-                                          << " not found in temp/world_models; skipping it." << std::endl;
-                                        continue;
-                                    }
-                                    try{
-                                        // Convert the texture from .tex to .png.
-                                        TexFile tex(output_dir_ + "temp/world_models/" + unit->getTextureName());
-
-                                        // Ensure the output material script references png files
-                                        // rather than tex files.
-                                        Ogre::String base_name;
-                                        VGears::StringUtil::splitBase(unit->getTextureName(), base_name);
-                                        unit->setTextureName(base_mesh_name + "_" + base_name + ".png");
-
-                                        const auto plain_png = outdir + base_name + ".png";
-                                        const auto model_png = outdir + base_mesh_name + "_" + base_name + ".png";
-                                        tex.SavePng(plain_png, 0);
-                                        boost::filesystem::copy_file(
-                                          plain_png, model_png, boost::filesystem::copy_options::overwrite_existing
-                                        );
-                                    }
-                                    catch (const std::exception& ex){
-                                        std::cerr << "[ERROR] Texture export failed for "
-                                          << unit->getTextureName() << ": " << ex.what() << std::endl;
-                                    }
-                                }
-                            }
-                        }
-                    }
-                }
-            }
-            // Queue each material once. Exporting with an empty queue throws in Ogre.
-            if (queued_materials.insert(sub_mesh->getMaterialName()).second){
-                mat_ser.queueForExport(mat);
-                has_queued_materials = true;
-            }
+}
 
-        }
-        ++ i;
+void WorldInstaller::ExtractTextures(){
+    boost::filesystem::create_directories(data_dir_ + "world/textures/");
+    WorldArchive archive(ArchivePath());
+    for (const VGears::LGPArchive::FileEntry& entry : archive.Entries()){
+        if (!archive.Contains(entry)) continue;
+        const std::string name = WorldArchive::LowerName(entry);
+        if (name.size() < 4 || name.compare(name.size() - 4, 4, ".tex") != 0) continue;
+        archive.Open(entry).WriteFile(data_dir_ + "world/textures/" + name);
     }
-    if (has_queued_materials) mat_ser.exportQueued(outdir + base_mesh_name + VGears::EXT_MATERIAL);
 }
 
+std::string WorldInstaller::ArchivePath(){
+    const auto path = disk_image_.filePath("data/wm/world_us.lgp");
+    return path ? *path : std::string();
+}

+ 44 - 270
src/installer/extractors/WorldInstaller.h

@@ -15,16 +15,22 @@
 
 #pragma once
 
-#include <string>
 #include <map>
+#include <string>
 #include <vector>
-#include <common/TypeDefine.h>
+#include <OgreResourceGroupManager.h>
+#include "common/TypeDefine.h"
 #include "installer/formats/DiskImage.h"
-#include "common/File.h"
-#include "formats/lgp/LGPArchive.h"
+#include "WorldEncounterInstaller.h"
+#include "WorldModelInstaller.h"
+#include "WorldScriptInstaller.h"
 
 /**
  * The world map data installer.
+ *
+ * It copies the maps and their textures, which the game reads as they are. The rest of the work
+ * is done by {@see WorldScriptInstaller}, {@see WorldEncounterInstaller} and
+ * {@see WorldModelInstaller}.
  */
 class WorldInstaller{
 
@@ -47,284 +53,49 @@ class WorldInstaller{
         ~WorldInstaller();
 
         /**
-         * Initializes the installer.
-         *
-         * @return The number of maps to process.
-         */
-        unsigned int Initialize();
-
-        /**
-         * Extracts and processes the models in data/wm/world_us.lgp
-         */
-        void ProcessModels();
-
-        /**
-         * Generates the materials needed for the world map.
-         *
-         * @todo Note that this function stil doesn't use the game data, and it
-         * has a lot of hardcoded things.
+         * Copies the map files and the textures of the terrain.
          */
-        void GenerateMaterials();
+        void InstallMaps();
 
         /**
-         * Processes the next map to process.
+         * Exports the scripts of the world maps and the random encounters.
          *
-         * @return True if, once the map has been processed, all maps are
-         * processed. False if there are more maps to process.
-         */
-        bool ProcessMap();
-
-        /**
-         * Exports the random encounters of the world map to world/world_encounters.xml.
-         *
-         * @param[in] archive_file World map archive file.
-         * @param[in] entry Entry of ENC_W.BIN in the archive.
-         */
-        void ExportEncounters(File& archive_file, const VGears::LGPArchive::FileEntry& entry);
-
-                bool GenerateScripts(
-                    const std::vector<std::string>& field_names,
-                    const std::map<u16, float>& field_scale_factors,
-                    const std::vector<std::string>& converted_fields,
-                    std::string& error_message
-                );
+         * @param[in] field_names The names of the fields, by ID.
+         * @param[in] field_scale_factors The scale factors of the fields.
+         * @param[in] converted_fields The names of the installed fields.
+         * @param[out] error_message Why the scripts could not be written.
+         * @return True if the scripts were written.
+         */
+        bool GenerateScripts(
+          const std::vector<std::string>& field_names,
+          const std::map<u16, float>& field_scale_factors,
+          const std::vector<std::string>& converted_fields, std::string& error_message
+        );
 
         /**
-         * Copies the textures of the world map archive to "world/textures". The game uses them for the terrain.
+         * Converts the models of the world map.
          */
-        void ExtractTextures();
-
-        //void ReadMapFile(std::string file_name);
-
-        //void GenerateMap(std::string file_name, std::string output);
+        void ProcessModels();
 
     private:
 
         /**
-         * UV coordinates for a vertex.
+         * Copies the map files to "world/maps".
          */
-        struct UVCoord{
-
-            /**
-             * U coordinate.
-             */
-            u8 u;
-
-            /**
-             * V coordinate.
-             */
-            u8 v;
-        };
-
-        /**
-         * Mesh triangle data.
-         */
-        struct Triangle{
-
-            /**
-             * Index for each triangle vertex.
-             */
-            u8 vertex_index[3];
-
-            /**
-             * Walkability info.
-             *
-             * Shares byte with {@see function_id}, 5 bytes.
-             */
-            int walkability;
-
-            /**
-             * ID of the function triggered when entering the triangle.
-             *
-             * Shares byte with {@see walkability}, 3 bytes.
-             */
-            int function_id;
-
-            /**
-             * UV coordinates in texture for each vertex.
-             */
-            UVCoord vertex_coord[3];
-
-            /**
-             * Texture id.
-             *
-             * Shares bytes with {@see location_id}, 9 bytes.
-             */
-            u16 texture;
-
-            /**
-             * Location message ID.
-             *
-             * Shares bytes with {@see texture}, 7 bytes.
-             */
-            u16 location;
-        };
+        void CopyMaps();
 
         /**
-         * Mesh vertex data.
-         *
-         * Can also be used for normal data.
+         * Copies the textures of the world map archive to "world/textures". The game uses them for
+         * the terrain.
          */
-        struct Vertex{
-
-            /**
-             * X coordinate.
-             */
-            u16 x;
-
-            /**
-             * Y coordinate.
-             */
-            u16 y;
-
-            /**
-             * Z coordinate.
-             */
-            u16 z;
-
-            /**
-             * Unknown value, unused.
-             */
-            u16 unknown;
-        };
-
-        /**
-         * Mesh data.
-         */
-        struct Mesh{ // 0xB800 / 0x0F
-
-            /**
-             * Number of triangles in the mesh.
-             */
-            u16 triangle_count;
-
-            /**
-             * Number of vertices in the mesh.
-             */
-            u16 vertex_count;
-
-            /**
-             * Mesh triangle data.
-             *
-             * Size must equal {@see triangle_count}.
-             */
-            std::vector<Triangle> triangles;
-
-            /**
-             * Mesh vertex data.
-             *
-             * Size must equal {@see vertex_count}.
-             */
-            std::vector<Vertex> vertices;
-
-            /**
-             * Mesh normal data.
-             *
-             * Size must equal {@see vertex_count}.
-             */
-            std::vector<Vertex> normals;
-        };
-
-        /**
-         * Each block of a map.
-         *
-         * A block is always 0xB800 bytes and it's always composed of 16 meshes.
-         */
-        struct Block{ // 0xB800
-
-            /**
-             * Block meshes.
-             */
-            Mesh mesh[16];
-        };
-
-        /**
-         * A map.
-         *
-         * A map is defined in a WM*.MAP file. Divided in 0xB800 byte blocks.
-         */
-        struct Map{
-
-            /**
-             * Map blocks.
-             */
-            std::vector<Block> blocks;
-        };
-
-        /**
-         * World map texture.
-         */
-        struct Texture{
-
-            /**
-             * Texture ID.
-             */
-            int id;
-
-            /**
-             * Texture name.
-             */
-            std::string name;
-
-            /**
-             * Texture width.
-             */
-            int w;
-
-            /**
-             * Texture height.
-             */
-            int h;
-
-            /**
-             * U offset of the texture.
-             */
-            int u_offset;
-
-            /**
-             * V offset of the texture.
-             */
-            int v_offset;
-        };
-
-        /**
-         * Path to the world map elements models directory.
-         *
-         * Elements can be locations, playable characters, enemies,
-         * transportations... anything that it's not in itself part of the
-         * terrain.
-         */
-        static std::string ELEMENT_MODELS_DIR;
-
-        /**
-         * Path to the world map terrain models directory.
-         */
-        static std::string TERRAIN_MODELS_DIR;
+        void ExtractTextures();
 
         /**
-         * Exports a mesh to a file.
-         *
-         * The file will have the mesh name.
+         * Finds the world map archive in the disk.
          *
-         * @param[in] outdir Path to the directory where the file will be saved.
-         * @param[in] mesh The mesh to export.
-         */
-        void ExportMesh(const std::string outdir, const Ogre::MeshPtr &mesh);
-
-        /**
-         * Pointer to the application resource manager.
+         * @return The path of the archive, or an empty string if it's not in the disk.
          */
-        Ogre::ResourceGroupManager* res_mgr_;
-
-        /**
-         * Each of the original WM*.MAP in the installation disk.
-         */
-        std::vector<File> wm_map_;
-
-        /**
-         * List with all the texture names
-         */
-        std::vector<Texture> texture_;
+        std::string ArchivePath();
 
         /**
          * The disk image to extract the PC game data from.
@@ -332,19 +103,22 @@ class WorldInstaller{
         DiskImage disk_image_;
 
         /**
-         * The path to the directory where to save the V-Gears data.
+         * Directory where the game data is installed.
          */
-        std::string output_dir_;
+        std::string data_dir_;
 
         /**
-         * Directory where the game data is installed (<install dir>/data/).
+         * Writes the scripts of the maps.
          */
-        std::string data_dir_;
+        WorldScriptInstaller script_installer_;
 
         /**
-         * Number of maps already processed.
+         * Writes the random encounters.
          */
-        unsigned int processed_maps_;
-
+        WorldEncounterInstaller encounter_installer_;
 
+        /**
+         * Converts the models.
+         */
+        WorldModelInstaller model_installer_;
 };

+ 184 - 0
src/installer/extractors/WorldModelInstaller.cpp

@@ -0,0 +1,184 @@
+/*
+ * 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 <iostream>
+#include <set>
+#include <boost/filesystem.hpp>
+#include <OgreMaterialManager.h>
+#include <OgreMaterialSerializer.h>
+#include <OgreMeshManager.h>
+#include <OgreMeshSerializer.h>
+#include <OgreSkeletonSerializer.h>
+#include <OgreSubMesh.h>
+#include <OgreTechnique.h>
+#include "common/StringUtil.h"
+#include "formats/FF7NameLookup.h"
+#include "formats/model/AFileManager.h"
+#include "formats/model/HRCFileManager.h"
+#include "installer/formats/TexFile.h"
+#include "installer/tables/ModelMaterials.h"
+#include "installer/tables/WorldModelTable.h"
+#include "WorldModelInstaller.h"
+
+WorldModelInstaller::WorldModelInstaller(
+  const std::string& output_dir, const std::string& data_dir, Ogre::ResourceGroupManager* res_mgr
+): output_dir_(output_dir), data_dir_(data_dir), res_mgr_(res_mgr){}
+
+void WorldModelInstaller::Install(WorldArchive& archive){
+    boost::filesystem::create_directories(TempDir());
+    boost::filesystem::create_directories(ModelsDir());
+    // All the files are extracted first, so the ones a model depends on (.rsd, .p, .tex) exist
+    // when it is converted.
+    for (const std::string& file_name : ExtractFiles(archive)) ConvertModel(file_name);
+}
+
+std::vector<std::string> WorldModelInstaller::ExtractFiles(WorldArchive& archive){
+    std::vector<std::string> models;
+    for (const VGears::LGPArchive::FileEntry& entry : archive.Entries()){
+        if (!archive.Contains(entry)) continue;
+        const std::string name = WorldArchive::LowerName(entry);
+        archive.Open(entry).WriteFile(TempDir() + name);
+        if (name.size() >= 7 && name.substr(4, 3) == "hrc") models.push_back(name);
+    }
+    return models;
+}
+
+void WorldModelInstaller::ConvertModel(const std::string& file_name){
+    // TODO: Can this be done with declare resource?
+    // TODO: If not, declare all the HRC files first, and register the folder only once.
+    res_mgr_->declareResource(TempDir() + file_name, "Skeleton", "FFVII");
+    res_mgr_->removeResourceLocation(TempDir(), "FFVII");
+    res_mgr_->addResourceLocation(TempDir(), "FileSystem", "FFVII", true, true);
+    VGears::HRCFileManager& hrc_manager = VGears::HRCFileManager::GetSingleton();
+    try{
+        // TODO: This needs work to assemble all the pieces. Similar to field models.
+        Ogre::ResourcePtr hrc = hrc_manager.load(file_name, "FFVII");
+        Ogre::String base_name;
+        VGears::StringUtil::splitBase(file_name, base_name);
+        const auto mesh_name = VGears::NameLookup::model(base_name) + ".mesh";
+        Ogre::MeshPtr mesh(Ogre::MeshManager::getSingleton().load(mesh_name, "FFVII"));
+        Ogre::SkeletonPtr skeleton(mesh->getSkeleton());
+        AddAnimations(base_name, skeleton);
+        ExportMesh(mesh);
+        // Models can share a skeleton name with different bones (also with field models), so drop
+        // this one (with its skeleton and mesh) before converting the next.
+        hrc_manager.remove(file_name, "FFVII");
+    }
+    catch (const std::exception& ex){
+        std::cerr << "[ERROR] Exception converting world model " << file_name << ": " << ex.what()
+          << std::endl;
+        if (hrc_manager.resourceExists(file_name, "FFVII")) hrc_manager.remove(file_name, "FFVII");
+    }
+}
+
+void WorldModelInstaller::AddAnimations(const std::string& model_name, Ogre::SkeletonPtr& skeleton){
+    // The animations of the model, from the tables of ff7.exe (see WorldModelTable.h). Their
+    // names are the ones of the A files, in lower case.
+    for (const WorldModelTable::Model& model : WorldModelTable::MODELS){
+        if (model_name != model.hrc) continue;
+        for (unsigned int i = 0; i < model.animation_count; ++ i){
+            const std::string animation_file = std::string(model.animations[i]) + ".a";
+            try{
+                VGears::AFilePtr animation = VGears::AFileManager::GetSingleton().load(
+                  animation_file, "FFVII"
+                ).staticCast<VGears::AFile>();
+                animation->AddTo(skeleton, model.animations[i]);
+            }
+            catch (const std::exception& ex){
+                std::cerr << "[ERROR] Exception converting animation " << animation_file
+                  << " of world model " << model_name << ".hrc: " << ex.what() << std::endl;
+            }
+        }
+        return;
+    }
+}
+
+void WorldModelInstaller::ExportMesh(const Ogre::MeshPtr& mesh){
+    if (mesh.isNull()){
+        std::cerr << "[ERROR] ExportMesh called with null mesh." << std::endl;
+        return;
+    }
+    VGears::String base_mesh_name;
+    VGears::StringUtil::splitFull(mesh->getName(), base_mesh_name);
+    MakeMaterialsUnique(mesh, base_mesh_name);
+    Ogre::SkeletonPtr skeleton(mesh->getSkeleton());
+    if (!skeleton.isNull()){
+        Ogre::SkeletonSerializer skeleton_serializer;
+        skeleton_serializer.exportSkeleton(
+          skeleton.getPointer(), ModelsDir() + base_mesh_name + ".skeleton"
+        );
+        mesh->setSkeletonName(base_mesh_name + ".skeleton");
+    }
+    Ogre::MeshSerializer mesh_serializer;
+    mesh_serializer.exportMesh(mesh.getPointer(), ModelsDir() + mesh->getName());
+    Ogre::MaterialSerializer material_serializer;
+    std::set<std::string> queued_materials;
+    Ogre::Mesh::SubMeshIterator it(mesh->getSubMeshIterator());
+    while (it.hasMoreElements()){
+        Ogre::SubMesh* sub_mesh(it.getNext());
+        Ogre::MaterialPtr material(
+          Ogre::MaterialManager::getSingleton().getByName(sub_mesh->getMaterialName())
+        );
+        if (material == nullptr) continue;
+        for (size_t t = 0; t < material->getNumTechniques(); t ++){
+            Ogre::Technique* technique = material->getTechnique(t);
+            if (technique == nullptr) continue;
+            for (size_t p = 0; p < technique->getNumPasses(); p ++){
+                Ogre::Pass* pass = technique->getPass(p);
+                if (pass == nullptr) continue;
+                for (size_t u = 0; u < pass->getNumTextureUnitStates(); u ++){
+                    Ogre::TextureUnitState* unit = pass->getTextureUnitState(u);
+                    if (unit != nullptr && !unit->getTextureName().empty())
+                        ConvertTexture(*unit, base_mesh_name);
+                }
+            }
+        }
+        // Each material is queued once.
+        if (queued_materials.insert(sub_mesh->getMaterialName()).second)
+            material_serializer.queueForExport(material);
+    }
+    // Exporting with an empty queue throws in Ogre.
+    if (!queued_materials.empty())
+        material_serializer.exportQueued(ModelsDir() + base_mesh_name + VGears::EXT_MATERIAL);
+}
+
+void WorldModelInstaller::ConvertTexture(
+  Ogre::TextureUnitState& unit, const std::string& base_mesh_name
+){
+    // Materials are shared by name across all model types, so this one may have already been
+    // converted for a field or battle model (its texture is then a png).
+    if (!boost::filesystem::exists(TempDir() + unit.getTextureName())){
+        std::cerr << "[WARNING] Texture " << unit.getTextureName()
+          << " not found in temp/world_models; skipping it." << std::endl;
+        return;
+    }
+    try{
+        TexFile tex(TempDir() + unit.getTextureName());
+        // The material uses the png, under the name of the model.
+        Ogre::String base_name;
+        VGears::StringUtil::splitBase(unit.getTextureName(), base_name);
+        const std::string png_name = base_mesh_name + "_" + base_name + ".png";
+        unit.setTextureName(png_name);
+        tex.SavePng(ModelsDir() + png_name, 0);
+    }
+    catch (const std::exception& ex){
+        std::cerr << "[ERROR] Texture export failed for " << unit.getTextureName() << ": "
+          << ex.what() << std::endl;
+    }
+}
+
+std::string WorldModelInstaller::TempDir() const{return output_dir_ + "temp/world_models/";}
+
+std::string WorldModelInstaller::ModelsDir() const{return data_dir_ + "world/models/";}

+ 117 - 0
src/installer/extractors/WorldModelInstaller.h

@@ -0,0 +1,117 @@
+/*
+ * 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 <OgreMesh.h>
+#include <OgreResourceGroupManager.h>
+#include "WorldArchive.h"
+
+/**
+ * Converts the models of the world map, with their animations and textures.
+ */
+class WorldModelInstaller{
+
+    public:
+
+        /**
+         * Constructor.
+         *
+         * @param[in] output_dir The installation folder.
+         * @param[in] data_dir The game data folder.
+         * @param[in] res_mgr The application resource manager.
+         */
+        WorldModelInstaller(
+          const std::string& output_dir, const std::string& data_dir,
+          Ogre::ResourceGroupManager* res_mgr
+        );
+
+        /**
+         * Converts the models of the world map archive.
+         *
+         * Errors are written to the log.
+         *
+         * @param[in] archive The world map archive.
+         */
+        void Install(WorldArchive& archive);
+
+    private:
+
+        /**
+         * Extracts all the files of the archive to the temporary folder of the models.
+         *
+         * @param[in] archive The world map archive.
+         * @return The names of the model (HRC) files.
+         */
+        std::vector<std::string> ExtractFiles(WorldArchive& archive);
+
+        /**
+         * Converts a model.
+         *
+         * @param[in] file_name Name of the HRC file of the model.
+         */
+        void ConvertModel(const std::string& file_name);
+
+        /**
+         * Adds the animations of a model to its skeleton.
+         *
+         * @param[in] model_name Name of the model, without extension.
+         * @param[in,out] skeleton The skeleton.
+         */
+        static void AddAnimations(const std::string& model_name, Ogre::SkeletonPtr& skeleton);
+
+        /**
+         * Exports a mesh, with its skeleton, materials and textures.
+         *
+         * @param[in] mesh The mesh.
+         */
+        void ExportMesh(const Ogre::MeshPtr& mesh);
+
+        /**
+         * Converts the texture of a texture unit and makes the unit use the converted one.
+         *
+         * Errors are written to the log.
+         *
+         * @param[in,out] unit The texture unit.
+         * @param[in] base_mesh_name Name of the mesh, without extension.
+         */
+        void ConvertTexture(Ogre::TextureUnitState& unit, const std::string& base_mesh_name);
+
+        /**
+         * Folder where the files of the models are extracted.
+         */
+        std::string TempDir() const;
+
+        /**
+         * Folder of the converted models.
+         */
+        std::string ModelsDir() const;
+
+        /**
+         * The installation folder.
+         */
+        std::string output_dir_;
+
+        /**
+         * The game data folder.
+         */
+        std::string data_dir_;
+
+        /**
+         * The application resource manager.
+         */
+        Ogre::ResourceGroupManager* res_mgr_;
+};

+ 250 - 0
src/installer/extractors/WorldScriptInstaller.cpp

@@ -0,0 +1,250 @@
+/*
+ * 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 <fstream>
+#include <iostream>
+#include <sstream>
+#include <boost/filesystem.hpp>
+#include "decompiler/ControlFlow.h"
+#include "decompiler/DecompilerException.h"
+#include "decompiler/world/WorldEngine.h"
+#include "WorldScriptInstaller.h"
+
+const size_t WorldScriptInstaller::FIELD_TABLE_SIZE = 64 * 24;
+
+namespace{
+
+    /**
+     * Number of functions of an event file.
+     */
+    const unsigned int FUNCTION_COUNT = 256;
+
+    /**
+     * Reads a little endian 16 bit value.
+     *
+     * @param[in] data The data.
+     * @param[in] offset Offset of the value.
+     * @return The value.
+     */
+    uint16 ReadU16(const std::vector<u8>& data, const size_t offset){
+        return static_cast<uint16>(data[offset] | (data[offset + 1] << 8));
+    }
+
+    /**
+     * Reads the type of a function of an event file.
+     *
+     * @param[in] event_data The event file.
+     * @param[in] generated Which functions are in the script.
+     * @param[in] index Index of the function.
+     * @param[in] kind The wanted kind of function (the two upper bits of the type).
+     * @param[out] type The type of the function.
+     * @return True if the function is in the script and is of the wanted kind.
+     */
+    bool FunctionType(
+      const std::vector<u8>& event_data, const std::vector<bool>& generated, const size_t index,
+      const unsigned int kind, uint16& type
+    ){
+        if (!generated[index] || index * 4 + 1 >= event_data.size()) return false;
+        type = ReadU16(event_data, index * 4);
+        return (type >> 14) == kind;
+    }
+}
+
+WorldScriptInstaller::WorldScriptInstaller(const std::string& data_dir):
+  script_dir_(data_dir + "world/scripts")
+{}
+
+bool WorldScriptInstaller::Install(
+  WorldArchive& archive, const std::vector<std::string>& field_names,
+  const std::map<u16, float>& field_scale_factors,
+  const std::vector<std::string>& converted_fields, std::string& error_message
+){
+    std::vector<const VGears::LGPArchive::FileEntry*> event_entries;
+    const VGears::LGPArchive::FileEntry* field_table_entry = nullptr;
+    bool has_wm0 = false;
+    for (const VGears::LGPArchive::FileEntry& entry : archive.Entries()){
+        const std::string name = WorldArchive::LowerName(entry);
+        if (IsEventFile(name)){
+            event_entries.push_back(&entry);
+            if (name == "wm0.ev") has_wm0 = true;
+        }
+        else if (name == "field.tbl") field_table_entry = &entry;
+    }
+    if (event_entries.empty() || !has_wm0 || field_table_entry == nullptr){
+        error_message = "WM0.EV, other world event files, or FIELD.TBL were not found inside WORLD_US.LGP.";
+        return false;
+    }
+    if (field_table_entry->data_size != FIELD_TABLE_SIZE){
+        error_message = "FIELD.TBL has an unexpected size.";
+        return false;
+    }
+    const std::vector<u8> field_table = archive.Read(*field_table_entry);
+    boost::filesystem::create_directories(script_dir_);
+    for (const VGears::LGPArchive::FileEntry* event_entry : event_entries){
+        if (!WriteScript(
+          archive, *event_entry, field_table, field_names, field_scale_factors, converted_fields,
+          error_message
+        )) return false;
+    }
+    return true;
+}
+
+bool WorldScriptInstaller::IsEventFile(const std::string& name){
+    if (name.size() <= 5 || name.compare(0, 2, "wm") != 0) return false;
+    if (name.compare(name.size() - 3, 3, ".ev") != 0) return false;
+    return std::all_of(
+      name.begin() + 2, name.end() - 3,
+      [](char character){return character >= '0' && character <= '9';}
+    );
+}
+
+bool WorldScriptInstaller::WriteScript(
+  WorldArchive& archive, const VGears::LGPArchive::FileEntry& event_entry,
+  const std::vector<u8>& field_table, const std::vector<std::string>& field_names,
+  const std::map<u16, float>& field_scale_factors,
+  const std::vector<std::string>& converted_fields, std::string& error_message
+){
+    const std::vector<u8> event_data = archive.Read(event_entry);
+    if (event_data.empty()){
+        error_message = event_entry.file_name + " inside WORLD_US.LGP is empty.";
+        return false;
+    }
+    const std::string name = WorldArchive::LowerName(event_entry);
+    const std::string map_name = name.substr(0, name.size() - 3);
+    const std::string path = script_dir_ + "/" + map_name + ".lua";
+    std::ofstream script(path);
+    if (!script){
+        error_message = "Cannot create script output in " + script_dir_ + ".";
+        return false;
+    }
+    script << "-- Decompiled from the user's " << event_entry.file_name << " data.\n\n";
+    const std::vector<bool> generated = WriteFunctions(script, event_data, map_name);
+    script << "-- " << map_name << " mesh-function call-table mapping.\n";
+    WriteMeshFunctions(script, event_data, generated);
+    WriteEntityFunctions(script, event_data, generated);
+    WriteFieldTable(script, field_table, field_names, field_scale_factors, converted_fields);
+    script.flush();
+    if (!script){
+        error_message = "Failed while writing " + path + ".";
+        return false;
+    }
+    if (std::find(generated.begin(), generated.end(), true) == generated.end()){
+        error_message = "No functions in " + event_entry.file_name + " could be decompiled.";
+        return false;
+    }
+    return true;
+}
+
+std::vector<bool> WorldScriptInstaller::WriteFunctions(
+  std::ostream& script, const std::vector<u8>& event_data, const std::string& map_name
+){
+    std::vector<bool> generated(FUNCTION_COUNT, false);
+    for (unsigned int index = 0; index < FUNCTION_COUNT; ++ index){
+        try{
+            WorldEngine engine(index);
+            InstVec instructions;
+            std::unique_ptr<Disassembler> disassembler = engine.GetDisassembler(instructions);
+            disassembler->Open(event_data);
+            disassembler->Disassemble();
+            if (instructions.empty()) continue;
+            ControlFlow control_flow(instructions, engine);
+            control_flow.CreateGroups();
+            std::ostringstream function;
+            std::unique_ptr<CodeGenerator> code_generator
+              = engine.GetCodeGenerator(instructions, function);
+            code_generator->Generate(instructions, control_flow.GetGraph());
+            script << function.str() << "\n";
+            generated[index] = true;
+        }
+        catch (const DecompilerException&){
+            std::cerr << "[WARNING] World function " << index << " of " << map_name
+              << " could not be decompiled." << std::endl;
+            script << "-- world function " << index << " could not be decompiled.\n";
+        }
+        catch (const std::exception& exception){
+            std::cerr << "[WARNING] World function " << index << " of " << map_name
+              << " failed: " << exception.what() << std::endl;
+            script << "-- world function " << index << " failed: " << exception.what() << ".\n";
+        }
+    }
+    return generated;
+}
+
+void WorldScriptInstaller::WriteMeshFunctions(
+  std::ostream& script, const std::vector<u8>& event_data, const std::vector<bool>& generated
+){
+    for (size_t index = 0; index < generated.size(); ++ index){
+        uint16 type = 0;
+        if (!FunctionType(event_data, generated, index, 2, type)) continue;
+        const uint16 mesh = (type >> 4) & 0x03FF;
+        const unsigned int function = type & 0x0F;
+        if (mesh >= 36 * 28 || function > 4) continue;
+        script << "System.WorldMap.triangle_functions[" << mesh << "]"
+          << " = System.WorldMap.triangle_functions[" << mesh << "] or {}\n"
+          << "System.WorldMap.triangle_functions[" << mesh << "][" << function << "] = "
+          << index << "\n";
+    }
+}
+
+void WorldScriptInstaller::WriteEntityFunctions(
+  std::ostream& script, const std::vector<u8>& event_data, const std::vector<bool>& generated
+){
+    // The type of the entity is in the bits 8 to 13 of the type of the function, and the event in
+    // the low byte.
+    script << "System.WorldMap.entity_functions = {}\n";
+    for (size_t index = 0; index < generated.size(); ++ index){
+        uint16 type = 0;
+        if (!FunctionType(event_data, generated, index, 1, type)) continue;
+        const unsigned int entity = (type >> 8) & 0x3F;
+        const unsigned int event = type & 0xFF;
+        script << "System.WorldMap.entity_functions[" << entity << "] = "
+          << "System.WorldMap.entity_functions[" << entity << "] or {}\n"
+          << "System.WorldMap.entity_functions[" << entity << "][" << event << "] = "
+          << index << "\n";
+    }
+}
+
+void WorldScriptInstaller::WriteFieldTable(
+  std::ostream& script, const std::vector<u8>& field_table,
+  const std::vector<std::string>& field_names, const std::map<u16, float>& field_scale_factors,
+  const std::vector<std::string>& converted_fields
+){
+    script << "System.WorldMap.field_table = {}\n";
+    for (size_t record = 0; record < 64; ++ record){
+        for (size_t scenario = 0; scenario < 2; ++ scenario){
+            const size_t offset = record * 24 + scenario * 12;
+            const uint16 field_id = ReadU16(field_table, offset + 6);
+            if (field_id >= field_names.size()) continue;
+            const std::string& field_name = field_names[field_id];
+            if (std::find(converted_fields.begin(), converted_fields.end(), field_name)
+              == converted_fields.end()) continue;
+            const auto scale = field_scale_factors.find(field_id);
+            if (scale == field_scale_factors.end() || scale->second <= 0) continue;
+            const float downscale = 128.0f * scale->second;
+            const float x = static_cast<int16>(ReadU16(field_table, offset)) / downscale;
+            const float y = static_cast<int16>(ReadU16(field_table, offset + 2)) / downscale;
+            const int16 triangle = static_cast<int16>(ReadU16(field_table, offset + 4));
+            const float direction
+              = 360.0f * static_cast<float>(field_table[offset + 8]) / 256.0f;
+            const size_t table_id = record + 1;
+            script << "System.WorldMap.field_table[" << table_id << "]"
+              << " = System.WorldMap.field_table[" << table_id << "] or {}\n"
+              << "System.WorldMap.field_table[" << table_id << "][" << scenario << "] = {"
+              << "field = \"" << field_name << "\", x = " << x << ", y = " << y
+              << ", triangle = " << triangle << ", direction = " << direction << "}\n";
+        }
+    }
+}

+ 149 - 0
src/installer/extractors/WorldScriptInstaller.h

@@ -0,0 +1,149 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#pragma once
+
+#include <map>
+#include <ostream>
+#include <string>
+#include <vector>
+#include "common/TypeDefine.h"
+#include "WorldArchive.h"
+
+/**
+ * Writes the scripts of the world maps (world/scripts/wm<N>.lua), decompiled from the event files
+ * of the game, with the tables that tell when each function runs and where the field exits are.
+ */
+class WorldScriptInstaller{
+
+    public:
+
+        /**
+         * Constructor.
+         *
+         * @param[in] data_dir The game data folder.
+         */
+        explicit WorldScriptInstaller(const std::string& data_dir);
+
+        /**
+         * Writes the script of every world map.
+         *
+         * @param[in] archive The world map archive.
+         * @param[in] field_names The names of the fields, by ID.
+         * @param[in] field_scale_factors The scale factors of the fields.
+         * @param[in] converted_fields The names of the installed fields.
+         * @param[out] error_message Why the scripts could not be written.
+         * @return True if all the scripts were written.
+         */
+        bool Install(
+          WorldArchive& archive, const std::vector<std::string>& field_names,
+          const std::map<u16, float>& field_scale_factors,
+          const std::vector<std::string>& converted_fields, std::string& error_message
+        );
+
+        /**
+         * Checks if a file is the event file of a world map (wm<N>.ev).
+         *
+         * @param[in] name Name of the file, in lower case.
+         * @return True if it is an event file.
+         */
+        static bool IsEventFile(const std::string& name);
+
+        /**
+         * Writes the table of the functions that run when an entity walks on a mesh.
+         *
+         * @param[out] script The script.
+         * @param[in] event_data The event file, which starts with the types of the functions.
+         * @param[in] generated Which functions are in the script.
+         */
+        static void WriteMeshFunctions(
+          std::ostream& script, const std::vector<u8>& event_data, const std::vector<bool>& generated
+        );
+
+        /**
+         * Writes the table of the functions that run when an entity of a type is created, and for
+         * the other events of the entities.
+         *
+         * @param[out] script The script.
+         * @param[in] event_data The event file, which starts with the types of the functions.
+         * @param[in] generated Which functions are in the script.
+         */
+        static void WriteEntityFunctions(
+          std::ostream& script, const std::vector<u8>& event_data, const std::vector<bool>& generated
+        );
+
+        /**
+         * Writes the table of the places where the exits to fields take the player.
+         *
+         * The exits to fields that are not installed are left out.
+         *
+         * @param[out] script The script.
+         * @param[in] field_table The contents of FIELD.TBL, of {@see FIELD_TABLE_SIZE} bytes.
+         * @param[in] field_names The names of the fields, by ID.
+         * @param[in] field_scale_factors The scale factors of the fields.
+         * @param[in] converted_fields The names of the installed fields.
+         */
+        static void WriteFieldTable(
+          std::ostream& script, const std::vector<u8>& field_table,
+          const std::vector<std::string>& field_names,
+          const std::map<u16, float>& field_scale_factors,
+          const std::vector<std::string>& converted_fields
+        );
+
+        /**
+         * Size of FIELD.TBL: 64 records of 2 destinations of 12 bytes.
+         */
+        static const size_t FIELD_TABLE_SIZE;
+
+    private:
+
+        /**
+         * Decompiles the functions of an event file and writes them.
+         *
+         * Functions that can't be decompiled are replaced by a comment.
+         *
+         * @param[out] script The script.
+         * @param[in] event_data The event file.
+         * @param[in] map_name Name of the map, for the warnings.
+         * @return Which functions were written.
+         */
+        static std::vector<bool> WriteFunctions(
+          std::ostream& script, const std::vector<u8>& event_data, const std::string& map_name
+        );
+
+        /**
+         * Writes the script of a world map.
+         *
+         * @param[in] archive The world map archive.
+         * @param[in] event_entry The event file of the map.
+         * @param[in] field_table The contents of FIELD.TBL.
+         * @param[in] field_names The names of the fields, by ID.
+         * @param[in] field_scale_factors The scale factors of the fields.
+         * @param[in] converted_fields The names of the installed fields.
+         * @param[out] error_message Why the script could not be written.
+         * @return True if the script was written.
+         */
+        bool WriteScript(
+          WorldArchive& archive, const VGears::LGPArchive::FileEntry& event_entry,
+          const std::vector<u8>& field_table, const std::vector<std::string>& field_names,
+          const std::map<u16, float>& field_scale_factors,
+          const std::vector<std::string>& converted_fields, std::string& error_message
+        );
+
+        /**
+         * The folder of the scripts.
+         */
+        std::string script_dir_;
+};

+ 0 - 1
src/installer/formats/CMakeLists.txt

@@ -6,5 +6,4 @@ vgears_sources(
     DaFile.cpp
     DiskImage.cpp
     TexFile.cpp
-    WorldMapWalkmesh.cpp
 )

+ 0 - 217
src/installer/formats/WorldMapWalkmesh.cpp

@@ -1,217 +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 <tinyxml.h>
-#include "installer/formats/WorldMapWalkmesh.h"
-
-WorldMapWalkmesh::Triangle::Triangle(
-  const unsigned int id, const Ogre::Vector3 a, const Ogre::Vector3 b,
-  const Ogre::Vector3 c, const unsigned int walkability, const int event
-): id_(id), a_(a), b_(b), c_(c), walkability_(walkability), event_(event){
-    ab_.id = -1;
-    ab_.warp = false;
-    bc_.id = -1;
-    bc_.warp = false;
-    ca_.id = -1;
-    ca_.warp = false;
-}
-
-unsigned int WorldMapWalkmesh::Triangle::getId() const{return id_;}
-
-Ogre::Vector3 WorldMapWalkmesh::Triangle::getA() const {return a_;}
-
-Ogre::Vector3 WorldMapWalkmesh::Triangle::getB() const {return b_;}
-
-Ogre::Vector3 WorldMapWalkmesh::Triangle::getC() const {return c_;}
-
-WorldMapWalkmesh::Triangle::Target WorldMapWalkmesh::Triangle::getAB() const {return ab_;}
-
-WorldMapWalkmesh::Triangle::Target WorldMapWalkmesh::Triangle::getBC() const {return bc_;}
-
-WorldMapWalkmesh::Triangle::Target WorldMapWalkmesh::Triangle::getCA() const {return ca_;}
-
-unsigned int WorldMapWalkmesh::Triangle::getWalkability() const {return walkability_;}
-
-int WorldMapWalkmesh::Triangle::getEvent() const {return event_;}
-
-void WorldMapWalkmesh::Triangle::setAB(const int id, const bool warp){
-    ab_.id = std::max(id, -1);
-    ab_.warp = warp;
-}
-
-void WorldMapWalkmesh::Triangle::setBC(const int id, const bool warp){
-    bc_.id = std::max(id, -1);
-    bc_.warp = warp;
-}
-
-void WorldMapWalkmesh::Triangle::setCA(const int id, const bool warp){
-    ca_.id = std::max(id, -1);
-    ca_.warp = warp;
-}
-
-WorldMapWalkmesh::WorldMapWalkmesh(const unsigned int id, const bool warp): id_(id), warp_(warp), calculated_(false){
-    triangles_.clear();
-}
-
-void WorldMapWalkmesh::addTriangle(
-  const Ogre::Vector3 a, const Ogre::Vector3 b, const Ogre::Vector3 c,
-  const unsigned int walkability, const int event
-){
-    calculated_ = false;
-    Triangle tri(triangles_.size(), a, b, c, walkability, event);
-    //if (id_ == 0 && triangles_.size() < 50){
-    //    std::cout << "Adding triangle " << tri.getId() << " W: "<< walkability << " - " << tri.getWalkability()
-    //      << "     E: " << event << " - " << tri.getEvent() << std::endl;
-    //}
-    triangles_.push_back(tri);
-}
-
-void WorldMapWalkmesh::generate(std::string path){
-    if (!calculated_) calculate();
-    TiXmlDocument doc;
-    std::unique_ptr<TiXmlElement> xml(new TiXmlElement("walkmesh"));
-    for (Triangle tri: triangles_){
-        std::unique_ptr<TiXmlElement> xml_tri(new TiXmlElement("triangle"));
-        xml_tri->SetAttribute("id", std::to_string(tri.getId()));
-        xml_tri->SetAttribute(
-          "a",
-          std::to_string(static_cast<int>(tri.getA()[0])) + " "
-          + std::to_string(static_cast<int>(tri.getA()[1])) + " "
-          + std::to_string(static_cast<int>(tri.getA()[2]))
-        );
-        xml_tri->SetAttribute(
-          "b",
-          std::to_string(static_cast<int>(tri.getB()[0])) + " "
-          + std::to_string(static_cast<int>(tri.getB()[1])) + " "
-          + std::to_string(static_cast<int>(tri.getB()[2]))
-        );
-        xml_tri->SetAttribute(
-          "c",
-          std::to_string(static_cast<int>(tri.getA()[0])) + " "
-          + std::to_string(static_cast<int>(tri.getC()[1])) + " "
-          + std::to_string(static_cast<int>(tri.getC()[2]))
-        );
-        // WARN: This is never actually calculated. See the comments on calculate()
-        if (tri.getAB().id > -1)
-            xml_tri->SetAttribute("a_b", std::to_string(tri.getAB().id) + (tri.getAB().warp ? " warp" : ""));
-        if (tri.getBC().id > -1)
-            xml_tri->SetAttribute("b_c", std::to_string(tri.getBC().id) + (tri.getBC().warp ? " warp" : ""));
-        if (tri.getCA().id > -1)
-            xml_tri->SetAttribute("c_a", std::to_string(tri.getCA().id) + (tri.getCA().warp ? " warp" : ""));
-        xml_tri->SetAttribute("walkability", std::to_string(tri.getWalkability()));
-        if (tri.getEvent() > -1) xml_tri->SetAttribute("event", std::to_string(tri.getEvent()));
-        xml->LinkEndChild(xml_tri.release());
-    }
-    doc.LinkEndChild(xml.release());
-    doc.SaveFile(path);
-}
-
-void WorldMapWalkmesh::calculate(){
-    // FIXME: This is super time-consumming. Either optimize it or skip it and calculate it on
-    // runtime.
-    calculated_ = true;
-    return;
-    // FIXME: The actual function starts here.
-    if (calculated_) return;
-    for (Triangle tri: triangles_){
-        tri.setAB(-1, false);
-        tri.setBC(-1, false);
-        tri.setCA(-1, false);
-    }
-    for (Triangle tri: triangles_){
-        if (tri.getAB().id != -1) continue;
-        for (Triangle compare: triangles_){
-            // For each triangle combination, check if any two vertices match,
-            // and set AB/BC/CA for both of them.
-            if (tri.getId() != compare.getId()){
-                if (
-                  (tri.getA() == compare.getA() && tri.getB() == compare.getB())
-                  || (tri.getB() == compare.getA() && tri.getA() == compare.getB())
-                ){
-                    // AB <-> AB match
-                    tri.setAB(compare.getId(), false);
-                    compare.setAB(tri.getId(), false);
-                }
-                if (
-                  (tri.getA() == compare.getB() && tri.getB() == compare.getC())
-                  || (tri.getB() == compare.getB() && tri.getA() == compare.getC())
-                ){
-                    // AB <-> BC match
-                    tri.setAB(compare.getId(), false);
-                    compare.setBC(tri.getId(), false);
-                }
-                if (
-                  (tri.getA() == compare.getC() && tri.getB() == compare.getA())
-                  || (tri.getB() == compare.getC() && tri.getA() == compare.getA())
-                ){
-                    // AB <-> CA match
-                    tri.setAB(compare.getId(), false);
-                    compare.setCA(tri.getId(), false);
-                }
-                if (
-                  (tri.getB() == compare.getA() && tri.getC() == compare.getB())
-                  || (tri.getC() == compare.getA() && tri.getB() == compare.getB())
-                ){
-                    // BC <-> AB match
-                    tri.setBC(compare.getId(), false);
-                    compare.setAB(tri.getId(), false);
-                }
-                if (
-                  (tri.getB() == compare.getB() && tri.getC() == compare.getC())
-                  || (tri.getC() == compare.getB() && tri.getB() == compare.getC())
-                ){
-                    // BC <-> BC match
-                    tri.setBC(compare.getId(), false);
-                    compare.setBC(tri.getId(), false);
-                }
-                if (
-                  (tri.getB() == compare.getC() && tri.getC() == compare.getA())
-                  || (tri.getC() == compare.getC() && tri.getB() == compare.getA())
-                ){
-                    // BC <-> CA match
-                    tri.setBC(compare.getId(), false);
-                    compare.setCA(tri.getId(), false);
-                }
-                if (
-                  (tri.getC() == compare.getA() && tri.getA() == compare.getB())
-                  || (tri.getA() == compare.getA() && tri.getC() == compare.getB())
-                ){
-                    // CA <-> AB match
-                    tri.setBC(compare.getId(), false);
-                    compare.setAB(tri.getId(), false);
-                }
-                if (
-                  (tri.getC() == compare.getB() && tri.getA() == compare.getC())
-                  || (tri.getA() == compare.getB() && tri.getC() == compare.getC())
-                ){
-                    // CA <-> BC match
-                    tri.setCA(compare.getId(), false);
-                    compare.setBC(tri.getId(), false);
-                }
-                if (
-                  (tri.getC() == compare.getC() && tri.getA() == compare.getA())
-                  || (tri.getA() == compare.getC() && tri.getC() == compare.getA())
-                ){
-                    // CA <-> CA match
-                    tri.setCA(compare.getId(), false);
-                    compare.setCA(tri.getId(), false);
-                }
-                // TODO: For warping worlds, check warping
-            }
-        }
-    }
-    calculated_ = true;
-}

+ 0 - 282
src/installer/formats/WorldMapWalkmesh.h

@@ -1,282 +0,0 @@
-/*
- * V-Gears
- * Copyright (C) 2022 V-Gears Team
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program 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.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-
-#pragma once
-
-#include "OGRE/Ogre.h"
-#include "common/TypeDefine.h"
-
-/**
- * Represents a walkmesh for a world map.
- */
-class WorldMapWalkmesh{
-
-    public:
-
-        class Triangle{
-
-            public:
-
-                /**
-                 * Triangle reached when exiting this triangle from one of its
-                 * borders.
-                 */
-                struct Target{
-
-                    /**
-                     * Target triangle ID.
-                     *
-                     * If -1, there is no way out by this side.
-                     */
-                    int id;
-
-                    /**
-                     * False if the target triangle is truly adjacent, true if
-                     * it warps to other side of the world.
-                     */
-                    bool warp;
-                };
-
-                /**
-                 * Creates a triangle
-                 *
-                 * @param[in] id Triangle ID.
-                 * @param[in] a X, Y, Z coordinates of the first vertex.
-                 * @param[in] b X, Y, Z coordinates of the second vertex.
-                 * @param[in] c X, Y, Z coordinates of the third vertex.
-                 * @param[in] walkability Walkability mode ID.
-                 * @param[in] event Event triggered upon entering the triangle,
-                 * or -1 for no event.
-                 */
-                Triangle(
-                  const unsigned int id, Ogre::Vector3 a, const Ogre::Vector3 b,
-                  const Ogre::Vector3 c, const unsigned int walkability, const int event
-                );
-
-                /**
-                 * Retrieves the triangle ID in the walkmesh.
-                 *
-                 * @return The triangle ID.
-                 */
-                unsigned int getId() const;
-
-                /**
-                 * Retrieves the coordinates of the first vertex
-                 *
-                 * @return Vertex coordinates (X, Y, Z).
-                 */
-                Ogre::Vector3 getA() const;
-
-                /**
-                 * Retrieves the coordinates of the second vertex
-                 *
-                 * @return Vertex coordinates (X, Y, Z).
-                 */
-                Ogre::Vector3 getB() const;
-
-                /**
-                 * Retrieves the coordinates of the third vertex
-                 *
-                 * @return Vertex coordinates (X, Y, Z).
-                 */
-                Ogre::Vector3 getC() const;
-
-                /**
-                 * Retrieves the triangle reached when exiting the triangle by
-                 * the side between the vertices A and B.
-                 *
-                 * @return Target triangle.
-                 */
-                Target getAB() const;
-
-                /**
-                 * Retrieves the triangle reached when exiting the triangle by
-                 * the side between the vertices B and C.
-                 *
-                 * @return Target triangle.
-                 */
-                Target getBC() const;
-
-                /**
-                 * Retrieves the triangle reached when exiting the triangle by
-                 * the side between the vertices C and A.
-                 *
-                 * @return Target triangle.
-                 */
-                Target getCA() const;
-
-                /**
-                 * Retrieves the triangle walkability mode.
-                 *
-                 * @return The walkability mode number.
-                 */
-                unsigned int getWalkability() const;
-
-                /**
-                 * Retrieves the event triggered upon entering the triangle.
-                 *
-                 * @return The ID of the event triggered on entering, or -1 if
-                 * none.
-                 */
-                int getEvent() const;
-
-                /**
-                 * Sets the triangle reached when exiting the triangle by the
-                 * side between the vertices A and B.
-                 *
-                 * @param[in] id Target triangle ID. -1 to indicate no way out
-                 * by the edge.
-                 * @param[in] warp True to indicate world warping (ie, if
-                 * walking into an edge of the world gets you at the other end).
-                 */
-                void setAB(const int id, const bool warp);
-
-                /**
-                 * Sets the triangle reached when exiting the triangle by the
-                 * side between the vertices B and C.
-                 *
-                 * @param[in] id Target triangle ID. -1 to indicate no way out
-                 * by the edge.
-                 * @param[in] warp True to indicate world warping (ie, if
-                 * walking into an edge of the world gets you at the other end).
-                 */
-                void setBC(const int id, const bool warp);
-
-                /**
-                 * Sets the triangle reached when exiting the triangle by the
-                 * side between the vertices C and A.
-                 *
-                 * @param[in] id Target triangle ID. -1 to indicate no way out
-                 * by the edge.
-                 * @param[in] warp True to indicate world warping (ie, if
-                 * walking into an edge of the world gets you at the other end).
-                 * the world gets you at the other end).
-                 */
-                void setCA(const int id, const bool warp);
-
-            private:
-
-                /**
-                 * Triangle ID.
-                 */
-                unsigned int id_;
-
-                /**
-                 * First vertex, X, Y, Z coordinates.
-                 */
-                Ogre::Vector3 a_;
-
-                /**
-                 * Second vertex, X, Y, Z coordinates.
-                 */
-                Ogre::Vector3 b_;
-
-                /**
-                 * Third vertex, X, Y, Z coordinates.
-                 */
-                Ogre::Vector3 c_;
-
-                /**
-                 * Target reached when exiting by the side formed by {@see a_}
-                 * and {@see b_}.
-                 */
-                Target ab_;
-
-                /**
-                 * Target reached when exiting by the side formed by {@see b_}
-                 * and {@see c_}.
-                 */
-                Target bc_;
-
-                /**
-                 * Target reached when exiting by the side formed by {@see c_}
-                 * and {@see a_}.
-                 */
-                Target ca_;
-
-                /**
-                 * Walkability mode.
-                 */
-                unsigned int walkability_;
-
-                /**
-                 * Id of the event triggered upon entering the triangle.
-                 */
-                int event_;
-        };
-
-        /**
-         * Constructor.
-         *
-         * @param[in] id World map ID.
-         * @param[in] warp Indicates if the world map is warpable (ie, if
-         * walking into an edge of the world gets you at the other end).
-         */
-        WorldMapWalkmesh(const unsigned int id, const bool warp);
-
-        /**
-         * Adds a triangle.
-         *
-         * @param[in] a X, Y, Z coordinates of the first vertex.
-         * @param[in] b X, Y, Z coordinates of the second vertex.
-         * @param[in] c X, Y, Z coordinates of the third vertex.
-         * @param[in] walkability Walkability mode ID.
-         * @param[in] event Event triggered upon entering the triangle. -1 for
-         * no event.
-         */
-        void addTriangle(
-          const Ogre::Vector3 a, const Ogre::Vector3 b, const Ogre::Vector3 c,
-          const unsigned int walkability, const int event
-        );
-
-        /**
-         * Generates a world map walkmesh file.
-         *
-         * @param[in] path Path where the file will be saved (directory must
-         * exist).
-         */
-        void generate(const std::string path);
-
-    private:
-
-        /**
-         * Worldmap ID
-         */
-        unsigned int id_;
-
-        /**
-         * Indicates if the world is a warpable one.
-         */
-        bool warp_;
-
-        /**
-         * The list of triangles.
-         */
-        std::vector<Triangle> triangles_;
-
-        /**
-         * Indicates if the relations between triangles has been calculated
-         * since the last triangle was added.
-         */
-        bool calculated_;
-
-        /**
-         * Calculates the relations between triangles.
-         */
-        void calculate();
-};

+ 11 - 16
src/installer/steps/DataInstaller.cpp

@@ -83,7 +83,7 @@ const char* DataInstaller::StepGroup(int state){
     if (state >= FIELD_SPAWN_POINTS_AND_SCALE_FACTORS_INIT && state <= FIELD_WRITE_END)
         return "Field maps";
     if (state == WM_MODELS) return "World map models";
-    if (state >= WM_INIT && state <= WM_MAPS) return "World map";
+    if (state >= WM_INIT && state <= WM_SCRIPTS) return "World map";
     if (state >= MEDIA_MUSICS_INIT && state < FIELD_SPAWN_POINTS_AND_SCALE_FACTORS_INIT)
         return "Music";
     if (state >= MEDIA_SOUNDS_INIT && state < MEDIA_MUSICS_INIT) return "Sounds";
@@ -477,31 +477,26 @@ float DataInstaller::Progress(){
             }
             write_output_line_("Extracting world map data...", 2, true);
             UseModelParts("temp/world_models/");
-            substeps_ = world_installer_->Initialize();
+            world_installer_->InstallMaps();
+            substeps_ = 0;
             cur_substep_ = 0;
-            installation_state_ = WM_MATERIALS;
-            return CalcProgress();
-        case WM_MATERIALS:
-            world_installer_->GenerateMaterials();
-            installation_state_ = WM_MAPS;
+            installation_state_ = WM_SCRIPTS;
             return CalcProgress();
-        case WM_MAPS:
-            if (world_installer_->ProcessMap() == false) cur_substep_ ++;
-            else{
+        case WM_SCRIPTS:
+            {
                 std::string script_error;
-                                if (world_installer_->GenerateScripts(
-                                        field_installer_->GetMapList(), field_installer_->GetFieldScaleFactors(),
-                                        field_installer_->GetConvertedMapList(), script_error
-                                    )){
+                if (world_installer_->GenerateScripts(
+                  field_installer_->GetMapList(), field_installer_->GetFieldScaleFactors(),
+                  field_installer_->GetConvertedMapList(), script_error
+                )){
                     write_output_line_("Generated world-map scripts.", 2, true);
                 }
                 else{
                     write_output_line_("Could not generate world-map scripts: " + script_error, 2, true);
                 }
                 installation_state_ = WM_MODELS;
-                cur_substep_ = 0;
+                return CalcProgress();
             }
-            return CalcProgress();
         case WM_MODELS:
             if (!options_.wm_models) write_output_line_("Skipping world map model installation...", 2, true);
             else world_installer_->ProcessModels();

+ 3 - 8
src/installer/steps/DataInstaller.h

@@ -419,19 +419,14 @@ class DataInstaller{
             FIELD_CONVERT_MODELS,
 
             /**
-             * Prepares the installer for world map data installation.
+             * Copies the world maps and their textures.
              */
             WM_INIT,
 
             /**
-             * Generates the materials for the world map terrain.
+             * Step that writes the world map scripts and encounters.
              */
-            WM_MATERIALS,
-
-            /**
-             * Step that extracts world map terrain data.
-             */
-            WM_MAPS,
+            WM_SCRIPTS,
 
             /**
              * Step that extracts world map models.

+ 3 - 4
src/installer/steps/InstallLayout.cpp

@@ -90,9 +90,8 @@ namespace InstallLayout{
         static const std::vector<std::string> dirs = {
           "kernel", "field/maps", "field/models", "battle/enemies", "battle/attacks", "battle/formations",
           "battle/effects", "battle/scripts", "battle/images", "battle/models/characters", "battle/models/scenes",
-          "battle/models/enemies", "battle/models/attacks", "battle/models/effects", "world/maps/0", "world/maps/1",
-          "world/maps/2", "world/textures", "world/scripts", "world/models/terrain/0", "world/models/terrain/1",
-          "world/models/terrain/2", "world/models/elements", "ui/images/icons", "ui/images/other",
+          "battle/models/enemies", "battle/models/attacks", "battle/models/effects", "world/maps", "world/textures",
+          "world/scripts", "world/models", "ui/images/icons", "ui/images/other",
           "ui/images/characters", "ui/images/fonts", "ui/images/reels", "ui/images/window", "ui/fonts",
           "audio/music", "audio/sounds"
         };
@@ -100,7 +99,7 @@ namespace InstallLayout{
     }
 
     const std::vector<std::string>& TempSubdirs(){
-        static const std::vector<std::string> dirs = {"char", "battle_models", "world_models", "spell_models", "effects", "wm"};
+        static const std::vector<std::string> dirs = {"char", "battle_models", "world_models", "spell_models", "effects"};
         return dirs;
     }
 

+ 0 - 1
src/installer/steps/InstallVerifier.cpp

@@ -215,7 +215,6 @@ VerifyResult VerifyInstallation(
     for (const char* file : {"triangle_triggers.lua", "vehicles.lua", "script_stubs.lua"})
         check.File(world, std::string("engine/scripts/world/") + file);
     check.File(world, "game/world/world_encounters.xml");
-    check.Files(world, "game/world/models/terrain/0", ".mesh", 1);
     check.Files(world, "game/world/textures", ".tex", 1);
 
     const std::string world_models = "World map models";

+ 1 - 0
test/installer/extractors/CMakeLists.txt

@@ -4,6 +4,7 @@ vgears_tests(
     KernelData.cpp
     SfxDump.cpp
     WindowFonts.cpp
+    WorldData.cpp
 )
 vgears_installer_tests(
     MovieCamera.cpp

+ 87 - 0
test/installer/extractors/WorldData.cpp

@@ -0,0 +1,87 @@
+/*
+ * 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 <sstream>
+#include <boost/test/unit_test.hpp>
+#include "installer/extractors/WorldEncounterInstaller.h"
+#include "installer/extractors/WorldScriptInstaller.h"
+
+BOOST_AUTO_TEST_CASE(TestWorldEventFileNames){
+    BOOST_CHECK(WorldScriptInstaller::IsEventFile("wm0.ev"));
+    BOOST_CHECK(WorldScriptInstaller::IsEventFile("wm12.ev"));
+    BOOST_CHECK(!WorldScriptInstaller::IsEventFile("wm.ev"));
+    BOOST_CHECK(!WorldScriptInstaller::IsEventFile("wmx.ev"));
+    BOOST_CHECK(!WorldScriptInstaller::IsEventFile("wm0.tex"));
+    BOOST_CHECK(!WorldScriptInstaller::IsEventFile("ab0.ev"));
+}
+
+BOOST_AUTO_TEST_CASE(TestWorldFunctionTables){
+    // Function 0 is of an entity (type 1) and function 1 of a mesh (type 2).
+    const unsigned int entity = (1 << 14) | (5 << 8) | 3;
+    const unsigned int mesh = (2 << 14) | (100 << 4) | 2;
+    const std::vector<u8> events{
+      static_cast<u8>(entity & 0xFF), static_cast<u8>(entity >> 8), 0, 0,
+      static_cast<u8>(mesh & 0xFF), static_cast<u8>(mesh >> 8), 0, 0
+    };
+    std::ostringstream meshes;
+    WorldScriptInstaller::WriteMeshFunctions(meshes, events, {true, true});
+    BOOST_CHECK(meshes.str().find("System.WorldMap.triangle_functions[100][2] = 1\n") != std::string::npos);
+    BOOST_CHECK(meshes.str().find("= 0\n") == std::string::npos);
+    std::ostringstream entities;
+    WorldScriptInstaller::WriteEntityFunctions(entities, events, {true, true});
+    BOOST_CHECK(entities.str().find("System.WorldMap.entity_functions[5][3] = 0\n") != std::string::npos);
+    BOOST_CHECK(entities.str().find("= 1\n") == std::string::npos);
+    // Functions that were not decompiled are not in the tables.
+    std::ostringstream none;
+    WorldScriptInstaller::WriteMeshFunctions(none, events, {false, false});
+    BOOST_CHECK(none.str().empty());
+}
+
+BOOST_AUTO_TEST_CASE(TestWorldFieldTableSkipsFieldsNotInstalled){
+    std::vector<u8> table(WorldScriptInstaller::FIELD_TABLE_SIZE, 0xFF);
+    // First record, first scenario: field 1, at (-256, 128), triangle 7, direction 64.
+    const u8 first[12] = {0x00, 0xFF, 0x80, 0x00, 7, 0, 1, 0, 64, 0, 0, 0};
+    std::copy(first, first + 12, table.begin());
+    // First record, second scenario: field 2, which is not installed.
+    const u8 second[12] = {0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0};
+    std::copy(second, second + 12, table.begin() + 12);
+    std::ostringstream script;
+    WorldScriptInstaller::WriteFieldTable(
+      script, table, {"startmap", "md1stin", "md1_1"}, {{1, 1.0f}, {2, 1.0f}}, {"md1stin"}
+    );
+    BOOST_CHECK(script.str().find(
+      "System.WorldMap.field_table[1][0] = {field = \"md1stin\", x = -2, y = 1, triangle = 7, direction = 90}"
+    ) != std::string::npos);
+    BOOST_CHECK(script.str().find("md1_1") == std::string::npos);
+}
+
+BOOST_AUTO_TEST_CASE(TestWorldEncounters){
+    BOOST_CHECK(!WorldEncounterInstaller::CreateEncounters(std::vector<u8>(100)));
+    std::vector<u8> data(0xA0 + 64 * 32, 0);
+    // Region 1, terrain group 2: enabled, rate 40, first word 0x1234.
+    const size_t record = 0xA0 + 6 * 32;
+    data[record] = 1;
+    data[record + 1] = 40;
+    data[record + 2] = 0x34;
+    data[record + 3] = 0x12;
+    const auto encounters = WorldEncounterInstaller::CreateEncounters(data);
+    BOOST_REQUIRE(encounters);
+    const TiXmlElement* element = encounters->FirstChildElement("record");
+    for (int i = 0; i < 6; ++ i) element = element->NextSiblingElement("record");
+    BOOST_CHECK_EQUAL(std::string(element->Attribute("region")), "1");
+    BOOST_CHECK_EQUAL(std::string(element->Attribute("enabled")), "1");
+    BOOST_CHECK_EQUAL(std::string(element->Attribute("rate")), "40");
+    BOOST_CHECK_EQUAL(std::string(element->Attribute("words")).substr(0, 7), "4660 0 ");
+}