Przeglądaj źródła

Split the battle scene parser and fixed the enemy items

- There is a reader of the raw data of a scene and a converter that builds the enemies, the attacks and the formations. The location names are a table.
- Added the missing include guards of the attack, enemy and formation headers.
- The items that enemies drop or that can be stolen were read into 8 bits, so armors and accessories became other items.
- Attacks without an effect had the effect 255 instead of none.
- Added tests for the converted values and the AI scripts.
Iñigo Valentin 4 dni temu
rodzic
commit
5d58c3b0b4

+ 1 - 1
src/installer/extractors/BattleSceneInstaller.cpp

@@ -103,7 +103,7 @@ unsigned int BattleSceneInstaller::ProcessScene(){
         next_scene_ ++;
         return next_scene_;
     }
-    BattleSceneFile scene(next_scene_, *scene_file);
+    BattleSceneFile scene(*scene_file);
     scenes_.push_back(scene);
     // Add new enemies to the list.
     std::vector<Enemy> enemies = scene.GetEnemies();

+ 2 - 0
src/installer/formats/Attack.h

@@ -16,6 +16,8 @@
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  */
 
+#pragma once
+
 #include <string>
 #include "common/TypeDefine.h"
 #include "common/GameData.h"

+ 485 - 0
src/installer/formats/BattleSceneConverter.cpp

@@ -0,0 +1,485 @@
+/*
+ * V-Gears
+ * Copyright (C) 2022 V-Gears Team
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <algorithm>
+#include <iterator>
+#include "installer/support/Utility.h"
+#include "installer/tables/FF7Data.h"
+#include "BattleSceneConverter.h"
+
+namespace{
+
+    /**
+     * The names of the battle locations, by ID.
+     */
+    const char* const LOCATION_NAMES[] = {
+      "blank",
+      "bizarro_battle_center",
+      "grassland",
+      "mt_nibel",
+      "forest",
+      "beach",
+      "desert",
+      "snow",
+      "swamp",
+      "sector_1_train_station",
+      "reactor_1",
+      "reactor_1_core",
+      "reactor_1_entrance",
+      "sector_4_subway",
+      "nibel_caves",
+      "shinra_hq",
+      "midgar_raid_subway",
+      "hojo_lab",
+      "shinra_elevators",
+      "shinra_roof",
+      "midgar_highway",
+      "wutai_pagoda",
+      "church",
+      "coral_valley",
+      "midgar_slums",
+      "sector_4_corridors",
+      "sector_4_gantries",
+      "sector_7_pillar_stairway",
+      "sector_7pillar_top",
+      "sector_8",
+      "sewers",
+      "mythril_mines",
+      "crater_floating_platforms",
+      "corel_mountain_path",
+      "junon_beach",
+      "junon_cargo_ship",
+      "corel_prison",
+      "battle_square",
+      "da_chao_rapps_battle",
+      "cids_backyard",
+      "final_descent_to_sephiroth",
+      "reactor_5_entrance",
+      "ancients_escher_room",
+      "shinra_mansion",
+      "junon_airship_dock",
+      "whirlwind_maze",
+      "junon_underwater_reactor",
+      "gongaga_reactor",
+      "gelnika",
+      "train_graveyard",
+      "ice_caves",
+      "sister_ray",
+      "sister_ray_base",
+      "forgotten_city_altar",
+      "crater_descent",
+      "crater_hatchery",
+      "crater_water_area",
+      "safer_battle",
+      "kalm_flashback_dragon",
+      "junon_pipe",
+      "blank",
+      "railway_canyon",
+      "whirlwind_maze_crater",
+      "railway_rollercoaster",
+      "wooden_bridge",
+      "da_chao",
+      "fort_condor",
+      "dirt_wasteland",
+      "bizarro_battle_right",
+      "bizarro_battle_left",
+      "jenova_synthesis",
+      "corel_train_battle",
+      "cosmo_canyon",
+      "caverns_of_the_gi",
+      "nibelheim_mansion_basement",
+      "ancients_demons_gate",
+      "ancients_mural_room",
+      "ancients_clock_passage",
+      "final_battle",
+      "jungle",
+      "ultimate_weapon_highwind",
+      "corel_reactor",
+      "unused",
+      "don_corneos_mansion",
+      "emerald_weapon_battle",
+      "reactor_5",
+      "shinra_hq_-_escape",
+      "ultimate_weapon_gongaga",
+      "corel_prison_dyne",
+      "ultimate_weapon_forest"
+    };
+
+    /**
+     * Checks if the list has an element with an ID.
+     */
+    template<typename Element>
+    bool Contains(const std::vector<Element>& elements, const unsigned int id){
+        return std::any_of(elements.begin(), elements.end(), [id](const Element& element){
+            return element.id == id;
+        });
+    }
+
+    /**
+     * Checks if some bits are all set in a value.
+     */
+    bool Has(const unsigned int value, const unsigned int bits){return value == (value | bits);}
+
+    /**
+     * Adds the attacks that an enemy can use. Each of the 16 slots has an attack ID, the
+     * animation script of the model to play and the camera to use.
+     */
+    void AddAttacks(const BattleSceneData::EnemyData& data, Enemy& enemy){
+        for (int a = 0; a < 16; a ++){
+            if (data.attacks[a] == 0xFFFF) continue;
+            Enemy::Attack attack;
+            attack.id = data.attacks[a];
+            attack.animation = (data.animation_index[a] != 0xFF) ? data.animation_index[a] : -1;
+            attack.camera = (data.attack_camera[a] != 0xFFFF) ? data.attack_camera[a] : -1;
+            enemy.attacks.push_back(attack);
+        }
+    }
+
+    /**
+     * Adds the elemental defenses of an enemy.
+     */
+    void AddElements(const BattleSceneData::EnemyData& data, Enemy& enemy){
+        for (int l = 0; l < 8; l ++){
+            if (data.elements[l] == 0xFF || data.element_rates[l] == 0xFF) continue;
+            Enemy::Element element;
+            element.id = data.elements[l];
+            element.factor = BattleSceneConverter::ElementFactor(data.element_rates[l]);
+            enemy.elements.push_back(element);
+        }
+    }
+
+    /**
+     * Adds the status immunities of an enemy.
+     *
+     * They are a bitmask: the bit position is the status ID, as in the original game (0 death,
+     * 1 near death, 2 sleep, 3 poison, 4 sadness, 5 fury, 6 confusion, 7 silence...).
+     */
+    void AddImmunities(const BattleSceneData::EnemyData& data, Enemy& enemy){
+        if (data.immunities == 0xFFFFFFFF) return;
+        for (int bit = 0; bit < 32; bit ++){
+            if ((data.immunities & (1u << bit)) == 0) continue;
+            Enemy::Immunity immunity;
+            immunity.status = bit;
+            immunity.rate = 1.0f;
+            enemy.immunities.push_back(immunity);
+        }
+    }
+
+    /**
+     * Adds the items that an enemy drops and the ones that can be stolen from it.
+     */
+    void AddItems(const BattleSceneData::EnemyData& data, Enemy& enemy){
+        for (int i = 0; i < 4; i ++){
+            if (data.item[i] == 0xFFFF) continue;
+            Enemy::Item item;
+            item.id = data.item[i];
+            // The highest bit of the rate marks the items to steal.
+            if (data.item_rate[i] < 0x80){
+                item.rate = data.item_rate[i] / 63.0f;
+                enemy.drop.push_back(item);
+            }
+            else{
+                item.rate = (data.item_rate[i] - 0x80) / 63.0f;
+                enemy.steal.push_back(item);
+            }
+        }
+    }
+
+    /**
+     * Converts the data of an enemy.
+     */
+    Enemy ConvertEnemy(const BattleSceneData& scene, const int index){
+        const BattleSceneData::EnemyData& data = scene.enemy_data[index];
+        Enemy enemy;
+        enemy.id = scene.enemy[index];
+        enemy.model = FF7Data::GetEnemyModelFromEnemyId(enemy.id);
+        enemy.name = VGears::Utility::DecodeString(data.name, 32);
+        enemy.level = data.level;
+        enemy.str = data.str;
+        enemy.mag = data.mag;
+        enemy.def = data.def;
+        enemy.mdef = data.mdef;
+        enemy.spd = data.spd;
+        enemy.lck = data.lck;
+        enemy.eva = data.eva;
+        enemy.hp = data.hp;
+        enemy.mp = data.mp;
+        enemy.exp = data.exp;
+        enemy.ap = data.ap;
+        enemy.money = data.money;
+        enemy.back_damage = data.back_damage / 8.0f;
+        for (int a = 0; a < 16; a ++){
+            if (data.animation_index[a] != 0xFF) enemy.animations.push_back(data.animation_index[a]);
+        }
+        enemy.ai_scripts = scene.ai_scripts[index];
+        AddAttacks(data, enemy);
+        AddElements(data, enemy);
+        AddImmunities(data, enemy);
+        for (int m = 0; m < 3; m ++){
+            if (data.maniputale_attacks[m] != 0xFFFF)
+                enemy.manipulate_attacks.push_back(data.maniputale_attacks[m]);
+        }
+        AddItems(data, enemy);
+        if (data.morph != 0xFFFF) enemy.morph = data.morph;
+        return enemy;
+    }
+
+    /**
+     * Sets the animations, sounds and cameras of an attack.
+     */
+    void SetAnimation(const BattleSceneData::AttackData& data, Attack& attack){
+        if (data.impact_effect != 0xFF) attack.animation.impact_effect = data.impact_effect;
+        if (data.hurt_anim != 0xFF) attack.animation.hurt_anim = data.hurt_anim;
+        if (data.sound != 0xFFFF) attack.animation.sound = data.sound;
+        if (data.camera_single != 0xFFFF) attack.animation.camera_single = data.camera_single;
+        if (data.camera_multiple != 0xFFFF) attack.animation.camera_multiple = data.camera_multiple;
+        if (data.effect != 0xFF) attack.animation.effect = data.effect;
+    }
+
+    /**
+     * Sets how an attack chooses its targets.
+     */
+    void SetTarget(const BattleSceneData::AttackData& data, Attack& attack){
+        attack.target.selection_enabled = Has(data.target, 0x01);
+        attack.target.default_enemy = Has(data.target, 0x02);
+        attack.target.default_multiple = Has(data.target, 0x04);
+        attack.target.toggle_multiple = Has(data.target, 0x08);
+        attack.target.fixed_row = Has(data.target, 0x10);
+        attack.target.short_range = Has(data.target, 0x20);
+        attack.target.all_rows = Has(data.target, 0x40);
+        attack.target.random = Has(data.target, 0x80);
+    }
+
+    /**
+     * Sets the damage of an attack.
+     */
+    void SetDamage(const BattleSceneData::AttackData& data, Attack& attack){
+        attack.damage.accuracy = data.accuracy / 255.0f;
+        attack.damage.formula = data.damage >> 4;
+        attack.damage.modifier = data.damage & 15;
+        attack.damage.power = data.power;
+        switch(data.condition){
+            case 0: attack.damage.restore = GameData::RestoreType::HP; break;
+            case 1: attack.damage.restore = GameData::RestoreType::MP; break;
+            case 2: attack.damage.restore = GameData::RestoreType::STATUS; break;
+            default: attack.damage.restore = GameData::RestoreType::NONE;
+        }
+    }
+
+    /**
+     * Adds the statuses that an attack causes or removes.
+     *
+     * The lower 6 bits of the status change byte are the chance out of 63, and the upper 2 bits
+     * the mode (0x80 toggles the statuses, 0x40 cures them, otherwise they are inflicted). The
+     * status bitmask has the status IDs as bit positions, as in the original game.
+     */
+    void AddStatusEffects(const BattleSceneData::AttackData& data, Attack& attack){
+        if (data.status == 0xFFFFFFFF) return;
+        int mode = GameData::STATUS_EFFECT_MODE::INFLICT;
+        if ((data.status_change & 0x80) != 0) mode = GameData::STATUS_EFFECT_MODE::TOGGLE;
+        else if ((data.status_change & 0x40) != 0) mode = GameData::STATUS_EFFECT_MODE::CURE;
+        const float chance = (data.status_change & 0x3F) / 63.0f;
+        for (int bit = 0; bit < 32; bit ++){
+            if ((data.status & (1u << bit)) == 0) continue;
+            Attack::StatusEffect effect;
+            effect.id = bit;
+            effect.chance = chance;
+            effect.type = mode;
+            attack.status_effects.push_back(effect);
+        }
+    }
+
+    /**
+     * Sets the special properties of an attack. Each one is on when its bit is not set.
+     */
+    void SetSpecialFlags(const BattleSceneData::AttackData& data, Attack& attack){
+        const auto on = [&data](const unsigned int bit){return !Has(data.special, bit);};
+        attack.damage.damage_mp = on(0x0001);
+        attack.damage.affected_by_darkness = on(0x0004);
+        if (on(0x0010)){
+            if (attack.damage.damage_mp) attack.damage.drain_mp = true;
+            else attack.damage.drain_hp = true;
+        }
+        if (on(0x0020)){
+            attack.damage.drain_hp = true;
+            attack.damage.drain_mp = true;
+        }
+        attack.damage.ignore_status_defense = on(0x0080);
+        attack.target.only_for_dead = on(0x0100);
+        attack.reflectable = on(0x0200);
+        attack.target.no_re_target = on(0x0800);
+        attack.damage.critical = on(0x2000);
+    }
+
+    /**
+     * Converts the data of an attack.
+     */
+    Attack ConvertAttack(const BattleSceneData& scene, const int index){
+        const BattleSceneData::AttackData& data = scene.attack_data[index];
+        Attack attack;
+        attack.id = scene.attack_ids[index];
+        attack.name = VGears::Utility::DecodeString(scene.attack_names[index], 32);
+        attack.mp = data.mp;
+        SetAnimation(data, attack);
+        SetTarget(data, attack);
+        SetDamage(data, attack);
+        AddStatusEffects(data, attack);
+        // Attack elements are a bitmask (0x0001 is fire, 0x0002 ice...), while enemies elements
+        // are indexes (0 is fire, 1 is ice...). Elements are stored as indexes.
+        if (data.element != 0xFFFF){
+            for (int bit = 0; bit < 16; bit ++){
+                if ((data.element & (1 << bit)) != 0) attack.elements.push_back(bit);
+            }
+        }
+        SetSpecialFlags(data, attack);
+        // TODO: Parse additional_effects with additional_effects_mod for special attack
+        // modifiers (23 total). https://wiki.ffrtt.ru/index.php/FF7/Battle/Attack_Special_Effects
+        return attack;
+    }
+
+    /**
+     * Converts an enemy of a formation.
+     */
+    Formation::Enemy ConvertFormationEnemy(const BattleSceneData::Formation& data){
+        Formation::Enemy enemy;
+        enemy.id = data.id;
+        enemy.x = data.x;
+        enemy.y = data.y;
+        enemy.z = data.z;
+        enemy.row = data.row;
+        for (int cover = 0; cover < 5; cover ++)
+            enemy.cover[cover] = Has(data.cover_flags, 1u << cover) ? '1' : '0';
+        // TODO: These are always true: the comparisons are done before the bits are added.
+        enemy.visible = (data.flags == data.flags | 0x01);
+        enemy.direction = ((data.flags == data.flags | 0x02) ? 1 : 0);
+        enemy.targeteable = (data.flags == data.flags | 0x08);
+        enemy.main_script_active = (data.flags == data.flags | 0x10);
+        return enemy;
+    }
+
+    /**
+     * Converts a camera position of a formation.
+     */
+    Formation::Camera ConvertCamera(const BattleSceneData::Camera::Position& data){
+        // The original data has x to the side, y down and z in depth (the enemies are in the
+        // negative side). The scene has the same x, the depth in y and z up, in units 255 times
+        // bigger, like the positions of the enemies.
+        Formation::Camera camera;
+        camera.x = data.x / 255.0f;
+        camera.y = data.z / 255.0f;
+        camera.z = -data.y / 255.0f;
+        camera.d_x = data.d_x / 255.0f;
+        camera.d_y = data.d_z / 255.0f;
+        camera.d_z = -data.d_y / 255.0f;
+        return camera;
+    }
+
+    /**
+     * Converts the data of a formation.
+     */
+    Formation ConvertFormation(const BattleSceneData& scene, const int index){
+        const BattleSceneData::Setup& setup = scene.setup[index];
+        Formation formation;
+        if (setup.next_battle != 0xFFFF) formation.next_formation = setup.next_battle;
+        formation.escape_counter = (setup.escape_counter / 64.0f);
+        // Observed in the original scene.bin (1024 setups): the upper byte is always 0xFF and
+        // bit 0x02 is clear in most random battles, so it means "can't escape" (inverted).
+        // TODO: What is flag 0x01?
+        formation.escapable = ((setup.flags & 0x02) == 0);
+        // TODO: Bits 0x04, 0x08 and 0x10 are set in almost every setup, so they can't be read as
+        // positive "skip victory pose", "skip spoils" and "preemptive disabled" flags. The
+        // defaults are used until their meaning is verified against known battles.
+        formation.skip_victory_pose = false;
+        formation.skip_spoils = false;
+        formation.preemptive_disabled = false;
+        // TODO: What are flags 0x20, 0x40 and 0x80?
+        formation.layout = BattleSceneConverter::Layout(setup.layout);
+        for (const BattleSceneData::Formation& enemy : scene.formation[index]){
+            if (enemy.id != 0xFFFF) formation.enemies.push_back(ConvertFormationEnemy(enemy));
+        }
+        formation.location = setup.location;
+        formation.location_name = BattleSceneConverter::LocationName(setup.location);
+        for (const BattleSceneData::Camera::Position& camera : scene.camera[index].camera)
+            formation.camera_positions.push_back(ConvertCamera(camera));
+        // The camera byte of the formation is the script of the camera at the start of the
+        // battle, which ends at the first camera of the formation unless it chooses another one.
+        formation.intro_camera = setup.camera;
+        for (const u16 candidate : setup.next_arena_candidates){
+            if (candidate == 999) continue;
+            formation.next_arena_formation_candidates.push_back(candidate);
+            formation.is_arena_battle = true;
+        }
+        return formation;
+    }
+}
+
+namespace BattleSceneConverter{
+
+    std::vector<Enemy> Enemies(const BattleSceneData& data){
+        std::vector<Enemy> enemies;
+        for (int e = 0; e < 3; e ++){
+            if (data.enemy[e] != 0xFFFF && !Contains(enemies, data.enemy[e]))
+                enemies.push_back(ConvertEnemy(data, e));
+        }
+        return enemies;
+    }
+
+    std::vector<Attack> Attacks(const BattleSceneData& data){
+        std::vector<Attack> attacks;
+        for (int a = 0; a < 32; a ++){
+            if (data.attack_ids[a] != 0xFFFF && !Contains(attacks, data.attack_ids[a]))
+                attacks.push_back(ConvertAttack(data, a));
+        }
+        return attacks;
+    }
+
+    std::vector<Formation> Formations(const BattleSceneData& data){
+        std::vector<Formation> formations;
+        for (int f = 0; f < 4; f ++) formations.push_back(ConvertFormation(data, f));
+        return formations;
+    }
+
+    float ElementFactor(const u8 rate){
+        switch (rate){
+            case 0x00: return 11.0f; // Death.
+            case 0x02: return 2.0f; // Double damage.
+            case 0x04: return 0.5f; // Half damage.
+            case 0x05: return 0.0f; // Nullify.
+            case 0x06: return -1.0f; // Absorb 100%.
+            case 0x07: return -11.0f; // Full cure.
+            default: return 1.0f; // Normal damage.
+        }
+    }
+
+    Formation::Layout Layout(const u8 layout){
+        static const Formation::Layout LAYOUTS[] = {
+          Formation::Layout::NORMAL, Formation::Layout::PREEMPTIVE,
+          Formation::Layout::BACK_ATTACK, Formation::Layout::SIDE_ATTACK,
+          Formation::Layout::PINCER_ATTACK, Formation::Layout::PINCER_ATTACK,
+          Formation::Layout::SIDE_ATTACK, Formation::Layout::SIDE_ATTACK,
+          Formation::Layout::LOCKED
+        };
+        if (layout >= std::end(LAYOUTS) - std::begin(LAYOUTS)) return Formation::Layout::NORMAL;
+        return LAYOUTS[layout];
+    }
+
+    std::string LocationName(const unsigned int id){
+        if (id >= std::end(LOCATION_NAMES) - std::begin(LOCATION_NAMES)) return "unknonw_location";
+        return LOCATION_NAMES[id];
+    }
+}

