Browse Source

Split the field data installer and fixed four bugs in it

- There is an installer for each part of a field: the script and texts, the map and walkmesh, the background, and the models. FieldDataInstaller keeps its public functions, which pass the calls on.
- The script formatters are in their own header, and the types, constants and lookups that the parts share are in FieldDataTypes.h.
- Broke up the writing of the map file and of the background.
- Removed WillCrash, which never found a field, and some unused members.
- The field model textures were also saved without the model name, and those 685 files were never used.
- The search for music tracks could read past the end of a short script.
- Writing the list of fields checked the index against the wrong list, and converting a model no field uses crashed.
- Added tests for the script header, the spawn points, the music tracks and the blending names.
Iñigo Valentin 4 days ago
parent
commit
fcd7da11ef

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

@@ -6,7 +6,11 @@ vgears_sources(
     BattleModelInstaller.cpp
     BattleModelInstaller.cpp
     BattleModelTools.cpp
     BattleModelTools.cpp
     BattleSceneInstaller.cpp
     BattleSceneInstaller.cpp
+    FieldBackgroundInstaller.cpp
     FieldDataInstaller.cpp
     FieldDataInstaller.cpp
+    FieldMapWriter.cpp
+    FieldModelInstaller.cpp
+    FieldScriptInstaller.cpp
     FieldTextWriter.cpp
     FieldTextWriter.cpp
     KernelAttacks.cpp
     KernelAttacks.cpp
     KernelCharacters.cpp
     KernelCharacters.cpp

+ 190 - 0
src/installer/extractors/FieldBackgroundInstaller.cpp

@@ -0,0 +1,190 @@
+/*
+ * 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 <cmath>
+#include <fstream>
+#include <OgreImage.h>
+#include <OgreStringConverter.h>
+#include "FieldBackgroundInstaller.h"
+
+const int FieldBackgroundInstaller::SCALE_UP_FACTOR = 3;
+
+const int FieldBackgroundInstaller::SCREEN_WIDTH = 320;
+
+const int FieldBackgroundInstaller::SCREEN_HEIGHT = 240;
+
+FieldBackgroundInstaller::FieldBackgroundInstaller(const std::string& data_dir): data_dir_(data_dir){}
+
+void FieldBackgroundInstaller::Install(
+  const VGears::FLevelFilePtr& field, const FieldDecompiler::DecompiledScript& decompiled,
+  const float scale
+){
+    const std::string dir = data_dir_ + "/" + FieldData::MAPS_DIR + "/";
+    const VGears::PaletteFilePtr& palette = field->GetPalette();
+    const VGears::BackgroundFilePtr& background = field->GetBackground();
+    std::unique_ptr<Ogre::Image> image(background->CreateImage(palette));
+    image->encode("png");
+    image->save(dir + field->getName() + "/tiles.png");
+    TiXmlDocument doc;
+    std::unique_ptr<TiXmlElement> element(new TiXmlElement("background2d"));
+    element->SetAttribute("image", field->getName() + "/tiles.png");
+    WriteCamera(field, scale, *element);
+    // The palette animations: the tiles of the palettes a script changes are painted again by
+    // the engine.
+    if (!decompiled.palette_pages.empty() || decompiled.palette_pages_dynamic){
+        const std::string palette_name = field->getName() + "/palette.bin";
+        if (WritePaletteFile(
+          dir + palette_name, palette, background->GetPaletteTiles(), decompiled.palette_pages,
+          decompiled.palette_pages_dynamic
+        )){
+            element->SetAttribute("palette", palette_name);
+        }
+    }
+    // TODO: Should only the tiles of the enabled layers be written?
+    const int width = image->getWidth();
+    const int height = image->getHeight();
+    int layer_index = -1;
+    for (const auto& layer : background->GetLayers()){
+        ++ layer_index;
+        for (const VGears::BackgroundFile::SpriteData& sprite : layer.sprites)
+            element->LinkEndChild(CreateTile(sprite, layer_index, width, height, scale).release());
+    }
+    doc.LinkEndChild(element.release());
+    doc.SaveFile(dir + field->getName() + "/bg.xml");
+}
+
+std::string FieldBackgroundInstaller::BlendingName(const int blending){
+    if (blending == 0) return "alpha";
+    // 3 is source + 0.25 * destination:
+    if (blending == 1 || blending == 3) return "add";
+    if (blending == 2) return "subtract";
+    // TODO: Should probably throw to fail conversion:
+    return "unknown";
+}
+
+void FieldBackgroundInstaller::WriteCamera(
+  const VGears::FLevelFilePtr& field, const float scale, TiXmlElement& background
+){
+    const VGears::CameraMatrixFilePtr& camera_matrix = field->GetCameraMatrix();
+    const Ogre::Vector3 position = camera_matrix->GetPosition() / scale;
+    const Ogre::Quaternion orientation = camera_matrix->GetOrientation();
+    const Ogre::Degree fov = camera_matrix->GetFov(static_cast<float>(SCREEN_HEIGHT));
+    const auto& range = field->GetTriggers()->GetCameraRange();
+    background.SetAttribute("position", Ogre::StringConverter::toString(position));
+    background.SetAttribute("orientation", Ogre::StringConverter::toString(orientation));
+    background.SetAttribute("fov", Ogre::StringConverter::toString(fov));
+    background.SetAttribute(
+      "range",
+      std::to_string(range.left * SCALE_UP_FACTOR) + " " + std::to_string(range.top * SCALE_UP_FACTOR)
+      + " " + std::to_string(range.right * SCALE_UP_FACTOR) + " "
+      + std::to_string(range.bottom * SCALE_UP_FACTOR)
+    );
+    background.SetAttribute(
+      "clip",
+      std::to_string(SCREEN_WIDTH * SCALE_UP_FACTOR) + " " + std::to_string(SCREEN_HEIGHT * SCALE_UP_FACTOR)
+    );
+}
+
+std::unique_ptr<TiXmlElement> FieldBackgroundInstaller::CreateTile(
+  const VGears::BackgroundFile::SpriteData& sprite, const int layer, const int width,
+  const int height, const float scale
+){
+    std::unique_ptr<TiXmlElement> element(new TiXmlElement("tile"));
+    element->SetAttribute(
+      "destination",
+      Ogre::StringConverter::toString(sprite.dst.x * SCALE_UP_FACTOR) + " "
+      + Ogre::StringConverter::toString(sprite.dst.y * SCALE_UP_FACTOR)
+    );
+    element->SetAttribute("width", Ogre::StringConverter::toString(sprite.width * SCALE_UP_FACTOR));
+    element->SetAttribute("height", Ogre::StringConverter::toString(sprite.height * SCALE_UP_FACTOR));
+    // The tiles are in one image: the UV coordinates are in the 0 to 1 range.
+    const float u0 = static_cast<float>(sprite.src.x) / width;
+    const float v0 = static_cast<float>(sprite.src.y) / height;
+    const float u1 = static_cast<float>(sprite.src.x + sprite.width) / width;
+    const float v1 = static_cast<float>(sprite.src.y + sprite.height) / height;
+    element->SetAttribute(
+      "uv",
+      Ogre::StringConverter::toString(u0) + " " + Ogre::StringConverter::toString(v0) + " "
+      + Ogre::StringConverter::toString(u1) + " " + Ogre::StringConverter::toString(v1)
+    );
+    // TODO: It works (on FFVII PC), but why this number?
+    // The depth is a distance from the camera, so it has the scale of the field like the position
+    // of the camera does. The far depths (the backgrounds, from 127 on) are only an order and are
+    // kept.
+    float depth = static_cast<float>(sprite.depth) * (0.03125f);
+    if (depth < 127.0f) depth /= scale;
+    element->SetAttribute("depth", Ogre::StringConverter::toString(depth));
+    element->SetAttribute("blending", BlendingName(sprite.blending));
+    // Type 3 adds only a quarter of the colour of the tile: with all of it the glows turn white
+    // (ujunon4).
+    if (sprite.blending == 3) element->SetAttribute("intensity", "0.25");
+    // The layer is needed by the scripts that scroll them at their own speed.
+    element->SetAttribute("layer", layer);
+    // The sprites that belong to a group (animation_id) are drawn only while a script (BGON) or a
+    // background trigger turns on one of their states. The original game clears the state of
+    // every group when it loads a field, so a group that nothing turns on is never drawn (the
+    // debris behind the doors of mds6_2, for example).
+    if (sprite.animation_id != 0){
+        element->SetAttribute("area", static_cast<int>(sprite.animation_id));
+        element->SetAttribute("state", static_cast<int>(sprite.animation_frame));
+    }
+    return element;
+}
+
+bool FieldBackgroundInstaller::WritePaletteFile(
+  const std::string& path, const VGears::PaletteFilePtr& palette,
+  const std::vector<VGears::BackgroundFile::PaletteTile>& tiles, const std::set<int>& pages,
+  bool all_pages
+){
+    std::vector<const VGears::BackgroundFile::PaletteTile*> used;
+    for (const auto& tile : tiles){
+        if (all_pages || pages.count(tile.palette_page) > 0) used.push_back(&tile);
+    }
+    if (used.empty() || palette.isNull() || palette->GetPages().empty()) return false;
+    std::ofstream file(path, std::ios::binary);
+    if (!file.is_open()) return false;
+    auto write16 = [&file](uint16_t v){
+        const char bytes[2] = {static_cast<char>(v & 0xFF), static_cast<char>(v >> 8)};
+        file.write(bytes, 2);
+    };
+    const auto& palette_pages = palette->GetPages();
+    file.write("VGPL", 4);
+    write16(static_cast<uint16_t>(palette_pages.size()));
+    write16(static_cast<uint16_t>(palette_pages[0].size()));
+    for (const auto& page : palette_pages){
+        for (const auto& color : page){
+            const int r = static_cast<int>(std::lround(color.r * 31.0f));
+            const int g = static_cast<int>(std::lround(color.g * 31.0f));
+            const int b = static_cast<int>(std::lround(color.b * 31.0f));
+            write16(static_cast<uint16_t>(r | (g << 5) | (b << 10) | (color.a > 0.0f ? 0x8000 : 0)));
+        }
+    }
+    const uint32_t count = static_cast<uint32_t>(used.size());
+    write16(static_cast<uint16_t>(count & 0xFFFF));
+    write16(static_cast<uint16_t>(count >> 16));
+    for (const auto* tile : used){
+        write16(tile->x);
+        write16(tile->y);
+        write16(tile->width);
+        write16(tile->height);
+        write16(tile->palette_page);
+        file.put(tile->first_color_hidden ? 1 : 0);
+        file.write(
+          reinterpret_cast<const char*>(tile->indexes.data()),
+          static_cast<std::streamsize>(tile->indexes.size())
+        );
+    }
+    return true;
+}

+ 130 - 0
src/installer/extractors/FieldBackgroundInstaller.h

@@ -0,0 +1,130 @@
+/*
+ * 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 <set>
+#include <string>
+#include <tinyxml.h>
+#include "decompiler/field/FieldDecompiler.h"
+#include "formats/field/FLevelFile.h"
+#include "FieldDataTypes.h"
+
+/**
+ * Writes the background of a field: the image with its tiles (tiles.png), their description
+ * (bg.xml) and, if a script animates the palettes, the data to repaint them (palette.bin).
+ */
+class FieldBackgroundInstaller{
+
+    public:
+
+        /**
+         * Constructor.
+         *
+         * @param[in] data_dir The game data folder.
+         */
+        explicit FieldBackgroundInstaller(const std::string& data_dir);
+
+        /**
+         * Writes the background of a field.
+         *
+         * @param[in] field The field.
+         * @param[in] decompiled The decompiled script of the field. It tells which palettes the
+         * scripts animate.
+         * @param[in] scale The scale factor of the field.
+         */
+        void Install(
+          const VGears::FLevelFilePtr& field, const FieldDecompiler::DecompiledScript& decompiled,
+          const float scale
+        );
+
+        /**
+         * Names the blending mode of a tile.
+         *
+         * Type 3 is source + 0.25 * destination, written as "add" with an intensity.
+         *
+         * @param[in] blending The blending type of the original game.
+         * @return The name of the blending mode, or "unknown".
+         */
+        static std::string BlendingName(const int blending);
+
+    private:
+
+        /**
+         * Scale of the background, from the screen of the original game.
+         */
+        static const int SCALE_UP_FACTOR;
+
+        /**
+         * Width of the screen of the original game.
+         */
+        static const int SCREEN_WIDTH;
+
+        /**
+         * Height of the screen of the original game.
+         */
+        static const int SCREEN_HEIGHT;
+
+        /**
+         * Writes the camera, the range and the clip area of a background.
+         *
+         * @param[in] field The field.
+         * @param[in] scale The scale factor of the field.
+         * @param[out] background The background element.
+         */
+        static void WriteCamera(const VGears::FLevelFilePtr& field, const float scale, TiXmlElement& background);
+
+        /**
+         * Creates the element of a tile.
+         *
+         * @param[in] sprite The tile.
+         * @param[in] layer Index of the layer of the tile.
+         * @param[in] width Width of the image with the tiles.
+         * @param[in] height Height of the image with the tiles.
+         * @param[in] scale The scale factor of the field.
+         * @return The element of the tile.
+         */
+        static std::unique_ptr<TiXmlElement> CreateTile(
+          const VGears::BackgroundFile::SpriteData& sprite, const int layer, const int width,
+          const int height, const float scale
+        );
+
+        /**
+         * Writes the data the engine needs to animate the palettes of a background.
+         *
+         * Format (little endian): "VGPL", u16 number of pages, u16 colors per page, the colors of
+         * the pages as the u16 values of the original game (5 bits per channel and the 0x8000
+         * flag), u32 number of tiles, and for each tile: u16 x, y, width, height in the image,
+         * u16 page, u8 first color hidden, and one byte per pixel with the palette index.
+         *
+         * @param[in] path Path of the file.
+         * @param[in] palette The palettes of the field.
+         * @param[in] tiles The tiles of the background that use a palette.
+         * @param[in] pages The palette pages that the scripts animate.
+         * @param[in] all_pages True if the scripts may animate any page.
+         * @return True if the file was written. It is not when no tile uses an animated palette.
+         */
+        static bool WritePaletteFile(
+          const std::string& path, const VGears::PaletteFilePtr& palette,
+          const std::vector<VGears::BackgroundFile::PaletteTile>& tiles,
+          const std::set<int>& pages, bool all_pages
+        );
+
+        /**
+         * The game data folder.
+         */
+        std::string data_dir_;
+};

+ 100 - 1005
src/installer/extractors/FieldDataInstaller.cpp

@@ -13,307 +13,44 @@
  * GNU General Public License for more details.
  * GNU General Public License for more details.
  */
  */
 
 
-#include <cmath>
-#include <set>
-#include <string>
-#include <fstream>
+
 #include <algorithm>
 #include <algorithm>
+#include <fstream>
+#include <iostream>
 #include <boost/filesystem.hpp>
 #include <boost/filesystem.hpp>
 #include <QtCore/QDir>
 #include <QtCore/QDir>
-#include "installer/formats/DiskImage.h"
-#include "FieldDataInstaller.h"
-#include "installer/tables/ModelMaterials.h"
-#include "installer/formats/TexFile.h"
-#include "common/File.h"
-#include "formats/field/MapListFile.h"
+#include "common/StringUtil.h"
 #include "formats/field/LZSFLevelFileManager.h"
 #include "formats/field/LZSFLevelFileManager.h"
-#include "formats/model/HRCFileManager.h"
-#include "formats/lgp/LGPArchive.h"
-#include "formats/model/AFileManager.h"
-
-float FieldDataInstaller::LINE_SCALE_FACTOR(0.0078124970964f);
-
-std::string FieldDataInstaller::FIELD_MODELS_DIR("field/models");
-
-std::string FieldDataInstaller::FIELD_MAPS_DIR("field/maps");
-
-int FieldDataInstaller::INACTIVE_GATEWAY_ID(32767);
-
-const std::vector<int> FieldDataInstaller::TEMPORARY_BANKS{5};
-
-std::string FieldDataInstaller::FieldScriptHeader(const int field_id){
-    std::string header = "EntityContainer = {}\n\n";
-    if (field_id >= 0){
-        // LSTMP reads the ID of the field the player comes from. The field being left is the
-        // previous one, unless the field was just reloaded (after a battle, for example).
-        header += "-- The IDs of this field and of the previous one, for LSTMP.\n"
-          "if Data.FieldId ~= " + std::to_string(field_id) + " then\n"
-          "    Data.PreviousFieldId = Data.FieldId or 0\n"
-          "    Data.FieldId = " + std::to_string(field_id) + "\n"
-          "end\n\n";
-    }
-    for (const int bank : TEMPORARY_BANKS){
-        header += "-- Temporary variables start at zero in every field.\n"
-          "for address = 0, Banks.SIZE do\n"
-          "    Banks[" + std::to_string(bank) + "][address] = 0\n"
-          "end\n\n";
-    }
-    return header;
-}
-
-std::string FieldDataInstaller::CreateGateWayScript(
-  const std::string& gateway_entity_name, const std::string& target_map_name,
-  const std::string& source_spawn_point_name
-){
-    return
-      "\nEntityContainer[ \"" + gateway_entity_name + "\" ] = {\n\n"
-      "    on_start = function(self)\n"
-      "        return 0\n"
-      "    end,\n\n"
-      "    on_approach = function(self, entity)\n"
-      "        return 0\n"
-      "    end,\n\n"
-      "    on_cross = function(self, entity)\n"
-      "        return 0\n"
-      "    end,\n\n"
-      "    on_near = function(self, entity)\n"
-      "        if entity ~= nil then\n"
-      "            if not Data.DisableGateways then\n"
-      "                load_field_map_request(\"" + target_map_name + "\", \"" + source_spawn_point_name + "\")\n"
-      "            end\n"
-      "        end\n"
-      "        return 0\n"
-      "    end,\n\n"
-      "    on_leave = function(self, entity)\n"
-      "        return 0\n"
-      "    end,\n"
-      "}\n\n";
-}
-
-namespace{
-    /**
-     * Checks if a background trigger is in use. Unused ones are all zeroes.
-     */
-    bool IsBackgroundTriggerUsed(const VGears::TriggersFile::Trigger& t){
-        for (const auto& v : t.trigger_line){
-            if (v.x != 0 || v.y != 0 || v.z != 0) return true;
-        }
-        return false;
-    }
-
-    /**
-     * Creates the script of the entity of a background trigger.
-     *
-     * Behaviors: 0 on, 1 off, 2 on and off when away, 3 off and on when away, 4 and 5 the same as
-     * 2 and 3 (the original only reverts when the player leaves by the plus side of the line; here
-     * it is when the player leaves the line on any side).
-     */
-    std::string CreateBackgroundTriggerScript(
-      const std::string& name, const VGears::TriggersFile::Trigger& t
-    ){
-        const std::string area = std::to_string(t.background_parameter);
-        const std::string state = std::to_string(t.background_state);
-        const std::string on = "background2d:area_on(" + area + ", " + state + ")";
-        const std::string off = "background2d:area_off(" + area + ", " + state + ")";
-        std::string enter, leave;
-        switch (t.behavior){
-            case 0: enter = on; break;
-            case 1: enter = off; break;
-            case 2: case 4: enter = on; leave = off; break;
-            case 3: case 5: enter = off; leave = on; break;
-            default: break;
-        }
-        return
-          "\nEntityContainer[ \"" + name + "\" ] = {\n\n"
-          "    on_start = function(self)\n"
-          "        return 0\n"
-          "    end,\n\n"
-          "    on_approach = function(self, entity)\n"
-          "        if entity ~= nil then " + enter + " end\n"
-          "        return 0\n"
-          "    end,\n\n"
-          "    on_cross = function(self, entity)\n"
-          "        return 0\n"
-          "    end,\n\n"
-          "    on_near = function(self, entity)\n"
-          "        return 0\n"
-          "    end,\n\n"
-          "    on_leave = function(self, entity)\n"
-          "        if entity ~= nil then " + leave + " end\n"
-          "        return 0\n"
-          "    end,\n"
-          "}\n\n";
-    }
-}
-
-namespace{
-    /**
-     * Writes the data the engine needs to animate the palettes of a background.
-     *
-     * Format (little endian): "VGPL", u16 number of pages, u16 colors per page, the colors of the
-     * pages as the u16 values of the original game (5 bits per channel and the 0x8000 flag), u32
-     * number of tiles, and for each tile: u16 x, y, width, height in the image, u16 page, u8 first
-     * color hidden, and one byte per pixel with the palette index.
-     *
-     * @return True if the file was written. It is not when no tile uses an animated palette.
-     */
-    bool WritePaletteFile(
-      const std::string& path, const VGears::PaletteFilePtr& palette,
-      const std::vector<VGears::BackgroundFile::PaletteTile>& tiles,
-      const std::set<int>& pages, bool all_pages
-    ){
-        std::vector<const VGears::BackgroundFile::PaletteTile*> used;
-        for (const auto& tile : tiles){
-            if (all_pages || pages.count(tile.palette_page) > 0) used.push_back(&tile);
-        }
-        if (used.empty() || palette.isNull() || palette->GetPages().empty()) return false;
-        std::ofstream file(path, std::ios::binary);
-        if (!file.is_open()) return false;
-        auto write16 = [&file](uint16_t v){
-            const char bytes[2] = {static_cast<char>(v & 0xFF), static_cast<char>(v >> 8)};
-            file.write(bytes, 2);
-        };
-        const auto& palette_pages = palette->GetPages();
-        file.write("VGPL", 4);
-        write16(static_cast<uint16_t>(palette_pages.size()));
-        write16(static_cast<uint16_t>(palette_pages[0].size()));
-        for (const auto& page : palette_pages){
-            for (const auto& color : page){
-                const int r = static_cast<int>(std::lround(color.r * 31.0f));
-                const int g = static_cast<int>(std::lround(color.g * 31.0f));
-                const int b = static_cast<int>(std::lround(color.b * 31.0f));
-                write16(static_cast<uint16_t>(r | (g << 5) | (b << 10) | (color.a > 0.0f ? 0x8000 : 0)));
-            }
-        }
-        const uint32_t count = static_cast<uint32_t>(used.size());
-        write16(static_cast<uint16_t>(count & 0xFFFF));
-        write16(static_cast<uint16_t>(count >> 16));
-        for (const auto* tile : used){
-            write16(tile->x);
-            write16(tile->y);
-            write16(tile->width);
-            write16(tile->height);
-            write16(tile->palette_page);
-            file.put(tile->first_color_hidden ? 1 : 0);
-            file.write(
-              reinterpret_cast<const char*>(tile->indexes.data()),
-              static_cast<std::streamsize>(tile->indexes.size())
-            );
-        }
-        return true;
-    }
-}
-
-size_t FieldDataInstaller::GetFieldId(
-  const std::string& name, const std::vector<std::string>& field_id_to_name_lookup
-){
-    for (size_t i = 0; i < field_id_to_name_lookup.size(); i ++){
-        if (field_id_to_name_lookup[i] == name) return i;
-    }
-    throw std::runtime_error("No Id found for field name");
-}
-
-bool FieldDataInstaller::IsAFieldFile(const Ogre::String& resource_name){
-    return (
-      !VGears::StringUtil::endsWith(resource_name, ".tex")
-      && !VGears::StringUtil::endsWith(resource_name, ".tut")
-      && !VGears::StringUtil::endsWith(resource_name, ".siz")
-      && resource_name != "maplist"
-    );
-}
-
-bool FieldDataInstaller::WillCrash(const Ogre::String& resource_name){
-    // No field is known to crash at the moment.
-    (void)resource_name;
-    return false;
-}
-
-void FieldDataInstaller::CreateDir(const std::string& path){
-    QString target = QString::fromStdString(data_dir_ + path);
-    QDir dir(target);
-    if (!dir.mkpath(".")) throw std::runtime_error("Failed to mkpath");
-}
-
-void FieldDataInstaller::CollectFieldScaleFactors(
-  VGears::FLevelFilePtr& field, FieldScaleFactorMap& scale_factors,
-  const std::vector<std::string>& field_id_to_name_lookup
-){
-    scale_factors[GetFieldId(field->getName(), field_id_to_name_lookup)]
-      = FieldDecompiler::ScaleFactor(field->GetRawScript());
-}
-
-bool FieldDataInstaller::CollectSpawnPoints(
-  VGears::FLevelFilePtr& field, const std::vector<std::string>& field_id_to_name_lookup,
-  FieldSpawnPointsMap& spawn_points
-){
-    const size_t this_field_id = GetFieldId(field->getName(), field_id_to_name_lookup);
-    // Decompile the script just so the MAPJUMPs can be collected. This is needed to construct the
-    // full list of entries to each field.
-    try{
-        // Get the raw script bytes.
-        FieldDecompiler::DecompiledScript decompiled;
-        const std::vector<u8> raw_field_data = field->GetRawScript();
-        // Decompile to LUA.
-        FF7FieldScriptGatewayCollector formatter(
-          field->getName(), field_id_to_name_lookup, spawn_points, this_field_id
-        );
-        decompiled = FieldDecompiler::Decompile(
-          field->getName(), raw_field_data, formatter, "", "EntityContainer = {}\n\n"
-        );
-    }
-    catch (const ::DecompilerException& ex){
-        std::cerr << "[WARNING] CollectSpawnPoints: decompiler failed for " << field->getName()
-          << ": " << ex.what() << std::endl;
-                return false;
-    }
-    const VGears::TriggersFilePtr& triggers = field->GetTriggers();
-    if (triggers.isNull()){
-        std::cerr << "CollectSpawnPoints: missing trigger data for " << field->getName() << std::endl;
-        return false;
-    }
-    const auto& gateways = triggers->GetGateways();
-    for (size_t i = 0; i < gateways.size(); i ++){
-        const VGears::TriggersFile::Gateway& gateway = gateways[i];
-        if (gateway.destination_field_id != INACTIVE_GATEWAY_ID){
-            auto it = spawn_points.find(gateway.destination_field_id);
-            if (it != std::end(spawn_points)){
-                // Add to the list of gateways that link to
-                // destination_field_id.
-                SpawnPointDb::Record rec;
-                rec.field_id = this_field_id;
-                rec.gateway = gateway;
-                rec.gateway_index_or_map_jump_address = i;
-                it->second.gateways_to_this_field.push_back(rec);
-            }
-            else{
-                // Create a new record for destination_field_id.
-                SpawnPointDb db;
-                db.target_field_id = gateway.destination_field_id;
-                SpawnPointDb::Record rec;
-                rec.field_id = this_field_id;
-                rec.gateway = gateway;
-                rec.gateway_index_or_map_jump_address = i;
-                db.gateways_to_this_field.push_back(rec);
-                spawn_points.insert(std::make_pair(db.target_field_id, db));
-            }
-        }
-    }
-    return true;
-}
+#include "formats/field/MapListFile.h"
+#include "FieldDataInstaller.h"
+#include "FieldScriptFormatters.h"
 
 
 FieldDataInstaller::FieldDataInstaller(
 FieldDataInstaller::FieldDataInstaller(
     const DiskImage& disk_image, const std::string output_dir,
     const DiskImage& disk_image, const std::string output_dir,
     std::function<void(std::string)> log_output_line
     std::function<void(std::string)> log_output_line
 ):
 ):
-    disk_image_(disk_image), output_dir_(output_dir), data_dir_(output_dir + "game/"),
-    write_output_line_(log_output_line)
+    output_dir_(output_dir), data_dir_(output_dir + "game/"), write_output_line_(log_output_line),
+    script_installer_(data_dir_, map_list_, spawn_points_, log_output_line),
+    map_writer_(
+      data_dir_, map_list_, spawn_points_, scale_factors_, used_models_and_anims_, log_output_line
+    ),
+    background_installer_(data_dir_),
+    model_installer_(disk_image, output_dir_, data_dir_, used_models_and_anims_, log_output_line)
 {}
 {}
 
 
 FieldDataInstaller::~FieldDataInstaller(){}
 FieldDataInstaller::~FieldDataInstaller(){}
 
 
+void FieldDataInstaller::LoadInstalledFields(){
+    converted_map_list_.clear();
+    for (const std::string& name : map_list_){
+        if (boost::filesystem::exists(data_dir_ + FieldData::MAPS_DIR + "/" + name + "/map.xml")){
+            converted_map_list_.push_back(name);
+        }
+    }
+}
+
 int FieldDataInstaller::CollectSpawnAndScaleFactorsInit(Ogre::ResourceGroupManager* res_mgr){
 int FieldDataInstaller::CollectSpawnAndScaleFactorsInit(Ogre::ResourceGroupManager* res_mgr){
     // List what's in the LGP archive.
     // List what's in the LGP archive.
-    //flevel_file_list_ = application_.ResMgr()->listResourceNames("FFVIIFields", "*");
     flevel_file_list_ = res_mgr->listResourceNames("FFVIIFields", "*");
     flevel_file_list_ = res_mgr->listResourceNames("FFVIIFields", "*");
     // Load the map list field.
     // Load the map list field.
     VGears::MapListFilePtr map_list = VGears::MapListFileManager::GetSingleton().load(
     VGears::MapListFilePtr map_list = VGears::MapListFileManager::GetSingleton().load(
@@ -324,44 +61,32 @@ int FieldDataInstaller::CollectSpawnAndScaleFactorsInit(Ogre::ResourceGroupManag
 }
 }
 
 
 void FieldDataInstaller::CollectSpawnAndScaleFactors(int field_index){
 void FieldDataInstaller::CollectSpawnAndScaleFactors(int field_index){
-    // On the first pass collate required field information.
-    progress_step_num_elements_ = flevel_file_list_->size();
-    if (field_index >= flevel_file_list_->size()){
-        // TODO: Show invalid index.
-        return;
-    }
-    auto resource_name = (*flevel_file_list_)[field_index];
+    // TODO: Show invalid index.
+    if (field_index >= flevel_file_list_->size()) return;
+    const auto resource_name = (*flevel_file_list_)[field_index];
     // Exclude things that are not fields.
     // Exclude things that are not fields.
-    if (IsAFieldFile(resource_name) && !WillCrash(resource_name)){
-                try{
-                        VGears::FLevelFilePtr field = VGears::LZSFLevelFileManager::GetSingleton()
-                            .load(resource_name, "FFVIIFields").staticCast<VGears::FLevelFile>();
-                        if (!CollectSpawnPoints(field, map_list_, spawn_points_)){
-                                failed_fields_.push_back(resource_name);
-                                return;
-                        }
-                        CollectFieldScaleFactors(field, scale_factors_, map_list_);
-                }
-                catch (const std::exception& exception){
-                        failed_fields_.push_back(resource_name);
-                        std::cerr << "[WARNING] CollectSpawnAndScaleFactors: skipped " << resource_name
-                            << " after error: " << exception.what() << std::endl;
-                }
-    }
-}
-
-void FieldDataInstaller::LoadInstalledFields(){
-    converted_map_list_.clear();
-    for (const std::string& name : map_list_){
-        if (boost::filesystem::exists(data_dir_ + FIELD_MAPS_DIR + "/" + name + "/map.xml")){
-            converted_map_list_.push_back(name);
+    if (!IsAFieldFile(resource_name)) return;
+    try{
+        VGears::FLevelFilePtr field = VGears::LZSFLevelFileManager::GetSingleton()
+          .load(resource_name, "FFVIIFields").staticCast<VGears::FLevelFile>();
+        if (!CollectSpawnPoints(field)){
+            failed_fields_.push_back(resource_name);
+            return;
         }
         }
+        scale_factors_[FieldData::FieldId(field->getName(), map_list_)]
+          = FieldDecompiler::ScaleFactor(field->GetRawScript());
+    }
+    catch (const std::exception& exception){
+        failed_fields_.push_back(resource_name);
+        std::cerr << "[WARNING] CollectSpawnAndScaleFactors: skipped " << resource_name
+          << " after error: " << exception.what() << std::endl;
     }
     }
 }
 }
 
 
 void FieldDataInstaller::WriteWorldArrivals(){
 void FieldDataInstaller::WriteWorldArrivals(){
-    // The exits to the world map ("wm<N>") have no field to write the spawn points into, so the coordinates
-    // that each exit gives (world units) are written for the world map scripts, by spawn point name.
+    // The exits to the world map ("wm<N>") have no field to write the spawn points into, so the
+    // coordinates that each exit gives (world units) are written for the world map scripts, by
+    // spawn point name.
     std::string output = "-- Generated by the installer: where each field exit puts the player in the world map.\n"
     std::string output = "-- Generated by the installer: where each field exit puts the player in the world map.\n"
       "WorldArrivals = {\n";
       "WorldArrivals = {\n";
     for (const auto& entry : spawn_points_){
     for (const auto& entry : spawn_points_){
@@ -392,31 +117,21 @@ void FieldDataInstaller::WriteWorldArrivals(){
 
 
 void FieldDataInstaller::Convert(int field_index){
 void FieldDataInstaller::Convert(int field_index){
     if (field_index == 0) WriteWorldArrivals();
     if (field_index == 0) WriteWorldArrivals();
-    // Do the full conversion with the collated data.
-    if (field_index >= flevel_file_list_->size()){
-        // TODO: Show invalid index.
-        return;
-    }
-    auto resource_name = (*flevel_file_list_)[field_index];
+    // TODO: Show invalid index.
+    if (field_index >= flevel_file_list_->size()) return;
+    const auto resource_name = (*flevel_file_list_)[field_index];
     // Exclude things that are not fields.
     // Exclude things that are not fields.
-    if (IsAFieldFile(resource_name)){
-                if (std::find(failed_fields_.begin(), failed_fields_.end(), resource_name)
-                    != failed_fields_.end()){
-                        std::cerr << "[ERROR] Skip field: " << resource_name
-                            << " because its scripts or scale factor could not be collected." << std::endl;
-                }
-                else if (!WillCrash(resource_name)){
-            //write_output_line_("Converting field " + resource_name);
-            CreateDir(FIELD_MAPS_DIR + "/" + resource_name);
-            VGears::FLevelFilePtr field = VGears::LZSFLevelFileManager::GetSingleton()
-              .load(resource_name, "FFVIIFields").staticCast<VGears::FLevelFile>();
-            PcFieldToVGearsField(field);
-        }
-        else{
-                        std::cerr << "[ERROR] Skip field: " << resource_name
-                            << " due to a known crash or hang issue." << std::endl;
-        }
+    if (!IsAFieldFile(resource_name)) return;
+    if (std::find(failed_fields_.begin(), failed_fields_.end(), resource_name) != failed_fields_.end()){
+        std::cerr << "[ERROR] Skip field: " << resource_name
+          << " because its scripts or scale factor could not be collected." << std::endl;
+        return;
     }
     }
+    const QString dir = QString::fromStdString(data_dir_ + FieldData::MAPS_DIR + "/" + resource_name);
+    if (!QDir(dir).mkpath(".")) throw std::runtime_error("Failed to mkpath");
+    VGears::FLevelFilePtr field = VGears::LZSFLevelFileManager::GetSingleton()
+      .load(resource_name, "FFVIIFields").staticCast<VGears::FLevelFile>();
+    PcFieldToVGearsField(field);
 }
 }
 
 
 int FieldDataInstaller::WriteInit(){
 int FieldDataInstaller::WriteInit(){
@@ -427,12 +142,9 @@ int FieldDataInstaller::WriteInit(){
 
 
 void FieldDataInstaller::Write(int field_index){
 void FieldDataInstaller::Write(int field_index){
     // TODO: Probably need to inject "empty" and "test" fields.
     // TODO: Probably need to inject "empty" and "test" fields.
-    if (field_index >= flevel_file_list_->size()){
-        // TODO: Show invalid index.
-        return;
-    }
-    auto map = converted_map_list_[field_index];
-    //write_output_line_("Writing field " + FieldName(map));
+    // TODO: Show invalid index.
+    if (field_index >= converted_map_list_.size()) return;
+    const auto map = converted_map_list_[field_index];
     std::unique_ptr<TiXmlElement> xml_element(new TiXmlElement("map"));
     std::unique_ptr<TiXmlElement> xml_element(new TiXmlElement("map"));
     xml_element->SetAttribute("name", map);
     xml_element->SetAttribute("name", map);
     xml_element->SetAttribute("file_name", map + "/map.xml");
     xml_element->SetAttribute("file_name", map + "/map.xml");
@@ -444,675 +156,58 @@ void FieldDataInstaller::WriteEnd(){
     doc_->SaveFile(data_dir_ + "/field/maps/_fields.xml");
     doc_->SaveFile(data_dir_ + "/field/maps/_fields.xml");
 }
 }
 
 
-std::vector<std::string> FieldDataInstaller::ConvertModelsInit(){
-    std::vector<std::string> models;
+std::vector<std::string> FieldDataInstaller::ConvertModelsInit(){return model_installer_.Initialize();}
 
 
-    // Open char_lgp as a lgp archive
-    VGears::LGPArchive char_lgp(*disk_image_.filePath("data/field/char.lgp"), "LGP");
-    char_lgp.open(*disk_image_.filePath("data/field/char.lgp"), true);
-    char_lgp.load();
-    // Also, open it as a file for reading
-    File char_file(*disk_image_.filePath("data/field/char.lgp"));
+void FieldDataInstaller::ConvertModels(std::string model_name){model_installer_.ConvertModel(model_name);}
 
 
-    //Ogre::StringVectorPtr file_list = char_lgp.list(true, true);
-    field_model_file_list_ = char_lgp.list(true, true);
-    VGears::LGPArchive::FileList files = char_lgp.GetFiles();
-    for (int i = 0; i < field_model_file_list_->size(); i ++){
-        VGears::LGPArchive::FileEntry f = files.at(i);
-        // Save the TEX File
-        std::fstream out;
-        out.open(output_dir_ + "temp/char/" + f.file_name, std::ios::out);
-        char_file.SetOffset(f.data_offset);
-        for (int j = 0; j < f.data_size; j ++) out << char_file.readU8();
-        out.close();
-        //field_model_file_list_->push_back(f.file_name);
-    }
-    // Ogre indexes a resource location when it is added, so files written afterwards are not found until the
-    // location is registered again. On a clean install the folder was empty when it was first added.
-    Ogre::ResourceGroupManager& res_mgr = Ogre::ResourceGroupManager::getSingleton();
-    res_mgr.removeResourceLocation(output_dir_ + "temp/char/", "FFVII");
-    res_mgr.addResourceLocation(output_dir_ + "temp/char/", "FileSystem", "FFVII", true, true);
-    for (auto it = used_models_and_anims_.map.begin(); it != used_models_and_anims_.map.end(); it ++){
-        models.push_back(it->first);
-    }
-    return models;
+bool FieldDataInstaller::IsAFieldFile(const Ogre::String& resource_name){
+    return (
+      !VGears::StringUtil::endsWith(resource_name, ".tex")
+      && !VGears::StringUtil::endsWith(resource_name, ".tut")
+      && !VGears::StringUtil::endsWith(resource_name, ".siz")
+      && resource_name != "maplist"
+    );
 }
 }
 
 
-void FieldDataInstaller::ConvertModels(std::string model_name){
-    auto model = used_models_and_anims_.map.find(model_name);
+bool FieldDataInstaller::CollectSpawnPoints(const VGears::FLevelFilePtr& field){
+    const size_t field_id = FieldData::FieldId(field->getName(), map_list_);
+    // Decompile the script just so the MAPJUMPs can be collected. This is needed to construct the
+    // full list of entries to each field.
     try{
     try{
-        Ogre::ResourcePtr hrc = VGears::HRCFileManager::GetSingleton().load(model->first, "FFVII");
-        //Ogre::ResourcePtr hrc = VGears::HRCFile();
-        Ogre::String base_name;
-        VGears::StringUtil::splitBase(model->first, base_name);
-        auto mesh_name = VGears::NameLookup::model(base_name) + ".mesh";
-        Ogre::MeshPtr mesh(Ogre::MeshManager::getSingleton().load(mesh_name, "FFVII"));
-        Ogre::SkeletonPtr skeleton(mesh->getSkeleton());
-        const Ogre::AxisAlignedBox bind_bounds = mesh->getBounds();
-        Ogre::AxisAlignedBox translation_bounds(Ogre::Vector3::ZERO, Ogre::Vector3::ZERO);
-        for (auto& anim : model->second){
-            VGears::AFileManager &afl_mgr(VGears::AFileManager::GetSingleton());
-            VGears::AFilePtr a = afl_mgr.load(anim, "FFVII").staticCast<VGears::AFile>();
-            // Convert the FF7 name to a more readable name set in the meta data.
-            VGears::StringUtil::splitBase(anim, base_name);
-            a->AddTo(skeleton, VGears::NameLookup::Animation(base_name), true);
-                        translation_bounds.merge(a->GetRootTranslationBounds(true));
-                }
-                if (bind_bounds.isFinite()){
-                        const Ogre::AxisAlignedBox animated_bounds(
-                            bind_bounds.getMinimum() + translation_bounds.getMinimum(),
-                            bind_bounds.getMaximum() + translation_bounds.getMaximum()
-                        );
-                        mesh->_setBounds(animated_bounds, false);
-                        mesh->_setBoundingSphereRadius(std::max(
-                            mesh->getBoundingSphereRadius(),
-                            animated_bounds.getCenter().length() + animated_bounds.getHalfSize().length()
-                        ));
-        }
-        ExportMesh(data_dir_ + FIELD_MODELS_DIR + "/", mesh);
-        // Models can share a skeleton name with different bones. Drop the model (and its skeleton and mesh) so the
-        // next one doesn't reuse them.
-        VGears::HRCFileManager::GetSingleton().remove(model->first, "FFVII");
-    }
-    catch (const Ogre::Exception& ex){
-        if (VGears::HRCFileManager::GetSingleton().resourceExists(model->first, "FFVII"))
-            VGears::HRCFileManager::GetSingleton().remove(model->first, "FFVII");
-        write_output_line_("[ERROR] Ogre exception converting model " + model->first + ": " + ex.what());
-    }
-    catch (const std::exception& ex){
-        if (VGears::HRCFileManager::GetSingleton().resourceExists(model->first, "FFVII"))
-            VGears::HRCFileManager::GetSingleton().remove(model->first, "FFVII");
-        write_output_line_("[ERROR] Exception converting model " + model->first + ": " + ex.what());
-    }
-}
-
-
-void FieldDataInstaller::ExportMesh(const std::string outdir, const Ogre::MeshPtr &mesh){
-
-    // 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());
-    Ogre::SkeletonSerializer skeleton_serializer;
-    skeleton_serializer.exportSkeleton(skeleton.getPointer(), outdir + base_mesh_name + ".skeleton");
-    mesh->setSkeletonName(base_mesh_name + ".skeleton");
-    mesh_serializer.exportMesh(mesh.getPointer(), outdir + mesh->getName());
-    Ogre::Mesh::SubMeshIterator it(mesh->getSubMeshIterator());
-    Ogre::MaterialSerializer mat_ser;
-    size_t i(0);
-    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 battle model (its texture is then a png in
-                                    // another folder). There is nothing to convert in that case.
-                                    if (!boost::filesystem::exists(output_dir_ + "temp/char/" + unit->getTextureName())){
-                                        write_output_line_(
-                                          "[WARNING] Texture " + unit->getTextureName() + " of model " + base_mesh_name
-                                          + " not found; skipping it."
-                                        );
-                                        continue;
-                                    }
-                                    // Convert the texture from .tex to .png.
-                                    TexFile tex(output_dir_ + "temp/char/" + 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");
-
-                                    tex.SavePng(data_dir_ + FIELD_MODELS_DIR + "/" + base_name + ".png", 0);
-                                    // Copy subtexture (xxxx.png) to model_xxxx.png
-                                    // TODO: obtain the "data" folder
-                                    // programatically.
-                                    boost::filesystem::copy_file(
-                                        data_dir_ + FIELD_MODELS_DIR + "/" + base_name + ".png",
-                                        data_dir_ + FIELD_MODELS_DIR + "/"
-                                        + base_mesh_name + "_" + base_name + ".png",
-                                      boost::filesystem::copy_options::overwrite_existing
-                                    );
-                                }
-                            }
-                        }
-                    }
-                }
-            }
-            if (std::count(materials_.begin(), materials_.end(), sub_mesh->getMaterialName()) == 0){
-                mat_ser.queueForExport(mat);
-                materials_.push_back(sub_mesh->getMaterialName());
-            }
-
-        }
-        ++ i;
+        FF7FieldScriptGatewayCollector formatter(field->getName(), map_list_, spawn_points_, field_id);
+        FieldDecompiler::Decompile(
+          field->getName(), field->GetRawScript(), formatter, "", "EntityContainer = {}\n\n"
+        );
     }
     }
-    mat_ser.exportQueued(outdir + base_mesh_name + VGears::EXT_MATERIAL);
-}
-
-float FieldDataInstaller::GetFieldScaleFactor(size_t field_id){
-    auto it = scale_factors_.find(field_id);
-    if (it == std::end(scale_factors_)) throw std::runtime_error("Scale factor not found for field id");
-    return it->second;
-}
-
-std::vector<int> FieldDataInstaller::ExtractMusicTrackIds(VGears::FLevelFilePtr& field){
-    // Search for the "AKAO" string in the raw field data.
-    // The next byte is a track id.
-    const std::vector<u8> raw = field->GetRawScript();
-    std::vector<int> tracks;
-    for (int i = 0; i < raw.size() - 5; i ++){
-        if (raw[i] == 0x41){                   // A
-            if (raw[i + 1] == 0x4B){           // K
-                if (raw[i + 2] == 0x41){       // A
-                    if (raw[i + 3] == 0x4f){   // O
-                        tracks.push_back(static_cast<int>(raw[i + 4]) - 2);
-                    }
-                }
-            }
-        }
+    catch (const ::DecompilerException& ex){
+        std::cerr << "[WARNING] CollectSpawnPoints: decompiler failed for " << field->getName()
+          << ": " << ex.what() << std::endl;
+        return false;
     }
     }
-    return tracks;
-}
-
-void FieldDataInstaller::PcFieldToVGearsField(VGears::FLevelFilePtr& field){
-    // Generate triggers script to insert into main
-    // decompiled FF7 field -> LUA script.
-    std::string gateway_script_data;
     const VGears::TriggersFilePtr& triggers = field->GetTriggers();
     const VGears::TriggersFilePtr& triggers = field->GetTriggers();
+    if (triggers.isNull()){
+        std::cerr << "CollectSpawnPoints: missing trigger data for " << field->getName() << std::endl;
+        return false;
+    }
     const auto& gateways = triggers->GetGateways();
     const auto& gateways = triggers->GetGateways();
     for (size_t i = 0; i < gateways.size(); i ++){
     for (size_t i = 0; i < gateways.size(); i ++){
-        const VGears::TriggersFile::Gateway& gateway = gateways[i];
-        if (gateway.destination_field_id != INACTIVE_GATEWAY_ID){
-            const std::string gateway_entity_name = "Gateway" + std::to_string(i);
-            gateway_script_data += CreateGateWayScript(
-              gateway_entity_name, map_list_.at(gateway.destination_field_id),
-              "Spawn_" + field->getName() + "_" + std::to_string(i)
-            );
-        }
-    }
-    const auto& bg_triggers = triggers->GetBackgroundTriggers();
-    for (size_t i = 0; i < bg_triggers.size(); i ++){
-        if (IsBackgroundTriggerUsed(bg_triggers[i])){
-            gateway_script_data += CreateBackgroundTriggerScript(
-              "BgTrigger" + std::to_string(i), bg_triggers[i]
-            );
-        }
-    }
-    const VGears::ModelListFilePtr& models = field->GetModelList();
-    FieldDecompiler::DecompiledScript decompiled;
-    FF7FieldScriptFormatter formatter(field->getName(), models, map_list_, spawn_points_);
-    try{
-        // Get the raw script bytes.
-        const std::vector<u8> raw_field_data = field->GetRawScript();
-
-        // Decompile to LUA.
-        decompiled = FieldDecompiler::Decompile(
-          field->getName(), raw_field_data, formatter, gateway_script_data,
-          FieldScriptHeader(static_cast<int>(GetFieldId(field->getName(), map_list_)))
-        );
-        std::ofstream script_file(data_dir_ + "/" + FIELD_MAPS_DIR + "/" + field->getName() + "/script.lua");
-        if (script_file.is_open()){
-            script_file << decompiled.luaScript;
-            field_text_writer_.Begin(data_dir_ + "/" + FIELD_MAPS_DIR + "/" + field->getName() + "/text.xml");
-            try{field_text_writer_.Write(raw_field_data, field->getName());}
-            catch (const std::out_of_range& ex){
-                write_output_line_("[ERROR] Failed to read texts from field " + field->getName() + ": " + ex.what());
-            }
-            field_text_writer_.End();
-        }
-        else{
-            write_output_line_("[ERROR] Failed to open script file from field " + field->getName() + " for writing.");
-        }
+        if (gateways[i].destination_field_id == FieldData::INACTIVE_GATEWAY_ID) continue;
+        SpawnPointDb::Record record;
+        record.field_id = static_cast<u16>(field_id);
+        record.gateway = gateways[i];
+        record.gateway_index_or_map_jump_address = static_cast<u32>(i);
+        FieldData::AddSpawnPoint(spawn_points_, record);
     }
     }
-    catch (const ::DecompilerException& ex){
-        write_output_line_("[ERROR] Internal decompiler error in field " + field->getName() + ": " + ex.what());
-    }
-    // Write out the map file which links all the other files together for a given field.
-    {
-        TiXmlDocument doc;
-        std::unique_ptr<TiXmlElement> element(new TiXmlElement("map"));
-        // Script.
-        std::unique_ptr<TiXmlElement> xml_script_element(new TiXmlElement("script"));
-        xml_script_element->SetAttribute("file_name", field->getName() + "/script.lua");
-        element->LinkEndChild(xml_script_element.release());
-        // Background.
-        std::unique_ptr<TiXmlElement> xml_background_2d(new TiXmlElement("background2d"));
-        xml_background_2d->SetAttribute("file_name", field->getName() + "/bg.xml");
-        element->LinkEndChild(xml_background_2d.release());
-        // Texts.
-        std::unique_ptr<TiXmlElement> xml_texts(new TiXmlElement("texts"));
-        xml_texts->SetAttribute("file_name", field->getName() + "/text.xml");
-        element->LinkEndChild(xml_texts.release());
-        // Walkmesh.
-        std::unique_ptr<TiXmlElement> xml_walkmesh(new TiXmlElement("walkmesh"));
-        xml_walkmesh->SetAttribute("file_name", field->getName() + "/wm.xml");
-        element->LinkEndChild(xml_walkmesh.release());
-        // Forward direction (angle player moves when "up" is pressed)
-        std::unique_ptr<TiXmlElement> xml_forward_direction(new TiXmlElement("movement_rotation"));
-        xml_forward_direction->SetAttribute("degree", std::to_string(triggers->MovementRotation()));
-        element->LinkEndChild(xml_forward_direction.release());
-        // Random encounters. The section has two tables of 24 bytes: enabled (1 byte), rate
-        // (1 byte), six standard and four special encounters (16 bits each, battle ID in the lower
-        // 10 bits and probability, out of 64, in the upper 6), and 2 bytes of padding.
-        {
-            const std::vector<u8>& raw_encounter = field->GetRawEncounter();
-            std::unique_ptr<TiXmlElement> xml_encounters(new TiXmlElement("encounters"));
-            bool any_table = false;
-            for (int table = 0; table < 2 && raw_encounter.size() >= static_cast<size_t>(24 * (table + 1)); table ++){
-                const u8* data = raw_encounter.data() + 24 * table;
-                if (data[0] == 0) continue;
-                std::unique_ptr<TiXmlElement> xml_table(new TiXmlElement("table"));
-                xml_table->SetAttribute("id", table + 1);
-                xml_table->SetAttribute("rate", static_cast<int>(data[1]));
-                for (int e = 0; e < 10; e ++){
-                    const unsigned int value = data[2 + 2 * e] | (data[3 + 2 * e] << 8);
-                    const int battle = value & 0x3FF;
-                    const int probability = value >> 10;
-                    if (probability == 0) continue;
-                    std::unique_ptr<TiXmlElement> xml_encounter(new TiXmlElement(e < 6 ? "battle" : "special"));
-                    xml_encounter->SetAttribute("id", battle);
-                    xml_encounter->SetAttribute("probability", probability);
-                    xml_table->LinkEndChild(xml_encounter.release());
-                }
-                xml_encounters->LinkEndChild(xml_table.release());
-                any_table = true;
-            }
-            if (any_table) element->LinkEndChild(xml_encounters.release());
-        }
-        // Get this fields Id.
-        const size_t this_field_id = GetFieldId(field->getName(), map_list_);
-        // Use the ID to find the pre-computed list of gateways in all other fields that link to
-        // this field.
-        auto spawn_iterator = spawn_points_.find(this_field_id);
-        Ogre::Vector3 first_entity_point = Ogre::Vector3::ZERO;
-
-        // If none found it probably just means no other fields have doors to this one.
-        if (spawn_iterator != std::end(spawn_points_)){
-            const std::vector<SpawnPointDb::Record>& spawn_point_records
-              = spawn_iterator->second.gateways_to_this_field;
-            for (size_t i = 0; i < spawn_point_records.size(); i ++){
-                const VGears::TriggersFile::Gateway& gateway = spawn_point_records[i].gateway;
-                // Entity_point:
-                std::unique_ptr<TiXmlElement> xml_entity_point(new TiXmlElement("entity_point"));
-                if (spawn_point_records[i].from_script){
-                    // Spawn points from map jumps have a another algorithm.
-                    xml_entity_point->SetAttribute(
-                      "name",
-                      map_list_.at(
-                        spawn_point_records[i].field_id) + "_" + spawn_point_records[i].entity_name
-                        + "_" + spawn_point_records[i].script_function_name + "_addr_"
-                        + std::to_string(spawn_point_records[i].gateway_index_or_map_jump_address)
-                      );
-                }
-                else{
-                    // Must also include the gateway index for the case where 2
-                    // fields have more than one door linking to each other.
-                    xml_entity_point->SetAttribute(
-                      "name",
-                      "Spawn_" + map_list_.at(spawn_point_records[i].field_id) + "_"
-                        + std::to_string(spawn_point_records[i].gateway_index_or_map_jump_address)
-                    );
-                }
-                const float downscaler_next = 128.0f * GetFieldScaleFactor(gateway.destination_field_id);
-
-                // Position Z is actually the target walkmesh triangle ID, so this is tiny bit more
-                // complex. Now "get the Z value of the triangle with that ID". Note that ID
-                // actually just means index.
-                unsigned int triangle_index = static_cast<unsigned int>(gateway.destination.z);
-                const auto& triangles = field->GetWalkmesh()->GetTriangles();
-                if (triangle_index >= triangles.size()){
-                    // Some map jumps of the original scripts have a triangle that is not in the walkmesh (pillar_3
-                    // to mds6_22). The one under the position is used instead, in the units the walkmesh is
-                    // written in.
-                    const float scale = GetFieldScaleFactor(this_field_id);
-                    const float x = gateway.destination.x / downscaler_next;
-                    const float y = gateway.destination.y / downscaler_next;
-                    const auto side = [x, y](const Ogre::Vector3& a, const Ogre::Vector3& b){
-                        return (x - b.x) * (a.y - b.y) - (a.x - b.x) * (y - b.y);
-                    };
-                    size_t under = triangles.size();
-                    for (size_t t = 0; t < triangles.size() && under == triangles.size(); t ++){
-                        const Ogre::Vector3 a = triangles[t].a / scale, b = triangles[t].b / scale;
-                        const Ogre::Vector3 c = triangles[t].c / scale;
-                        const float d1 = side(a, b), d2 = side(b, c), d3 = side(c, a);
-                        const bool negative = d1 < 0 || d2 < 0 || d3 < 0, positive = d1 > 0 || d2 > 0 || d3 > 0;
-                        if (!(negative && positive)) under = t;
-                    }
-                    const SpawnPointDb::Record& record = spawn_point_records[i];
-                    const std::string source = record.from_script
-                      ? "the script " + record.entity_name + ":" + record.script_function_name + " (address "
-                        + std::to_string(record.gateway_index_or_map_jump_address) + ")"
-                      : "the door " + std::to_string(record.gateway_index_or_map_jump_address);
-                    // Only reported when the position is not on the walkmesh either: those jumps are of the debug
-                    // rooms (blackbg1, blackbg4) or of scenes that place the player themselves.
-                    if (under == triangles.size()){
-                        write_output_line_(
-                          "[WARNING] In field " + field->getName() + ": the entrance from "
-                          + map_list_.at(record.field_id) + " (" + source + ") is on the walkmesh triangle "
-                          + std::to_string(triangle_index) + ", which the walkmesh doesn't have (it has "
-                          + std::to_string(triangles.size()) + "), at (" + std::to_string(gateway.destination.x) + ", "
-                          + std::to_string(gateway.destination.y) + "), which is not on the walkmesh."
-                        );
-                        triangle_index = 0;
-                    }
-                    else triangle_index = static_cast<unsigned int>(under);
-                }
-                const float z_of_triangle_with_id
-                  = field->GetWalkmesh()->GetTriangles().at(triangle_index).a.z / GetFieldScaleFactor(this_field_id);
-                const Ogre::Vector3 position(
-                  gateway.destination.x / downscaler_next, gateway.destination.y / downscaler_next,
-                  z_of_triangle_with_id
-                );
-                if (position != Ogre::Vector3::ZERO && first_entity_point == Ogre::Vector3::ZERO){
-                    first_entity_point = position;
-                }
-                xml_entity_point->SetAttribute("position", Ogre::StringConverter::toString(position));
-                const float rotation = (360.0f * static_cast<float>(gateway.dir)) / 256.0f;
-                xml_entity_point->SetAttribute("rotation", std::to_string(rotation));
-                element->LinkEndChild(xml_entity_point.release());
-            }
-        }
-
-        // The entities (lines, scripts and models) must be in the order of the original field:
-        // the engine starts their scripts in that order, and some scripts depend on it (a script
-        // that clears the background areas has to start before the doors that set them).
-        std::vector<std::pair<uint, std::unique_ptr<TiXmlElement>>> ordered_entities;
-        // Get lines. Add them to a list, so they aren't processed later as regular entities.
-        std::vector<std::string> line_entities;
-        const float line_scale = LINE_SCALE_FACTOR / GetFieldScaleFactor(this_field_id);
-        for (FieldDecompiler::Line line : decompiled.lines){
-
-            std::unique_ptr<TiXmlElement> xml_entity_trigger(new TiXmlElement("entity_trigger"));
-            line_entities.push_back(line.name);
-            xml_entity_trigger->SetAttribute("name", line.name);
-            xml_entity_trigger->SetAttribute(
-              "point1",
-              std::to_string(line.point_a[0] * line_scale)
-                + " " + std::to_string(line.point_a[1] * line_scale)
-                + " " + std::to_string(line.point_a[2] * line_scale)
-            );
-            xml_entity_trigger->SetAttribute(
-              "point2",
-              std::to_string(line.point_b[0] * line_scale)
-                + " " + std::to_string(line.point_b[1] * line_scale)
-                + " " + std::to_string(line.point_b[2] * line_scale)
-            );
-            xml_entity_trigger->SetAttribute("enabled", "true");
-            ordered_entities.emplace_back(line.index, std::move(xml_entity_trigger));
-        }
-
-        // Get entities.
-        for (FieldDecompiler::FieldEntity entity : decompiled.entities){
-            // If the entity has been added as a line, skip.
-            if (line_entities.size() > 0){
-                                if (std::find(line_entities.begin(), line_entities.end(), entity.name)
-                                    != line_entities.end()) continue;
-            }
-            const int char_id = entity.char_id;
-            if (char_id != -1){
-                const VGears::ModelListFile::ModelDescription& desc = models->GetModels().at(char_id);
-                auto& animations = used_models_and_anims_.ModelAnimations(desc.hrc_name);
-                for (const auto& anim : desc.animations){
-                    animations.insert(used_models_and_anims_.NormalizeAnimationName(anim.name));
-                }
-                std::unique_ptr<TiXmlElement> xml_entity_script(new TiXmlElement("entity_model"));
-                xml_entity_script->SetAttribute("name", entity.name);
-                // TODO: Add to list of HRC's to convert, obtain name of converted .mesh file.
-                auto lower_case_hrc_name = desc.hrc_name;
-                VGears::StringUtil::toLowerCase(lower_case_hrc_name);
-                xml_entity_script->SetAttribute(
-                  "file_name", used_models_and_anims_.ModelMetaDataName(lower_case_hrc_name)
-                );
-                xml_entity_script->SetAttribute("index", entity.index);
-                if (desc.type == VGears::ModelListFile::PLAYER){
-                    // For player models the position is set manually in the xml because if a map
-                    // is loaded manually this is where the player will end up. Hence we set the
-                    // position to the first entity_point that we have.
-                    xml_entity_script->SetAttribute("position", Ogre::StringConverter::toString(first_entity_point));
-                }
-                else{
-                    xml_entity_script->SetAttribute("position", Ogre::StringConverter::toString(Ogre::Vector3::ZERO));
-                }
-                xml_entity_script->SetAttribute("direction", "0");
-                // TODO: This isn't quite right, the models animation
-                // translation seems to be inverted?
-                xml_entity_script->SetAttribute("scale", "0.03125 0.03125 0.03125");
-                xml_entity_script->SetAttribute("root_orientation", "0.7071067811865476 0.7071067811865476 0 0");
-                ordered_entities.emplace_back(entity.index, std::move(xml_entity_script));
-            }
-            else{
-                std::unique_ptr<TiXmlElement> xml_entity_script(new TiXmlElement("entity_script"));
-                xml_entity_script->SetAttribute("name", entity.name);//it.first);
-                ordered_entities.emplace_back(entity.index, std::move(xml_entity_script));
-            }
-        }
-        std::stable_sort(
-          ordered_entities.begin(), ordered_entities.end(),
-          [](const auto& a, const auto& b){return a.first < b.first;}
-        );
-        for (auto& ordered : ordered_entities) element->LinkEndChild(ordered.second.release());
-        const float downscaler_this = 128.0f * GetFieldScaleFactor(this_field_id);
-        for (size_t i = 0; i < gateways.size(); i ++){
-            const VGears::TriggersFile::Gateway& gateway = gateways[i];
-            // If non-inactive gateway:
-            if (gateway.destination_field_id != INACTIVE_GATEWAY_ID){
-                std::unique_ptr<TiXmlElement> xml_entity_trigger(new TiXmlElement("entity_trigger"));
-                xml_entity_trigger->SetAttribute("name", "Gateway" + std::to_string(i));
-                xml_entity_trigger->SetAttribute(
-                  "point1",
-                  Ogre::StringConverter::toString(
-                    Ogre::Vector3(
-                      gateway.exit_line[0].x, gateway.exit_line[0].y, gateway.exit_line[0].z) / downscaler_this
-                  )
-                );
-                xml_entity_trigger->SetAttribute(
-                  "point2",
-                  Ogre::StringConverter::toString(
-                    Ogre::Vector3(
-                      gateway.exit_line[1].x, gateway.exit_line[1].y, gateway.exit_line[1].z) / downscaler_this
-                    )
-                  );
-                // Enabled is hard coded to true.
-                xml_entity_trigger->SetAttribute("enabled", "true");
-                element->LinkEndChild(xml_entity_trigger.release());
-            }
-        }
-
-        // Background triggers (doors and similar that change tiles).
-        const auto& bg_triggers_xml = triggers->GetBackgroundTriggers();
-        for (size_t i = 0; i < bg_triggers_xml.size(); i ++){
-            const VGears::TriggersFile::Trigger& bg_trigger = bg_triggers_xml[i];
-            if (!IsBackgroundTriggerUsed(bg_trigger)) continue;
-            std::unique_ptr<TiXmlElement> xml_entity_trigger(new TiXmlElement("entity_trigger"));
-            xml_entity_trigger->SetAttribute("name", "BgTrigger" + std::to_string(i));
-            xml_entity_trigger->SetAttribute(
-              "point1",
-              Ogre::StringConverter::toString(Ogre::Vector3(
-                bg_trigger.trigger_line[0].x, bg_trigger.trigger_line[0].y,
-                bg_trigger.trigger_line[0].z
-              ) / downscaler_this)
-            );
-            xml_entity_trigger->SetAttribute(
-              "point2",
-              Ogre::StringConverter::toString(Ogre::Vector3(
-                bg_trigger.trigger_line[1].x, bg_trigger.trigger_line[1].y,
-                bg_trigger.trigger_line[1].z
-              ) / downscaler_this)
-            );
-            xml_entity_trigger->SetAttribute("enabled", "true");
-            element->LinkEndChild(xml_entity_trigger.release());
-        }
-
-        // Get music tracks
-        std::vector<int> tracks = ExtractMusicTrackIds(field);
-        std::unique_ptr<TiXmlElement> xml_tracks(new TiXmlElement("tracks"));
-        for (int t = 0; t < tracks.size(); t ++){
-            std::unique_ptr<TiXmlElement> xml_track(new TiXmlElement("track"));
-            xml_track->SetAttribute("id", t);
-            xml_track->SetAttribute("track_id", tracks[t]);
-            xml_tracks->LinkEndChild(xml_track.release());
-        }
-        element->LinkEndChild(xml_tracks.release());
-
-        doc.LinkEndChild(element.release());
-
-        doc.SaveFile(data_dir_ + "/" + FIELD_MAPS_DIR + "/" + field->getName() + "/map.xml");
-        const VGears::PaletteFilePtr& pal = field->GetPalette();
-        const VGears::BackgroundFilePtr& bg = field->GetBackground();
-        std::unique_ptr<Ogre::Image> bg_image(bg->CreateImage(pal));
-        bg_image->encode("png");
-        bg_image->save(data_dir_ + "/" + FIELD_MAPS_DIR + "/" + field->getName() + "/tiles.png");
-        {
-            TiXmlDocument bg_doc;
-            std::unique_ptr<TiXmlElement> bg_element(new TiXmlElement("background2d"));
-            // Magic constants.
-            const int BG_SCALE_UP_FACTOR = 3;
-            const int BG_PSX_SCREEN_WIDTH = 320;
-            const int BG_PSX_SCREEN_HEIGHT = 240;
-            // Get texture atlas size.
-            const int width = bg_image->getWidth();
-            const int height = bg_image->getHeight();
-            const VGears::CameraMatrixFilePtr& camera_matrix = field->GetCameraMatrix();
-            const Ogre::Vector3 position = camera_matrix->GetPosition() / GetFieldScaleFactor(this_field_id);
-            const Ogre::Quaternion orientation = camera_matrix->GetOrientation();
-            const Ogre::Degree fov = camera_matrix->GetFov(static_cast<float>(BG_PSX_SCREEN_HEIGHT));
-            const int min_x = triggers->GetCameraRange().left * BG_SCALE_UP_FACTOR;
-            const int min_y = triggers->GetCameraRange().top * BG_SCALE_UP_FACTOR;
-            const int max_x = triggers->GetCameraRange().right * BG_SCALE_UP_FACTOR;
-            const int max_y = triggers->GetCameraRange().bottom * BG_SCALE_UP_FACTOR;
-            bg_element->SetAttribute("image", field->getName() + "/tiles.png");
-            bg_element->SetAttribute("position", Ogre::StringConverter::toString(position));
-            bg_element->SetAttribute("orientation", Ogre::StringConverter::toString(orientation));
-            bg_element->SetAttribute("fov", Ogre::StringConverter::toString(fov));
-            bg_element->SetAttribute(
-              "range",
-              std::to_string(min_x) + " " + std::to_string(min_y) + " "
-              + std::to_string(max_x) + " " + std::to_string(max_y)
-            );
-            bg_element->SetAttribute(
-              "clip",
-              std::to_string(BG_PSX_SCREEN_WIDTH * BG_SCALE_UP_FACTOR) + " "
-              + std::to_string(BG_PSX_SCREEN_HEIGHT * BG_SCALE_UP_FACTOR)
-            );
-            // The palette animations: the tiles of the palettes a script changes are painted again
-            // by the engine.
-            if (
-              !decompiled.palette_pages.empty() || decompiled.palette_pages_dynamic
-            ){
-                const std::string palette_name = field->getName() + "/palette.bin";
-                if (WritePaletteFile(
-                  data_dir_ + "/" + FIELD_MAPS_DIR + "/" + palette_name, pal, bg->GetPaletteTiles(),
-                  decompiled.palette_pages, decompiled.palette_pages_dynamic
-                )){
-                    bg_element->SetAttribute("palette", palette_name);
-                }
-            }
-            // Write out the *_BG.XML data.
-            auto& layers = bg->GetLayers();
-            int layer_index = -1;
-            for (const auto& layer : layers){
-                ++ layer_index;
-                // TODO: Should only the tiles to construct enabled layers be outputted?
-                //  if (layer.enabled){
+    return true;
+}
 
 
-                for (const VGears::BackgroundFile::SpriteData& sprite : layer.sprites){
-                    std::unique_ptr<TiXmlElement> xml_element(new TiXmlElement("tile"));
-                    xml_element->SetAttribute(
-                      "destination",
-                      Ogre::StringConverter::toString(sprite.dst.x * BG_SCALE_UP_FACTOR) + " "
-                      + Ogre::StringConverter::toString(sprite.dst.y * BG_SCALE_UP_FACTOR)
-                    );
-                    xml_element->SetAttribute(
-                      "width", Ogre::StringConverter::toString(sprite.width * BG_SCALE_UP_FACTOR)
-                    );
-                    xml_element->SetAttribute(
-                      "height", Ogre::StringConverter::toString(sprite.height * BG_SCALE_UP_FACTOR)
-                    );
-                    // Each tile is added to a big texture atlas with hard coded size of 1024x1024,
-                    // convert UV's to the 0.0f to 1.0f range.
-                    const float u0 = static_cast<float>(sprite.src.x) / width;
-                    const float v0 = static_cast<float>(sprite.src.y) / height;
-                    const float u1 = static_cast<float>(sprite.src.x + sprite.width) / width;
-                    const float v1 = static_cast<float>(sprite.src.y + sprite.height) / height;
-                    xml_element->SetAttribute(
-                      "uv",
-                      Ogre::StringConverter::toString(u0) + " " + Ogre::StringConverter::toString(v0) + " "
-                      + Ogre::StringConverter::toString(u1) + " " + Ogre::StringConverter::toString(v1)
-                    );
-                    // TODO: It works (on FFVII PC), but why this number?
-                    // The depth is a distance from the camera, so it has the scale of the field
-                    // like the position of the camera does. The far depths (the backgrounds, from
-                    // 127 on) are only an order and are kept.
-                    float tile_depth = static_cast<float>(sprite.depth) * (0.03125f);
-                    if (tile_depth < 127.0f) tile_depth /= GetFieldScaleFactor(this_field_id);
-                    xml_element->SetAttribute("depth", Ogre::StringConverter::toString(tile_depth));
-                    // TODO: Copied from DatFile::AddTile.
-                    // Add to common method.
-                    Ogre::String blending_str = "";
-                    if (sprite.blending == 0) blending_str = "alpha";
-                    // 3 is source + 0.25 * destination:
-                    else if (sprite.blending == 1 || sprite.blending == 3) blending_str = "add";
-                    else if (sprite.blending == 2) blending_str = "subtract";
-                    // TODO: Should probably throw to fail conversion:
-                    else blending_str = "unknown";
-                    xml_element->SetAttribute("blending", blending_str);
-                    // Type 3 adds only a quarter of the colour of the tile: with all of it the
-                    // glows turn white (ujunon4).
-                    if (sprite.blending == 3) xml_element->SetAttribute("intensity", "0.25");
-                    // The layer is needed by the scripts that scroll them at their own speed.
-                    xml_element->SetAttribute("layer", layer_index);
-                    // The sprites that belong to a group (animation_id) are drawn only while a
-                    // script (BGON) or a background trigger turns on one of their states. The
-                    // original game clears the state of every group when it loads a field, so a
-                    // group that nothing turns on is never drawn (the debris behind the doors of
-                    // mds6_2, for example).
-                    if (sprite.animation_id != 0){
-                        xml_element->SetAttribute("area", static_cast<int>(sprite.animation_id));
-                        xml_element->SetAttribute("state", static_cast<int>(sprite.animation_frame));
-                    }
-                    bg_element->LinkEndChild(xml_element.release());
-                }
-                //}
-            }
-            bg_doc.LinkEndChild(bg_element.release());
-            bg_doc.SaveFile(data_dir_ + "/" + FIELD_MAPS_DIR + "/" + field->getName() + "/bg.xml");
-        }
-    }
-    {
-        // Save out the walk mesh as XML.
-        const VGears::WalkmeshFilePtr& walkmesh = field->GetWalkmesh();
-        // Scripts, gateways and the camera use the field's scale, so the walkmesh must too.
-        const float field_scale = GetFieldScaleFactor(GetFieldId(field->getName(), map_list_));
-        TiXmlDocument doc;
-        std::unique_ptr<TiXmlElement> wmesh_element(new TiXmlElement("walkmesh"));
-        for (VGears::WalkmeshFile::Triangle& tri : walkmesh->GetTriangles()){
-            std::unique_ptr<TiXmlElement> xml_element(new TiXmlElement("triangle"));
-            xml_element->SetAttribute("a", Ogre::StringConverter::toString(tri.a / field_scale));
-            xml_element->SetAttribute("b", Ogre::StringConverter::toString(tri.b / field_scale));
-            xml_element->SetAttribute("c", Ogre::StringConverter::toString(tri.c / field_scale));
-            xml_element->SetAttribute("a_b", std::to_string(tri.access_side[0]));
-            xml_element->SetAttribute("b_c", std::to_string(tri.access_side[1]));
-            xml_element->SetAttribute("c_a", std::to_string(tri.access_side[2]));
-            wmesh_element->LinkEndChild(xml_element.release());
-        }
-        doc.LinkEndChild(wmesh_element.release());
-        doc.SaveFile(data_dir_ + "/" + FIELD_MAPS_DIR + "/" + field->getName() + "/wm.xml");
-    }
+void FieldDataInstaller::PcFieldToVGearsField(const VGears::FLevelFilePtr& field){
+    const FieldDecompiler::DecompiledScript decompiled = script_installer_.Install(field);
+    map_writer_.WriteMap(field, decompiled);
+    const float scale = FieldData::ScaleFactor(
+      scale_factors_, FieldData::FieldId(field->getName(), map_list_)
+    );
+    background_installer_.Install(field, decompiled, scale);
+    map_writer_.WriteWalkmesh(field);
     converted_map_list_.push_back(field->getName());
     converted_map_list_.push_back(field->getName());
 }
 }

+ 81 - 554
src/installer/extractors/FieldDataInstaller.h

@@ -15,331 +15,29 @@
 
 
 #pragma once
 #pragma once
 
 
-#include <vector>
+#include <functional>
+#include <memory>
 #include <string>
 #include <string>
-#include <OgreMesh.h>
+#include <vector>
+#include <OgreResourceGroupManager.h>
 #include <tinyxml.h>
 #include <tinyxml.h>
 #include "formats/field/FLevelFile.h"
 #include "formats/field/FLevelFile.h"
 #include "installer/formats/DiskImage.h"
 #include "installer/formats/DiskImage.h"
-#include "ScopedLgp.h"
-#include "installer/tables/SpawnPointDb.h"
+#include "FieldBackgroundInstaller.h"
+#include "FieldDataTypes.h"
+#include "FieldMapWriter.h"
+#include "FieldModelInstaller.h"
+#include "FieldScriptInstaller.h"
 #include "ModelsAndAnimationsDb.h"
 #include "ModelsAndAnimationsDb.h"
-#include "FieldTextWriter.h"
-#include "decompiler/field/FieldScriptFormatter.h"
-#include "decompiler/field/FieldDecompiler.h"
-#include "formats/FF7NameLookup.h"
-
-typedef std::vector<std::string> MapList;
-
-typedef std::map<u16, SpawnPointDb> FieldSpawnPointsMap;
-
-typedef std::map<u16, float> FieldScaleFactorMap;
-
-class BaseFF7FieldScriptFormatter : public FieldScriptFormatter{
-
-    public:
-
-        /**
-         * Constructor.
-         *
-         * @param[in] field_name The field name.
-         * @param[in] field_id_to_name_lookup Field name lookup table to use.
-         * @param[in] spawn_points The list of spawn points.
-         */
-        BaseFF7FieldScriptFormatter(
-          const std::string& field_name, const std::vector<std::string>& field_id_to_name_lookup,
-          FieldSpawnPointsMap& spawn_points
-        ) : field_name_(field_name), field_id_to_name_lookup_(field_id_to_name_lookup), spawn_points_(spawn_points)
-        {}
-
-        /**
-         * Composes a spawn point name
-         *
-         * The name will have the format
-         * {FIELD_NAME}_{ENTITY}_{FUNCTION_NAME}_addr_{ADDRESS}
-         *
-         * @param[in] map_id Unused.
-         * @param[in] entity Entity name.
-         * @param[in] function_name Name of the function.
-         * @param[in] address @todo Understand and document.
-         * @return The composed spawn point name.
-         */
-        virtual std::string GetSpawnPointName(
-          unsigned int map_id, const std::string& entity, const std::string& function_name, unsigned int address
-        ) override{
-            return field_name_ + "_" + entity + "_" + function_name + "_addr_" + std::to_string(address);
-        }
-
-        /**
-         * Retrieves a map name from it's ID.
-         *
-         * @param[in] map_id The map ID.
-         * @return The map name.
-         */
-        virtual std::string GetMapName(unsigned int map_id) override{return field_id_to_name_lookup_[map_id];}
-
-        /**
-         * Retrieves a user friendly variable name.
-         *
-         * @param[in] bank Variable bank.
-         * @param[in] addr Variable address.
-         * @return Friendly name for the variable, or an empty string if it
-         * doesn't have one assigned.
-         */
-        virtual std::string GetFriendlyVarName(unsigned int bank, unsigned int addr) override{
-            return VGears::NameLookup::FieldScriptVarName(bank, addr);
-        }
-
-        /**
-         * Retrieves a user friendly entity name.
-         *
-         * @param[in] entity Entity name.
-         * @return Friendly name for the entity, or the current name if it
-         * doesn't have one assigned.
-         */
-        virtual std::string GetFriendlyEntityName(const std::string& entity) override{
-            return VGears::NameLookup::FieldScriptEntityName(entity);
-        }
-
-        /**
-         * Retrieves a user friendly character name.
-         *
-         * @param[in] char_id Character ID.
-         * @return Friendly name for the entity, or an empty string if it
-         * doesn't have one assigned.
-         */
-        virtual std::string GetFriendlyCharName(int char_id) override{return VGears::NameLookup::CharName(char_id);}
-
-        /**
-         * Retrieves a user friendly function name.
-         *
-         * @param[in] entity The name of the entity the function belongs to.
-         * @param[in] function_name Function name.
-         * @return Friendly name for the function, or the current name if it
-         * doesn't have one assigned.
-         */
-        virtual std::string GetFriendlyFunctionName(
-          const std::string& entity, const std::string& function_name
-        ) override{
-            return VGears::NameLookup::FieldScriptFunctionName(field_name_, entity, function_name);
-        }
-
-        /**
-         * Retrieves the header comment for a function in an entity.
-         *
-         * @param[in] entity The name of the entity the function belongs to.
-         * @param[in] function_name Function name.
-         * @return Friendly comment for the function, or an empty string if it
-         * doesn't have one assigned.
-         */
-        virtual std::string GetFunctionComment(const std::string& entity, const std::string& function_name) override{
-            return VGears::NameLookup::FieldScriptFunctionComment(field_name_, entity, function_name);
-        }
-
-    protected:
-
-        /**
-         * The field name.
-         */
-        std::string field_name_;
-
-        /**
-         * The list of spawn points.
-         */
-        FieldSpawnPointsMap& spawn_points_;
-
-        /**
-         * Look up table relatingfield IDs and names.
-         */
-        const std::vector<std::string>& field_id_to_name_lookup_;
-};
 
 
 /**
 /**
- * Handles the script gateway colection.
- */
-class FF7FieldScriptGatewayCollector : public BaseFF7FieldScriptFormatter{
-
-    // TODO: Move declaration to a .h file.
-
-    public:
-
-        /**
-         * Cosntructor.
-         */
-        FF7FieldScriptGatewayCollector(
-          const std::string& field_name, const std::vector<std::string>& field_id_to_name_lookup,
-          FieldSpawnPointsMap& spawn_points, size_t this_field_id
-        ) : BaseFF7FieldScriptFormatter(field_name,field_id_to_name_lookup, spawn_points), field_id_(this_field_id)
-        {}
-
-        /**
-         * Adds an spawn point.
-         *
-         * If the spawn is new, a new record will be added to the spawn point
-         * database. If it was already there, update the record to add the
-         * origin.
-         *
-         * @param[in] map_id The target map ID.
-         * @param[in] entity The entity that acts as the spawn point.
-         * @param[in] function_name The spawn function name.
-         * @param[in] address @todo Understand and document.
-         * @param[in] x X coordinate of the field target at which to spawn.
-         * @param[in] y Y coordinate of the field target at which to spawn.
-         * @param[in] z Z coordinate of the field target at which to spawn.
-         * @param[in] angle Orientation at which to spawn.
-         */
-        virtual void AddSpawnPoint(
-          unsigned int map_id, const std::string& entity, const std::string& function_name,
-          unsigned int address, int x, int y, int z, int angle
-        ) override {
-            auto it = spawn_points_.find(map_id);
-            VGears::TriggersFile::Gateway gw = {};
-            gw.destination_field_id = map_id;
-            gw.destination.x = x;
-            gw.destination.y = y;
-            gw.destination.z = z;
-            gw.dir = angle;
-            if (it != std::end(spawn_points_)){
-                // Add to the list of gateways that link to destination_field_id.
-                SpawnPointDb::Record rec;
-                rec.from_script = true;
-                rec.field_id = field_id_;
-                rec.gateway = gw;
-                rec.entity_name = entity;
-                rec.script_function_name = function_name;
-                rec.gateway_index_or_map_jump_address = address;
-                it->second.gateways_to_this_field.push_back(rec);
-            }
-            else{
-                // Create a new record for destination_field_id
-                SpawnPointDb db;
-                db.target_field_id = map_id;
-                SpawnPointDb::Record rec;
-                rec.from_script = true;
-                rec.field_id = field_id_;
-                rec.gateway = gw;
-                rec.entity_name = entity;
-                rec.script_function_name = function_name;
-                rec.gateway_index_or_map_jump_address = address;
-                db.gateways_to_this_field.push_back(rec);
-                spawn_points_.insert(std::make_pair(db.target_field_id, db));
-            }
-        }
-
-    private:
-
-        /**
-         * The field map ID.
-         */
-        size_t field_id_;
-
-};
-
-/**
- * Handles the formatting of field scripts.
+ * Installs the fields: their scripts, texts, maps, backgrounds and walkmeshes, the list of fields
+ * and the models they use.
+ *
+ * The work is done by {@see FieldScriptInstaller}, {@see FieldMapWriter},
+ * {@see FieldBackgroundInstaller} and {@see FieldModelInstaller}. This class collects the data
+ * that they need from every field, and runs them in steps.
  */
  */
-class FF7FieldScriptFormatter : public BaseFF7FieldScriptFormatter{
-
-    public:
-
-        /**
-         * Constructor.
-         *
-         * @param[in] field_name The field name.
-         * @param[in] models The list of field models.
-         * @param[in] field_id_to_name_lookup Field name lookup table to use.
-         * @param[in] spawn_points The list of spawn points.
-         */
-        FF7FieldScriptFormatter(
-          const std::string& field_name, const VGears::ModelListFilePtr& models,
-          const std::vector<std::string>& field_id_to_name_lookup, FieldSpawnPointsMap& spawn_points
-        ) : BaseFF7FieldScriptFormatter(field_name, field_id_to_name_lookup, spawn_points), model_loader_(models)
-        {}
-
-        // Names an animation, can't return empty
-        /**
-         * Retreieves an animation name from iths ID.
-         *
-         * @param[in] char_id ID of the character the animation belogs to.
-         * @param[in] id Animation ID.
-         * @return The animation name. If there is no name assigned, or it
-         * can't be found, a string with the animation ID.
-         */
-        virtual std::string GetFriendlyAnimationName(int char_id, int id) override{
-            // Get the animation file name, then look up the friendly name of
-            // the "raw" animation.
-            if (static_cast<unsigned int>(char_id) >= model_loader_->GetModels().size()){
-                std::cerr << "FF7FieldScriptFormatter::AnimationName ERROR:"
-                  << "Char ID " << char_id << " out of bounds" << std::endl;
-                return std::to_string(id);
-            }
-            const auto& model_info = model_loader_->GetModels().at(char_id);
-            if (static_cast<unsigned int>(id) >= model_info.animations.size()){
-                std::cerr << "FF7FieldScriptFormatter::AnimationName ERROR:" << "In field " << field_name_
-                  << " the model " << model_info.name << " animation with ID " << id << " is out of bounds ("
-                  << model_info.animations.size() << ")" << std::endl;
-                return std::to_string(id);
-            }
-            const auto raw_name = model_info.animations.at(id).name;
-            // Trim off ".yos" or whatever extension the model loader adds in.
-            Ogre::String base_name;
-            VGears::StringUtil::splitBase(raw_name, base_name);
-            VGears::StringUtil::toLowerCase(base_name);
-            return VGears::NameLookup::Animation(base_name);
-        }
-
-        /**
-         * Retrieves the animation a model must play when its script doesn't set a default one.
-         *
-         * In the original game a model without a requested animation plays the first one of its
-         * list.
-         *
-         * @param[in] char_id ID of the model, as given to the CHAR opcode.
-         * @return Name of the first animation of the model. An empty string if the model already
-         * has an animation called "Idle", or it has no animations.
-         */
-        virtual std::string GetDefaultAnimationName(int char_id) override{
-            if (static_cast<unsigned int>(char_id) >= model_loader_->GetModels().size()) return "";
-            const auto& animations = model_loader_->GetModels().at(char_id).animations;
-            if (animations.empty()) return "";
-            std::string first;
-            for (size_t i = 0; i < animations.size(); ++ i){
-                Ogre::String base_name;
-                VGears::StringUtil::splitBase(animations[i].name, base_name);
-                VGears::StringUtil::toLowerCase(base_name);
-                const std::string friendly = VGears::NameLookup::Animation(base_name);
-                if (friendly == "Idle") return "";
-                if (i == 0) first = friendly;
-            }
-            return first;
-        }
-
-        /**
-         * Retrieves the animation a model plays when it walks or runs on its own.
-         *
-         * @param[in] char_id ID of the model, as given to the CHAR opcode.
-         * @param[in] index 1 for the walk animation, 2 for the run animation.
-         * @return Name of the animation, or an empty string if the model hasn't got it.
-         */
-        virtual std::string GetMoveAnimationName(int char_id, int index) override{
-            if (char_id < 0 || static_cast<unsigned int>(char_id) >= model_loader_->GetModels().size())
-                return "";
-            const auto& animations = model_loader_->GetModels().at(char_id).animations;
-            if (static_cast<unsigned int>(index) >= animations.size()) return "";
-            Ogre::String base_name;
-            VGears::StringUtil::splitBase(animations[index].name, base_name);
-            VGears::StringUtil::toLowerCase(base_name);
-            return VGears::NameLookup::Animation(base_name);
-        }
-
-    private:
-
-        /**
-         * The field model loader.
-         */
-        const VGears::ModelListFilePtr& model_loader_;
-};
-
 class FieldDataInstaller{
 class FieldDataInstaller{
 
 
     public:
     public:
@@ -348,32 +46,50 @@ class FieldDataInstaller{
          * Installer constructor
          * Installer constructor
          *
          *
          * @param[in] disk_image Disk image to extract the data from.
          * @param[in] disk_image Disk image to extract the data from.
-         * @param[in] output_dir Path to the directory to write generated data
-         * to.
+         * @param[in] output_dir Path to the directory to write generated data to.
+         * @param[in] log_output_line Function to write a line to the installation log.
          */
          */
         FieldDataInstaller(
         FieldDataInstaller(
           const DiskImage& disk_image, const std::string output_dir,
           const DiskImage& disk_image, const std::string output_dir,
           std::function<void(std::string)> log_output_line
           std::function<void(std::string)> log_output_line
         );
         );
 
 
+        /**
+         * Installer destructor.
+         */
+        ~FieldDataInstaller();
+
         /**
         /**
          * Fills the converted field list with the fields already installed in the data directory.
          * Fills the converted field list with the fields already installed in the data directory.
          *
          *
-         * Used when the fields are not converted in this run but other steps (like the world map scripts) need them.
+         * Used when the fields are not converted in this run but other steps (like the world map
+         * scripts) need them.
          */
          */
         void LoadInstalledFields();
         void LoadInstalledFields();
 
 
         /**
         /**
-         * Installer destructor.
+         * Retrieves the names of the fields, by ID.
+         *
+         * @return The names of the fields.
          */
          */
-        ~FieldDataInstaller();
-
         const MapList& GetMapList() const{return map_list_;}
         const MapList& GetMapList() const{return map_list_;}
+
+        /**
+         * Retrieves the scale factors of the fields.
+         *
+         * @return The scale factors, by field ID.
+         */
         const FieldScaleFactorMap& GetFieldScaleFactors() const{return scale_factors_;}
         const FieldScaleFactorMap& GetFieldScaleFactors() const{return scale_factors_;}
+
+        /**
+         * Retrieves the names of the fields that have been converted.
+         *
+         * @return The names of the converted fields.
+         */
         const MapList& GetConvertedMapList() const{return converted_map_list_;}
         const MapList& GetConvertedMapList() const{return converted_map_list_;}
 
 
         /**
         /**
-         * Initializer for {@see CollectionFieldSpawnAndScaleFactors}.
+         * Initializer for {@see CollectSpawnAndScaleFactors}.
          *
          *
          * Installation step 1.
          * Installation step 1.
          *
          *
@@ -387,9 +103,8 @@ class FieldDataInstaller{
          *
          *
          * Installation step 2.
          * Installation step 2.
          *
          *
-         * @param[in] field_index Index of the field to collect from. Must be
-         * less than the value returned by
-         * {@see CollectSpawnAndScaleFactorsInit}.
+         * @param[in] field_index Index of the field to collect from. Must be less than the value
+         * returned by {@see CollectSpawnAndScaleFactorsInit}.
          */
          */
         void CollectSpawnAndScaleFactors(int field_index);
         void CollectSpawnAndScaleFactors(int field_index);
 
 
@@ -401,14 +116,13 @@ class FieldDataInstaller{
         /**
         /**
          * Converts FFVII PC fields to V-Gears format.
          * Converts FFVII PC fields to V-Gears format.
          *
          *
-         * @param[in] field_index Index of the field to collect from. Must be
-         * less than the value returned by
-         * {@see CollectSpawnAndScaleFactorsInit}.
+         * @param[in] field_index Index of the field to convert. Must be less than the value
+         * returned by {@see CollectSpawnAndScaleFactorsInit}.
          */
          */
         void Convert(int field_index);
         void Convert(int field_index);
 
 
         /**
         /**
-         * Initializer for {@see WriteMapsXmlIteration}.
+         * Initializer for {@see Write}.
          *
          *
          * Installation step 3.
          * Installation step 3.
          *
          *
@@ -417,24 +131,24 @@ class FieldDataInstaller{
         int WriteInit();
         int WriteInit();
 
 
         /**
         /**
-         * Saves the game maps to XML files.
+         * Adds a converted field to the list of fields.
          *
          *
          * Installation step 4.
          * Installation step 4.
          *
          *
-         * @param[in] field_index Index of the field to collect from. Must be
-         * less than the value returned by {@see WriteInit}.
+         * @param[in] field_index Index of the field. Must be less than the value returned by
+         * {@see WriteInit}.
          */
          */
         void Write(int field_index);
         void Write(int field_index);
 
 
         /**
         /**
-         * Cleans up after {@see WriteMapsXmlIteration}.
+         * Saves the list of fields (field/maps/_fields.xml).
          *
          *
          * Installation step 5.
          * Installation step 5.
          */
          */
         void WriteEnd();
         void WriteEnd();
 
 
         /**
         /**
-         * Initializer for {@see ConvertFieldModelsIteration}.
+         * Initializer for {@see ConvertModels}.
          *
          *
          * Installation step 6.
          * Installation step 6.
          *
          *
@@ -443,7 +157,7 @@ class FieldDataInstaller{
         std::vector<std::string> ConvertModelsInit();
         std::vector<std::string> ConvertModelsInit();
 
 
         /**
         /**
-         * Converts the field models to V-Gears format.
+         * Converts a field model to V-Gears format.
          *
          *
          * Installation step 7 and final.
          * Installation step 7 and final.
          *
          *
@@ -451,53 +165,13 @@ class FieldDataInstaller{
          */
          */
         void ConvertModels(std::string model_name);
         void ConvertModels(std::string model_name);
 
 
-        /**
-         * Memory banks that are temporary: every field starts with them set to zero.
-         */
-        static const std::vector<int> TEMPORARY_BANKS;
-
-        /**
-         * Retrieves the Lua code every field script starts with.
-         *
-         * It creates the entity container, and sets the temporary memory banks to zero. In the
-         * original game a field can't see what the previous one left in them, but here the
-         * banks live as long as the game, so scripts that wait for a bank to change would see
-         * leftovers.
-         *
-         * @return Lua code to put at the beginning of a field script.
-         */
-        static std::string FieldScriptHeader(const int field_id = -1);
-
     private:
     private:
 
 
-        /**
-         * Creates a gateway script.
-         *
-         * @param[in] gateway_entity_name Name of the gateway entity.
-         * @param[in] target_map_name Name of the target map.
-         * @param[in] source_spawn_point_name The spawn point name.
-         * @return Gateway LUA script.
-         */
-        static std::string CreateGateWayScript(
-          const std::string& gateway_entity_name, const std::string& target_map_name,
-          const std::string& source_spawn_point_name
-        );
-
-        /**
-         * Retrieves a field ID from a name.
-         *
-         * @param[in] name The name of the field.
-         * @param[in] field_id_to_name_lookup Lookup table to use.
-         * @return The field ID for the specified name.
-         * @throws std::runtime_error If there is no ID for the field name.
-         */
-        static size_t GetFieldId(const std::string& name, const std::vector<std::string>& field_id_to_name_lookup);
-
         /**
         /**
          * Checks if a file is a field file.
          * Checks if a file is a field file.
          *
          *
-         * To verify it, it just checks that the extension is not '.tex', '.tut'
-         * or '.siz' and that the name is not 'maplist'.
+         * To verify it, it just checks that the extension is not '.tex', '.tut' or '.siz' and
+         * that the name is not 'maplist'.
          *
          *
          * @param[in] resource_name The name of the file to test.
          * @param[in] resource_name The name of the file to test.
          * @return False if the file is surely not a field file, true otherwise.
          * @return False if the file is surely not a field file, true otherwise.
@@ -505,245 +179,98 @@ class FieldDataInstaller{
         static bool IsAFieldFile(const Ogre::String& resource_name);
         static bool IsAFieldFile(const Ogre::String& resource_name);
 
 
         /**
         /**
-         * Checks if a map cause fatal crash bugs.
-         *
-         * It uses a hardcoded list of maps that are known to cause errors. This
-         * can be removed when whatever is causing the crash(s) is fixed.
-         *
-         * @note: Even so, conversion of all models will fail with a bone index
-         * out of bounds.
-         * @param[in] resource_name The name of the map file to test.
-         * @return True if the map will crash, false otherwise.
-         */
-        static bool WillCrash(const Ogre::String& resource_name);
-
-        /**
-         * Collects the scale factor from a map.
+         * Collects the spawn points that the gateways and the map jumps of a field add to other
+         * fields.
          *
          *
          * @param[in] field The field to collect from.
          * @param[in] field The field to collect from.
-         * @param[out] scale_factors The scale factor for the map will be set
-         * here, in the appropiate map entry.
-         * @param[in] field_id_to_name_lookup Lookup table to relate field IDs
-         * and names.
-         */
-        static void CollectFieldScaleFactors(
-          VGears::FLevelFilePtr& field, FieldScaleFactorMap& scale_factors,
-          const std::vector<std::string>& field_id_to_name_lookup
-        );
-
-        /**
-         * Collects the spawn point from a field.
-         *
-         * If a spawn is new, a new record will be added to the spawn point
-         * database. If it was already there, update the record to add the
-         * origin.
-         *
-         * @param[in] field The field to collect from.
-         * @param[in] field_id_to_name_lookup Lookup table to relate field IDs
-         * and names.
-         * @param[out] spawn_points Spawn points will be added sequentially to
-         * the end of this map.
-         */
-        static bool CollectSpawnPoints(
-          VGears::FLevelFilePtr& field, const std::vector<std::string>& field_id_to_name_lookup,
-          FieldSpawnPointsMap& spawn_points
-        );
-
-        /**
-         * The scale factor for line point coordinates.
-         *
-         * When a LINE opcode is found in the game scripts, the line points X
-         * and Y coordinates must be scaled down by this factor.
-         */
-        static float LINE_SCALE_FACTOR;
-
-        /**
-         * Path to the field models directory.
-         */
-        static std::string FIELD_MODELS_DIR;
-
-        /**
-         * Path to the field maps directory.
-         */
-        static std::string FIELD_MAPS_DIR;
-
-        /**
-         * Gateways to this map ID are considered to be inactive.
-         */
-        static int INACTIVE_GATEWAY_ID;
-
-        /**
-         * Exports a mesh to a file.
-         *
-         * The file will have the mesh name.
-         *
-         * @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);
-
-        /**
-         * Reads the music track IDs from a specific field.
-         *
-         * @param[in] field The field to extract tracks from.
-         * @return The list of tracks. It can be empty.
+         * @return False if the script can't be decompiled or the field has no triggers.
          */
          */
-        std::vector<int> ExtractMusicTrackIds(VGears::FLevelFilePtr& field);
+        bool CollectSpawnPoints(const VGears::FLevelFilePtr& field);
 
 
         /**
         /**
          * Converts a FFVII PC field to a V-Gears field.
          * Converts a FFVII PC field to a V-Gears field.
          *
          *
          * @param[in] field The field map to convert.
          * @param[in] field The field map to convert.
          */
          */
-        void PcFieldToVGearsField(VGears::FLevelFilePtr& field);
+        void PcFieldToVGearsField(const VGears::FLevelFilePtr& field);
 
 
         /**
         /**
-         * Retrieves a field scale factor.
-         *
-         * @param[in] field_id The id (name) of the field.
-         * @return The scale factor for the map.
-         * @throws std::runtime_error If there is no ID for the field name.
-         */
-        float GetFieldScaleFactor(size_t field_id);
-
-        /**
-         * Creates a directory in the outputh path.
-         *
-         * @param[in] dir Path of the directory to create, relative to the
-         * output path..
-         * @throws std::runtime_error If the directory can't be created.
-         */
-        void CreateDir(const std::string& dir);
-
-        /**
-         * The path to the directory from which to read the PC game data.
-         */
-        DiskImage disk_image_;
-
-        /**
-         * The path to the directory where to save the V-Gears data.
+         * Path to the directory to write generated data to.
          */
          */
         std::string output_dir_;
         std::string output_dir_;
 
 
         /**
         /**
-         * Directory where the game data is installed (<install dir>/data/).
+         * The game data folder.
          */
          */
         std::string data_dir_;
         std::string data_dir_;
 
 
         /**
         /**
-         * Helper variable to indicate internal progress of installation steps.
-         */
-        size_t conversion_step_;
-
-        /**
-         * Helper variable to indicate internal progress of installation steps.
-         */
-        size_t progress_step_num_elements_;
-
-        /**
-         * Iterator counter.
-         */
-        size_t iterator_counter_;
-
-        /**
-         * LGP archive with field data.
+         * Function to write a line to the installation log.
          */
          */
-        std::unique_ptr<ScopedLgp> fields_lgp_;
-
-        /**
-         * LGP archive with texture data.
-         */
-        std::unique_ptr<ScopedLgp> textures_lgp_;
+        std::function<void(std::string)> write_output_line_;
 
 
         /**
         /**
-         * LGP archive with field model data.
+         * The files of the field archive.
          */
          */
-        std::unique_ptr<ScopedLgp> field_models_lgp_;
-
+        Ogre::StringVectorPtr flevel_file_list_;
 
 
         /**
         /**
-         * List of flevel files.
+         * The names of the fields, by ID.
          */
          */
-        Ogre::StringVectorPtr flevel_file_list_;
+        MapList map_list_;
 
 
         /**
         /**
-         * The list of maps.
+         * The fields whose data could not be collected. They are not converted.
          */
          */
-        std::vector<std::string> map_list_;
-
         std::vector<std::string> failed_fields_;
         std::vector<std::string> failed_fields_;
 
 
         /**
         /**
-         * Map of the collected spawn points.
+         * The spawn points of every field.
          */
          */
         FieldSpawnPointsMap spawn_points_;
         FieldSpawnPointsMap spawn_points_;
 
 
         /**
         /**
-         * Map of th collected scale factors.
+         * The scale factors of the fields.
          */
          */
         FieldScaleFactorMap scale_factors_;
         FieldScaleFactorMap scale_factors_;
 
 
         /**
         /**
-         * ModelsAndAnimationsUsedByConvertedFields
+         * The models that the fields use, and their animations.
          */
          */
         ModelsAndAnimationsDb used_models_and_anims_;
         ModelsAndAnimationsDb used_models_and_anims_;
 
 
         /**
         /**
-         * List of converted maps.
+         * The names of the converted fields.
          */
          */
         MapList converted_map_list_;
         MapList converted_map_list_;
 
 
         /**
         /**
-         * Iterator for {@see converted_map_list}.
-         */
-        MapList::iterator converted_map_list_iterator_;
-
-        /**
-         * Field currently being processed.
-         */
-        VGears::FLevelFilePtr field_;
-
-        /**
-         * List of model files.
-         */
-        Ogre::StringVectorPtr field_model_file_list_;
-
-        /**
-         * An XML document.
-         *
-         * Internally used during some installation steps.
+         * The document of the list of fields.
          */
          */
         std::unique_ptr<TiXmlDocument> doc_;
         std::unique_ptr<TiXmlDocument> doc_;
 
 
         /**
         /**
-         * An XML element.
-         *
-         * Internally used during some installation steps.
+         * The root element of the list of fields.
          */
          */
         std::unique_ptr<TiXmlElement> element_;
         std::unique_ptr<TiXmlElement> element_;
 
 
         /**
         /**
-         * Iterator for {@see used_models_and_anims_}.
-         */
-        ModelAnimationMap::iterator model_animation_map_iterator_;
-
-        /**
-         * Function used to print text to the log output, line by line.
+         * Writes the scripts and the texts of the fields.
          */
          */
-        std::function<void(std::string)> write_output_line_;
+        FieldScriptInstaller script_installer_;
 
 
         /**
         /**
-         * Function used to print set the current installation progress text.
+         * Writes the maps and the walkmeshes of the fields.
          */
          */
-        std::function<void(std::string)> set_progress_label_;
+        FieldMapWriter map_writer_;
 
 
         /**
         /**
-         * Field text writer.
+         * Writes the backgrounds of the fields.
          */
          */
-        FieldTextWriter field_text_writer_;
+        FieldBackgroundInstaller background_installer_;
 
 
         /**
         /**
-         * Written materials.
+         * Converts the models of the fields.
          */
          */
-        std::vector<std::string> materials_;
+        FieldModelInstaller model_installer_;
 };
 };

+ 114 - 0
src/installer/extractors/FieldDataTypes.h

@@ -0,0 +1,114 @@
+/*
+ * 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 <stdexcept>
+#include <string>
+#include <vector>
+#include "formats/field/TriggersFile.h"
+#include "installer/tables/SpawnPointDb.h"
+
+/**
+ * The names of the fields, by field ID.
+ */
+typedef std::vector<std::string> MapList;
+
+/**
+ * The spawn points of each field, by field ID.
+ */
+typedef std::map<u16, SpawnPointDb> FieldSpawnPointsMap;
+
+/**
+ * The scale factor of each field, by field ID.
+ */
+typedef std::map<u16, float> FieldScaleFactorMap;
+
+/**
+ * Data and helpers shared by the parts of the field installer.
+ */
+namespace FieldData{
+
+    /**
+     * Folder of the field models, relative to the game data folder.
+     */
+    const std::string MODELS_DIR("field/models");
+
+    /**
+     * Folder of the field maps, relative to the game data folder.
+     */
+    const std::string MAPS_DIR("field/maps");
+
+    /**
+     * Destination of the gateways that are not in use.
+     */
+    const int INACTIVE_GATEWAY_ID = 32767;
+
+    /**
+     * Finds the ID of a field.
+     *
+     * @param[in] name Name of the field.
+     * @param[in] map_list The names of the fields, by ID.
+     * @return The ID of the field.
+     * @throws std::runtime_error If the field is not in the list.
+     */
+    inline size_t FieldId(const std::string& name, const MapList& map_list){
+        for (size_t i = 0; i < map_list.size(); i ++){
+            if (map_list[i] == name) return i;
+        }
+        throw std::runtime_error("No Id found for field name");
+    }
+
+    /**
+     * Finds the scale factor of a field.
+     *
+     * @param[in] scale_factors The scale factors of the fields.
+     * @param[in] field_id ID of the field.
+     * @return The scale factor of the field.
+     * @throws std::runtime_error If the field has no scale factor.
+     */
+    inline float ScaleFactor(const FieldScaleFactorMap& scale_factors, const size_t field_id){
+        auto it = scale_factors.find(static_cast<u16>(field_id));
+        if (it == std::end(scale_factors)) throw std::runtime_error("Scale factor not found for field id");
+        return it->second;
+    }
+
+    /**
+     * Checks if a background trigger is in use. Unused ones are all zeroes.
+     *
+     * @param[in] trigger The trigger to check.
+     * @return True if the trigger is in use.
+     */
+    inline bool IsBackgroundTriggerUsed(const VGears::TriggersFile::Trigger& trigger){
+        for (const auto& v : trigger.trigger_line){
+            if (v.x != 0 || v.y != 0 || v.z != 0) return true;
+        }
+        return false;
+    }
+
+    /**
+     * Adds an entrance to the spawn points of the field it leads to.
+     *
+     * @param[in,out] spawn_points The spawn points of every field.
+     * @param[in] record The entrance. Its gateway has the destination field.
+     */
+    inline void AddSpawnPoint(FieldSpawnPointsMap& spawn_points, const SpawnPointDb::Record& record){
+        const u16 target = record.gateway.destination_field_id;
+        SpawnPointDb& db = spawn_points[target];
+        db.target_field_id = target;
+        db.gateways_to_this_field.push_back(record);
+    }
+}

+ 365 - 0
src/installer/extractors/FieldMapWriter.cpp

@@ -0,0 +1,365 @@
+/*
+ * 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 <memory>
+#include <utility>
+#include <OgreStringConverter.h>
+#include "common/StringUtil.h"
+#include "FieldMapWriter.h"
+
+const float FieldMapWriter::LINE_SCALE_FACTOR(0.0078124970964f);
+
+namespace{
+
+    /**
+     * Creates an element with a file name attribute.
+     *
+     * @param[in] name Name of the element.
+     * @param[in] file_name The file name.
+     * @return The element.
+     */
+    std::unique_ptr<TiXmlElement> CreateFileLink(const std::string& name, const std::string& file_name){
+        std::unique_ptr<TiXmlElement> element(new TiXmlElement(name));
+        element->SetAttribute("file_name", file_name);
+        return element;
+    }
+
+    /**
+     * Creates the element of a trigger line.
+     *
+     * @param[in] name Name of the entity of the trigger.
+     * @param[in] point1 First point of the line.
+     * @param[in] point2 Second point of the line.
+     * @return The element.
+     */
+    std::unique_ptr<TiXmlElement> CreateTriggerLine(
+      const std::string& name, const std::string& point1, const std::string& point2
+    ){
+        std::unique_ptr<TiXmlElement> element(new TiXmlElement("entity_trigger"));
+        element->SetAttribute("name", name);
+        element->SetAttribute("point1", point1);
+        element->SetAttribute("point2", point2);
+        element->SetAttribute("enabled", "true");
+        return element;
+    }
+
+    /**
+     * Converts a vertex of a trigger line to the units of the field.
+     *
+     * @param[in] vertex The vertex.
+     * @param[in] downscaler What the coordinates are divided by.
+     * @return The vertex, as text.
+     */
+    std::string TriggerPoint(const VGears::TriggersFile::TriggerVertex& vertex, const float downscaler){
+        return Ogre::StringConverter::toString(Ogre::Vector3(vertex.x, vertex.y, vertex.z) / downscaler);
+    }
+
+    /**
+     * Converts a point of a script line to the units of the field.
+     *
+     * @param[in] point The point.
+     * @param[in] scale What the coordinates are multiplied by.
+     * @return The point, as text.
+     */
+    template<typename Point> std::string LinePoint(const Point& point, const float scale){
+        return std::to_string(point[0] * scale) + " " + std::to_string(point[1] * scale)
+          + " " + std::to_string(point[2] * scale);
+    }
+
+    /**
+     * Names the spawn point of an entrance to a field.
+     *
+     * @param[in] record The entrance.
+     * @param[in] map_list The names of the fields, by ID.
+     * @return The name of the spawn point.
+     */
+    std::string SpawnPointName(const SpawnPointDb::Record& record, const MapList& map_list){
+        // Spawn points from map jumps have a another algorithm.
+        if (record.from_script){
+            return map_list.at(record.field_id) + "_" + record.entity_name + "_"
+              + record.script_function_name + "_addr_"
+              + std::to_string(record.gateway_index_or_map_jump_address);
+        }
+        // Must also include the gateway index for the case where 2 fields have more than one door
+        // linking to each other.
+        return "Spawn_" + map_list.at(record.field_id) + "_"
+          + std::to_string(record.gateway_index_or_map_jump_address);
+    }
+}
+
+FieldMapWriter::FieldMapWriter(
+  const std::string& data_dir, const MapList& map_list, const FieldSpawnPointsMap& spawn_points,
+  const FieldScaleFactorMap& scale_factors, ModelsAndAnimationsDb& used_models,
+  std::function<void(std::string)> log_output_line
+):
+  data_dir_(data_dir), map_list_(map_list), spawn_points_(spawn_points),
+  scale_factors_(scale_factors), used_models_(used_models), write_output_line_(log_output_line)
+{}
+
+void FieldMapWriter::WriteMap(
+  const VGears::FLevelFilePtr& field, const FieldDecompiler::DecompiledScript& decompiled
+){
+    TiXmlDocument doc;
+    std::unique_ptr<TiXmlElement> map(new TiXmlElement("map"));
+    WriteFileLinks(field->getName(), *map);
+    // Forward direction (angle player moves when "up" is pressed)
+    std::unique_ptr<TiXmlElement> forward_direction(new TiXmlElement("movement_rotation"));
+    forward_direction->SetAttribute("degree", std::to_string(field->GetTriggers()->MovementRotation()));
+    map->LinkEndChild(forward_direction.release());
+    WriteEncounters(field->GetRawEncounter(), *map);
+    const Ogre::Vector3 first_entity_point = WriteEntityPoints(field, *map);
+    WriteEntities(field, decompiled, first_entity_point, *map);
+    WriteTriggerLines(field, *map);
+    WriteTracks(field, *map);
+    doc.LinkEndChild(map.release());
+    doc.SaveFile(data_dir_ + "/" + FieldData::MAPS_DIR + "/" + field->getName() + "/map.xml");
+}
+
+void FieldMapWriter::WriteWalkmesh(const VGears::FLevelFilePtr& field){
+    const VGears::WalkmeshFilePtr& walkmesh = field->GetWalkmesh();
+    // Scripts, gateways and the camera use the field's scale, so the walkmesh must too.
+    const float field_scale
+      = FieldData::ScaleFactor(scale_factors_, FieldData::FieldId(field->getName(), map_list_));
+    TiXmlDocument doc;
+    std::unique_ptr<TiXmlElement> walkmesh_element(new TiXmlElement("walkmesh"));
+    for (const VGears::WalkmeshFile::Triangle& triangle : walkmesh->GetTriangles()){
+        std::unique_ptr<TiXmlElement> element(new TiXmlElement("triangle"));
+        element->SetAttribute("a", Ogre::StringConverter::toString(triangle.a / field_scale));
+        element->SetAttribute("b", Ogre::StringConverter::toString(triangle.b / field_scale));
+        element->SetAttribute("c", Ogre::StringConverter::toString(triangle.c / field_scale));
+        element->SetAttribute("a_b", std::to_string(triangle.access_side[0]));
+        element->SetAttribute("b_c", std::to_string(triangle.access_side[1]));
+        element->SetAttribute("c_a", std::to_string(triangle.access_side[2]));
+        walkmesh_element->LinkEndChild(element.release());
+    }
+    doc.LinkEndChild(walkmesh_element.release());
+    doc.SaveFile(data_dir_ + "/" + FieldData::MAPS_DIR + "/" + field->getName() + "/wm.xml");
+}
+
+std::vector<int> FieldMapWriter::ExtractMusicTrackIds(const std::vector<u8>& raw_script){
+    std::vector<int> tracks;
+    for (size_t i = 0; i + 4 < raw_script.size(); i ++){
+        if (
+          raw_script[i] == 'A' && raw_script[i + 1] == 'K'
+          && raw_script[i + 2] == 'A' && raw_script[i + 3] == 'O'
+        ){
+            tracks.push_back(static_cast<int>(raw_script[i + 4]) - 2);
+        }
+    }
+    return tracks;
+}
+
+void FieldMapWriter::WriteFileLinks(const std::string& field_name, TiXmlElement& map){
+    map.LinkEndChild(CreateFileLink("script", field_name + "/script.lua").release());
+    map.LinkEndChild(CreateFileLink("background2d", field_name + "/bg.xml").release());
+    map.LinkEndChild(CreateFileLink("texts", field_name + "/text.xml").release());
+    map.LinkEndChild(CreateFileLink("walkmesh", field_name + "/wm.xml").release());
+}
+
+void FieldMapWriter::WriteEncounters(const std::vector<u8>& raw_encounter, TiXmlElement& map){
+    std::unique_ptr<TiXmlElement> encounters(new TiXmlElement("encounters"));
+    bool any_table = false;
+    for (int table = 0; table < 2 && raw_encounter.size() >= static_cast<size_t>(24 * (table + 1)); table ++){
+        const u8* data = raw_encounter.data() + 24 * table;
+        if (data[0] == 0) continue;
+        std::unique_ptr<TiXmlElement> xml_table(new TiXmlElement("table"));
+        xml_table->SetAttribute("id", table + 1);
+        xml_table->SetAttribute("rate", static_cast<int>(data[1]));
+        for (int e = 0; e < 10; e ++){
+            const unsigned int value = data[2 + 2 * e] | (data[3 + 2 * e] << 8);
+            const int battle = value & 0x3FF;
+            const int probability = value >> 10;
+            if (probability == 0) continue;
+            std::unique_ptr<TiXmlElement> encounter(new TiXmlElement(e < 6 ? "battle" : "special"));
+            encounter->SetAttribute("id", battle);
+            encounter->SetAttribute("probability", probability);
+            xml_table->LinkEndChild(encounter.release());
+        }
+        encounters->LinkEndChild(xml_table.release());
+        any_table = true;
+    }
+    if (any_table) map.LinkEndChild(encounters.release());
+}
+
+Ogre::Vector3 FieldMapWriter::WriteEntityPoints(const VGears::FLevelFilePtr& field, TiXmlElement& map){
+    const size_t field_id = FieldData::FieldId(field->getName(), map_list_);
+    Ogre::Vector3 first_entity_point = Ogre::Vector3::ZERO;
+    // The gateways and map jumps of the other fields that lead to this one. If there are none, no
+    // other field has doors to this one.
+    auto spawn_iterator = spawn_points_.find(static_cast<u16>(field_id));
+    if (spawn_iterator == std::end(spawn_points_)) return first_entity_point;
+    const float scale = FieldData::ScaleFactor(scale_factors_, field_id);
+    const auto& triangles = field->GetWalkmesh()->GetTriangles();
+    for (const SpawnPointDb::Record& record : spawn_iterator->second.gateways_to_this_field){
+        const VGears::TriggersFile::Gateway& gateway = record.gateway;
+        std::unique_ptr<TiXmlElement> entity_point(new TiXmlElement("entity_point"));
+        entity_point->SetAttribute("name", SpawnPointName(record, map_list_));
+        const float downscaler
+          = 128.0f * FieldData::ScaleFactor(scale_factors_, gateway.destination_field_id);
+        const float x = gateway.destination.x / downscaler;
+        const float y = gateway.destination.y / downscaler;
+        const unsigned int triangle = FindEntranceTriangle(field, record, x, y);
+        const Ogre::Vector3 position(x, y, triangles.at(triangle).a.z / scale);
+        if (position != Ogre::Vector3::ZERO && first_entity_point == Ogre::Vector3::ZERO){
+            first_entity_point = position;
+        }
+        entity_point->SetAttribute("position", Ogre::StringConverter::toString(position));
+        const float rotation = (360.0f * static_cast<float>(gateway.dir)) / 256.0f;
+        entity_point->SetAttribute("rotation", std::to_string(rotation));
+        map.LinkEndChild(entity_point.release());
+    }
+    return first_entity_point;
+}
+
+unsigned int FieldMapWriter::FindEntranceTriangle(
+  const VGears::FLevelFilePtr& field, const SpawnPointDb::Record& record, const float x, const float y
+){
+    const VGears::TriggersFile::Gateway& gateway = record.gateway;
+    const unsigned int triangle_index = static_cast<unsigned int>(gateway.destination.z);
+    const auto& triangles = field->GetWalkmesh()->GetTriangles();
+    if (triangle_index < triangles.size()) return triangle_index;
+    const float scale
+      = FieldData::ScaleFactor(scale_factors_, FieldData::FieldId(field->getName(), map_list_));
+    const auto side = [x, y](const Ogre::Vector3& a, const Ogre::Vector3& b){
+        return (x - b.x) * (a.y - b.y) - (a.x - b.x) * (y - b.y);
+    };
+    for (size_t t = 0; t < triangles.size(); t ++){
+        const Ogre::Vector3 a = triangles[t].a / scale, b = triangles[t].b / scale;
+        const Ogre::Vector3 c = triangles[t].c / scale;
+        const float d1 = side(a, b), d2 = side(b, c), d3 = side(c, a);
+        const bool negative = d1 < 0 || d2 < 0 || d3 < 0, positive = d1 > 0 || d2 > 0 || d3 > 0;
+        if (!(negative && positive)) return static_cast<unsigned int>(t);
+    }
+    // Only reported when the position is not on the walkmesh either: those jumps are of the debug
+    // rooms (blackbg1, blackbg4) or of scenes that place the player themselves.
+    const std::string source = record.from_script
+      ? "the script " + record.entity_name + ":" + record.script_function_name + " (address "
+        + std::to_string(record.gateway_index_or_map_jump_address) + ")"
+      : "the door " + std::to_string(record.gateway_index_or_map_jump_address);
+    write_output_line_(
+      "[WARNING] In field " + field->getName() + ": the entrance from "
+      + map_list_.at(record.field_id) + " (" + source + ") is on the walkmesh triangle "
+      + std::to_string(triangle_index) + ", which the walkmesh doesn't have (it has "
+      + std::to_string(triangles.size()) + "), at (" + std::to_string(gateway.destination.x) + ", "
+      + std::to_string(gateway.destination.y) + "), which is not on the walkmesh."
+    );
+    return 0;
+}
+
+void FieldMapWriter::WriteEntities(
+  const VGears::FLevelFilePtr& field, const FieldDecompiler::DecompiledScript& decompiled,
+  const Ogre::Vector3& first_entity_point, TiXmlElement& map
+){
+    const size_t field_id = FieldData::FieldId(field->getName(), map_list_);
+    std::vector<std::pair<uint, std::unique_ptr<TiXmlElement>>> ordered_entities;
+    // The lines. Their entities are not written again as scripts.
+    std::vector<std::string> line_entities;
+    const float line_scale = LINE_SCALE_FACTOR / FieldData::ScaleFactor(scale_factors_, field_id);
+    for (const FieldDecompiler::Line& line : decompiled.lines){
+        line_entities.push_back(line.name);
+        ordered_entities.emplace_back(
+          line.index,
+          CreateTriggerLine(line.name, LinePoint(line.point_a, line_scale), LinePoint(line.point_b, line_scale))
+        );
+    }
+    const VGears::ModelListFilePtr& models = field->GetModelList();
+    for (const FieldDecompiler::FieldEntity& entity : decompiled.entities){
+        if (std::find(line_entities.begin(), line_entities.end(), entity.name) != line_entities.end())
+            continue;
+        if (entity.char_id != -1){
+            ordered_entities.emplace_back(
+              entity.index,
+              CreateModelEntity(entity, models->GetModels().at(entity.char_id), first_entity_point)
+            );
+        }
+        else{
+            std::unique_ptr<TiXmlElement> script(new TiXmlElement("entity_script"));
+            script->SetAttribute("name", entity.name);
+            ordered_entities.emplace_back(entity.index, std::move(script));
+        }
+    }
+    std::stable_sort(
+      ordered_entities.begin(), ordered_entities.end(),
+      [](const auto& a, const auto& b){return a.first < b.first;}
+    );
+    for (auto& ordered : ordered_entities) map.LinkEndChild(ordered.second.release());
+}
+
+std::unique_ptr<TiXmlElement> FieldMapWriter::CreateModelEntity(
+  const FieldDecompiler::FieldEntity& entity, const VGears::ModelListFile::ModelDescription& model,
+  const Ogre::Vector3& first_entity_point
+){
+    auto& animations = used_models_.ModelAnimations(model.hrc_name);
+    for (const auto& animation : model.animations){
+        animations.insert(used_models_.NormalizeAnimationName(animation.name));
+    }
+    std::unique_ptr<TiXmlElement> element(new TiXmlElement("entity_model"));
+    element->SetAttribute("name", entity.name);
+    auto lower_case_hrc_name = model.hrc_name;
+    VGears::StringUtil::toLowerCase(lower_case_hrc_name);
+    element->SetAttribute("file_name", used_models_.ModelMetaDataName(lower_case_hrc_name));
+    element->SetAttribute("index", entity.index);
+    // The position of the player models is where the player ends up if the field is loaded
+    // without an entrance: the first entity point.
+    element->SetAttribute(
+      "position",
+      Ogre::StringConverter::toString(
+        model.type == VGears::ModelListFile::PLAYER ? first_entity_point : Ogre::Vector3::ZERO
+      )
+    );
+    element->SetAttribute("direction", "0");
+    // TODO: This isn't quite right, the models animation translation seems to be inverted?
+    element->SetAttribute("scale", "0.03125 0.03125 0.03125");
+    element->SetAttribute("root_orientation", "0.7071067811865476 0.7071067811865476 0 0");
+    return element;
+}
+
+void FieldMapWriter::WriteTriggerLines(const VGears::FLevelFilePtr& field, TiXmlElement& map){
+    const size_t field_id = FieldData::FieldId(field->getName(), map_list_);
+    const float downscaler = 128.0f * FieldData::ScaleFactor(scale_factors_, field_id);
+    const VGears::TriggersFilePtr& triggers = field->GetTriggers();
+    const auto& gateways = triggers->GetGateways();
+    for (size_t i = 0; i < gateways.size(); i ++){
+        const VGears::TriggersFile::Gateway& gateway = gateways[i];
+        if (gateway.destination_field_id == FieldData::INACTIVE_GATEWAY_ID) continue;
+        map.LinkEndChild(CreateTriggerLine(
+          "Gateway" + std::to_string(i), TriggerPoint(gateway.exit_line[0], downscaler),
+          TriggerPoint(gateway.exit_line[1], downscaler)
+        ).release());
+    }
+    // Background triggers (doors and similar that change tiles).
+    const auto& bg_triggers = triggers->GetBackgroundTriggers();
+    for (size_t i = 0; i < bg_triggers.size(); i ++){
+        const VGears::TriggersFile::Trigger& trigger = bg_triggers[i];
+        if (!FieldData::IsBackgroundTriggerUsed(trigger)) continue;
+        map.LinkEndChild(CreateTriggerLine(
+          "BgTrigger" + std::to_string(i), TriggerPoint(trigger.trigger_line[0], downscaler),
+          TriggerPoint(trigger.trigger_line[1], downscaler)
+        ).release());
+    }
+}
+
+void FieldMapWriter::WriteTracks(const VGears::FLevelFilePtr& field, TiXmlElement& map){
+    const std::vector<int> tracks = ExtractMusicTrackIds(field->GetRawScript());
+    std::unique_ptr<TiXmlElement> xml_tracks(new TiXmlElement("tracks"));
+    for (int t = 0; t < tracks.size(); t ++){
+        std::unique_ptr<TiXmlElement> track(new TiXmlElement("track"));
+        track->SetAttribute("id", t);
+        track->SetAttribute("track_id", tracks[t]);
+        xml_tracks->LinkEndChild(track.release());
+    }
+    map.LinkEndChild(xml_tracks.release());
+}

+ 209 - 0
src/installer/extractors/FieldMapWriter.h

@@ -0,0 +1,209 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#pragma once
+
+#include <functional>
+#include <string>
+#include <vector>
+#include <OgreVector3.h>
+#include <tinyxml.h>
+#include "decompiler/field/FieldDecompiler.h"
+#include "formats/field/FLevelFile.h"
+#include "FieldDataTypes.h"
+#include "ModelsAndAnimationsDb.h"
+
+/**
+ * Writes the map file of a field (map.xml), which links the other files of the field and has its
+ * entities, and the walkmesh (wm.xml).
+ */
+class FieldMapWriter{
+
+    public:
+
+        /**
+         * Constructor.
+         *
+         * @param[in] data_dir The game data folder.
+         * @param[in] map_list The names of the fields, by ID.
+         * @param[in] spawn_points The spawn points of every field.
+         * @param[in] scale_factors The scale factors of the fields.
+         * @param[in,out] used_models The models that the fields use, and their animations. The
+         * models of each field are added to it.
+         * @param[in] log_output_line Function to write a line to the installation log.
+         */
+        FieldMapWriter(
+          const std::string& data_dir, const MapList& map_list,
+          const FieldSpawnPointsMap& spawn_points, const FieldScaleFactorMap& scale_factors,
+          ModelsAndAnimationsDb& used_models, std::function<void(std::string)> log_output_line
+        );
+
+        /**
+         * Writes the map file of a field.
+         *
+         * @param[in] field The field.
+         * @param[in] decompiled The decompiled script of the field, with its lines and entities.
+         */
+        void WriteMap(const VGears::FLevelFilePtr& field, const FieldDecompiler::DecompiledScript& decompiled);
+
+        /**
+         * Writes the walkmesh of a field.
+         *
+         * @param[in] field The field.
+         */
+        void WriteWalkmesh(const VGears::FLevelFilePtr& field);
+
+        /**
+         * Finds the IDs of the music tracks of a field.
+         *
+         * Each "AKAO" string in the script section of the field is followed by the ID of a track.
+         *
+         * @param[in] raw_script The script section of the field.
+         * @return The IDs of the tracks, in the order of the field.
+         */
+        static std::vector<int> ExtractMusicTrackIds(const std::vector<u8>& raw_script);
+
+    private:
+
+        /**
+         * Factor of the lines of the scripts, before the scale of the field.
+         */
+        static const float LINE_SCALE_FACTOR;
+
+        /**
+         * Writes the elements that link the other files of the field.
+         *
+         * @param[in] field_name Name of the field.
+         * @param[out] map The map element.
+         */
+        static void WriteFileLinks(const std::string& field_name, TiXmlElement& map);
+
+        /**
+         * Writes the random encounters of a field.
+         *
+         * The section has two tables of 24 bytes: enabled (1 byte), rate (1 byte), six standard
+         * and four special encounters (16 bits each, battle ID in the lower 10 bits and
+         * probability, out of 64, in the upper 6), and 2 bytes of padding.
+         *
+         * @param[in] raw_encounter The encounter section of the field.
+         * @param[out] map The map element.
+         */
+        static void WriteEncounters(const std::vector<u8>& raw_encounter, TiXmlElement& map);
+
+        /**
+         * Writes the points where the player enters the field, from doors and scripts of other
+         * fields.
+         *
+         * @param[in] field The field.
+         * @param[out] map The map element.
+         * @return The position of the first entrance that is not at the origin, or the origin.
+         */
+        Ogre::Vector3 WriteEntityPoints(const VGears::FLevelFilePtr& field, TiXmlElement& map);
+
+        /**
+         * Finds the walkmesh triangle of an entrance.
+         *
+         * The Z coordinate of the destination of an entrance is the index of the triangle. Some
+         * map jumps of the original scripts have a triangle that is not in the walkmesh (pillar_3
+         * to mds6_22): then the one under the position is used.
+         *
+         * @param[in] field The field.
+         * @param[in] record The entrance.
+         * @param[in] x X coordinate of the entrance, in the units of the walkmesh.
+         * @param[in] y Y coordinate of the entrance, in the units of the walkmesh.
+         * @return The index of the triangle. If the position is not on the walkmesh either, 0.
+         */
+        unsigned int FindEntranceTriangle(
+          const VGears::FLevelFilePtr& field, const SpawnPointDb::Record& record,
+          const float x, const float y
+        );
+
+        /**
+         * Writes the lines, scripts and models of a field.
+         *
+         * They are written in the order of the original field: the engine starts their scripts in
+         * that order, and some scripts depend on it (a script that clears the background areas
+         * has to start before the doors that set them).
+         *
+         * @param[in] field The field.
+         * @param[in] decompiled The decompiled script of the field.
+         * @param[in] first_entity_point Where the player models are placed.
+         * @param[out] map The map element.
+         */
+        void WriteEntities(
+          const VGears::FLevelFilePtr& field, const FieldDecompiler::DecompiledScript& decompiled,
+          const Ogre::Vector3& first_entity_point, TiXmlElement& map
+        );
+
+        /**
+         * Creates the element of an entity with a model, and adds the model and its animations to
+         * the used models.
+         *
+         * @param[in] entity The entity.
+         * @param[in] model The model of the entity.
+         * @param[in] first_entity_point Where the player models are placed.
+         * @return The element of the entity.
+         */
+        std::unique_ptr<TiXmlElement> CreateModelEntity(
+          const FieldDecompiler::FieldEntity& entity,
+          const VGears::ModelListFile::ModelDescription& model, const Ogre::Vector3& first_entity_point
+        );
+
+        /**
+         * Writes the lines of the gateways and of the background triggers in use.
+         *
+         * @param[in] field The field.
+         * @param[out] map The map element.
+         */
+        void WriteTriggerLines(const VGears::FLevelFilePtr& field, TiXmlElement& map);
+
+        /**
+         * Writes the music tracks of a field.
+         *
+         * @param[in] field The field.
+         * @param[out] map The map element.
+         */
+        static void WriteTracks(const VGears::FLevelFilePtr& field, TiXmlElement& map);
+
+        /**
+         * The game data folder.
+         */
+        std::string data_dir_;
+
+        /**
+         * The names of the fields, by ID.
+         */
+        const MapList& map_list_;
+
+        /**
+         * The spawn points of every field.
+         */
+        const FieldSpawnPointsMap& spawn_points_;
+
+        /**
+         * The scale factors of the fields.
+         */
+        const FieldScaleFactorMap& scale_factors_;
+
+        /**
+         * The models that the fields use, and their animations.
+         */
+        ModelsAndAnimationsDb& used_models_;
+
+        /**
+         * Function to write a line to the installation log.
+         */
+        std::function<void(std::string)> write_output_line_;
+};

+ 193 - 0
src/installer/extractors/FieldModelInstaller.cpp

@@ -0,0 +1,193 @@
+/*
+ * 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 <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/File.h"
+#include "formats/FF7NameLookup.h"
+#include "formats/lgp/LGPArchive.h"
+#include "formats/model/AFileManager.h"
+#include "formats/model/HRCFileManager.h"
+#include "installer/formats/TexFile.h"
+#include "installer/tables/ModelMaterials.h"
+#include "FieldDataTypes.h"
+#include "FieldModelInstaller.h"
+
+FieldModelInstaller::FieldModelInstaller(
+  const DiskImage& disk_image, const std::string& output_dir, const std::string& data_dir,
+  ModelsAndAnimationsDb& used_models, std::function<void(std::string)> log_output_line
+):
+  disk_image_(disk_image), output_dir_(output_dir), data_dir_(data_dir), used_models_(used_models),
+  write_output_line_(log_output_line)
+{}
+
+std::vector<std::string> FieldModelInstaller::Initialize(){
+    ExtractModelFiles();
+    // Ogre indexes a resource location when it is added, so files written afterwards are not
+    // found until the location is registered again. On a clean install the folder was empty when
+    // it was first added.
+    Ogre::ResourceGroupManager& res_mgr = Ogre::ResourceGroupManager::getSingleton();
+    res_mgr.removeResourceLocation(TempDir(), "FFVII");
+    res_mgr.addResourceLocation(TempDir(), "FileSystem", "FFVII", true, true);
+    std::vector<std::string> models;
+    for (const auto& model : used_models_.map) models.push_back(model.first);
+    return models;
+}
+
+void FieldModelInstaller::ConvertModel(const std::string& model_name){
+    auto model = used_models_.map.find(model_name);
+    if (model == used_models_.map.end()){
+        write_output_line_("[ERROR] Model " + model_name + " is not used by any field.");
+        return;
+    }
+    VGears::HRCFileManager& hrc_manager = VGears::HRCFileManager::GetSingleton();
+    try{
+        Ogre::ResourcePtr hrc = hrc_manager.load(model->first, "FFVII");
+        Ogre::String base_name;
+        VGears::StringUtil::splitBase(model->first, 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());
+        const Ogre::AxisAlignedBox bind_bounds = mesh->getBounds();
+        Ogre::AxisAlignedBox translation_bounds(Ogre::Vector3::ZERO, Ogre::Vector3::ZERO);
+        for (const auto& animation_name : model->second){
+            VGears::AFilePtr animation = VGears::AFileManager::GetSingleton()
+              .load(animation_name, "FFVII").staticCast<VGears::AFile>();
+            // Convert the FF7 name to a more readable name set in the meta data.
+            VGears::StringUtil::splitBase(animation_name, base_name);
+            animation->AddTo(skeleton, VGears::NameLookup::Animation(base_name), true);
+            translation_bounds.merge(animation->GetRootTranslationBounds(true));
+        }
+        ExtendBounds(mesh, bind_bounds, translation_bounds);
+        ExportMesh(ModelsDir(), mesh);
+        // Models can share a skeleton name with different bones. Drop the model (and its skeleton
+        // and mesh) so the next one doesn't reuse them.
+        hrc_manager.remove(model->first, "FFVII");
+    }
+    catch (const Ogre::Exception& ex){
+        if (hrc_manager.resourceExists(model->first, "FFVII")) hrc_manager.remove(model->first, "FFVII");
+        write_output_line_("[ERROR] Ogre exception converting model " + model->first + ": " + ex.what());
+    }
+    catch (const std::exception& ex){
+        if (hrc_manager.resourceExists(model->first, "FFVII")) hrc_manager.remove(model->first, "FFVII");
+        write_output_line_("[ERROR] Exception converting model " + model->first + ": " + ex.what());
+    }
+}
+
+void FieldModelInstaller::ExtractModelFiles(){
+    const std::string path = *disk_image_.filePath("data/field/char.lgp");
+    // Read the list of files as an archive, and their contents as a file.
+    VGears::LGPArchive char_lgp(path, "LGP");
+    char_lgp.open(path, true);
+    char_lgp.load();
+    File char_file(path);
+    const Ogre::StringVectorPtr file_list = char_lgp.list(true, true);
+    const VGears::LGPArchive::FileList files = char_lgp.GetFiles();
+    for (size_t i = 0; i < file_list->size(); i ++){
+        const VGears::LGPArchive::FileEntry& entry = files.at(i);
+        std::fstream out;
+        out.open(TempDir() + entry.file_name, std::ios::out);
+        char_file.SetOffset(entry.data_offset);
+        for (int j = 0; j < entry.data_size; j ++) out << char_file.readU8();
+        out.close();
+    }
+}
+
+void FieldModelInstaller::ExtendBounds(
+  const Ogre::MeshPtr& mesh, const Ogre::AxisAlignedBox& bind_bounds,
+  const Ogre::AxisAlignedBox& translation_bounds
+){
+    if (!bind_bounds.isFinite()) return;
+    const Ogre::AxisAlignedBox animated_bounds(
+      bind_bounds.getMinimum() + translation_bounds.getMinimum(),
+      bind_bounds.getMaximum() + translation_bounds.getMaximum()
+    );
+    mesh->_setBounds(animated_bounds, false);
+    mesh->_setBoundingSphereRadius(std::max(
+      mesh->getBoundingSphereRadius(),
+      animated_bounds.getCenter().length() + animated_bounds.getHalfSize().length()
+    ));
+}
+
+void FieldModelInstaller::ExportMesh(const std::string& outdir, const Ogre::MeshPtr& mesh){
+    VGears::String base_mesh_name;
+    VGears::StringUtil::splitFull(mesh->getName(), base_mesh_name);
+    MakeMaterialsUnique(mesh, base_mesh_name);
+    Ogre::SkeletonPtr skeleton(mesh->getSkeleton());
+    Ogre::SkeletonSerializer skeleton_serializer;
+    skeleton_serializer.exportSkeleton(skeleton.getPointer(), outdir + base_mesh_name + ".skeleton");
+    mesh->setSkeletonName(base_mesh_name + ".skeleton");
+    Ogre::MeshSerializer mesh_serializer;
+    mesh_serializer.exportMesh(mesh.getPointer(), outdir + mesh->getName());
+    Ogre::MaterialSerializer material_serializer;
+    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);
+                }
+            }
+        }
+        if (std::count(materials_.begin(), materials_.end(), sub_mesh->getMaterialName()) == 0){
+            material_serializer.queueForExport(material);
+            materials_.push_back(sub_mesh->getMaterialName());
+        }
+    }
+    material_serializer.exportQueued(outdir + base_mesh_name + VGears::EXT_MATERIAL);
+}
+
+void FieldModelInstaller::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 battle model (its texture is then a png in another folder). There is
+    // nothing to convert in that case.
+    if (!boost::filesystem::exists(TempDir() + unit.getTextureName())){
+        write_output_line_(
+          "[WARNING] Texture " + unit.getTextureName() + " of model " + base_mesh_name
+          + " not found; skipping it."
+        );
+        return;
+    }
+    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);
+}
+
+std::string FieldModelInstaller::TempDir() const{return output_dir_ + "temp/char/";}
+
+std::string FieldModelInstaller::ModelsDir() const{return data_dir_ + FieldData::MODELS_DIR + "/";}

+ 136 - 0
src/installer/extractors/FieldModelInstaller.h

@@ -0,0 +1,136 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#pragma once
+
+#include <functional>
+#include <string>
+#include <vector>
+#include <OgreMesh.h>
+#include "installer/formats/DiskImage.h"
+#include "ModelsAndAnimationsDb.h"
+
+/**
+ * Converts the models that the fields use, with their animations and textures.
+ */
+class FieldModelInstaller{
+
+    public:
+
+        /**
+         * Constructor.
+         *
+         * @param[in] disk_image The image of the game disk.
+         * @param[in] output_dir The installation folder.
+         * @param[in] data_dir The game data folder.
+         * @param[in] used_models The models that the fields use, and their animations.
+         * @param[in] log_output_line Function to write a line to the installation log.
+         */
+        FieldModelInstaller(
+          const DiskImage& disk_image, const std::string& output_dir, const std::string& data_dir,
+          ModelsAndAnimationsDb& used_models, std::function<void(std::string)> log_output_line
+        );
+
+        /**
+         * Extracts the files of the models and lists the models to convert.
+         *
+         * @return The names of the models that the fields use.
+         */
+        std::vector<std::string> Initialize();
+
+        /**
+         * Converts a model and the animations that the fields use.
+         *
+         * Errors are written to the log.
+         *
+         * @param[in] model_name Name of the model, as returned by {@see Initialize}.
+         */
+        void ConvertModel(const std::string& model_name);
+
+    private:
+
+        /**
+         * Extracts the files of char.lgp to the temporary folder of the models.
+         */
+        void ExtractModelFiles();
+
+        /**
+         * Makes the bounds of a mesh hold the positions the animations move its root to.
+         *
+         * @param[in,out] mesh The mesh.
+         * @param[in] bind_bounds The bounds of the mesh, without animations.
+         * @param[in] translation_bounds The bounds of the root translations of the animations.
+         */
+        static void ExtendBounds(
+          const Ogre::MeshPtr& mesh, const Ogre::AxisAlignedBox& bind_bounds,
+          const Ogre::AxisAlignedBox& translation_bounds
+        );
+
+        /**
+         * Exports a mesh, with its skeleton, materials and textures.
+         *
+         * @param[in] outdir Folder to export to.
+         * @param[in] mesh The mesh.
+         */
+        void ExportMesh(const std::string& outdir, const Ogre::MeshPtr& mesh);
+
+        /**
+         * Converts the texture of a texture unit and makes the unit use the converted one.
+         *
+         * @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 image of the game disk.
+         */
+        DiskImage disk_image_;
+
+        /**
+         * The installation folder.
+         */
+        std::string output_dir_;
+
+        /**
+         * The game data folder.
+         */
+        std::string data_dir_;
+
+        /**
+         * The models that the fields use, and their animations.
+         */
+        ModelsAndAnimationsDb& used_models_;
+
+        /**
+         * Function to write a line to the installation log.
+         */
+        std::function<void(std::string)> write_output_line_;
+
+        /**
+         * The materials already exported.
+         */
+        std::vector<std::string> materials_;
+};

+ 312 - 0
src/installer/extractors/FieldScriptFormatters.h

@@ -0,0 +1,312 @@
+/*
+ * 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 <iostream>
+#include <string>
+#include <vector>
+#include "decompiler/field/FieldScriptFormatter.h"
+#include "formats/FF7NameLookup.h"
+#include "formats/model/FF7ModelListFile.h"
+#include "FieldDataTypes.h"
+
+/**
+ * Names of the fields, entities, variables and functions shared by the field script formatters.
+ */
+class BaseFF7FieldScriptFormatter : public FieldScriptFormatter{
+
+    public:
+
+        /**
+         * Constructor.
+         *
+         * @param[in] field_name The field name.
+         * @param[in] field_id_to_name_lookup Field name lookup table to use.
+         * @param[in] spawn_points The list of spawn points.
+         */
+        BaseFF7FieldScriptFormatter(
+          const std::string& field_name, const std::vector<std::string>& field_id_to_name_lookup,
+          FieldSpawnPointsMap& spawn_points
+        ) : field_name_(field_name), field_id_to_name_lookup_(field_id_to_name_lookup), spawn_points_(spawn_points)
+        {}
+
+        /**
+         * Composes a spawn point name
+         *
+         * The name will have the format
+         * {FIELD_NAME}_{ENTITY}_{FUNCTION_NAME}_addr_{ADDRESS}
+         *
+         * @param[in] map_id Unused.
+         * @param[in] entity Entity name.
+         * @param[in] function_name Name of the function.
+         * @param[in] address @todo Understand and document.
+         * @return The composed spawn point name.
+         */
+        virtual std::string GetSpawnPointName(
+          unsigned int map_id, const std::string& entity, const std::string& function_name, unsigned int address
+        ) override{
+            return field_name_ + "_" + entity + "_" + function_name + "_addr_" + std::to_string(address);
+        }
+
+        /**
+         * Retrieves a map name from it's ID.
+         *
+         * @param[in] map_id The map ID.
+         * @return The map name.
+         */
+        virtual std::string GetMapName(unsigned int map_id) override{return field_id_to_name_lookup_[map_id];}
+
+        /**
+         * Retrieves a user friendly variable name.
+         *
+         * @param[in] bank Variable bank.
+         * @param[in] addr Variable address.
+         * @return Friendly name for the variable, or an empty string if it
+         * doesn't have one assigned.
+         */
+        virtual std::string GetFriendlyVarName(unsigned int bank, unsigned int addr) override{
+            return VGears::NameLookup::FieldScriptVarName(bank, addr);
+        }
+
+        /**
+         * Retrieves a user friendly entity name.
+         *
+         * @param[in] entity Entity name.
+         * @return Friendly name for the entity, or the current name if it
+         * doesn't have one assigned.
+         */
+        virtual std::string GetFriendlyEntityName(const std::string& entity) override{
+            return VGears::NameLookup::FieldScriptEntityName(entity);
+        }
+
+        /**
+         * Retrieves a user friendly character name.
+         *
+         * @param[in] char_id Character ID.
+         * @return Friendly name for the entity, or an empty string if it
+         * doesn't have one assigned.
+         */
+        virtual std::string GetFriendlyCharName(int char_id) override{return VGears::NameLookup::CharName(char_id);}
+
+        /**
+         * Retrieves a user friendly function name.
+         *
+         * @param[in] entity The name of the entity the function belongs to.
+         * @param[in] function_name Function name.
+         * @return Friendly name for the function, or the current name if it
+         * doesn't have one assigned.
+         */
+        virtual std::string GetFriendlyFunctionName(
+          const std::string& entity, const std::string& function_name
+        ) override{
+            return VGears::NameLookup::FieldScriptFunctionName(field_name_, entity, function_name);
+        }
+
+        /**
+         * Retrieves the header comment for a function in an entity.
+         *
+         * @param[in] entity The name of the entity the function belongs to.
+         * @param[in] function_name Function name.
+         * @return Friendly comment for the function, or an empty string if it
+         * doesn't have one assigned.
+         */
+        virtual std::string GetFunctionComment(const std::string& entity, const std::string& function_name) override{
+            return VGears::NameLookup::FieldScriptFunctionComment(field_name_, entity, function_name);
+        }
+
+    protected:
+
+        /**
+         * The field name.
+         */
+        std::string field_name_;
+
+        /**
+         * The list of spawn points.
+         */
+        FieldSpawnPointsMap& spawn_points_;
+
+        /**
+         * Look up table relatingfield IDs and names.
+         */
+        const std::vector<std::string>& field_id_to_name_lookup_;
+};
+
+/**
+ * Handles the script gateway collection.
+ */
+class FF7FieldScriptGatewayCollector : public BaseFF7FieldScriptFormatter{
+
+    public:
+
+        /**
+         * Constructor.
+         */
+        FF7FieldScriptGatewayCollector(
+          const std::string& field_name, const std::vector<std::string>& field_id_to_name_lookup,
+          FieldSpawnPointsMap& spawn_points, size_t this_field_id
+        ) : BaseFF7FieldScriptFormatter(field_name,field_id_to_name_lookup, spawn_points), field_id_(this_field_id)
+        {}
+
+        /**
+         * Adds an spawn point.
+         *
+         * If the spawn is new, a new record will be added to the spawn point
+         * database. If it was already there, update the record to add the
+         * origin.
+         *
+         * @param[in] map_id The target map ID.
+         * @param[in] entity The entity that acts as the spawn point.
+         * @param[in] function_name The spawn function name.
+         * @param[in] address @todo Understand and document.
+         * @param[in] x X coordinate of the field target at which to spawn.
+         * @param[in] y Y coordinate of the field target at which to spawn.
+         * @param[in] z Z coordinate of the field target at which to spawn.
+         * @param[in] angle Orientation at which to spawn.
+         */
+        virtual void AddSpawnPoint(
+          unsigned int map_id, const std::string& entity, const std::string& function_name,
+          unsigned int address, int x, int y, int z, int angle
+        ) override {
+            SpawnPointDb::Record record;
+            record.from_script = true;
+            record.field_id = static_cast<u16>(field_id_);
+            record.gateway = {};
+            record.gateway.destination_field_id = static_cast<u16>(map_id);
+            record.gateway.destination.x = x;
+            record.gateway.destination.y = y;
+            record.gateway.destination.z = z;
+            record.gateway.dir = angle;
+            record.entity_name = entity;
+            record.script_function_name = function_name;
+            record.gateway_index_or_map_jump_address = address;
+            FieldData::AddSpawnPoint(spawn_points_, record);
+        }
+
+    private:
+
+        /**
+         * The field map ID.
+         */
+        size_t field_id_;
+
+};
+
+/**
+ * Handles the formatting of field scripts.
+ */
+class FF7FieldScriptFormatter : public BaseFF7FieldScriptFormatter{
+
+    public:
+
+        /**
+         * Constructor.
+         *
+         * @param[in] field_name The field name.
+         * @param[in] models The list of field models.
+         * @param[in] field_id_to_name_lookup Field name lookup table to use.
+         * @param[in] spawn_points The list of spawn points.
+         */
+        FF7FieldScriptFormatter(
+          const std::string& field_name, const VGears::ModelListFilePtr& models,
+          const std::vector<std::string>& field_id_to_name_lookup, FieldSpawnPointsMap& spawn_points
+        ) : BaseFF7FieldScriptFormatter(field_name, field_id_to_name_lookup, spawn_points), model_loader_(models)
+        {}
+
+        // Names an animation, can't return empty
+        /**
+         * Retreieves an animation name from iths ID.
+         *
+         * @param[in] char_id ID of the character the animation belogs to.
+         * @param[in] id Animation ID.
+         * @return The animation name. If there is no name assigned, or it
+         * can't be found, a string with the animation ID.
+         */
+        virtual std::string GetFriendlyAnimationName(int char_id, int id) override{
+            // Get the animation file name, then look up the friendly name of
+            // the "raw" animation.
+            if (static_cast<unsigned int>(char_id) >= model_loader_->GetModels().size()){
+                std::cerr << "FF7FieldScriptFormatter::AnimationName ERROR:"
+                  << "Char ID " << char_id << " out of bounds" << std::endl;
+                return std::to_string(id);
+            }
+            const auto& model_info = model_loader_->GetModels().at(char_id);
+            if (static_cast<unsigned int>(id) >= model_info.animations.size()){
+                std::cerr << "FF7FieldScriptFormatter::AnimationName ERROR:" << "In field " << field_name_
+                  << " the model " << model_info.name << " animation with ID " << id << " is out of bounds ("
+                  << model_info.animations.size() << ")" << std::endl;
+                return std::to_string(id);
+            }
+            const auto raw_name = model_info.animations.at(id).name;
+            // Trim off ".yos" or whatever extension the model loader adds in.
+            Ogre::String base_name;
+            VGears::StringUtil::splitBase(raw_name, base_name);
+            VGears::StringUtil::toLowerCase(base_name);
+            return VGears::NameLookup::Animation(base_name);
+        }
+
+        /**
+         * Retrieves the animation a model must play when its script doesn't set a default one.
+         *
+         * In the original game a model without a requested animation plays the first one of its
+         * list.
+         *
+         * @param[in] char_id ID of the model, as given to the CHAR opcode.
+         * @return Name of the first animation of the model. An empty string if the model already
+         * has an animation called "Idle", or it has no animations.
+         */
+        virtual std::string GetDefaultAnimationName(int char_id) override{
+            if (static_cast<unsigned int>(char_id) >= model_loader_->GetModels().size()) return "";
+            const auto& animations = model_loader_->GetModels().at(char_id).animations;
+            if (animations.empty()) return "";
+            std::string first;
+            for (size_t i = 0; i < animations.size(); ++ i){
+                Ogre::String base_name;
+                VGears::StringUtil::splitBase(animations[i].name, base_name);
+                VGears::StringUtil::toLowerCase(base_name);
+                const std::string friendly = VGears::NameLookup::Animation(base_name);
+                if (friendly == "Idle") return "";
+                if (i == 0) first = friendly;
+            }
+            return first;
+        }
+
+        /**
+         * Retrieves the animation a model plays when it walks or runs on its own.
+         *
+         * @param[in] char_id ID of the model, as given to the CHAR opcode.
+         * @param[in] index 1 for the walk animation, 2 for the run animation.
+         * @return Name of the animation, or an empty string if the model hasn't got it.
+         */
+        virtual std::string GetMoveAnimationName(int char_id, int index) override{
+            if (char_id < 0 || static_cast<unsigned int>(char_id) >= model_loader_->GetModels().size())
+                return "";
+            const auto& animations = model_loader_->GetModels().at(char_id).animations;
+            if (static_cast<unsigned int>(index) >= animations.size()) return "";
+            Ogre::String base_name;
+            VGears::StringUtil::splitBase(animations[index].name, base_name);
+            VGears::StringUtil::toLowerCase(base_name);
+            return VGears::NameLookup::Animation(base_name);
+        }
+
+    private:
+
+        /**
+         * The field model loader.
+         */
+        const VGears::ModelListFilePtr& model_loader_;
+};

+ 179 - 0
src/installer/extractors/FieldScriptInstaller.cpp

@@ -0,0 +1,179 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <fstream>
+#include <stdexcept>
+#include "FieldScriptFormatters.h"
+#include "FieldScriptInstaller.h"
+
+const std::vector<int> FieldScriptInstaller::TEMPORARY_BANKS{5};
+
+FieldScriptInstaller::FieldScriptInstaller(
+  const std::string& data_dir, const MapList& map_list, FieldSpawnPointsMap& spawn_points,
+  std::function<void(std::string)> log_output_line
+):
+  data_dir_(data_dir), map_list_(map_list), spawn_points_(spawn_points),
+  write_output_line_(log_output_line)
+{}
+
+FieldDecompiler::DecompiledScript FieldScriptInstaller::Install(const VGears::FLevelFilePtr& field){
+    const std::string trigger_scripts = CreateTriggerScripts(field);
+    const VGears::ModelListFilePtr& models = field->GetModelList();
+    FieldDecompiler::DecompiledScript decompiled;
+    FF7FieldScriptFormatter formatter(field->getName(), models, map_list_, spawn_points_);
+    try{
+        const std::vector<u8> raw_script = field->GetRawScript();
+        decompiled = FieldDecompiler::Decompile(
+          field->getName(), raw_script, formatter, trigger_scripts,
+          FieldScriptHeader(static_cast<int>(FieldData::FieldId(field->getName(), map_list_)))
+        );
+        const std::string dir = data_dir_ + "/" + FieldData::MAPS_DIR + "/" + field->getName();
+        std::ofstream script_file(dir + "/script.lua");
+        if (script_file.is_open()){
+            script_file << decompiled.luaScript;
+            WriteTexts(field, raw_script);
+        }
+        else{
+            write_output_line_(
+              "[ERROR] Failed to open script file from field " + field->getName() + " for writing."
+            );
+        }
+    }
+    catch (const ::DecompilerException& ex){
+        write_output_line_(
+          "[ERROR] Internal decompiler error in field " + field->getName() + ": " + ex.what()
+        );
+    }
+    return decompiled;
+}
+
+std::string FieldScriptInstaller::FieldScriptHeader(const int field_id){
+    std::string header = "EntityContainer = {}\n\n";
+    if (field_id >= 0){
+        // LSTMP reads the ID of the field the player comes from. The field being left is the
+        // previous one, unless the field was just reloaded (after a battle, for example).
+        header += "-- The IDs of this field and of the previous one, for LSTMP.\n"
+          "if Data.FieldId ~= " + std::to_string(field_id) + " then\n"
+          "    Data.PreviousFieldId = Data.FieldId or 0\n"
+          "    Data.FieldId = " + std::to_string(field_id) + "\n"
+          "end\n\n";
+    }
+    for (const int bank : TEMPORARY_BANKS){
+        header += "-- Temporary variables start at zero in every field.\n"
+          "for address = 0, Banks.SIZE do\n"
+          "    Banks[" + std::to_string(bank) + "][address] = 0\n"
+          "end\n\n";
+    }
+    return header;
+}
+
+std::string FieldScriptInstaller::CreateTriggerScripts(const VGears::FLevelFilePtr& field) const{
+    std::string scripts;
+    const VGears::TriggersFilePtr& triggers = field->GetTriggers();
+    const auto& gateways = triggers->GetGateways();
+    for (size_t i = 0; i < gateways.size(); i ++){
+        const VGears::TriggersFile::Gateway& gateway = gateways[i];
+        if (gateway.destination_field_id == FieldData::INACTIVE_GATEWAY_ID) continue;
+        scripts += CreateGatewayScript(
+          "Gateway" + std::to_string(i), map_list_.at(gateway.destination_field_id),
+          "Spawn_" + field->getName() + "_" + std::to_string(i)
+        );
+    }
+    const auto& bg_triggers = triggers->GetBackgroundTriggers();
+    for (size_t i = 0; i < bg_triggers.size(); i ++){
+        if (!FieldData::IsBackgroundTriggerUsed(bg_triggers[i])) continue;
+        scripts += CreateBackgroundTriggerScript("BgTrigger" + std::to_string(i), bg_triggers[i]);
+    }
+    return scripts;
+}
+
+std::string FieldScriptInstaller::CreateGatewayScript(
+  const std::string& gateway_entity_name, const std::string& target_map_name,
+  const std::string& source_spawn_point_name
+){
+    return
+      "\nEntityContainer[ \"" + gateway_entity_name + "\" ] = {\n\n"
+      "    on_start = function(self)\n"
+      "        return 0\n"
+      "    end,\n\n"
+      "    on_approach = function(self, entity)\n"
+      "        return 0\n"
+      "    end,\n\n"
+      "    on_cross = function(self, entity)\n"
+      "        return 0\n"
+      "    end,\n\n"
+      "    on_near = function(self, entity)\n"
+      "        if entity ~= nil then\n"
+      "            if not Data.DisableGateways then\n"
+      "                load_field_map_request(\"" + target_map_name + "\", \"" + source_spawn_point_name + "\")\n"
+      "            end\n"
+      "        end\n"
+      "        return 0\n"
+      "    end,\n\n"
+      "    on_leave = function(self, entity)\n"
+      "        return 0\n"
+      "    end,\n"
+      "}\n\n";
+}
+
+std::string FieldScriptInstaller::CreateBackgroundTriggerScript(
+  const std::string& name, const VGears::TriggersFile::Trigger& trigger
+){
+    const std::string area = std::to_string(trigger.background_parameter);
+    const std::string state = std::to_string(trigger.background_state);
+    const std::string on = "background2d:area_on(" + area + ", " + state + ")";
+    const std::string off = "background2d:area_off(" + area + ", " + state + ")";
+    std::string enter, leave;
+    switch (trigger.behavior){
+        case 0: enter = on; break;
+        case 1: enter = off; break;
+        case 2: case 4: enter = on; leave = off; break;
+        case 3: case 5: enter = off; leave = on; break;
+        default: break;
+    }
+    return
+      "\nEntityContainer[ \"" + name + "\" ] = {\n\n"
+      "    on_start = function(self)\n"
+      "        return 0\n"
+      "    end,\n\n"
+      "    on_approach = function(self, entity)\n"
+      "        if entity ~= nil then " + enter + " end\n"
+      "        return 0\n"
+      "    end,\n\n"
+      "    on_cross = function(self, entity)\n"
+      "        return 0\n"
+      "    end,\n\n"
+      "    on_near = function(self, entity)\n"
+      "        return 0\n"
+      "    end,\n\n"
+      "    on_leave = function(self, entity)\n"
+      "        if entity ~= nil then " + leave + " end\n"
+      "        return 0\n"
+      "    end,\n"
+      "}\n\n";
+}
+
+void FieldScriptInstaller::WriteTexts(
+  const VGears::FLevelFilePtr& field, const std::vector<u8>& raw_script
+){
+    text_writer_.Begin(data_dir_ + "/" + FieldData::MAPS_DIR + "/" + field->getName() + "/text.xml");
+    try{text_writer_.Write(raw_script, field->getName());}
+    catch (const std::out_of_range& ex){
+        write_output_line_(
+          "[ERROR] Failed to read texts from field " + field->getName() + ": " + ex.what()
+        );
+    }
+    text_writer_.End();
+}

+ 148 - 0
src/installer/extractors/FieldScriptInstaller.h

@@ -0,0 +1,148 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#pragma once
+
+#include <functional>
+#include <string>
+#include <vector>
+#include "decompiler/field/FieldDecompiler.h"
+#include "formats/field/FLevelFile.h"
+#include "FieldDataTypes.h"
+#include "FieldTextWriter.h"
+
+/**
+ * Writes the script (script.lua) and the texts (text.xml) of a field.
+ *
+ * The script is the decompiled script of the original field, with the entities of the gateways
+ * and of the background triggers added.
+ */
+class FieldScriptInstaller{
+
+    public:
+
+        /**
+         * Constructor.
+         *
+         * @param[in] data_dir The game data folder.
+         * @param[in] map_list The names of the fields, by ID.
+         * @param[in,out] spawn_points The spawn points of every field. The decompiler names them.
+         * @param[in] log_output_line Function to write a line to the installation log.
+         */
+        FieldScriptInstaller(
+          const std::string& data_dir, const MapList& map_list, FieldSpawnPointsMap& spawn_points,
+          std::function<void(std::string)> log_output_line
+        );
+
+        /**
+         * Decompiles the script of a field and writes it, with its texts.
+         *
+         * The script and the texts are not written if the script can't be decompiled. The error
+         * is written to the log.
+         *
+         * @param[in] field The field.
+         * @return The decompiled script. It's empty if the decompiler failed.
+         */
+        FieldDecompiler::DecompiledScript Install(const VGears::FLevelFilePtr& field);
+
+        /**
+         * Creates the header of a field script.
+         *
+         * It creates the entity container, records the IDs of this field and of the previous one
+         * (for LSTMP), and sets the temporary memory banks to zero. In the original game a field
+         * can't see what the previous one left in them, but here the banks live as long as the
+         * game, so scripts that wait for a bank to change would see leftovers.
+         *
+         * @param[in] field_id ID of the field, or -1 to leave out the IDs.
+         * @return The header.
+         */
+        static std::string FieldScriptHeader(const int field_id = -1);
+
+        /**
+         * Banks of variables that start at zero in every field.
+         */
+        static const std::vector<int> TEMPORARY_BANKS;
+
+    private:
+
+        /**
+         * Creates the scripts of the entities of the gateways and of the background triggers.
+         *
+         * @param[in] field The field.
+         * @return The scripts of the entities.
+         */
+        std::string CreateTriggerScripts(const VGears::FLevelFilePtr& field) const;
+
+        /**
+         * Creates the script of the entity of a gateway.
+         *
+         * @param[in] gateway_entity_name Name of the entity.
+         * @param[in] target_map_name Name of the field the gateway leads to.
+         * @param[in] source_spawn_point_name Spawn point of the destination field.
+         * @return The script of the entity.
+         */
+        static std::string CreateGatewayScript(
+          const std::string& gateway_entity_name, const std::string& target_map_name,
+          const std::string& source_spawn_point_name
+        );
+
+        /**
+         * Creates the script of the entity of a background trigger.
+         *
+         * Behaviors: 0 on, 1 off, 2 on and off when away, 3 off and on when away, 4 and 5 the
+         * same as 2 and 3 (the original only reverts when the player leaves by the plus side of
+         * the line; here it is when the player leaves the line on any side).
+         *
+         * @param[in] name Name of the entity.
+         * @param[in] trigger The background trigger.
+         * @return The script of the entity.
+         */
+        static std::string CreateBackgroundTriggerScript(
+          const std::string& name, const VGears::TriggersFile::Trigger& trigger
+        );
+
+        /**
+         * Writes the texts of a field.
+         *
+         * @param[in] field The field.
+         * @param[in] raw_script The script section of the field, which has the texts.
+         */
+        void WriteTexts(const VGears::FLevelFilePtr& field, const std::vector<u8>& raw_script);
+
+        /**
+         * The game data folder.
+         */
+        std::string data_dir_;
+
+        /**
+         * The names of the fields, by ID.
+         */
+        const MapList& map_list_;
+
+        /**
+         * The spawn points of every field.
+         */
+        FieldSpawnPointsMap& spawn_points_;
+
+        /**
+         * Function to write a line to the installation log.
+         */
+        std::function<void(std::string)> write_output_line_;
+
+        /**
+         * Writes the texts of the fields.
+         */
+        FieldTextWriter text_writer_;
+};

+ 1 - 0
src/installer/steps/DataInstaller.h

@@ -27,6 +27,7 @@
 #include "installer/extractors/BattleDataInstaller.h"
 #include "installer/extractors/BattleDataInstaller.h"
 #include "installer/extractors/WorldInstaller.h"
 #include "installer/extractors/WorldInstaller.h"
 #include "installer/extractors/ModelsAndAnimationsDb.h"
 #include "installer/extractors/ModelsAndAnimationsDb.h"
+#include "installer/extractors/ScopedLgp.h"
 
 
 /**
 /**
  * The data installer.
  * The data installer.

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

@@ -1,6 +1,6 @@
 # Tests of this folder (see vgears_tests and vgears_installer_tests in test/CMakeLists.txt).
 # Tests of this folder (see vgears_tests and vgears_installer_tests in test/CMakeLists.txt).
 vgears_tests(
 vgears_tests(
-    FieldDataInstaller.cpp
+    FieldData.cpp
     KernelData.cpp
     KernelData.cpp
     SfxDump.cpp
     SfxDump.cpp
     WindowFonts.cpp
     WindowFonts.cpp

+ 101 - 0
test/installer/extractors/FieldData.cpp

@@ -0,0 +1,101 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <boost/test/unit_test.hpp>
+#include "installer/extractors/FieldBackgroundInstaller.h"
+#include "installer/extractors/FieldDataTypes.h"
+#include "installer/extractors/FieldMapWriter.h"
+#include "installer/extractors/FieldScriptInstaller.h"
+
+BOOST_AUTO_TEST_CASE(TestFieldScriptHeaderResetsTemporaryBanks){
+    const std::string header = FieldScriptInstaller::FieldScriptHeader();
+    // The container must exist before anything else in the script uses it.
+    BOOST_CHECK(header.find("EntityContainer = {}") == 0);
+    BOOST_CHECK(header.find("for address = 0, Banks.SIZE do") != std::string::npos);
+    BOOST_CHECK(header.find("Banks[5][address] = 0") != std::string::npos);
+    // Only the temporary banks are reset: saved variables must survive a field change.
+    BOOST_CHECK(header.find("Banks[1]") == std::string::npos);
+    BOOST_CHECK(header.find("Banks[2]") == std::string::npos);
+    // Without a field ID there is nothing for LSTMP.
+    BOOST_CHECK(header.find("Data.FieldId") == std::string::npos);
+}
+
+BOOST_AUTO_TEST_CASE(TestFieldScriptHeaderRecordsTheFieldIds){
+    const std::string header = FieldScriptInstaller::FieldScriptHeader(117);
+    BOOST_CHECK(header.find("if Data.FieldId ~= 117 then") != std::string::npos);
+    BOOST_CHECK(header.find("Data.PreviousFieldId = Data.FieldId or 0") != std::string::npos);
+}
+
+BOOST_AUTO_TEST_CASE(TestFieldIdAndScaleFactor){
+    const MapList map_list{"startmap", "md1stin", "md1_1"};
+    BOOST_CHECK_EQUAL(FieldData::FieldId("md1_1", map_list), 2u);
+    BOOST_CHECK_THROW(FieldData::FieldId("nowhere", map_list), std::runtime_error);
+    const FieldScaleFactorMap scale_factors{{1, 0.5f}};
+    BOOST_CHECK_EQUAL(FieldData::ScaleFactor(scale_factors, 1), 0.5f);
+    BOOST_CHECK_THROW(FieldData::ScaleFactor(scale_factors, 2), std::runtime_error);
+}
+
+BOOST_AUTO_TEST_CASE(TestSpawnPointsAreGroupedByDestination){
+    FieldSpawnPointsMap spawn_points;
+    SpawnPointDb::Record record;
+    record.gateway = {};
+    record.gateway.destination_field_id = 7;
+    record.field_id = 1;
+    FieldData::AddSpawnPoint(spawn_points, record);
+    record.field_id = 2;
+    FieldData::AddSpawnPoint(spawn_points, record);
+    record.gateway.destination_field_id = 9;
+    FieldData::AddSpawnPoint(spawn_points, record);
+    BOOST_REQUIRE_EQUAL(spawn_points.size(), 2u);
+    BOOST_CHECK_EQUAL(spawn_points[7].target_field_id, 7);
+    BOOST_REQUIRE_EQUAL(spawn_points[7].gateways_to_this_field.size(), 2u);
+    BOOST_CHECK_EQUAL(spawn_points[7].gateways_to_this_field[0].field_id, 1);
+    BOOST_CHECK_EQUAL(spawn_points[7].gateways_to_this_field[1].field_id, 2);
+    BOOST_CHECK_EQUAL(spawn_points[9].gateways_to_this_field.size(), 1u);
+}
+
+BOOST_AUTO_TEST_CASE(TestUnusedBackgroundTriggersAreAllZeroes){
+    VGears::TriggersFile::Trigger trigger = {};
+    BOOST_CHECK(!FieldData::IsBackgroundTriggerUsed(trigger));
+    trigger.trigger_line[1].z = -3;
+    BOOST_CHECK(FieldData::IsBackgroundTriggerUsed(trigger));
+}
+
+BOOST_AUTO_TEST_CASE(TestMusicTracksFollowTheAkaoStrings){
+    const std::vector<u8> script{
+      0, 'A', 'K', 'A', 'O', 5, 1, 2, 'A', 'K', 'O', 9, 'A', 'K', 'A', 'O', 14, 0, 0, 0, 0
+    };
+    const std::vector<int> tracks = FieldMapWriter::ExtractMusicTrackIds(script);
+    // The ID is the byte after the string, minus 2.
+    BOOST_REQUIRE_EQUAL(tracks.size(), 2u);
+    BOOST_CHECK_EQUAL(tracks[0], 3);
+    BOOST_CHECK_EQUAL(tracks[1], 12);
+}
+
+BOOST_AUTO_TEST_CASE(TestMusicTracksAtTheEndOfShortScripts){
+    // The string can end the script, and a script shorter than the string has no tracks.
+    BOOST_CHECK_EQUAL(FieldMapWriter::ExtractMusicTrackIds({'A', 'K', 'A', 'O', 7}).size(), 1u);
+    BOOST_CHECK(FieldMapWriter::ExtractMusicTrackIds({'A', 'K'}).empty());
+    BOOST_CHECK(FieldMapWriter::ExtractMusicTrackIds({}).empty());
+}
+
+BOOST_AUTO_TEST_CASE(TestBackgroundBlendingNames){
+    BOOST_CHECK_EQUAL(FieldBackgroundInstaller::BlendingName(0), "alpha");
+    BOOST_CHECK_EQUAL(FieldBackgroundInstaller::BlendingName(1), "add");
+    BOOST_CHECK_EQUAL(FieldBackgroundInstaller::BlendingName(2), "subtract");
+    // Type 3 is drawn as an addition with a quarter of the intensity.
+    BOOST_CHECK_EQUAL(FieldBackgroundInstaller::BlendingName(3), "add");
+    BOOST_CHECK_EQUAL(FieldBackgroundInstaller::BlendingName(4), "unknown");
+}

+ 0 - 28
test/installer/extractors/FieldDataInstaller.cpp

@@ -1,28 +0,0 @@
-/*
- * Copyright (C) 2022 The V-Gears Team
- *
- * This file is part of V-Gears
- *
- * V-Gears is free software: you can redistribute it and/or modify it under
- * terms of the GNU General Public License as published by the Free Software
- * Foundation, version 3.0 (GPLv3) of the License.
- *
- * V-Gears is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- */
-
-#include <boost/test/unit_test.hpp>
-#include "installer/extractors/FieldDataInstaller.h"
-
-BOOST_AUTO_TEST_CASE(TestFieldScriptHeaderResetsTemporaryBanks){
-    const std::string header = FieldDataInstaller::FieldScriptHeader();
-    // The container must exist before anything else in the script uses it.
-    BOOST_CHECK(header.find("EntityContainer = {}") == 0);
-    BOOST_CHECK(header.find("for address = 0, Banks.SIZE do") != std::string::npos);
-    BOOST_CHECK(header.find("Banks[5][address] = 0") != std::string::npos);
-    // Only the temporary banks are reset: saved variables must survive a field change.
-    BOOST_CHECK(header.find("Banks[1]") == std::string::npos);
-    BOOST_CHECK(header.find("Banks[2]") == std::string::npos);
-}