+ 80 - 0
src/installer/formats/BattleSceneConverter.h

@@ -0,0 +1,80 @@
+/*
+ * V-Gears
+ * Copyright (C) 2022 V-Gears Team
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#pragma once
+
+#include <string>
+#include <vector>
+#include "BattleSceneData.h"
+#include "installer/formats/Attack.h"
+#include "installer/formats/Enemy.h"
+#include "installer/formats/Formation.h"
+
+/**
+ * Converts the data of a battle scene to enemies, attacks and formations.
+ */
+namespace BattleSceneConverter{
+
+    /**
+     * Retrieves the enemies of a scene.
+     *
+     * @param[in] data The scene.
+     * @return The enemies, each one once.
+     */
+    std::vector<Enemy> Enemies(const BattleSceneData& data);
+
+    /**
+     * Retrieves the attacks of a scene.
+     *
+     * @param[in] data The scene.
+     * @return The attacks, each one once.
+     */
+    std::vector<Attack> Attacks(const BattleSceneData& data);
+
+    /**
+     * Retrieves the formations of a scene.
+     *
+     * @param[in] data The scene.
+     * @return The 4 formations.
+     */
+    std::vector<Formation> Formations(const BattleSceneData& data);
+
+    /**
+     * Converts the elemental rate of an enemy to the factor of the damage.
+     *
+     * @param[in] rate The rate of the original game.
+     * @return The factor.
+     */
+    float ElementFactor(const u8 rate);
+
+    /**
+     * Converts the layout of a formation.
+     *
+     * @param[in] layout The layout of the original game.
+     * @return The layout. Normal if it's unknown.
+     */
+    Formation::Layout Layout(const u8 layout);
+
+    /**
+     * Retrieves the name of a battle location.
+     *
+     * @param[in] id ID of the location.
+     * @return The name.
+     */
+    std::string LocationName(const unsigned int id);
+}

+ 563 - 0
src/installer/formats/BattleSceneData.h

@@ -0,0 +1,563 @@
+/*
+ * V-Gears
+ * Copyright (C) 2022 V-Gears Team
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#pragma once
+
+#include <vector>
+#include "common/TypeDefine.h"
+
+/**
+ * A battle scene structure.
+ */
+struct BattleSceneData{
+
+    /**
+     * Scene battle setup data (20 bytes).
+     */
+    struct Setup{
+
+        /**
+         * Battle location.
+         */
+        u16 location;
+
+        /**
+         * ID of the battle that start upon defeating all enemies.
+         *
+         * If set, a new set of enemies will be loaded when all the
+         * current ones are defeated, without ending the battle scene.
+         */
+        u16 next_battle;
+
+        /**
+         * @todo Understand and document.
+         */
+        u16 escape_counter;
+
+        /**
+         * Unused data.
+         */
+        u16 unused;
+
+        /**
+         * In arena battles, candidate enemy formation IDs for next
+         * round.
+         */
+        u16 next_arena_candidates[4];
+
+        /**
+         * Battle flags.
+         *
+         * Includes the escapable flag.
+         */
+        u16 flags;
+
+        /**
+         * Battle layout.
+         *
+         * 00 - Normal figh.t
+         * 01 - Preemptive.
+         * 02 - Back attack.
+         * 03 - Side attack.
+         * 04 - Attacked from both sides (pincer attack, reverse side).
+         * 05 - Another attack from both sides battle (different maybe?).
+         * 06 - Another side attack.
+         * 07 - A third side attack.
+         * 08 - Normal battle that locks player in the front row, change
+         * command disabled.
+         */
+        u8 layout;
+
+        /**
+         * Indexed Pre-Battle Camera position.
+         */
+        u8 camera;
+    };
+
+    /**
+     * Scene camera placement data.
+     */
+    struct Camera{
+
+        /**
+         * Position for a camera scene.
+         */
+        struct Position{
+
+            /**
+             * X position.
+             */
+            int x;
+
+            /**
+             * Y position.
+             */
+            int y;
+
+            /**
+             * z position.
+             */
+            int z;
+
+            /**
+             * X direction.
+             */
+            int d_x;
+
+            /**
+             * Y direction.
+             */
+            int d_y;
+
+            /**
+             * z direction.
+             */
+            int d_z;
+        };
+
+        /**
+         * Camera positions.
+         *
+         * Index 0 is primary, indexes 1 and 2 are secondary positions.
+         */
+        Position camera[3];
+
+        /**
+         * Unused data.
+         */
+        u8 unused[12];
+    };
+
+    /**
+     * A scene formation structure.
+     */
+    struct Formation{
+
+        /**
+         * Enemy ID.
+         */
+        u16 id;
+
+        /**
+         * Enemy X position.
+         */
+        int x;
+
+        /**
+         * Enemy Y position.
+         */
+        int y;
+
+        /**
+         * Enemy Z position.
+         */
+        int z;
+
+        /**
+         * Enemy row.
+         */
+        u16 row;
+
+        /**
+         * Binary "Cover Flags".
+         *
+         * These flags are used in conjunction with row to determine if
+         * a target can be selected as the target of a short-range
+         * attack. The determination of this is worked out in this way:
+         * An enemy exists in row 1 and another in row 2. If the enemy
+         * in row 1 shares a cover flag with the enemy in row 2 then the
+         * enemy in row 2 cannot be targeted until all enemies in row 1
+         * that share a cover flag with the row 2 enemy is defeated. It
+         * works like this. Two active enemies exist, A and B.
+         *
+         * If ((B's row > A's row) and
+         * (B's cover flags AND A's cover flags) > 0) then enemy B
+         * cannot be targeted by short-range attacks.
+         */
+        u16 cover_flags;
+
+        /**
+         * Initial condition flags. Only last 5 bits are considered.
+         * 0x0001  Visible.
+         * 0x0002  Indicates initial direction facing if players get a
+         * side attack.
+         * 0x0004  Unknown.
+         * 0x0008  Targetable.
+         * 0x0010  Main Script Active.
+         */
+        u32 flags;
+    };
+
+    struct EnemyData{
+
+        /**
+         * Enemy's name (completed by FFh bytes).
+         */
+        u8 name[32];
+
+        /**
+         * Enemy's level.
+         */
+        u8 level;
+
+        /**
+         * Enemy's speed.
+         */
+        u8 spd;
+
+        /**
+         * Enemy's luck.
+         */
+        u8 lck;
+
+        /**
+         * Enemy's evade stat.
+         */
+        u8 eva;
+
+        /**
+         * Enemy's strength.
+         */
+        u8 str;
+
+        /**
+         * Enemy's defense.
+         */
+        u8 def;
+
+        /**
+         * Enemy's magic.
+         */
+        u8 mag;
+
+        /**
+         * Enemy's magic defense.
+         */
+        u8 mdef;
+
+        /**
+         * Elements of the enemy.
+         */
+        u8 elements[8];
+
+        /**
+         * Element rates for @{see elements}, respectively.
+         */
+        u8 element_rates[8];
+
+        /**
+         * Animation index for each @{see attacks}.
+         */
+        u8 animation_index[16];
+
+        /**
+         * Enemy attack IDs.
+         */
+        u16 attacks[16];
+
+        /**
+         * Enemy Attacks Camera Movement Id for single and multiple
+         * targets (2 bytes each).
+         *
+         * If set this will overwrite camera movement set in attack
+         * itself.
+         */
+        u16 attack_camera[16];
+
+        /**
+         * Item drop/steal rates.
+         *
+         * These are chances to get items listed in @{see item}. 1 byte
+         * per item. If the rate is lower than 80h, for e.g. 08h - then
+         * this is a drop item and has 8/63 [63 is max] chance for drop.
+         * But if rate is higher than 80h, let's say... A0h, then this
+         * is an item for steal, and chances for successful steal is
+         * A0h - 80h = 20h = 32/63.
+         */
+        u8 item_rate[4];
+
+        /**
+         * IDs of items dropped/stolen from the enemy.
+         *
+         * 0xFFFF means no item.
+         */
+        u16 item[4];
+
+        /**
+         * IDs of attacks that can be performed while manipulated.
+         *
+         * The first one is the attack to use in berserk mode.
+         */
+        u16 maniputale_attacks[3];
+
+        /**
+         * Unknown data.
+         */
+        u16 unknown_0;
+
+        /**
+         * Enemy's MP.
+         */
+        u16 mp;
+
+        /**
+         * AP given upon enemy defeat.
+         */
+        u16 ap;
+
+        /**
+         * ID of the item the enemy can be morphed into.
+         *
+         * If 0xFFFF, the enemy can't be morphed
+         */
+        u16 morph;
+
+        /**
+         * Back damage multiplier.
+         *
+         * damage = damage * back_damage / 8.
+         */
+        u8 back_damage;
+
+        /**
+         * Unused data (align).
+         */
+        u8 unused;
+
+        /**
+         * Enemy's HP.
+         */
+        u32 hp;
+
+        /**
+         * Experience points given upon defeat.
+         */
+        u32 exp;
+
+        /**
+         * Money given upon defeat.
+         */
+        u32 money;
+
+        /**
+         * Status immunities.
+         *
+         * @todo: a bit set is an immunity?
+         */
+        u32 immunities;
+
+        /**
+         * Unknown data.
+         */
+        u32 unknown_1;
+    };
+
+    /**
+     * A battle scene attack data structure.
+     */
+    struct AttackData{
+
+        /**
+         * Probability of the attack to land. 1 byte.
+         */
+        u8 accuracy;
+
+        /**
+         * Impact effect. 1 byte.
+         *
+         * The sprite shown when the attack hits.
+         */
+        u8 impact_effect;
+
+        /**
+         * Index of the animation played by the target when hit. 1 byte.
+         */
+        u8 hurt_anim;
+
+        /**
+         * Unknown data. 1 bytes.
+         */
+        u8 unknown;
+
+        /**
+         * MP cost. 2 bytes.
+         *
+         * Determines the camera movement when the command is executed
+         * over a single target.
+         */
+        u16 mp;
+
+        /**
+         * Impact sound. 2 bytes.
+         *
+         * Determines the camera movement when the command is executed
+         * over multiple targets.
+         */
+        u16 sound;
+
+        /**
+         * Camera movement ID for single target. 2 bytes.
+         *
+         * Determines the camera movement when the command is executed
+         * over a single target.
+         */
+        u16 camera_single;
+
+        /**
+         * Camera movement ID for multiple target. 2 bytes.
+         *
+         * Determines the camera movement when the command is executed
+         * over multiple targets.
+         */
+        u16 camera_multiple;
+
+        /**
+         * Targeting mode. 1 byte.
+         */
+        u8 target;
+
+        /**
+         * Atack effect ID. 1 byte.
+         *
+         * Used for animation in battle.
+         */
+        u8 effect;
+
+        /**
+         * Damage formula. 1 byte.
+         *
+         * This byte is divided into two nybbles (four bits). Upper
+         * nybble determines what considerations are made in calculating
+         * damage such as physical/magical, allowing criticals, how to
+         * calculate accuracy, etc. There are also three sets of known
+         * formulae that are paired with the upper nybble values. These
+         * are selected in the Lower Nybble and determine how to
+         * calculate pre-defense damage
+         */
+        u8 damage;
+
+        /**
+         * The attack power. 1 byte.
+         *
+         * Used for damage/healing calculation.
+         */
+        u8 power;
+
+        /**
+         * The restore type.
+         */
+        u8 condition;
+
+        /**
+         * Information about status change mode and chance. 1 bytes.
+         */
+        u8 status_change;
+
+        /**
+         * Special flags. 1 byte.
+         *
+         * @todo Document and retrieve with info from
+         * https://wiki.ffrtt.ru/index.php?title=FF7/Battle/Attack_Special_Effects
+         */
+        u8 additional_effects;
+
+        /**
+         * Special flags. 1 byte.
+         *
+         * @todo Document and retrieve with info from
+         * https://wiki.ffrtt.ru/index.php?title=FF7/Item_data
+         */
+        u8 additional_effects_mod;
+
+        /**
+         * Information about what status can be inflicted or cured. 4
+         * bytes.
+         *
+         * The first six bits are the chance of inflicting/curing (out
+         * of 63). If the seventh bit is set, the status is cured
+         * instead of inflicted. If the eighth bit is set, then the
+         * status is toggled (cured if present, inflicted if not
+         * present).
+         */
+        u32 status;
+
+        /**
+         * Information about the item elements. 2 bytes.
+         */
+        u16 element;
+
+        /**
+         * Special flags. 2 bytes.
+         *
+         * @todo document and parse with info from
+         * https://wiki.ffrtt.ru/index.php?title=FF7/Battle/Special_Attack_Flags
+         */
+        u16 special;
+
+    };
+
+    /**
+     * Enemy IDs.
+     */
+    u16 enemy[3];
+
+    /**
+     * Unused data (padding).
+     */
+    u16 unused;
+
+    /**
+     * Battle scene set-ups.
+     */
+    Setup setup[4];
+
+    /**
+     * Camera placement data.
+     */
+    Camera camera[4];
+
+    /**
+     * Battle formation data.
+     */
+    Formation formation[4][6];
+
+    /**
+     * Enemy data.
+     */
+    EnemyData enemy_data[3];
+
+    /**
+     * Attack data.
+     */
+    AttackData attack_data[32];
+
+    /**
+     * Attack IDs.
+     */
+    u16 attack_ids[32];
+
+    /**
+     * Attack names.
+     */
+    u8 attack_names[32][32];
+
+    /**
+     * The AI scripts of the 3 enemies: 16 for each one, empty for the slots without one.
+     */
+    std::vector<std::vector<u8>> ai_scripts[3];
+};

+ 8 - 537
src/installer/formats/BattleSceneFile.cpp

@@ -16,548 +16,19 @@
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  */
 
-#include <iostream>
+#include "BattleSceneConverter.h"
 #include "BattleSceneFile.h"
-#include "installer/support/Utility.h"
-#include "installer/tables/FF7Data.h"
+#include "BattleSceneReader.h"
 
-BattleSceneFile::BattleSceneFile(const unsigned int id, File file): id_(id){Read(file);}
-
-BattleSceneFile::~BattleSceneFile(){}
+BattleSceneFile::BattleSceneFile(File file){
+    const BattleSceneData data = BattleSceneReader::Read(file);
+    enemies_ = BattleSceneConverter::Enemies(data);
+    attacks_ = BattleSceneConverter::Attacks(data);
+    formations_ = BattleSceneConverter::Formations(data);
+}
 
 std::vector<Attack> BattleSceneFile::GetAttacks(){return attacks_;}
 
 std::vector<Enemy> BattleSceneFile::GetEnemies(){return enemies_;}
 
 std::vector<Formation> BattleSceneFile::GetFormations(){return formations_;}
-
-void BattleSceneFile::Read(File file){
-    file.SetOffset(0);
-    scene_.enemy[0] = file.readU16LE();
-    scene_.enemy[1] = file.readU16LE();
-    scene_.enemy[2] = file.readU16LE();
-    scene_.unused = file.readU16LE();
-    for (int s = 0; s < 4; s ++){
-        scene_.setup[s].location = file.readU16LE();
-        scene_.setup[s].next_battle = file.readU16LE();
-        scene_.setup[s].escape_counter = file.readU16LE();
-        scene_.setup[s].unused = file.readU16LE();
-        for (int a = 0; a < 4; a ++) scene_.setup[s].next_arena_candidates[a] = file.readU16LE();
-        scene_.setup[s].flags = file.readU16LE();
-        scene_.setup[s].layout = file.readU8();
-        scene_.setup[s].camera = file.readU8();
-    }
-    for (int c = 0; c < 4; c ++){
-        for (int p = 0; p < 3; p ++){
-            // The position of the camera and the point it looks at, signed 16 bit values in the units of
-            // the original game. They are kept as they are, and converted when the formations are built.
-            scene_.camera[c].camera[p].x = static_cast<int16_t>(file.readU16LE());
-            scene_.camera[c].camera[p].y = static_cast<int16_t>(file.readU16LE());
-            scene_.camera[c].camera[p].z = static_cast<int16_t>(file.readU16LE());
-            scene_.camera[c].camera[p].d_x = static_cast<int16_t>(file.readU16LE());
-            scene_.camera[c].camera[p].d_y = static_cast<int16_t>(file.readU16LE());
-            scene_.camera[c].camera[p].d_z = static_cast<int16_t>(file.readU16LE());
-        }
-        for (int p = 0; p < 12; p ++) scene_.camera[c].unused[p] = file.readU8();
-    }
-    for (int f = 0; f < 4; f ++){
-        for (int e = 0; e < 6; e ++){
-            scene_.formation[f][e].id = file.readU16LE();
-            // Enemy positions are stored as 16 bit floats. Here, 16 bit are being read, then, the
-            // sign is checked to fit it into -32766 and 32767 (0x7F9b). Then, the number is
-            // divided by 255 (0xFF) to keep just the integer part.
-            scene_.formation[f][e].x = file.readU16LE();
-            if (scene_.formation[f][e].x > 0x7F9B) scene_.formation[f][e].x -= 0xFFFF;
-            scene_.formation[f][e].x /= 0xFF;
-            // Y and Z are inverted in original data.
-            scene_.formation[f][e].z = file.readU16LE();
-            if (scene_.formation[f][e].z > 0x7F9B) scene_.formation[f][e].z -= 0xFFFF;
-            scene_.formation[f][e].z /= 0xFF;
-            scene_.formation[f][e].y = file.readU16LE();
-            if (scene_.formation[f][e].y > 0x7F9B) scene_.formation[f][e].y -= 0xFFFF;
-            scene_.formation[f][e].y /= 0xFF;
-            scene_.formation[f][e].row = file.readU16LE();
-            scene_.formation[f][e].cover_flags = file.readU16LE();
-            scene_.formation[f][e].flags = file.readU32LE();
-        }
-    }
-    for (int e = 0; e < 3; e ++){
-        for (int n = 0; n < 32; n ++) scene_.enemy_data[e].name[n] = file.readU8();
-        scene_.enemy_data[e].level = file.readU8();
-        scene_.enemy_data[e].spd = file.readU8();
-        scene_.enemy_data[e].lck = file.readU8();
-        scene_.enemy_data[e].eva = file.readU8();
-        scene_.enemy_data[e].str = file.readU8();
-        scene_.enemy_data[e].def = file.readU8();
-        scene_.enemy_data[e].mag = file.readU8();
-        scene_.enemy_data[e].mdef = file.readU8();
-        for (int l = 0; l < 8; l ++) scene_.enemy_data[e].elements[l] = file.readU8();
-        for (int l = 0; l < 8; l ++) scene_.enemy_data[e].element_rates[l] = file.readU8();
-        for (int a = 0; a < 16; a ++) scene_.enemy_data[e].animation_index[a] = file.readU8();
-        for (int a = 0; a < 16; a ++) scene_.enemy_data[e].attacks[a] = file.readU16LE();
-        for (int a = 0; a < 16; a ++) scene_.enemy_data[e].attack_camera[a] = file.readU16LE();
-        for (int i = 0; i < 4; i ++) scene_.enemy_data[e].item_rate[i] = file.readU8();
-        for (int i = 0; i < 4; i ++) scene_.enemy_data[e].item[i] = file.readU16LE();
-        for (int m = 0; m < 3; m ++) scene_.enemy_data[e].maniputale_attacks[m] = file.readU16LE();
-        scene_.enemy_data[e].unknown_0 = file.readU16LE();
-        scene_.enemy_data[e].mp = file.readU16LE();
-        scene_.enemy_data[e].ap = file.readU16LE();
-        scene_.enemy_data[e].morph = file.readU16LE();
-        scene_.enemy_data[e].back_damage = file.readU8();
-        scene_.enemy_data[e].unused = file.readU8();
-        scene_.enemy_data[e].hp = file.readU32LE();
-        scene_.enemy_data[e].exp = file.readU32LE();
-        scene_.enemy_data[e].money = file.readU32LE();
-        scene_.enemy_data[e].immunities = file.readU32LE();
-        scene_.enemy_data[e].unknown_1 = file.readU32LE();
-    }
-    for (int a = 0; a < 32; a ++){
-        scene_.attack_data[a].accuracy = file.readU8();
-        scene_.attack_data[a].impact_effect = file.readU8();
-        scene_.attack_data[a].hurt_anim = file.readU8();
-        scene_.attack_data[a].unknown = file.readU8();
-        scene_.attack_data[a].mp = file.readU16LE();
-        scene_.attack_data[a].sound = file.readU16LE();
-        scene_.attack_data[a].camera_single = file.readU16LE();
-        scene_.attack_data[a].camera_multiple = file.readU16LE();
-        scene_.attack_data[a].target = file.readU8();
-        scene_.attack_data[a].effect = file.readU8();
-        scene_.attack_data[a].damage = file.readU8();
-        scene_.attack_data[a].power = file.readU8();
-        scene_.attack_data[a].condition = file.readU8();
-        scene_.attack_data[a].status_change = file.readU8();
-        scene_.attack_data[a].additional_effects = file.readU8();
-        scene_.attack_data[a].additional_effects_mod = file.readU8();
-        scene_.attack_data[a].status = file.readU32LE();
-        scene_.attack_data[a].element = file.readU16LE();
-        scene_.attack_data[a].special = file.readU16LE();
-    }
-    for (int a = 0; a < 32; a ++) scene_.attack_ids[a] = file.readU16LE();
-    for (int a = 0; a < 32; a ++) for (int b = 0; b < 32; b ++) scene_.attack_names[a][b] = file.readU8();
-    // AI scripts. The AI block is at a fixed offset, and starts with an offset for each of the 3
-    // enemies of the scene (0xFFFF if the enemy has none). Each enemy block has 16 offsets
-    // (0xFFFF for slots without a script) followed by the scripts, which end with the opcode 0x73.
-    for (int e = 0; e < 3; e ++) ai_scripts_[e].assign(16, std::vector<u8>());
-    {
-        const u32 ai_base = 0x0E80;
-        const u32 file_size = file.GetFileSize();
-        if (file_size > ai_base + 6){
-            std::vector<u8> bytes(file_size);
-            file.GetFileBuffer(bytes.data(), 0, file_size);
-            u16 block_offsets[3];
-            for (int e = 0; e < 3; e ++) block_offsets[e] = bytes[ai_base + 2 * e] | (bytes[ai_base + 2 * e + 1] << 8);
-            for (int e = 0; e < 3; e ++){
-                if (block_offsets[e] == 0xFFFF) continue;
-                const u32 block_start = ai_base + block_offsets[e];
-                // The block ends where the next enemy block starts, or at the end of the file.
-                u32 block_end = file_size;
-                for (int n = e + 1; n < 3; n ++){
-                    if (block_offsets[n] != 0xFFFF){
-                        block_end = ai_base + block_offsets[n];
-                        break;
-                    }
-                }
-                if (block_start + 32 > file_size || block_end > file_size) continue;
-                u16 entries[16];
-                for (int k = 0; k < 16; k ++) entries[k] = bytes[block_start + 2 * k] | (bytes[block_start + 2 * k + 1] << 8);
-                for (int k = 0; k < 16; k ++){
-                    if (entries[k] == 0xFFFF) continue;
-                    // A script ends where the next one starts, or at the end of the block.
-                    u32 script_end = block_end - block_start;
-                    for (int n = 0; n < 16; n ++){
-                        if (entries[n] != 0xFFFF && entries[n] > entries[k] && entries[n] < script_end) script_end = entries[n];
-                    }
-                    if (entries[k] >= script_end || block_start + script_end > file_size) continue;
-                    std::vector<u8> script(
-                      bytes.begin() + block_start + entries[k], bytes.begin() + block_start + script_end
-                    );
-                    // Padding at the end.
-                    while (!script.empty() && script.back() == 0xFF) script.pop_back();
-                    ai_scripts_[e][k] = script;
-                }
-            }
-        }
-    }
-
-    // All the data is read, now format it.
-
-    // Populate enemy list.
-    for (int e = 0; e < 3; e ++){
-        if (scene_.enemy[e] == 0xFFFF) continue;
-        // If the enemy is already on the list, skip it.
-        bool already_added = false;
-        for (int t = 0; t < enemies_.size(); t ++){
-            if (enemies_[t].id == scene_.enemy[e]){
-                already_added = true;
-                break;
-            }
-        }
-        if (already_added) continue;
-        // Create a new enemy
-        Enemy enemy;
-        enemy.id = scene_.enemy[e];
-        enemy.model = FF7Data::GetEnemyModelFromEnemyId(enemy.id);
-        enemy.name = VGears::Utility::DecodeString(scene_.enemy_data[e].name, 32);
-        enemy.level = scene_.enemy_data[e].level;
-        enemy.str = scene_.enemy_data[e].str;
-        enemy.mag = scene_.enemy_data[e].mag;
-        enemy.def = scene_.enemy_data[e].def;
-        enemy.mdef = scene_.enemy_data[e].mdef;
-        enemy.spd = scene_.enemy_data[e].spd;
-        enemy.lck = scene_.enemy_data[e].lck;
-        enemy.eva = scene_.enemy_data[e].eva;
-        enemy.hp = scene_.enemy_data[e].hp;
-        enemy.mp = scene_.enemy_data[e].mp;
-        enemy.exp = scene_.enemy_data[e].exp;
-        enemy.ap = scene_.enemy_data[e].ap;
-        enemy.money = scene_.enemy_data[e].money;
-        enemy.back_damage = scene_.enemy_data[e].back_damage / 8.0f;
-        for (int a = 0; a < 16; a ++){
-            if (scene_.enemy_data[e].animation_index[a] != 0xFF)
-                enemy.animations.push_back(scene_.enemy_data[e].animation_index[a]);
-        }
-        // Attacks. Each of the 16 slots has an attack ID, the animation script of the model to play
-        // and the camera to use.
-        // The AI scripts of the enemy.
-        enemy.ai_scripts = ai_scripts_[e];
-        for (int a = 0; a < 16; a ++){
-            if (scene_.enemy_data[e].attacks[a] == 0xFFFF) continue;
-            Enemy::Attack attack;
-            attack.id = scene_.enemy_data[e].attacks[a];
-            attack.animation
-              = (scene_.enemy_data[e].animation_index[a] != 0xFF)
-              ? scene_.enemy_data[e].animation_index[a] : -1;
-            attack.camera
-              = (scene_.enemy_data[e].attack_camera[a] != 0xFFFF)
-              ? scene_.enemy_data[e].attack_camera[a] : -1;
-            enemy.attacks.push_back(attack);
-        }
-        for (int l = 0; l < 8; l ++){
-            if (scene_.enemy_data[e].elements[l] != 0xFF && scene_.enemy_data[e].element_rates[l] != 0xFF ){
-                Enemy::Element element;
-                element.id = scene_.enemy_data[e].elements[l];
-                switch (scene_.enemy_data[e].element_rates[l]){
-                    case 0x00: element.factor =  11.0f; break; // Death.
-                    case 0x02: element.factor =   2.0f; break; // Double damage.
-                    case 0x04: element.factor =   0.5f; break; // Half damage.
-                    case 0x05: element.factor =   0.0f; break; // Nullify;
-                    case 0x06: element.factor =  -1.0f; break; // Absorb 100%;
-                    case 0x07: element.factor = -11.0f; break; // Full cure;
-                    default: element.factor = 1.0f; // Normal damage.
-                }
-                enemy.elements.push_back(element);
-            }
-        }
-        // Immunities are a bitmask: the bit position is the status ID, as in the original game
-        // (0 death, 1 near death, 2 sleep, 3 poison, 4 sadness, 5 fury, 6 confusion, 7 silence...).
-        if (scene_.enemy_data[e].immunities != 0xFFFFFFFF){
-            for (int bit = 0; bit < 32; bit ++){
-                if ((scene_.enemy_data[e].immunities & (1u << bit)) == 0) continue;
-                Enemy::Immunity immunity;
-                immunity.status = bit;
-                immunity.rate = 1.0f;
-                enemy.immunities.push_back(immunity);
-            }
-        }
-        for (int m = 0; m < 3; m ++){
-            if (scene_.enemy_data[e].maniputale_attacks[m] == 0xFFFF) continue;
-            enemy.manipulate_attacks.push_back(scene_.enemy_data[e].maniputale_attacks[m]);
-        }
-        for (int i = 0; i < 4; i ++){
-            if (scene_.enemy_data[e].item[i] == 0xFF) continue;
-            Enemy::Item item;
-            item.id = scene_.enemy_data[e].item[i];
-            if (scene_.enemy_data[e].item_rate[i] < 0x80){
-                item.rate = scene_.enemy_data[e].item_rate[i] / 63.0f;
-                enemy.drop.push_back(item);
-            }
-            else{
-                item.rate = (scene_.enemy_data[e].item_rate[i] - 0x80) / 63.0f;
-                enemy.steal.push_back(item);
-            }
-        }
-        if (scene_.enemy_data[e].morph != 0xFFFF) enemy.morph = scene_.enemy_data[e].morph;
-
-        enemies_.push_back(enemy);
-    }
-
-    // Populate attack list.
-    for (int a = 0; a < 32; a ++){
-        if (scene_.attack_ids[a] == 0xFFFF) continue;
-        // If the attack is already on the list, skip it.
-        bool already_added = false;
-        for (int t = 0; t < attacks_.size(); t ++){
-            if (attacks_[t].id == scene_.attack_ids[a]){
-                already_added = true;
-                break;
-            }
-        }
-        if (already_added) continue;
-        // Create a new attack.
-        Attack attack;
-        attack.id = scene_.attack_ids[a];
-        attack.name = VGears::Utility::DecodeString(scene_.attack_names[a], 32);
-        attack.damage.accuracy = scene_.attack_data[a].accuracy / 255.0f;
-        if (scene_.attack_data[a].impact_effect != 0xFF)
-            attack.animation.impact_effect = scene_.attack_data[a].impact_effect;
-        if (scene_.attack_data[a].hurt_anim != 0xFF) attack.animation.hurt_anim = scene_.attack_data[a].hurt_anim;
-        attack.mp = scene_.attack_data[a].mp;
-        if (scene_.attack_data[a].sound != 0xFFFF) attack.animation.sound = scene_.attack_data[a].sound;
-        if (scene_.attack_data[a].camera_single != 0xFFFF)
-            attack.animation.camera_single = scene_.attack_data[a].camera_single;
-        if (scene_.attack_data[a].camera_multiple != 0xFFFF)
-            attack.animation.camera_multiple = scene_.attack_data[a].camera_multiple;
-        attack.target.selection_enabled = (scene_.attack_data[a].target == (scene_.attack_data[a].target | 0x01));
-        attack.target.default_enemy = (scene_.attack_data[a].target == (scene_.attack_data[a].target | 0x02));
-        attack.target.default_multiple = (scene_.attack_data[a].target == (scene_.attack_data[a].target | 0x04));
-        attack.target.toggle_multiple = (scene_.attack_data[a].target == (scene_.attack_data[a].target | 0x08));
-        attack.target.fixed_row = (scene_.attack_data[a].target == (scene_.attack_data[a].target | 0x10));
-        attack.target.short_range = (scene_.attack_data[a].target == (scene_.attack_data[a].target | 0x20));
-        attack.target.all_rows = (scene_.attack_data[a].target == (scene_.attack_data[a].target | 0x40));
-        attack.target.random = (scene_.attack_data[a].target == (scene_.attack_data[a].target | 0x80));
-        if (scene_.attack_data[a].effect != 0xFFFF) attack.animation.effect = scene_.attack_data[a].effect;
-        attack.damage.formula = scene_.attack_data[a].damage >> 4;
-        attack.damage.modifier = scene_.attack_data[a].damage & 15;
-        attack.damage.power = scene_.attack_data[a].power;
-        switch(scene_.attack_data[a].condition){
-            case 0: attack.damage.restore = GameData::RestoreType::HP; break;
-            case 1: attack.damage.restore = GameData::RestoreType::MP; break;
-            case 2: attack.damage.restore = GameData::RestoreType::STATUS; break;
-            default: attack.damage.restore = GameData::RestoreType::NONE;
-        }
-        // Status attack byte: the lower 6 bits are the chance out of 63, and the upper 2 bits the
-        // mode (0x80 toggles the statuses, 0x40 cures them, otherwise they are inflicted).
-        // The status bitmask has the status IDs as bit positions, as in the original game.
-        const int status_chance_raw = scene_.attack_data[a].status_change & 0x3F;
-        int status_mode = GameData::STATUS_EFFECT_MODE::INFLICT;
-        if ((scene_.attack_data[a].status_change & 0x80) != 0) status_mode = GameData::STATUS_EFFECT_MODE::TOGGLE;
-        else if ((scene_.attack_data[a].status_change & 0x40) != 0) status_mode = GameData::STATUS_EFFECT_MODE::CURE;
-        if (scene_.attack_data[a].status != 0xFFFFFFFF){
-            const float status_chance = status_chance_raw / 63.0f;
-            for (int bit = 0; bit < 32; bit ++){
-                if ((scene_.attack_data[a].status & (1u << bit)) == 0) continue;
-                Attack::StatusEffect effect;
-                effect.id = bit;
-                effect.chance = status_chance;
-                effect.type = status_mode;
-                attack.status_effects.push_back(effect);
-            }
-        }
-        // Attack elements are a bitmask (0x0001 is fire, 0x0002 ice...), while enemies elements are
-        // indexes (0 is fire, 1 is ice...). Elements are stored as indexes.
-        if (scene_.attack_data[a].element != 0xFFFF){
-            for (int bit = 0; bit < 16; bit ++){
-                if ((scene_.attack_data[a].element & (1 << bit)) != 0) attack.elements.push_back(bit);
-            }
-        }
-        attack.damage.damage_mp = (scene_.attack_data[a].special != (scene_.attack_data[a].special | 0x0001));
-        attack.damage.affected_by_darkness = (scene_.attack_data[a].special != (scene_.attack_data[a].special | 0x0004));
-        if ((scene_.attack_data[a].special != (scene_.attack_data[a].special | 0x0010))){
-            if (attack.damage.damage_mp) attack.damage.drain_mp = true;
-            else attack.damage.drain_hp = true;
-        }
-        if ((scene_.attack_data[a].special != (scene_.attack_data[a].special | 0x0020))){
-            attack.damage.drain_hp = true;
-            attack.damage.drain_mp = true;
-        }
-        attack.damage.ignore_status_defense
-          = (scene_.attack_data[a].special != (scene_.attack_data[a].special | 0x0080));
-        attack.target.only_for_dead = (scene_.attack_data[a].special != (scene_.attack_data[a].special | 0x0100));
-        attack.reflectable = (scene_.attack_data[a].special != (scene_.attack_data[a].special | 0x0200));
-        attack.target.no_re_target = (scene_.attack_data[a].special != (scene_.attack_data[a].special | 0x0800));
-        attack.damage.critical = (scene_.attack_data[a].special != (scene_.attack_data[a].special | 0x2000));
-
-        // TODO: Parse scene_.attack_data[a].additional_effects with
-        // scene_.attack_data[a].additional_effects_mod for special attack modifiers (23 total).
-        // https://wiki.ffrtt.ru/index.php/FF7/Battle/Attack_Special_Effects
-
-        //std::cout << "ATTACK " << ((int) attack.id) << ": " << attack.name << "\n";
-        attacks_.push_back(attack);
-    }
-
-    // Formations
-    for (int f = 0; f < 4; f ++){
-        Formation formation;
-        if (scene_.setup[f].next_battle != 0xFFFF) formation.next_formation = scene_.setup[f].next_battle;
-        formation.escape_counter = (scene_.setup[f].escape_counter / 64.0f);
-        // Observed in the original scene.bin (1024 setups): the upper byte is always 0xFF and
-        // bit 0x02 is clear in most random battles, so it means "can't escape" (inverted).
-        // TODO: What is flag 0x01?
-        formation.escapable = ((scene_.setup[f].flags & 0x02) == 0);
-        // TODO: Bits 0x04, 0x08 and 0x10 are set in almost every setup, so they can't be read as
-        // positive "skip victory pose", "skip spoils" and "preemptive disabled" flags (the previous
-        // code, due to operator precedence, always set all three). Use defaults until their
-        // meaning is verified against known battles.
-        formation.skip_victory_pose = false;
-        formation.skip_spoils = false;
-        formation.preemptive_disabled = false;
-        // TODO: What is flag 0x20?
-        // TODO: What is flag 0x40?
-        // TODO: What is flag 0x80?
-        switch(scene_.setup[f].layout){
-            case 0x0: formation.layout = Formation::Layout::NORMAL; break;
-            case 0x1: formation.layout = Formation::Layout::PREEMPTIVE; break;
-            case 0x2: formation.layout = Formation::Layout::BACK_ATTACK; break;
-            case 0x3: formation.layout = Formation::Layout::SIDE_ATTACK; break;
-            case 0x4: formation.layout = Formation::Layout::PINCER_ATTACK; break;
-            case 0x5: formation.layout = Formation::Layout::PINCER_ATTACK; break;
-            case 0x6: formation.layout = Formation::Layout::SIDE_ATTACK; break;
-            case 0x7: formation.layout = Formation::Layout::SIDE_ATTACK; break;
-            case 0x8: formation.layout = Formation::Layout::LOCKED; break;
-            default: formation.layout = Formation::Layout::NORMAL;
-        }
-        for (int e = 0; e < 6; e ++){
-            if (scene_.formation[f][e].id != 0xFFFF){
-                Formation::Enemy enemy;
-                enemy.id = scene_.formation[f][e].id;
-                enemy.x = scene_.formation[f][e].x;
-                enemy.y = scene_.formation[f][e].y;
-                enemy.z = scene_.formation[f][e].z;
-                enemy.row = scene_.formation[f][e].row;
-                enemy.cover[0] = (
-                  scene_.formation[f][e].cover_flags == (scene_.formation[f][e].cover_flags | 0x01) ? '1' : '0'
-                );
-                enemy.cover[1] = (
-                  scene_.formation[f][e].cover_flags == (scene_.formation[f][e].cover_flags | 0x02) ? '1' : '0'
-                );
-                enemy.cover[2] = (
-                  scene_.formation[f][e].cover_flags == (scene_.formation[f][e].cover_flags | 0x04) ? '1' : '0'
-                );
-                enemy.cover[3] = (
-                  scene_.formation[f][e].cover_flags == (scene_.formation[f][e].cover_flags | 0x08) ? '1' : '0'
-                );
-                enemy.cover[4] = (
-                  scene_.formation[f][e].cover_flags == (scene_.formation[f][e].cover_flags | 0x10) ? '1' : '0'
-                );
-                enemy.visible = (scene_.formation[f][e].flags == scene_.formation[f][e].flags | 0x01);
-                enemy.direction = ((scene_.formation[f][e].flags == scene_.formation[f][e].flags | 0x02) ? 1 : 0);
-                enemy.targeteable = (scene_.formation[f][e].flags == scene_.formation[f][e].flags | 0x08);
-                enemy.main_script_active = (scene_.formation[f][e].flags == scene_.formation[f][e].flags | 0x10);
-                formation.enemies.push_back(enemy);
-            }
-        }
-        formation.location = scene_.setup[f].location;
-        formation.location_name = LocationToString(scene_.setup[f].location);
-        for (int c = 0; c < 3; c ++){
-            Formation::Camera camera;
-            // The original data has x to the side, y down and z in depth (the enemies are in the negative
-            // side). The scene has the same x, the depth in y and z up, in units 255 times bigger, like the
-            // positions of the enemies.
-            const BattleSceneFile::Scene::Camera::Position& source = scene_.camera[f].camera[c];
-            camera.x = source.x / 255.0f;
-            camera.y = source.z / 255.0f;
-            camera.z = -source.y / 255.0f;
-            camera.d_x = source.d_x / 255.0f;
-            camera.d_y = source.d_z / 255.0f;
-            camera.d_z = -source.d_y / 255.0f;
-            formation.camera_positions.push_back(camera);
-        }
-        // The camera byte of the formation is the script of the camera at the start of the battle, which
-        // ends at the first camera of the formation unless it chooses another one.
-        formation.intro_camera = scene_.setup[f].camera;
-        for (int a = 0; a < 4; a ++){
-            if (scene_.setup[f].next_arena_candidates[a] != 999){
-                formation.next_arena_formation_candidates.push_back(scene_.setup[f].next_arena_candidates[a]);
-                formation.is_arena_battle = true;
-            }
-        }
-        formations_.push_back(formation);
-    }
-
-}
-
-std::string BattleSceneFile::LocationToString(const int id){
-    switch(id){
-        case 0x0000: return "blank";
-        case 0x0001: return "bizarro_battle_center";
-        case 0x0002: return "grassland";
-        case 0x0003: return "mt_nibel";
-        case 0x0004: return "forest";
-        case 0x0005: return "beach";
-        case 0x0006: return "desert";
-        case 0x0007: return "snow";
-        case 0x0008: return "swamp";
-        case 0x0009: return "sector_1_train_station";
-        case 0x000a: return "reactor_1";
-        case 0x000b: return "reactor_1_core";
-        case 0x000c: return "reactor_1_entrance";
-        case 0x000d: return "sector_4_subway";
-        case 0x000e: return "nibel_caves";
-        case 0x000f: return "shinra_hq";
-        case 0x0010: return "midgar_raid_subway";
-        case 0x0011: return "hojo_lab";
-        case 0x0012: return "shinra_elevators";
-        case 0x0013: return "shinra_roof";
-        case 0x0014: return "midgar_highway";
-        case 0x0015: return "wutai_pagoda";
-        case 0x0016: return "church";
-        case 0x0017: return "coral_valley";
-        case 0x0018: return "midgar_slums";
-        case 0x0019: return "sector_4_corridors";
-        case 0x001a: return "sector_4_gantries";
-        case 0x001b: return "sector_7_pillar_stairway";
-        case 0x001c: return "sector_7pillar_top";
-        case 0x001d: return "sector_8";
-        case 0x001e: return "sewers";
-        case 0x001f: return "mythril_mines";
-        case 0x0020: return "crater_floating_platforms";
-        case 0x0021: return "corel_mountain_path";
-        case 0x0022: return "junon_beach";
-        case 0x0023: return "junon_cargo_ship";
-        case 0x0024: return "corel_prison";
-        case 0x0025: return "battle_square";
-        case 0x0026: return "da_chao_rapps_battle";
-        case 0x0027: return "cids_backyard";
-        case 0x0028: return "final_descent_to_sephiroth";
-        case 0x0029: return "reactor_5_entrance";
-        case 0x002a: return "ancients_escher_room";
-        case 0x002b: return "shinra_mansion";
-        case 0x002c: return "junon_airship_dock";
-        case 0x002d: return "whirlwind_maze";
-        case 0x002e: return "junon_underwater_reactor";
-        case 0x002f: return "gongaga_reactor";
-        case 0x0030: return "gelnika";
-        case 0x0031: return "train_graveyard";
-        case 0x0032: return "ice_caves";
-        case 0x0033: return "sister_ray";
-        case 0x0034: return "sister_ray_base";
-        case 0x0035: return "forgotten_city_altar";
-        case 0x0036: return "crater_descent";
-        case 0x0037: return "crater_hatchery";
-        case 0x0038: return "crater_water_area";
-        case 0x0039: return "safer_battle";
-        case 0x003a: return "kalm_flashback_dragon";
-        case 0x003b: return "junon_pipe";
-        case 0x003c: return "blank";
-        case 0x003d: return "railway_canyon";
-        case 0x003e: return "whirlwind_maze_crater";
-        case 0x003f: return "railway_rollercoaster";
-        case 0x0040: return "wooden_bridge";
-        case 0x0041: return "da_chao";
-        case 0x0042: return "fort_condor";
-        case 0x0043: return "dirt_wasteland";
-        case 0x0044: return "bizarro_battle_right";
-        case 0x0045: return "bizarro_battle_left";
-        case 0x0046: return "jenova_synthesis";
-        case 0x0047: return "corel_train_battle";
-        case 0x0048: return "cosmo_canyon";
-        case 0x0049: return "caverns_of_the_gi";
-        case 0x004a: return "nibelheim_mansion_basement";
-        case 0x004b: return "ancients_demons_gate";
-        case 0x004c: return "ancients_mural_room";
-        case 0x004d: return "ancients_clock_passage";
-        case 0x004e: return "final_battle";
-        case 0x004f: return "jungle";
-        case 0x0050: return "ultimate_weapon_highwind";
-        case 0x0051: return "corel_reactor";
-        case 0x0052: return "unused";
-        case 0x0053: return "don_corneos_mansion";
-        case 0x0054: return "emerald_weapon_battle";
-        case 0x0055: return "reactor_5";
-        case 0x0056: return "shinra_hq_-_escape";
-        case 0x0057: return "ultimate_weapon_gongaga";
-        case 0x0058: return "corel_prison_dyne";
-        case 0x0059: return "ultimate_weapon_forest";
-        default: return "unknonw_location";
-    }
-}

+ 13 - 582
src/installer/formats/BattleSceneFile.h

@@ -16,12 +16,17 @@
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  */
 
-#include <string>
-#include <common/File.h>
-#include <installer/formats/Attack.h>
-#include <installer/formats/Enemy.h>
-#include <installer/formats/Formation.h>
+#pragma once
 
+#include <vector>
+#include "common/File.h"
+#include "installer/formats/Attack.h"
+#include "installer/formats/Enemy.h"
+#include "installer/formats/Formation.h"
+
+/**
+ * A battle scene.
+ */
 class BattleSceneFile{
 
     public:
@@ -29,17 +34,12 @@ class BattleSceneFile{
         /**
          * Constructor.
          *
-         * Reads data from a file.
+         * Reads a scene, with {@see BattleSceneReader}, and converts it, with
+         * {@see BattleSceneConverter}.
          *
-         * @param[in] id ID of the file, the position at which it is found.
          * @param[in] file File to read from.
          */
-        BattleSceneFile(const unsigned int id, File file);
-
-        /**
-         * Destructor.
-         */
-        ~BattleSceneFile();
+        explicit BattleSceneFile(File file);
 
         /**
          * Retrieves the attacks found in the scene.
@@ -64,569 +64,6 @@ class BattleSceneFile{
 
     private:
 
-        /**
-         * A battle scene structure.
-         */
-        struct Scene{
-
-            /**
-             * Scene battle setup data (20 bytes).
-             */
-            struct Setup{
-
-                /**
-                 * Battle location.
-                 */
-                u16 location;
-
-                /**
-                 * ID of the battle that start upon defeating all enemies.
-                 *
-                 * If set, a new set of enemies will be loaded when all the
-                 * current ones are defeated, without ending the battle scene.
-                 */
-                u16 next_battle;
-
-                /**
-                 * @todo Understand and document.
-                 */
-                u16 escape_counter;
-
-                /**
-                 * Unused data.
-                 */
-                u16 unused;
-
-                /**
-                 * In arena battles, candidate enemy formation IDs for next
-                 * round.
-                 */
-                u16 next_arena_candidates[4];
-
-                /**
-                 * Battle flags.
-                 *
-                 * Includes the escapable flag.
-                 */
-                u16 flags;
-
-                /**
-                 * Battle layout.
-                 *
-                 * 00 - Normal figh.t
-                 * 01 - Preemptive.
-                 * 02 - Back attack.
-                 * 03 - Side attack.
-                 * 04 - Attacked from both sides (pincer attack, reverse side).
-                 * 05 - Another attack from both sides battle (different maybe?).
-                 * 06 - Another side attack.
-                 * 07 - A third side attack.
-                 * 08 - Normal battle that locks player in the front row, change
-                 * command disabled.
-                 */
-                u8 layout;
-
-                /**
-                 * Indexed Pre-Battle Camera position.
-                 */
-                u8 camera;
-            };
-
-            /**
-             * Scene camera placement data.
-             */
-            struct Camera{
-
-                /**
-                 * Position for a camera scene.
-                 */
-                struct Position{
-
-                    /**
-                     * X position.
-                     */
-                    int x;
-
-                    /**
-                     * Y position.
-                     */
-                    int y;
-
-                    /**
-                     * z position.
-                     */
-                    int z;
-
-                    /**
-                     * X direction.
-                     */
-                    int d_x;
-
-                    /**
-                     * Y direction.
-                     */
-                    int d_y;
-
-                    /**
-                     * z direction.
-                     */
-                    int d_z;
-                };
-
-                /**
-                 * Camera positions.
-                 *
-                 * Index 0 is primary, indexes 1 and 2 are secondary positions.
-                 */
-                Position camera[3];
-
-                /**
-                 * Unused data.
-                 */
-                u8 unused[12];
-            };
-
-            /**
-             * A scene formation structure.
-             */
-            struct Formation{
-
-                /**
-                 * Enemy ID.
-                 */
-                u16 id;
-
-                /**
-                 * Enemy X position.
-                 */
-                int x;
-
-                /**
-                 * Enemy Y position.
-                 */
-                int y;
-
-                /**
-                 * Enemy Z position.
-                 */
-                int z;
-
-                /**
-                 * Enemy row.
-                 */
-                u16 row;
-
-                /**
-                 * Binary "Cover Flags".
-                 *
-                 * These flags are used in conjunction with row to determine if
-                 * a target can be selected as the target of a short-range
-                 * attack. The determination of this is worked out in this way:
-                 * An enemy exists in row 1 and another in row 2. If the enemy
-                 * in row 1 shares a cover flag with the enemy in row 2 then the
-                 * enemy in row 2 cannot be targeted until all enemies in row 1
-                 * that share a cover flag with the row 2 enemy is defeated. It
-                 * works like this. Two active enemies exist, A and B.
-                 *
-                 * If ((B's row > A's row) and
-                 * (B's cover flags AND A's cover flags) > 0) then enemy B
-                 * cannot be targeted by short-range attacks.
-                 */
-                u16 cover_flags;
-
-                /**
-                 * Initial condition flags. Only last 5 bits are considered.
-                 * 0x0001  Visible.
-                 * 0x0002  Indicates initial direction facing if players get a
-                 * side attack.
-                 * 0x0004  Unknown.
-                 * 0x0008  Targetable.
-                 * 0x0010  Main Script Active.
-                 */
-                u32 flags;
-            };
-
-            struct EnemyData{
-
-                /**
-                 * Enemy's name (completed by FFh bytes).
-                 */
-                u8 name[32];
-
-                /**
-                 * Enemy's level.
-                 */
-                u8 level;
-
-                /**
-                 * Enemy's speed.
-                 */
-                u8 spd;
-
-                /**
-                 * Enemy's luck.
-                 */
-                u8 lck;
-
-                /**
-                 * Enemy's evade stat.
-                 */
-                u8 eva;
-
-                /**
-                 * Enemy's strength.
-                 */
-                u8 str;
-
-                /**
-                 * Enemy's defense.
-                 */
-                u8 def;
-
-                /**
-                 * Enemy's magic.
-                 */
-                u8 mag;
-
-                /**
-                 * Enemy's magic defense.
-                 */
-                u8 mdef;
-
-                /**
-                 * Elements of the enemy.
-                 */
-                u8 elements[8];
-
-                /**
-                 * Element rates for @{see elements}, respectively.
-                 */
-                u8 element_rates[8];
-
-                /**
-                 * Animation index for each @{see attacks}.
-                 */
-                u8 animation_index[16];
-
-                /**
-                 * Enemy attack IDs.
-                 */
-                u16 attacks[16];
-
-                /**
-                 * Enemy Attacks Camera Movement Id for single and multiple
-                 * targets (2 bytes each).
-                 *
-                 * If set this will overwrite camera movement set in attack
-                 * itself.
-                 */
-                u16 attack_camera[16];
-
-                /**
-                 * Item drop/steal rates.
-                 *
-                 * These are chances to get items listed in @{see item}. 1 byte
-                 * per item. If the rate is lower than 80h, for e.g. 08h - then
-                 * this is a drop item and has 8/63 [63 is max] chance for drop.
-                 * But if rate is higher than 80h, let's say... A0h, then this
-                 * is an item for steal, and chances for successful steal is
-                 * A0h - 80h = 20h = 32/63.
-                 */
-                u8 item_rate[4];
-
-                /**
-                 * IDs of items dropped/stolen from the enemy.
-                 *
-                 * 0xFFFF means no item.
-                 */
-                u8 item[4];
-
-                /**
-                 * IDs of attacks that can be performed while manipulated.
-                 *
-                 * The first one is the attack to use in berserk mode.
-                 */
-                u16 maniputale_attacks[3];
-
-                /**
-                 * Unknown data.
-                 */
-                u16 unknown_0;
-
-                /**
-                 * Enemy's MP.
-                 */
-                u16 mp;
-
-                /**
-                 * AP given upon enemy defeat.
-                 */
-                u16 ap;
-
-                /**
-                 * ID of the item the enemy can be morphed into.
-                 *
-                 * If 0xFFFF, the enemy can't be morphed
-                 */
-                u16 morph;
-
-                /**
-                 * Back damage multiplier.
-                 *
-                 * damage = damage * back_damage / 8.
-                 */
-                u8 back_damage;
-
-                /**
-                 * Unused data (align).
-                 */
-                u8 unused;
-
-                /**
-                 * Enemy's HP.
-                 */
-                u32 hp;
-
-                /**
-                 * Experience points given upon defeat.
-                 */
-                u32 exp;
-
-                /**
-                 * Money given upon defeat.
-                 */
-                u32 money;
-
-                /**
-                 * Status immunities.
-                 *
-                 * @todo: a bit set is an immunity?
-                 */
-                u32 immunities;
-
-                /**
-                 * Unknown data.
-                 */
-                u32 unknown_1;
-            };
-
-            /**
-             * A battle scene attack data structure.
-             */
-            struct AttackData{
-
-                /**
-                 * Probability of the attack to land. 1 byte.
-                 */
-                u8 accuracy;
-
-                /**
-                 * Impact effect. 1 byte.
-                 *
-                 * The sprite shown when the attack hits.
-                 */
-                u8 impact_effect;
-
-                /**
-                 * Index of the animation played by the target when hit. 1 byte.
-                 */
-                u8 hurt_anim;
-
-                /**
-                 * Unknown data. 1 bytes.
-                 */
-                u8 unknown;
-
-                /**
-                 * MP cost. 2 bytes.
-                 *
-                 * Determines the camera movement when the command is executed
-                 * over a single target.
-                 */
-                u16 mp;
-
-                /**
-                 * Impact sound. 2 bytes.
-                 *
-                 * Determines the camera movement when the command is executed
-                 * over multiple targets.
-                 */
-                u16 sound;
-
-                /**
-                 * Camera movement ID for single target. 2 bytes.
-                 *
-                 * Determines the camera movement when the command is executed
-                 * over a single target.
-                 */
-                u16 camera_single;
-
-                /**
-                 * Camera movement ID for multiple target. 2 bytes.
-                 *
-                 * Determines the camera movement when the command is executed
-                 * over multiple targets.
-                 */
-                u16 camera_multiple;
-
-                /**
-                 * Targeting mode. 1 byte.
-                 */
-                u8 target;
-
-                /**
-                 * Atack effect ID. 1 byte.
-                 *
-                 * Used for animation in battle.
-                 */
-                u8 effect;
-
-                /**
-                 * Damage formula. 1 byte.
-                 *
-                 * This byte is divided into two nybbles (four bits). Upper
-                 * nybble determines what considerations are made in calculating
-                 * damage such as physical/magical, allowing criticals, how to
-                 * calculate accuracy, etc. There are also three sets of known
-                 * formulae that are paired with the upper nybble values. These
-                 * are selected in the Lower Nybble and determine how to
-                 * calculate pre-defense damage
-                 */
-                u8 damage;
-
-                /**
-                 * The attack power. 1 byte.
-                 *
-                 * Used for damage/healing calculation.
-                 */
-                u8 power;
-
-                /**
-                 * The restore type.
-                 */
-                u8 condition;
-
-                /**
-                 * Information about status change mode and chance. 1 bytes.
-                 */
-                u8 status_change;
-
-                /**
-                 * Special flags. 1 byte.
-                 *
-                 * @todo Document and retrieve with info from
-                 * https://wiki.ffrtt.ru/index.php?title=FF7/Battle/Attack_Special_Effects
-                 */
-                u8 additional_effects;
-
-                /**
-                 * Special flags. 1 byte.
-                 *
-                 * @todo Document and retrieve with info from
-                 * https://wiki.ffrtt.ru/index.php?title=FF7/Item_data
-                 */
-                u8 additional_effects_mod;
-
-                /**
-                 * Information about what status can be inflicted or cured. 4
-                 * bytes.
-                 *
-                 * The first six bits are the chance of inflicting/curing (out
-                 * of 63). If the seventh bit is set, the status is cured
-                 * instead of inflicted. If the eighth bit is set, then the
-                 * status is toggled (cured if present, inflicted if not
-                 * present).
-                 */
-                u32 status;
-
-                /**
-                 * Information about the item elements. 2 bytes.
-                 */
-                u16 element;
-
-                /**
-                 * Special flags. 2 bytes.
-                 *
-                 * @todo document and parse with info from
-                 * https://wiki.ffrtt.ru/index.php?title=FF7/Battle/Special_Attack_Flags
-                 */
-                u16 special;
-
-            };
-
-            /**
-             * Enemy IDs.
-             */
-            u16 enemy[3];
-
-            /**
-             * Unused data (padding).
-             */
-            u16 unused;
-
-            /**
-             * Battle scene set-ups.
-             */
-            Setup setup[4];
-
-            /**
-             * Camera placement data.
-             */
-            Camera camera[4];
-
-            /**
-             * Battle formation data.
-             */
-            Formation formation[4][6];
-
-            /**
-             * Enemy data.
-             */
-            EnemyData enemy_data[3];
-
-            /**
-             * Attack data.
-             */
-            AttackData attack_data[32];
-
-            /**
-             * Attack IDs.
-             */
-            u16 attack_ids[32];
-
-            /**
-             * Attack names.
-             */
-            u8 attack_names[32][32];
-
-            // TOOD: AI
-        };
-
-        /**
-         * Retrieves a location name from it's ID.
-         *
-         * @param[in] id Location ID.
-         * @return The location name, or "UNKNOWN Location" for an invalid ID.
-         */
-        static std::string LocationToString(const int id);
-
-        /**
-         * Reads data from a file.
-         *
-         * @param[in] file File to read from.
-         */
-        void Read(File file);
-
-        /**
-         * The file ID.
-         */
-        unsigned int id_;
-
-        /**
-         * The scene data.
-         */
-        Scene scene_;
-
         /**
          * Attacks found in the scene.
          */
@@ -637,14 +74,8 @@ class BattleSceneFile{
          */
         std::vector<Enemy> enemies_;
 
-        /**
-         * AI scripts of the 3 enemies of the scene, 16 slots each.
-         */
-        std::vector<std::vector<u8>> ai_scripts_[3];
-
         /**
          * Formations found in the scene.
          */
         std::vector<Formation> formations_;
-
 };

+ 228 - 0
src/installer/formats/BattleSceneReader.cpp

@@ -0,0 +1,228 @@
+/*
+ * V-Gears
+ * Copyright (C) 2022 V-Gears Team
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "BattleSceneReader.h"
+
+namespace{
+
+    /**
+     * Offset of the AI scripts in a scene.
+     */
+    const u32 AI_OFFSET = 0x0E80;
+
+    /**
+     * Reads a coordinate of an enemy.
+     *
+     * It's stored as a 16 bit value in units 255 times bigger. Values over 0x7F9B are negative.
+     */
+    int ReadCoordinate(File& file){
+        int value = file.readU16LE();
+        if (value > 0x7F9B) value -= 0xFFFF;
+        return value / 0xFF;
+    }
+
+    /**
+     * Reads a little endian 16 bit value.
+     */
+    u16 ReadU16(const std::vector<u8>& bytes, const u32 offset){
+        return static_cast<u16>(bytes[offset] | (bytes[offset + 1] << 8));
+    }
+
+    void ReadSetups(File& file, BattleSceneData& data){
+        for (int s = 0; s < 4; s ++){
+            data.setup[s].location = file.readU16LE();
+            data.setup[s].next_battle = file.readU16LE();
+            data.setup[s].escape_counter = file.readU16LE();
+            data.setup[s].unused = file.readU16LE();
+            for (int a = 0; a < 4; a ++) data.setup[s].next_arena_candidates[a] = file.readU16LE();
+            data.setup[s].flags = file.readU16LE();
+            data.setup[s].layout = file.readU8();
+            data.setup[s].camera = file.readU8();
+        }
+    }
+
+    void ReadCameras(File& file, BattleSceneData& data){
+        for (int c = 0; c < 4; c ++){
+            for (int p = 0; p < 3; p ++){
+                // The position of the camera and the point it looks at, signed 16 bit values in the units of
+                // the original game. They are kept as they are, and converted when the formations are built.
+                data.camera[c].camera[p].x = static_cast<int16_t>(file.readU16LE());
+                data.camera[c].camera[p].y = static_cast<int16_t>(file.readU16LE());
+                data.camera[c].camera[p].z = static_cast<int16_t>(file.readU16LE());
+                data.camera[c].camera[p].d_x = static_cast<int16_t>(file.readU16LE());
+                data.camera[c].camera[p].d_y = static_cast<int16_t>(file.readU16LE());
+                data.camera[c].camera[p].d_z = static_cast<int16_t>(file.readU16LE());
+            }
+            for (int p = 0; p < 12; p ++) data.camera[c].unused[p] = file.readU8();
+        }
+    }
+
+    void ReadFormations(File& file, BattleSceneData& data){
+        for (int f = 0; f < 4; f ++){
+            for (int e = 0; e < 6; e ++){
+                data.formation[f][e].id = file.readU16LE();
+                data.formation[f][e].x = ReadCoordinate(file);
+                // Y and Z are inverted in original data.
+                data.formation[f][e].z = ReadCoordinate(file);
+                data.formation[f][e].y = ReadCoordinate(file);
+                data.formation[f][e].row = file.readU16LE();
+                data.formation[f][e].cover_flags = file.readU16LE();
+                data.formation[f][e].flags = file.readU32LE();
+            }
+        }
+    }
+
+    void ReadEnemies(File& file, BattleSceneData& data){
+        for (int e = 0; e < 3; e ++){
+            for (int n = 0; n < 32; n ++) data.enemy_data[e].name[n] = file.readU8();
+            data.enemy_data[e].level = file.readU8();
+            data.enemy_data[e].spd = file.readU8();
+            data.enemy_data[e].lck = file.readU8();
+            data.enemy_data[e].eva = file.readU8();
+            data.enemy_data[e].str = file.readU8();
+            data.enemy_data[e].def = file.readU8();
+            data.enemy_data[e].mag = file.readU8();
+            data.enemy_data[e].mdef = file.readU8();
+            for (int l = 0; l < 8; l ++) data.enemy_data[e].elements[l] = file.readU8();
+            for (int l = 0; l < 8; l ++) data.enemy_data[e].element_rates[l] = file.readU8();
+            for (int a = 0; a < 16; a ++) data.enemy_data[e].animation_index[a] = file.readU8();
+            for (int a = 0; a < 16; a ++) data.enemy_data[e].attacks[a] = file.readU16LE();
+            for (int a = 0; a < 16; a ++) data.enemy_data[e].attack_camera[a] = file.readU16LE();
+            for (int i = 0; i < 4; i ++) data.enemy_data[e].item_rate[i] = file.readU8();
+            for (int i = 0; i < 4; i ++) data.enemy_data[e].item[i] = file.readU16LE();
+            for (int m = 0; m < 3; m ++) data.enemy_data[e].maniputale_attacks[m] = file.readU16LE();
+            data.enemy_data[e].unknown_0 = file.readU16LE();
+            data.enemy_data[e].mp = file.readU16LE();
+            data.enemy_data[e].ap = file.readU16LE();
+            data.enemy_data[e].morph = file.readU16LE();
+            data.enemy_data[e].back_damage = file.readU8();
+            data.enemy_data[e].unused = file.readU8();
+            data.enemy_data[e].hp = file.readU32LE();
+            data.enemy_data[e].exp = file.readU32LE();
+            data.enemy_data[e].money = file.readU32LE();
+            data.enemy_data[e].immunities = file.readU32LE();
+            data.enemy_data[e].unknown_1 = file.readU32LE();
+        }
+    }
+
+    void ReadAttacks(File& file, BattleSceneData& data){
+        for (int a = 0; a < 32; a ++){
+            data.attack_data[a].accuracy = file.readU8();
+            data.attack_data[a].impact_effect = file.readU8();
+            data.attack_data[a].hurt_anim = file.readU8();
+            data.attack_data[a].unknown = file.readU8();
+            data.attack_data[a].mp = file.readU16LE();
+            data.attack_data[a].sound = file.readU16LE();
+            data.attack_data[a].camera_single = file.readU16LE();
+            data.attack_data[a].camera_multiple = file.readU16LE();
+            data.attack_data[a].target = file.readU8();
+            data.attack_data[a].effect = file.readU8();
+            data.attack_data[a].damage = file.readU8();
+            data.attack_data[a].power = file.readU8();
+            data.attack_data[a].condition = file.readU8();
+            data.attack_data[a].status_change = file.readU8();
+            data.attack_data[a].additional_effects = file.readU8();
+            data.attack_data[a].additional_effects_mod = file.readU8();
+            data.attack_data[a].status = file.readU32LE();
+            data.attack_data[a].element = file.readU16LE();
+            data.attack_data[a].special = file.readU16LE();
+        }
+        for (int a = 0; a < 32; a ++) data.attack_ids[a] = file.readU16LE();
+        for (int a = 0; a < 32; a ++) for (int b = 0; b < 32; b ++) data.attack_names[a][b] = file.readU8();
+    }
+
+    /**
+     * Reads the AI scripts of an enemy.
+     *
+     * An enemy block has 16 offsets (0xFFFF for slots without a script) followed by the scripts,
+     * which end with the opcode 0x73.
+     *
+     * @param[in] bytes The scene.
+     * @param[in] start Where the block of the enemy starts.
+     * @param[in] end Where it ends.
+     * @param[in,out] scripts The scripts of the enemy.
+     */
+    void ReadEnemyScripts(
+      const std::vector<u8>& bytes, const u32 start, const u32 end,
+      std::vector<std::vector<u8>>& scripts
+    ){
+        const u32 size = static_cast<u32>(bytes.size());
+        if (start + 32 > size || end > size) return;
+        u16 entries[16];
+        for (int k = 0; k < 16; k ++) entries[k] = ReadU16(bytes, start + 2 * k);
+        for (int k = 0; k < 16; k ++){
+            if (entries[k] == 0xFFFF) continue;
+            // A script ends where the next one starts, or at the end of the block.
+            u32 script_end = end - start;
+            for (int n = 0; n < 16; n ++){
+                if (entries[n] != 0xFFFF && entries[n] > entries[k] && entries[n] < script_end)
+                    script_end = entries[n];
+            }
+            if (entries[k] >= script_end || start + script_end > size) continue;
+            std::vector<u8> script(
+              bytes.begin() + start + entries[k], bytes.begin() + start + script_end
+            );
+            // Padding at the end.
+            while (!script.empty() && script.back() == 0xFF) script.pop_back();
+            scripts[k] = script;
+        }
+    }
+}
+
+namespace BattleSceneReader{
+
+    BattleSceneData Read(File file){
+        // Value initialized: the parts a short file doesn't have are zeroes.
+        BattleSceneData data{};
+        file.SetOffset(0);
+        for (int e = 0; e < 3; e ++) data.enemy[e] = file.readU16LE();
+        data.unused = file.readU16LE();
+        ReadSetups(file, data);
+        ReadCameras(file, data);
+        ReadFormations(file, data);
+        ReadEnemies(file, data);
+        ReadAttacks(file, data);
+        const u32 size = file.GetFileSize();
+        std::vector<u8> bytes(size);
+        if (size > 0) file.GetFileBuffer(bytes.data(), 0, size);
+        ReadAiScripts(bytes, data);
+        return data;
+    }
+
+    void ReadAiScripts(const std::vector<u8>& bytes, BattleSceneData& data){
+        for (int e = 0; e < 3; e ++) data.ai_scripts[e].assign(16, std::vector<u8>());
+        // The AI block is at a fixed offset, and starts with an offset for each of the 3 enemies
+        // of the scene (0xFFFF if the enemy has none).
+        const u32 size = static_cast<u32>(bytes.size());
+        if (size <= AI_OFFSET + 6) return;
+        u16 blocks[3];
+        for (int e = 0; e < 3; e ++) blocks[e] = ReadU16(bytes, AI_OFFSET + 2 * e);
+        for (int e = 0; e < 3; e ++){
+            if (blocks[e] == 0xFFFF) continue;
+            // The block ends where the next enemy block starts, or at the end of the file.
+            u32 end = size;
+            for (int n = e + 1; n < 3; n ++){
+                if (blocks[n] != 0xFFFF){
+                    end = AI_OFFSET + blocks[n];
+                    break;
+                }
+            }
+            ReadEnemyScripts(bytes, AI_OFFSET + blocks[e], end, data.ai_scripts[e]);
+        }
+    }
+}

+ 47 - 0
src/installer/formats/BattleSceneReader.h

@@ -0,0 +1,47 @@
+/*
+ * V-Gears
+ * Copyright (C) 2022 V-Gears Team
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#pragma once
+
+#include <vector>
+#include "common/File.h"
+#include "BattleSceneData.h"
+
+/**
+ * Reads the data of a battle scene, as it is in the file.
+ */
+namespace BattleSceneReader{
+
+    /**
+     * Reads a scene.
+     *
+     * @param[in] file The file of the scene.
+     * @return The data.
+     */
+    BattleSceneData Read(File file);
+
+    /**
+     * Reads the AI scripts of the enemies of a scene.
+     *
+     * Blocks and scripts that go past the end of the scene are left out.
+     *
+     * @param[in] bytes The whole scene.
+     * @param[in,out] data The scripts are set in it.
+     */
+    void ReadAiScripts(const std::vector<u8>& bytes, BattleSceneData& data);
+}

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

@@ -1,7 +1,9 @@
 # Sources of this folder (see vgears_sources in src/CMakeLists.txt).
 vgears_sources(
     AbFile.cpp
+    BattleSceneConverter.cpp
     BattleSceneFile.cpp
+    BattleSceneReader.cpp
     BinGZipFile.cpp
     DaFile.cpp
     DiskExtractor.cpp

+ 2 - 0
src/installer/formats/Enemy.h

@@ -16,6 +16,8 @@
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  */
 
+#pragma once
+
 #include <string>
 #include "common/TypeDefine.h"
 #include "common/GameData.h"

+ 2 - 0
src/installer/formats/Formation.h

@@ -16,6 +16,8 @@
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  */
 
+#pragma once
+
 #include <string>
 #include "common/TypeDefine.h"
 #include "common/GameData.h"

+ 132 - 0
test/installer/formats/BattleScene.cpp

@@ -0,0 +1,132 @@
+/*
+ * 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 <memory>
+#include <boost/test/unit_test.hpp>
+#include "installer/formats/BattleSceneConverter.h"
+#include "installer/formats/BattleSceneReader.h"
+
+namespace{
+
+    /**
+     * A scene with no enemies and no attacks. It's too big for the stack.
+     */
+    std::unique_ptr<BattleSceneData> EmptyScene(){
+        auto scene = std::make_unique<BattleSceneData>();
+        for (u16& enemy : scene->enemy) enemy = 0xFFFF;
+        for (u16& id : scene->attack_ids) id = 0xFFFF;
+        return scene;
+    }
+}
+
+BOOST_AUTO_TEST_CASE(TestBattleSceneValues){
+    BOOST_CHECK_EQUAL(BattleSceneConverter::ElementFactor(0x02), 2.0f);
+    BOOST_CHECK_EQUAL(BattleSceneConverter::ElementFactor(0x06), -1.0f);
+    BOOST_CHECK_EQUAL(BattleSceneConverter::ElementFactor(0x55), 1.0f);
+    BOOST_CHECK(BattleSceneConverter::Layout(5) == Formation::Layout::PINCER_ATTACK);
+    BOOST_CHECK(BattleSceneConverter::Layout(8) == Formation::Layout::LOCKED);
+    BOOST_CHECK(BattleSceneConverter::Layout(9) == Formation::Layout::NORMAL);
+    BOOST_CHECK_EQUAL(BattleSceneConverter::LocationName(2), "grassland");
+    BOOST_CHECK_EQUAL(BattleSceneConverter::LocationName(0x59), "ultimate_weapon_forest");
+    BOOST_CHECK_EQUAL(BattleSceneConverter::LocationName(0x5A), "unknonw_location");
+}
+
+BOOST_AUTO_TEST_CASE(TestBattleSceneAttacks){
+    auto scene = EmptyScene();
+    // The same attack in two slots is listed once.
+    scene->attack_ids[0] = scene->attack_ids[1] = 7;
+    scene->attack_data[0].effect = 0xFF;
+    scene->attack_data[0].impact_effect = 3;
+    scene->attack_data[0].status = 0x00000005;
+    scene->attack_data[0].status_change = 0x80 | 63;
+    scene->attack_data[0].element = 0x0003;
+    // The special properties are on when their bits are not set.
+    scene->attack_data[0].special = 0xFFFE;
+    const std::vector<Attack> attacks = BattleSceneConverter::Attacks(*scene);
+    BOOST_REQUIRE_EQUAL(attacks.size(), 1u);
+    BOOST_CHECK_EQUAL(attacks[0].animation.effect, -1);
+    BOOST_CHECK_EQUAL(attacks[0].animation.impact_effect, 3);
+    BOOST_REQUIRE_EQUAL(attacks[0].status_effects.size(), 2u);
+    BOOST_CHECK_EQUAL(attacks[0].status_effects[1].id, 2);
+    BOOST_CHECK_EQUAL(attacks[0].status_effects[1].chance, 1.0f);
+    // A copy of the constant, which has no definition to take the address of.
+    const int toggle = GameData::STATUS_EFFECT_MODE::TOGGLE;
+    BOOST_CHECK_EQUAL(attacks[0].status_effects[1].type, toggle);
+    BOOST_CHECK_EQUAL(attacks[0].elements.size(), 2u);
+    BOOST_CHECK(attacks[0].damage.damage_mp);
+    BOOST_CHECK(!attacks[0].reflectable);
+}
+
+BOOST_AUTO_TEST_CASE(TestBattleSceneEnemyItems){
+    auto scene = EmptyScene();
+    scene->enemy[0] = 0;
+    BattleSceneData::EnemyData& data = scene->enemy_data[0];
+    for (u16& attack : data.attacks) attack = 0xFFFF;
+    // An armor to drop, nothing, a weapon to steal and nothing.
+    const u16 items[4] = {297, 0xFFFF, 255, 0xFFFF};
+    const u8 rates[4] = {63, 0, 0x80 + 63, 0};
+    std::copy(items, items + 4, data.item);
+    std::copy(rates, rates + 4, data.item_rate);
+    const std::vector<Enemy> enemies = BattleSceneConverter::Enemies(*scene);
+    BOOST_REQUIRE_EQUAL(enemies.size(), 1u);
+    BOOST_REQUIRE_EQUAL(enemies[0].drop.size(), 1u);
+    BOOST_CHECK_EQUAL(enemies[0].drop[0].id, 297u);
+    BOOST_CHECK_EQUAL(enemies[0].drop[0].rate, 1.0f);
+    BOOST_REQUIRE_EQUAL(enemies[0].steal.size(), 1u);
+    BOOST_CHECK_EQUAL(enemies[0].steal[0].id, 255u);
+}
+
+BOOST_AUTO_TEST_CASE(TestBattleSceneFormations){
+    auto scene = EmptyScene();
+    for (auto& formation : scene->formation) for (auto& enemy : formation) enemy.id = 0xFFFF;
+    for (auto& setup : scene->setup){
+        for (u16& candidate : setup.next_arena_candidates) candidate = 999;
+    }
+    scene->formation[1][0].id = 5;
+    scene->formation[1][0].cover_flags = 0x11;
+    scene->setup[1].next_arena_candidates[2] = 30;
+    const std::vector<Formation> formations = BattleSceneConverter::Formations(*scene);
+    BOOST_REQUIRE_EQUAL(formations.size(), 4u);
+    BOOST_CHECK(formations[0].enemies.empty());
+    BOOST_CHECK(!formations[0].is_arena_battle);
+    BOOST_CHECK(formations[1].is_arena_battle);
+    BOOST_REQUIRE_EQUAL(formations[1].enemies.size(), 1u);
+    BOOST_CHECK_EQUAL(std::string(formations[1].enemies[0].cover, 5), "10001");
+}
+
+BOOST_AUTO_TEST_CASE(TestBattleSceneAiScripts){
+    // The block of the second enemy at 6 bytes from the AI section: two scripts after 32 bytes.
+    std::vector<u8> bytes(0x0E80 + 6 + 32 + 6, 0xFF);
+    bytes[0x0E82] = 6;
+    bytes[0x0E83] = 0;
+    const size_t block = 0x0E80 + 6;
+    bytes[block] = 32;
+    bytes[block + 1] = 0;
+    bytes[block + 4] = 35;
+    bytes[block + 5] = 0;
+    const u8 scripts[6] = {1, 0x73, 0xFF, 2, 0x73, 0xFF};
+    std::copy(scripts, scripts + 6, bytes.begin() + block + 32);
+    auto scene = EmptyScene();
+    BattleSceneReader::ReadAiScripts(bytes, *scene);
+    BOOST_REQUIRE_EQUAL(scene->ai_scripts[1].size(), 16u);
+    // Without the padding.
+    BOOST_CHECK(scene->ai_scripts[1][0] == std::vector<u8>({1, 0x73}));
+    BOOST_CHECK(scene->ai_scripts[1][1].empty());
+    BOOST_CHECK(scene->ai_scripts[1][2] == std::vector<u8>({2, 0x73}));
+    BOOST_CHECK(scene->ai_scripts[0][0].empty());
+    // A scene cut short has no scripts.
+    BattleSceneReader::ReadAiScripts(std::vector<u8>(100), *scene);
+    BOOST_CHECK(scene->ai_scripts[1][0].empty());
+}

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

@@ -1,4 +1,5 @@
 # Tests of this folder (see vgears_tests and vgears_installer_tests in test/CMakeLists.txt).
 vgears_tests(
+    BattleScene.cpp
     DiskImage.cpp
 )