فهرست منبع

Add battle rules, materia, limits and commands

Battle rules
- Damage formulas checked against ff7.exe: physical, magical, cure, critical, row, Berserk/Frog/Defend/Sadness, level attacks.
- Statuses with timers, Fury/Sadness (limit bar speed and colour), Near Death.
- ATB speed and turn order, counterattacks and action priority.
- Change and Defend side commands.

Materia
- Linked support materia (pairs of adjacent slots): All, MP Turbo, HP/MP Absorb, Quadra Magic, Counter, Magic Counter, Final Attack, Sneak Attack, Added Cut, Steal as well, Elemental, Added Effect.
- Independent materia: Cover, HP<->MP swap, encounter rate, EXP/Gil Plus.
- Magic list with one row per materia and modifier tags (ALL, MPT...).
- HP and MP are capped when the equipment changes.

Limits
- Limit bar filling, flashing, reset on death, Limit command and menu, pink limit windows and messages, Aerith's limits.
- Limit attack data found in ff7.exe and written by the kernel installer; physical limits use it.
- Limit animations extracted from magic.lgp and added to the party model.
- Multi-hit limits (Omnislash...) hit as many times as the attack data says, spread over the animation, at random enemies when flagged.

Commands
- Steal, Mug, Sense, Throw, Coin (gil window) and the double commands W-Magic, W-Summon and W-Item.
- Attack commands: 2x-Cut, 4x-Cut, Slash-All, Flash.

Installer and data
- Item, armor and accessory throwable flags, attack additional effects, limit animation conversion, item status decoding fix.
- Test helpers: debug enemy HP, debug party setups.
Iñigo Valentin 1 هفته پیش
والد
کامیت
b5fe5a198e

+ 57 - 0
data/data/screens/battle/battle.xml

@@ -58,17 +58,74 @@
                     <animation name="Position12" length="0" x="0:80" y="0:66%+7" />
                 </sprite>
             </widget>
+            <!-- Change (left of the commands) and Defend (right of them) have a window with one option each. -->
+            <widget name="Change" x="22%-56" y="5%" width="56" height="30%" visible="false">
+                <prototype name="Window" />
+                <text_area name="Text" x="10" y="4" width="100%-5" height="100%" font="FFVIIFont" text_name="BattleUiHp" visible="true" />
+                <sprite name="Cursor" image="icons/cursor.png" x="-15" y="5" width="24" height="16" visible="true" />
+            </widget>
+            <widget name="Defend" x="22%+120" y="5%" width="56" height="30%" visible="false">
+                <prototype name="Window" />
+                <text_area name="Text" x="10" y="4" width="100%-5" height="100%" font="FFVIIFont" text_name="BattleUiHp" visible="true" />
+                <sprite name="Cursor" image="icons/cursor.png" x="-15" y="5" width="24" height="16" visible="true" />
+            </widget>
+            <!-- Coin: window to choose the gil to throw. -->
+            <widget name="Coin" x="32%" y="5%" width="150" height="62%" visible="false">
+                <prototype name="Window" />
+                <text_area name="Title" x="10" y="0%+5" width="100%-5" height="30%" font="FFVIIFont" text_name="BattleUiHp" visible="true" />
+                <text_area name="Amount" x="10" y="28%+5" width="100%-5" height="30%" font="FFVIIFont" text_name="BattleUiHp" visible="true" />
+                <text_area name="Step" x="10" y="56%+5" width="100%-5" height="30%" font="FFVIIFont" text_name="BattleUiHp" visible="true" />
+            </widget>
             <widget name="List" x="32%" y="5%" width="120" height="95%" visible="false">
                 <prototype name="Window" />
                 <text_area name="List1" x="10" y="0%+5" width="100%-5" height="25%" font="FFVIIFont" visible="true" />
                 <text_area name="List2" x="10" y="22%+5" width="100%-5" height="25%" font="FFVIIFont" visible="true" />
                 <text_area name="List3" x="10" y="44%+5" width="100%-5" height="25%" font="FFVIIFont" visible="true" />
                 <text_area name="List4" x="10" y="66%+5" width="100%-5" height="25%" font="FFVIIFont" visible="true" />
+                <!-- The magic list has a row for each materia: the modifiers (in purple) and up to four
+                     spells. The window is made wider by the script when it is shown (see MAGIC_LIST_WIDTH). The first column fits
+                     three characters, and each of the others 10. -->
+                <text_area name="ListTag1" x="8" y="0%+5" width="30" height="25%" font="FFVIIFont" visible="false" />
+                <text_area name="ListTag2" x="8" y="22%+5" width="30" height="25%" font="FFVIIFont" visible="false" />
+                <text_area name="ListTag3" x="8" y="44%+5" width="30" height="25%" font="FFVIIFont" visible="false" />
+                <text_area name="ListTag4" x="8" y="66%+5" width="30" height="25%" font="FFVIIFont" visible="false" />
+                <text_area name="ListA1" x="42" y="0%+5" width="64" height="25%" font="FFVIIFont" visible="false" />
+                <text_area name="ListA2" x="42" y="22%+5" width="64" height="25%" font="FFVIIFont" visible="false" />
+                <text_area name="ListA3" x="42" y="44%+5" width="64" height="25%" font="FFVIIFont" visible="false" />
+                <text_area name="ListA4" x="42" y="66%+5" width="64" height="25%" font="FFVIIFont" visible="false" />
+                <text_area name="ListB1" x="106" y="0%+5" width="64" height="25%" font="FFVIIFont" visible="false" />
+                <text_area name="ListB2" x="106" y="22%+5" width="64" height="25%" font="FFVIIFont" visible="false" />
+                <text_area name="ListB3" x="106" y="44%+5" width="64" height="25%" font="FFVIIFont" visible="false" />
+                <text_area name="ListB4" x="106" y="66%+5" width="64" height="25%" font="FFVIIFont" visible="false" />
+                <text_area name="ListC1" x="170" y="0%+5" width="64" height="25%" font="FFVIIFont" visible="false" />
+                <text_area name="ListC2" x="170" y="22%+5" width="64" height="25%" font="FFVIIFont" visible="false" />
+                <text_area name="ListC3" x="170" y="44%+5" width="64" height="25%" font="FFVIIFont" visible="false" />
+                <text_area name="ListC4" x="170" y="66%+5" width="64" height="25%" font="FFVIIFont" visible="false" />
+                <text_area name="ListD1" x="234" y="0%+5" width="64" height="25%" font="FFVIIFont" visible="false" />
+                <text_area name="ListD2" x="234" y="22%+5" width="64" height="25%" font="FFVIIFont" visible="false" />
+                <text_area name="ListD3" x="234" y="44%+5" width="64" height="25%" font="FFVIIFont" visible="false" />
+                <text_area name="ListD4" x="234" y="66%+5" width="64" height="25%" font="FFVIIFont" visible="false" />
                 <sprite name="Cursor" image="icons/cursor.png" x="132" y="99" width="24" height="16" visible="true">
                     <animation name="Position1" length="0" x="0:-15" y="0:0%+7" />
                     <animation name="Position2" length="0" x="0:-15" y="0:22%+7" />
                     <animation name="Position3" length="0" x="0:-15" y="0:44%+7" />
                     <animation name="Position4" length="0" x="0:-15" y="0:66%+7" />
+                    <animation name="Position1_1" length="0" x="0:19" y="0:0%+7" />
+                    <animation name="Position1_2" length="0" x="0:83" y="0:0%+7" />
+                    <animation name="Position1_3" length="0" x="0:147" y="0:0%+7" />
+                    <animation name="Position1_4" length="0" x="0:211" y="0:0%+7" />
+                    <animation name="Position2_1" length="0" x="0:19" y="0:22%+7" />
+                    <animation name="Position2_2" length="0" x="0:83" y="0:22%+7" />
+                    <animation name="Position2_3" length="0" x="0:147" y="0:22%+7" />
+                    <animation name="Position2_4" length="0" x="0:211" y="0:22%+7" />
+                    <animation name="Position3_1" length="0" x="0:19" y="0:44%+7" />
+                    <animation name="Position3_2" length="0" x="0:83" y="0:44%+7" />
+                    <animation name="Position3_3" length="0" x="0:147" y="0:44%+7" />
+                    <animation name="Position3_4" length="0" x="0:211" y="0:44%+7" />
+                    <animation name="Position4_1" length="0" x="0:19" y="0:66%+7" />
+                    <animation name="Position4_2" length="0" x="0:83" y="0:66%+7" />
+                    <animation name="Position4_3" length="0" x="0:147" y="0:66%+7" />
+                    <animation name="Position4_4" length="0" x="0:211" y="0:66%+7" />
                 </sprite>
             </widget>
             <widget name="Target" x="42%" y="5%" width="160" height="95%" visible="false">

+ 37 - 0
data/data/screens/battle/battle_fx.lua

@@ -1438,6 +1438,30 @@ UiContainer.BattleFx = {
         t.camera_used = true
     end,
 
+    --- Ticks the party takes to fade out when a summon starts, and to fade in when it ends.
+    PARTY_FADE_OUT = 10,
+    PARTY_FADE_IN = 12,
+
+    --- Sets how visible the party members (and the weapons they hold) are.
+    --
+    -- Dead members stay as they are. At full opacity the normal drawing is restored.
+    set_party_alpha = function(self, alpha)
+        local party = UiContainer.BattleUi.party
+        for i = 1, Party.MAX do
+            local entity = party[i] ~= nil and UiContainer.BattleUi:get_entity(Battle.TargetGroup.PARTY, i) or nil
+            if entity ~= nil then
+                if alpha >= 1 or party[i].dead then
+                    -- Full opacity first (it only counts while the blend is not the normal one).
+                    entity:set_alpha(1)
+                    entity:set_blend(Entity.BLEND_NORMAL)
+                else
+                    entity:set_blend(Entity.BLEND_ALPHA)
+                    entity:set_alpha(alpha)
+                end
+            end
+        end
+    end,
+
     --- Advances the summons. The hit and the end are always called, even if the creature couldn't
     -- be shown, so the battle doesn't wait for them.
     update_timelines = function(self, dt)
@@ -1446,6 +1470,17 @@ UiContainer.BattleFx = {
             t.age = t.age + dt
             local tick = t.age * self.SUMMON_TPS
             local def = t.def
+            -- The party fades out while the summon is on and comes back when it ends.
+            if t.party_faded ~= false then
+                local fade_in_start = def.total - self.PARTY_FADE_IN
+                local alpha
+                if tick < fade_in_start then alpha = math.max(0, 1 - tick / self.PARTY_FADE_OUT)
+                else alpha = math.min(1, (tick - fade_in_start) / self.PARTY_FADE_IN) end
+                local ok, err = pcall(self.set_party_alpha, self, alpha)
+                if not ok then print("Party fade failed: " .. tostring(err)) end
+                t.party_faded = ok
+                if ok then t.party_touched = true end
+            end
             -- The creature is there from appear to leave, fading in and out.
             if tick >= def.appear and tick < def.leave then
                 if t.entity == nil and not t.creature_failed then
@@ -1493,6 +1528,7 @@ UiContainer.BattleFx = {
                 t.on_hit()
             end
             if tick >= def.total then
+                if t.party_touched then pcall(self.set_party_alpha, self, 1) end
                 if not t.hit_done then t.hit_done = true t.on_hit() end
                 if t.entity_name ~= nil then battle_manager:remove_effect_model(t.entity_name) end
                 if t.camera_used then self:restore_camera() end
@@ -1509,6 +1545,7 @@ UiContainer.BattleFx = {
     --- Removes the summons in progress, without finishing them.
     clear_timelines = function(self)
         for _, t in ipairs(self.timelines) do
+            if t.party_touched then pcall(self.set_party_alpha, self, 1) end
             if t.entity_name ~= nil then battle_manager:remove_effect_model(t.entity_name) end
             if t.camera_used then pcall(self.restore_camera, self) end
             pcall(self.remove_meshes, self, t)

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 674 - 60
data/data/scripts/battle/battle_ui.lua


+ 56 - 0
data/data/scripts/character_abilities.lua

@@ -91,6 +91,62 @@ Characters.get_abilities = function(char_id)
     return result
 end
 
+--- Gets what the independent materia (Long Range, Mega All, Counter Attack, Cover, Pre-Emptive, EXP
+-- Plus and Gil Plus) of a character do in battle.
+--
+-- @param char_id ID of the character.
+-- @return A table: long_range (boolean), mega_all (times per battle, 0 if none), counter_attack and
+-- cover (chance in percent, 0 if none), preemptive (percent points added to the chance of a pre-emptive
+-- attack), exp_plus and gil_plus (multipliers, 1 if none), and encounter (multiplier of the random
+-- encounters of the field, from Enemy Away and Enemy Lure).
+Characters.get_independent = function(char_id)
+    local result = {
+        long_range = false, mega_all = 0, counter_attack = 0, cover = 0, preemptive = 0,
+        exp_plus = 1, gil_plus = 1, encounter = 1,
+    }
+    local character = Characters[char_id]
+    if character == nil then return result end
+    for _, part in ipairs({ "weapon", "armor" }) do
+        for slot = 0, 7 do
+            local equipped = character[part].materia[slot]
+            local materia = (equipped ~= nil) and Game.Materia[equipped.id] or nil
+            if materia ~= nil and materia.type == Materia.TYPE.INDEPENDENT and materia.ability ~= nil then
+                local level = math.max(1, get_materia_level(materia, equipped.ap or 0))
+                local param = materia.ability.param or {}
+                -- The parameter of the level, or the last one if the materia has more levels.
+                local value = param[level] or param[#param] or 0
+                local id = materia.ability.id
+                if id == Materia.ABILITY.LONG_RANGE then result.long_range = true
+                elseif id == Materia.ABILITY.MEGA_ALL then result.mega_all = math.max(result.mega_all, value)
+                elseif id == Materia.ABILITY.COUNTER_ATTACK then result.counter_attack = math.max(result.counter_attack, value)
+                elseif id == Materia.ABILITY.COVER then result.cover = math.max(result.cover, value)
+                elseif id == Materia.ABILITY.PREEMPTIVE then result.preemptive = result.preemptive + value
+                -- The parameters of EXP Plus and Gil Plus are sixteenths: 24 is x1.5 and 32 is x2.
+                -- Enemy Away halves the encounters (a quarter when mastered) and Enemy Lure doubles them (x4).
+                -- TODO: Unverified, the parameters are 7 and 14.
+                elseif id == Materia.ABILITY.ENCOUNTER_DOWN then result.encounter = result.encounter * 0.5 ^ (value / 7)
+                elseif id == Materia.ABILITY.ENCOUNTER_UP then result.encounter = result.encounter * 2 ^ (value / 7)
+                elseif id == Materia.ABILITY.EXP_PLUS then result.exp_plus = math.max(result.exp_plus, value / 16)
+                elseif id == Materia.ABILITY.MONEY_PLUS then result.gil_plus = math.max(result.gil_plus, value / 16)
+                end
+            end
+        end
+    end
+    return result
+end
+
+--- Gets the multiplier of the random encounters of the field that the party causes with its Enemy Away and
+-- Enemy Lure materia (1 if it has none). The engine asks for it in every encounter check.
+Party.get_encounter_modifier = function()
+    local modifier = 1
+    for slot = 1, Party.MAX do
+        if Party[slot] ~= nil and Characters[Party[slot]] ~= nil then
+            modifier = modifier * Characters.get_independent(Party[slot]).encounter
+        end
+    end
+    return modifier
+end
+
 --- Status of death (see BattleStatus). The characters with no HP are dead.
 local STATUS_DEATH = 0
 

+ 17 - 3
data/data/scripts/character_effects.lua

@@ -37,6 +37,9 @@ local function materia_level(definition, ap)
     return math.max(level, 1)
 end
 
+--- Materia level (1-based) for an amount of AP, see {@see Characters.get_linked_slots}.
+Characters.get_materia_level = materia_level
+
 --- Mode an Elemental materia gives to armor, by materia level.
 local function elemental_armor_mode(level)
     if level >= 3 then return Characters.ELEMENT_MODE.ABSORB end
@@ -54,17 +57,28 @@ end
 
 --- Gets the materia linked to a slot.
 --
+-- Slots are linked in pairs: 1-2, 3-4, 5-6 and 7-8. A pair is linked if the first slot has a 1 in the
+-- slots of the item (the menus draw the link the same way).
+--
 -- @param item The weapon or armor definition.
 -- @param slot Slot of the item, 1-8.
 -- @return List of slots (1-8) linked to it.
 local function linked_slots(item, slot)
     local linked = {}
-    -- slots[n] == 1 means that slot n is linked to slot n + 1.
-    if item.slots[slot] == 1 and #(item.slots) > slot then table.insert(linked, slot + 1) end
-    if slot > 1 and item.slots[slot - 1] == 1 then table.insert(linked, slot - 1) end
+    local first = (slot % 2 == 1) and slot or slot - 1
+    if item.slots[first] == 1 and #(item.slots) > first then
+        table.insert(linked, slot == first and first + 1 or first)
+    end
     return linked
 end
 
+--- Gets the slots linked to a slot of a weapon or armor.
+--
+-- @param item The weapon or armor definition.
+-- @param slot Slot of the item, 1-8.
+-- @return List of slots (1-8).
+Characters.get_linked_slots = linked_slots
+
 --- Applies the link materia (Elemental, Added Effect) of a weapon or armor.
 local function apply_link_materia(char_id, part, result)
     local equipment = Characters[char_id][part]

+ 4 - 2
data/data/scripts/data.lua

@@ -153,6 +153,8 @@ Materia.ABILITY = {
     PREEMPTIVE = 103,
     ENC_DOWN = 107,
     ENC_UP = 108,
+    ENCOUNTER_DOWN = 107,
+    ENCOUNTER_UP = 108,
     ENC_CHOCOBO = 109
 }
 
@@ -166,8 +168,8 @@ Materia.LINK = {
     SNEAK_ATTACK = 86,
     FINAL_ATTACK = 87,
     MP_TURBO = 88,
-    MP_TURBO = 89,
-    MP_TURBO = 90,
+    MP_ABSORB = 89,
+    HP_ABSORB = 90,
     ADDED_CUT = 92,
     STEAL_AS_WELL = 93,
     ELEMENTAL = 94,

+ 60 - 27
data/data/scripts/debug_data.lua

@@ -49,53 +49,86 @@ Characters[0].stats.hp.base = 54321
 ]]
 Characters[0].stats.dex.base = 11
 Characters[0].stats.dex.total = 11
+-- Cloud has enough MP for Comet (70 MP) and Comet2 (110 MP).
+Characters[0].stats.mp.base = 400
+Characters[0].stats.mp.max = 400
+Characters[0].stats.mp.current = 400
 Characters[0].armor.id = 268
+-- The slots of this armor are linked in pairs: 0-1, 2-3, 4-5 and 6-7. Fire (0) is paired with MP
+-- Absorb, Ice (2) with MP Turbo, Restore (4) with Quadra Magic, and Lightning (6) with nothing. Contain (4 spells) is in the weapon. Before, Lightning (6) was with Contain, which
+-- is not a support materia (so nothing). All is not equipped any more. Slots of the weapon, which has
+-- one pair (0-1): Double Cut with Steal as well (his Attack steals too).
 Characters[0].armor.materia = {
-    [0] = {id = 75, ap = 15340},
-    [2] = {id = 44, ap = 0, skills = {}}, -- E. Skill
-    [3] = {id = 76, ap = 520},
-    [4] = {id = 77, ap = 0},
-    [5] = {id = 36, ap = 50000},
-    [6] = {id = 0, ap = 0},
-    [7] = {id = 26, ap = 0},
+    [0] = {id = 49, ap = 100000},  -- Fire
+    [1] = {id = 27, ap = 100000},  -- MP Absorb
+    [2] = {id = 50, ap = 100000},  -- Ice
+    [3] = {id = 26, ap = 120000},  -- MP Turbo
+    [4] = {id = 53, ap = 100000},  -- Restore
+    [5] = {id = 35, ap = 200000},  -- Quadra Magic
+    [6] = {id = 52, ap = 100000},  -- Lightning
 }
-Characters[0].weapon.materia[0] = {id = 64, ap = 15340}
-for i = 1, 24 do -- E. Skill list
-    if i == 1 or i == 6 or i == 9 or i == 13 or i == 14 or i == 15 or i == 23 or i == 24 then
-        Characters[0].armor.materia[2].skills[i] = true
-    else
-        Characters[0].armor.materia[2].skills[i] = false
-    end
-end
+-- Attack commands to test: Double Cut gives 2x-Cut (AP below 100000) or 4x-Cut (100000 or more), and Slash-All
+-- gives Slash-All (AP below 130000) or Flash (130000 or more). Cloud has Double Cut (4x-Cut) paired with Steal
+-- as well, and Tifa has Slash-All (Flash). Only the last attack command of a character is used.
+Characters[0].weapon.materia[0] = {id = 15, ap = 100000} -- Double Cut (4x-Cut)
 -- Magic for testing. Materia IDs: Fire 49, Ice 50, Earth 51, Lightning 52, Restore 53, Heal 54,
 -- Revive 55, Poison 60. AP is enough to reach the highest level.
-Characters[0].weapon.materia[1] = {id = 49, ap = 100000}
-Characters[0].armor.materia[1] = {id = 53, ap = 100000}
+Characters[0].weapon.materia[1] = {id = 34, ap = 200000} -- Steal as well (paired with Double Cut: his Attack steals too)
 Characters[2].weapon.materia[0] = {id = 50, ap = 100000}
 Characters[2].weapon.materia[1] = {id = 52, ap = 100000}
 Characters[2].armor.materia[0] = {id = 54, ap = 100000}
 Characters[2].armor.materia[1] = {id = 55, ap = 100000}
-Characters[3].weapon.materia[0] = {id = 53, ap = 100000}
-Characters[3].weapon.materia[1] = {id = 49, ap = 100000}
-Characters[3].armor.materia[0] = {id = 60, ap = 100000}
-Characters[3].armor.materia[1] = {id = 51, ap = 100000}
+-- Aerith has no materia.
+Characters[3].weapon.materia = {}
+Characters[3].armor.id = 268
+Characters[3].armor.materia = {}
 -- Status magic: Seal 56 (Sleepel, Silence), Mystify 57 (Confu, Berserk), Transform 58 (Mini, Toad),
 -- Time 65 (Haste, Slow, Stop), Destruct 68 (DeBarrier, DeSpell, Death). Cloud already has Barrier
 -- (62) in his armor.
-Characters[0].weapon.materia[2] = {id = 65, ap = 100000}
-Characters[0].weapon.materia[3] = {id = 56, ap = 100000}
+Characters[0].weapon.materia[2] = {id = 36, ap = 100000} -- Steal (mastered: Mug). Use ap = 0 for plain Steal.
+Characters[0].weapon.materia[3] = {id = 37, ap = 100000} -- Sense
 Characters[2].armor.materia[2] = {id = 68, ap = 100000}
 Characters[2].armor.materia[3] = {id = 57, ap = 100000}
-Characters[3].armor.materia[2] = {id = 58, ap = 100000}
+-- Limit bars to test the Limit command: everybody has the first limit and a bar of about 85% (217 of 255).
+-- The HP and MP are filled (the game caps them to the maximums when the battle starts).
+for _, c in ipairs({0, 2, 3}) do
+    Characters[c].limit.learned[1][1] = true
+    Characters[c].limit.bar = 217
+    Characters[c].stats.hp.current = 99999
+    Characters[c].stats.mp.current = 99999
+end
+-- Cloud: limit level 4 (Omnislash, the first technique of the level) and a full bar.
+Characters[0].limit.current = 4
+Characters[0].limit.learned[4] = Characters[0].limit.learned[4] or {}
+Characters[0].limit.learned[4][1] = true
+Characters[0].limit.bar = 255
 -- Summons: Choco/Mog 74, Shiva 75, Ifrit 76, Ramuh 77, Titan 78, Odin 79, Leviathan 80, Bahamut 81,
 -- Kjata 82, Alexander 83, Phoenix 84, Neo Bahamut 85, Hades 86, Typhoon 87, Bahamut ZERO 88,
 -- Knights of Round 89, Master Summon 90. They cost between 14 and 250 MP.
 Characters[0].weapon.materia[4] = {id = 75, ap = 100000} -- Shiva
-Characters[0].weapon.materia[5] = {id = 76, ap = 100000} -- Ifrit
+Characters[0].weapon.materia[6] = {id = 44, ap = 0, skills = {}} -- E. Skill
+Characters[0].weapon.materia[7] = {id = 69, ap = 100000} -- Contain (mastered: Freeze, Break, Tornado, Flare)
+for i = 1, 24 do -- E. Skill list
+    if i == 1 or i == 6 or i == 9 or i == 13 or i == 14 or i == 15 or i == 23 or i == 24 then
+        Characters[0].weapon.materia[6].skills[i] = true
+    else
+        Characters[0].weapon.materia[6].skills[i] = false
+    end
+end
 Characters[2].weapon.materia[2] = {id = 77, ap = 100000} -- Ramuh
 Characters[2].weapon.materia[3] = {id = 74, ap = 100000} -- Choco/Mog
-Characters[3].weapon.materia[2] = {id = 84, ap = 100000} -- Phoenix
-Characters[3].weapon.materia[3] = {id = 81, ap = 100000} -- Bahamut
+Characters[2].weapon.materia[4] = {id = 14, ap = 130000} -- Slash-All (Flash)
+Characters[2].weapon.materia[6] = {id = 16, ap = 40000} -- Cover (100%: takes the attacks for allies with critical HP)
+Characters[2].armor.materia[4] = {id = 39, ap = 0} -- Throw (level 1; mastered it is Coin)
+Characters[3].weapon.materia[0] = {id = 39, ap = 100000} -- Throw mastered: Aerith has Coin
+-- Double commands: Aerith W-Magic (with Fire and Restore to cast), Tifa W-Item, Cloud W-Summon (instead of Mega All, with Shiva).
+Characters[3].weapon.materia[1] = {id = 19, ap = 100000} -- W-Magic
+Characters[3].armor.materia[0] = {id = 49, ap = 100000} -- Fire
+Characters[3].armor.materia[1] = {id = 53, ap = 100000} -- Restore
+Characters[2].armor.materia[5] = {id = 21, ap = 100000} -- W-Item
+Characters[0].weapon.materia[5] = {id = 20, ap = 100000} -- W-Summon
+Inventory.add_item(129, 3) -- Mythril Saber (to throw)
+Inventory.add_item(130, 2)
 -- Items to try: Potion, Hi-Potion, Ether, Phoenix Down, Antidote, Echo Screen, Hyper, Tranquilizer,
 -- Remedy, Speed Drink, Grenade, Shrapnel, Molotov.
 for _, item in ipairs({{0, 6}, {1, 4}, {3, 4}, {7, 4}, {8, 3}, {12, 3}, {13, 2}, {14, 2}, {15, 2}, {17, 3}, {20, 5}, {21, 3}, {53, 3}}) do

+ 2 - 0
data/data/scripts/menu/materia_menu.lua

@@ -703,6 +703,8 @@ UiContainer.MateriaMenu = {
                 Characters[self.char_id].armor.materia[equip_slot] = nil
             end
         end
+        -- The materia change the stats, and the current HP and MP can't be over the new maximums.
+        Characters.recalculate_stats(self.char_id)
         -- Reload character data and list.
         self.populate_equip(self)
         self.populate_list(self)

+ 14 - 2
data/data/scripts/system.lua

@@ -552,6 +552,18 @@ Characters.recalculate_stats = function(id)
     stats.hp.max = math.floor(stats.hp.max)
     stats.mp.max = math.floor(stats.mp.max)
 
+    -- HP<->MP materia swap the maximum HP and MP. TODO: Unverified: its levels (it is done at any level).
+    for _, materia in ipairs(materias) do
+        if materia ~= nil and materia.type == Materia.TYPE.INDEPENDENT and materia.ability ~= nil
+          and materia.ability.id == Materia.ABILITY.HP_MP then
+            stats.hp.max, stats.mp.max = stats.mp.max, stats.hp.max
+            break
+        end
+    end
+    -- The current values can't be over the maximums.
+    if stats.hp.current ~= nil then stats.hp.current = math.min(stats.hp.current, math.max(1, stats.hp.max)) end
+    if stats.mp.current ~= nil then stats.mp.current = math.min(stats.mp.current, math.max(0, stats.mp.max)) end
+
     if stats.str.total < 1 then
         stats.str.total = 1
     end
@@ -609,8 +621,6 @@ Characters.recalculate_stats = function(id)
         stats.meva = 1
     end
 
-    -- TODO: If HP<->MP materia, invert values.
-
     -- Cap current HP/MP
     if stats.hp.current > stats.hp.max then
         stats.hp.current = stats.hp.max
@@ -703,6 +713,8 @@ Characters.equip = function(char_id, item_id)
     else
         return false
     end
+    -- The stats change with the equipment (and the maximum HP and MP, so the current ones may have to be capped).
+    Characters.recalculate_stats(char_id)
     return true
 end
 

+ 12 - 0
src/core/Enemy.cpp

@@ -307,6 +307,18 @@ float Enemy::ScriptGetDropRate(const unsigned int index) const{
     return drop_[index].rate;
 }
 
+int Enemy::ScriptGetStealCount() const{return steal_.size();}
+
+int Enemy::ScriptGetStealId(const unsigned int index) const{
+    if (index >= steal_.size()) return -1;
+    return steal_[index].id;
+}
+
+float Enemy::ScriptGetStealRate(const unsigned int index) const{
+    if (index >= steal_.size()) return 0.0f;
+    return steal_[index].rate;
+}
+
 int Enemy::ScriptGetCameraForAttack(const unsigned int index){
     if (index >= attacks_.size()) return -1;
     return attacks_[index].camera;

+ 29 - 0
src/core/Enemy.h

@@ -660,6 +660,35 @@ class Enemy{
          */
         int ScriptGetDropCount() const;
 
+        /**
+         * Retrieves the number of items that can be stolen from the enemy.
+         *
+         * To be used from Lua scripts.
+         *
+         * @return The number of stealable items.
+         */
+        int ScriptGetStealCount() const;
+
+        /**
+         * Retrieves the ID of a stealable item.
+         *
+         * To be used from Lua scripts.
+         *
+         * @param[in] index Steal index, must be lower than reported by {@see ScriptGetStealCount}.
+         * @return The item ID, -1 if the index is not valid.
+         */
+        int ScriptGetStealId(const unsigned int index) const;
+
+        /**
+         * Retrieves the steal rate of a stealable item.
+         *
+         * To be used from Lua scripts.
+         *
+         * @param[in] index Steal index, must be lower than reported by {@see ScriptGetStealCount}.
+         * @return The steal rate, between 0 and 1. 0 if the index is not valid.
+         */
+        float ScriptGetStealRate(const unsigned int index) const;
+
         /**
          * Retrieves the animation script of an attack.
          *

+ 16 - 0
src/core/Entity.h

@@ -370,6 +370,22 @@ class Entity{
             return std::make_tuple(0.0f, 0.0f, 0.0f);
         }
 
+        /**
+         * Attaches another model to a bone of this entity's skeleton, like the weapon a battle character
+         * holds. A previously attached model is replaced.
+         *
+         * @param[in] model Mesh file of the model to attach, a resource of the same group as the entity.
+         *     An empty name only removes the attached model.
+         * @param[in] bone Number of the bone to attach the model to (-1 for the last bone of the skeleton).
+         * @param[in] rx Extra rotation of the model around its own X axis, in degrees.
+         * @param[in] ry Extra rotation around its Y axis, in degrees.
+         * @param[in] rz Extra rotation around its Z axis, in degrees.
+         * @return True if the model was attached or removed.
+         */
+        virtual bool ScriptAttachModel(
+          const char* model, const int bone, const float rx, const float ry, const float rz
+        ){return false;}
+
         /**
          * Frees the resources that were created for the entity, before it is removed.
          */

+ 4 - 1
src/core/EntityManager.cpp

@@ -943,7 +943,10 @@ void EntityManager::UpdateEncounters(const bool walked){
     encounter_distance_ += Timer::getSingleton().GetGameTimeDelta() * 30.0f;
     while (encounter_distance_ >= ENCOUNTER_CHECK_FRAMES){
         encounter_distance_ -= ENCOUNTER_CHECK_FRAMES;
-        encounter_accumulator_ += static_cast<int>(ENCOUNTER_STEP_VALUE * multiplier * 256.0f) / rate;
+        // Enemy Away and Enemy Lure materia change the rate of the party (see Party.get_encounter_modifier).
+        const float materia_multiplier
+          = ScriptManager::getSingleton().EvaluateNumber("Party.get_encounter_modifier()", 1.0f);
+        encounter_accumulator_ += static_cast<int>(ENCOUNTER_STEP_VALUE * multiplier * materia_multiplier * 256.0f) / rate;
         const int roll = std::rand() % 256 * 256;
         if (cv_debug_encounters.GetB()){
             LOG_TRIVIAL(

+ 85 - 5
src/core/EntityModel.cpp

@@ -15,6 +15,7 @@
 
 #include <iostream>
 #include <algorithm>
+#include <vector>
 #include <OgreEntity.h>
 #include <OgreSubEntity.h>
 #include <OgreBone.h>
@@ -25,6 +26,7 @@
 #include <OgrePass.h>
 #include <OgreRoot.h>
 #include <OgreTextureManager.h>
+#include <OgreHardwarePixelBuffer.h>
 #include "core/EntityModel.h"
 #include "core/EntityManager.h"
 #include "core/Logger.h"
@@ -51,6 +53,7 @@ EntityModel::EntityModel(
     }
     }
     scene_manager = Ogre::Root::getSingleton().getSceneManager("Scene");
+    resource_group_ = res_group;
     model_ = scene_manager->createEntity(name_, file_name, res_group);
     model_->setVisible(false);
     PlayAnimation(animation_default_, Entity::AUTO_ANIMATION, Entity::PLAY_LOOPED, 0, -1);
@@ -58,6 +61,7 @@ EntityModel::EntityModel(
 }
 
 EntityModel::~EntityModel(){
+    ScriptAttachModel("", -1, 0.0f, 0.0f, 0.0f);
     Ogre::Root::getSingleton().getSceneManager("Scene")->destroyEntity(model_);
 }
 
@@ -66,7 +70,10 @@ void EntityModel::Update(){
     Entity::Update();
 }
 
-void EntityModel::SetVisible(const bool visible){model_->setVisible(visible);}
+void EntityModel::SetVisible(const bool visible){
+    model_->setVisible(visible);
+    if (attached_model_ != nullptr) attached_model_->setVisible(visible);
+}
 
 bool EntityModel::IsVisible() const{return model_->isVisible();}
 
@@ -132,11 +139,61 @@ std::tuple<float, float, float> EntityModel::ScriptGetBonePosition(const int bon
     return std::make_tuple(position.x, position.y, position.z);
 }
 
+bool EntityModel::ScriptAttachModel(
+  const char* model, const int bone, const float rx, const float ry, const float rz
+){
+    Ogre::SceneManager* scene_manager = Ogre::Root::getSingleton().getSceneManager("Scene");
+    if (attached_model_ != nullptr){
+        model_->detachObjectFromBone(attached_model_);
+        scene_manager->destroyEntity(attached_model_);
+        attached_model_ = nullptr;
+    }
+    const Ogre::String file(model);
+    if (file.empty()) return true;
+    Ogre::SkeletonInstance* skeleton = model_->getSkeleton();
+    if (skeleton == nullptr){
+        LOG_WARNING("The model '" + name_ + "' has no skeleton to attach '" + file + "' to.");
+        return false;
+    }
+    // Bones are called bone0, bone1... and the skeleton also has a root bone.
+    const int bone_number = (bone >= 0) ? bone : static_cast<int>(skeleton->getNumBones()) - 2;
+    const Ogre::String bone_name = "bone" + std::to_string(bone_number);
+    if (!skeleton->hasBone(bone_name)){
+        LOG_WARNING("The model '" + name_ + "' has no bone '" + bone_name + "'.");
+        return false;
+    }
+    if (!Ogre::ResourceGroupManager::getSingleton().resourceExists(resource_group_, file)){
+        LOG_WARNING("The model '" + file + "' to attach to '" + name_ + "' doesn't exist.");
+        return false;
+    }
+    attached_model_ = scene_manager->createEntity(name_ + "/" + bone_name + "/" + file, file, resource_group_);
+    // The vertices of an exported model already include the orientation of the root of its skeleton, the
+    // same one the bone of this skeleton has. Undo it, or it would be applied twice.
+    Ogre::Quaternion offset = Ogre::Quaternion::IDENTITY;
+    Ogre::SkeletonInstance* attached_skeleton = attached_model_->getSkeleton();
+    if (attached_skeleton != nullptr && attached_skeleton->hasBone("root")){
+        offset = attached_skeleton->getBone("root")->getOrientation().Inverse();
+    }
+    // Extra rotation around the axes of the model itself (the ones of the original files).
+    const Ogre::Quaternion extra
+      = Ogre::Quaternion(Ogre::Degree(rx), Ogre::Vector3::UNIT_X)
+      * Ogre::Quaternion(Ogre::Degree(ry), Ogre::Vector3::UNIT_Y)
+      * Ogre::Quaternion(Ogre::Degree(rz), Ogre::Vector3::UNIT_Z);
+    offset = extra * offset;
+    model_->attachObjectToBone(bone_name, attached_model_, offset);
+    attached_model_->setVisible(model_->isVisible());
+    return true;
+}
+
 void EntityModel::ScriptSetBlend(const int blend){
     if (blend == blend_) return;
     blend_ = blend;
-    for (unsigned int s = 0; s < model_->getNumSubEntities(); ++ s){
-        Ogre::SubEntity* sub_entity = model_->getSubEntity(s);
+    // The model held in a bone (a weapon) is drawn like the body.
+    std::vector<Ogre::Entity*> entities {model_};
+    if (attached_model_ != nullptr) entities.push_back(attached_model_);
+    for (Ogre::Entity* entity : entities)
+    for (unsigned int s = 0; s < entity->getNumSubEntities(); ++ s){
+        Ogre::SubEntity* sub_entity = entity->getSubEntity(s);
         // Materials are shared among all the entities of a mesh, so use one of its own.
         Ogre::MaterialPtr material = OwnMaterial(sub_entity);
         for (unsigned short t = 0; t < material->getNumTechniques(); ++ t){
@@ -163,15 +220,38 @@ void EntityModel::ScriptSetBlend(const int blend){
     }
 }
 
+/**
+ * Gets a texture of one white pixel, for the parts that have no texture (they only have the colours of
+ * the vertices), so a texture unit can give them an opacity.
+ */
+static Ogre::TexturePtr GetWhiteTexture(){
+    const Ogre::String name = "vgears_white_1x1";
+    Ogre::TextureManager& manager = Ogre::TextureManager::getSingleton();
+    Ogre::TexturePtr texture = manager.getByName(name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
+    if (texture != nullptr) return texture;
+    texture = manager.createManual(
+      name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D, 1, 1, 0, Ogre::PF_BYTE_RGBA
+    );
+    unsigned char pixel[4] = {255, 255, 255, 255};
+    Ogre::PixelBox box(Ogre::Box(0, 0, 1, 1), Ogre::PF_BYTE_RGBA, pixel);
+    texture->getBuffer()->blitFromMemory(box);
+    return texture;
+}
+
 void EntityModel::ScriptSetAlpha(const float alpha){
     if (blend_ == BLEND_NORMAL) return;
     const float a = std::max(0.0f, std::min(1.0f, alpha));
-    for (unsigned int s = 0; s < model_->getNumSubEntities(); ++ s){
-        Ogre::MaterialPtr material = model_->getSubEntity(s)->getMaterial();
+    std::vector<Ogre::Entity*> entities {model_};
+    if (attached_model_ != nullptr) entities.push_back(attached_model_);
+    for (Ogre::Entity* entity : entities)
+    for (unsigned int s = 0; s < entity->getNumSubEntities(); ++ s){
+        Ogre::MaterialPtr material = entity->getSubEntity(s)->getMaterial();
         for (unsigned short t = 0; t < material->getNumTechniques(); ++ t){
             Ogre::Technique* technique = material->getTechnique(t);
             for (unsigned short p = 0; p < technique->getNumPasses(); ++ p){
                 Ogre::Pass* pass = technique->getPass(p);
+                // Parts with only vertex colours have no texture unit to change, so give them a white one.
+                if (pass->getNumTextureUnitStates() == 0) pass->createTextureUnitState()->setTexture(GetWhiteTexture());
                 for (unsigned short u = 0; u < pass->getNumTextureUnitStates(); ++ u){
                     Ogre::TextureUnitState* unit = pass->getTextureUnitState(u);
                     if (blend_ == BLEND_ADDITIVE){

+ 14 - 0
src/core/EntityModel.h

@@ -74,6 +74,10 @@ class EntityModel : public Entity{
 
         virtual std::tuple<float, float, float> ScriptGetBonePosition(const int bone);
 
+        virtual bool ScriptAttachModel(
+          const char* model, const int bone, const float rx, const float ry, const float rz
+        );
+
         virtual void ReleaseResources();
 
         /**
@@ -122,6 +126,16 @@ class EntityModel : public Entity{
          */
         Ogre::Entity* model_;
 
+        /**
+         * Model attached to a bone of the skeleton (a weapon), nullptr if there is none.
+         */
+        Ogre::Entity* attached_model_ = nullptr;
+
+        /**
+         * Resource group of the model, to load the attached models from.
+         */
+        Ogre::String resource_group_;
+
         /**
          * The current animation state.
          */

+ 13 - 0
src/core/ScriptManager.cpp

@@ -391,6 +391,19 @@ void ScriptManager::RunString(const Ogre::String& lua){
     }
 }
 
+float ScriptManager::EvaluateNumber(const Ogre::String& expression, const float default_value){
+    const int pre_eval_index = lua_gettop(lua_state_);
+    float result = default_value;
+    if (luaL_dostring(lua_state_, ("return " + expression).c_str()) != 0){
+        LOG_ERROR("ScriptManager::EvaluateNumber error: " + Ogre::String(lua_tostring(lua_state_, -1)));
+    }
+    else if (lua_gettop(lua_state_) > pre_eval_index && lua_isnumber(lua_state_, -1)){
+        result = static_cast<float>(lua_tonumber(lua_state_, -1));
+    }
+    lua_settop(lua_state_, pre_eval_index);
+    return result;
+}
+
 void ScriptManager::RunFile(const Ogre::String& file){
     if (luaL_dofile(lua_state_, ("./data/" + file).c_str()) == 1)
         LOG_ERROR(Ogre::String(lua_tostring(lua_state_, -1)));

+ 9 - 0
src/core/ScriptManager.h

@@ -236,6 +236,15 @@ class ScriptManager : public Manager, public Ogre::Singleton<ScriptManager>{
          */
         void RunString(const Ogre::String& lua);
 
+        /**
+         * Evaluates a lua expression that returns a number.
+         *
+         * @param[in] expression Lua expression, like "Party.get_encounter_modifier()".
+         * @param[in] default_value Value to return if the expression fails or is not a number.
+         * @return The value of the expression.
+         */
+        float EvaluateNumber(const Ogre::String& expression, const float default_value);
+
         /**
          * Runs a lua file.
          *

+ 10 - 1
src/core/ScriptManagerBinds.h

@@ -139,6 +139,12 @@ void ScriptManager::InitBinds(){
       "set_alpha", &Entity::ScriptSetAlpha,
       "set_texture", &Entity::ScriptSetTexture,
       "get_bone_position", &Entity::ScriptGetBonePosition,
+      "attach_model", sol::overload(
+        [](Entity& entity, const char* model, const int bone){
+            return entity.ScriptAttachModel(model, bone, 0.0f, 0.0f, 0.0f);
+        },
+        &Entity::ScriptAttachModel
+      ),
       "is_visible", &Entity::IsVisible,
       "set_move_auto_speed", &Entity::SetMoveAutoSpeed,
       "get_move_auto_speed", &Entity::GetMoveAutoSpeed,
@@ -333,7 +339,10 @@ void ScriptManager::InitBinds(){
       "get_model_prefix", &Enemy::ScriptGetModelPrefix,
       "get_model", &Enemy::GetModel,
       "get_drop_id", &Enemy::ScriptGetDropId,
-      "get_drop_rate", &Enemy::ScriptGetDropRate
+      "get_drop_rate", &Enemy::ScriptGetDropRate,
+      "get_steal_count", &Enemy::ScriptGetStealCount,
+      "get_steal_id", &Enemy::ScriptGetStealId,
+      "get_steal_rate", &Enemy::ScriptGetStealRate
       // TODO: Implement cover flags.
       // TODO: Implement immunities
       // TODO: Implement elements

+ 114 - 1
src/installer/BattleDataInstaller.cpp

@@ -22,6 +22,8 @@
 #include <map>
 #include <set>
 #include <cctype>
+#include <cstdio>
+#include <cstdlib>
 #include <algorithm>
 #include <zlib.h>
 #include <tinyxml.h>
@@ -463,8 +465,60 @@ unsigned int BattleDataInstaller::ProcessSpellModel(){
     return next_model_to_process_;
 }
 
+namespace{
+
+/**
+ * Files of magic.lgp (without extension) with the animations of the limit breaks of each model of the party.
+ * The animation files have the format of the animations of the models, with 8 animations for the skeleton of
+ * the character (the animations 44 to 51 of the model, which are empty in battle.lgp) and 8 for its weapon.
+ * The files are in the order of the techniques of the character (limit level 1 first and second, level 2, ...):
+ * the table that ff7.exe uses to load them (at 0x7b7b58) has them in groups of 7 by character.
+ */
+const std::map<std::string, std::vector<std::string>>& LimitAnimationFiles(){
+    static const std::vector<std::string> cloud = {"blaver", "kyou", "limcl2", "limcl6", "limcl3", "limcl7", "limcl4"};
+    static const std::vector<std::string> barret = {"hvshot", "limbr5", "limbr2", "limbr6", "limbr3", "limbr7", "limbr4"};
+    static const std::map<std::string, std::vector<std::string>> files = {
+        {"rt", cloud}, {"si", cloud},
+        {"ru", {"limfast"}}, // Tifa.
+        {"rv", {"iyash", "limea5", "limea2", "limea6", "limea3", "kodo", "limea4"}}, // Aerith.
+        {"rw", {"limsled", "limrd5", "limsled", "limrd6", "limrd3", "limrd7", "limrd4"}}, // Red XIII.
+        {"rx", {"limyf1", "limyf5", "limyf2", "limyf6", "limyf3", "limyf7", "limyf4"}}, // Yuffie.
+        {"ry", {"dice"}}, // Cait Sith.
+        {"rz", {"limcd1", "limcd5", "limcd2", "limcd6", "limcd3", "limcd7", "limcd4"}}, // Cid.
+        {"sb", barret}, {"sc", barret}, {"sd", barret}, {"se", barret},
+    };
+    return files;
+}
+
+}
+
 unsigned int BattleDataInstaller::ConvertBattleModelsInit(){
     next_model_to_convert_ = 0;
+    // The animations of the limit breaks are in magic.lgp. Take the ones of the party to the folder of the battle
+    // models, so they are converted with them.
+    try{
+        std::set<std::string> wanted;
+        for (const auto& entry : LimitAnimationFiles()){
+            for (const std::string& tag : entry.second) wanted.insert(tag + ".a00");
+        }
+        File magic_lgp_file(*disk_image_.filePath("data/battle/magic.lgp"));
+        VGears::LGPArchive magic_lgp(*disk_image_.filePath("data/battle/magic.lgp"), "LGP");
+        magic_lgp.open(*disk_image_.filePath("data/battle/magic.lgp"), true);
+        magic_lgp.load();
+        VGears::LGPArchive::FileList file_list = magic_lgp.GetFiles();
+        for (int i = 0; i < file_list.size(); i ++){
+            VGears::LGPArchive::FileEntry f = file_list.at(i);
+            std::string name = f.file_name;
+            std::transform(name.begin(), name.end(), name.begin(), ::tolower);
+            if (wanted.count(name) == 0) continue;
+            if (f.data_offset + f.data_size > magic_lgp_file.GetFileSize()) continue;
+            File limit_file(&magic_lgp_file, f.data_offset, f.data_size);
+            limit_file.WriteFile(output_dir_ + "temp/battle_models/limit_" + name);
+        }
+    }
+    catch (const std::exception& ex){
+        std::cerr << "[ERROR] Exception reading the limit animations: " << ex.what() << std::endl;
+    }
     return battle_models_.size();
 }
 
@@ -504,11 +558,60 @@ unsigned int BattleDataInstaller::ConvertBattleModel(){
             for (std::string file_name : a_files) model.a.push_back(file_name);
         }
 
+        // Limit breaks of the party: their animations are in files of magic.lgp. Each one is added to the model with
+        // the names <model>_<file>_00 to _07, which replace the empty animations 44 to 51 for that limit.
+        if (info.is_player){
+            auto limits = LimitAnimationFiles().find(model.id);
+            if (limits != LimitAnimationFiles().end()){
+                std::set<std::string> converted;
+                for (const std::string& tag : limits->second){
+                    if (!converted.insert(tag).second) continue;
+                    std::string limit_path = output_dir_ + "temp/battle_models/limit_" + tag + ".a00";
+                    if (!std::ifstream(limit_path).good()) continue;
+                    try{
+                        File limit_file(limit_path);
+                        DaFile limit_da(limit_file);
+                        std::vector<std::string> limit_files = limit_da.GenerateAFiles(
+                          model.id + "_" + tag, output_dir_ + "temp/battle_models/"
+                        );
+                        for (const std::string& file_name : limit_files){
+                            // Only the animations of the skeleton (0 to 7), not the ones of the weapon.
+                            size_t dot = file_name.find_last_of('.');
+                            int number = std::atoi(file_name.substr(dot - 2, 2).c_str());
+                            if (number < 8) model.a.push_back(file_name);
+                        }
+                    }
+                    catch (const std::exception& ex){
+                        std::cerr << "[ERROR] Exception reading the limit animation " << tag << ": " << ex.what() << std::endl;
+                    }
+                }
+            }
+        }
+
         if ("" != model.script){ // Skip non scripted models
-            AbFile ab(File(output_dir_ + "temp/battle_models/" + model.script), info.is_enemy);
+            // Only the models of the party have the 74 scripts (the limits are the ones from 60 up). The other
+            // ones (enemies and the rest of the models with scripts) have 32.
+            AbFile ab(File(output_dir_ + "temp/battle_models/" + model.script), !info.is_player);
             ab.GenerateScripts(model.id + "_" + info.name_normal, data_dir_ + "scripts/battle_models/");
         }
 
+        // Playable characters hold their weapons in battle (but Red XIII, who has none). Each one is a
+        // polygon file by itself, named <id>c<k..z>, so make a model for each with a single bone.
+        std::vector<std::pair<std::string, std::string>> weapons; // Polygon file, mesh name.
+        if (info.is_player && model.id != "rw"){
+            for (std::string p : model.p){
+                if (p.length() < 4 || p[2] != 'c' || p[3] < 'k' || p[3] > 'z') continue;
+                char number[8];
+                std::snprintf(number, sizeof(number), "%02d", p[3] - 'k');
+                const std::string weapon_name = model.id + "_" + info.name_normal + "_weapon_" + number;
+                std::ofstream hrc(output_dir_ + "temp/battle_models/" + weapon_name + ".hrc");
+                hrc << ":HEADER_BLOCK 2\n:SKELETON " << weapon_name << "\n:BONES 1\n\nbone0\nroot\n0.000000\n1 "
+                    << p.substr(0, 4) << "\n\n";
+                hrc.close();
+                weapons.push_back(std::make_pair(p, weapon_name));
+            }
+        }
+
         // Reload the resources for the newly created hrc and rsd.
         // TODO: Could this be done with res_mgr_->declareResource() ? Probably faster
         res_mgr_->removeResourceLocation(output_dir_ + "temp/battle_models/", "FFVII");
@@ -532,6 +635,16 @@ unsigned int BattleDataInstaller::ConvertBattleModel(){
             a->AddTo(skeleton, VGears::NameLookup::Animation(base_name));
         }
         ExportMesh(path, mesh);
+        for (const auto& weapon : weapons){
+            try{
+                VGears::HRCFileManager::GetSingleton().load(weapon.second + ".hrc", "FFVII");
+                Ogre::MeshPtr weapon_mesh(Ogre::MeshManager::getSingleton().load(weapon.second + ".mesh", "FFVII"));
+                ExportMesh(path, weapon_mesh);
+            }
+            catch (const Ogre::Exception& ex){
+                std::cerr << "[ERROR] Ogre exception converting weapon " << weapon.second << ": " << ex.what() << std::endl;
+            }
+        }
     }
     catch (const Ogre::Exception& ex){
         std::cerr << "[ERROR] Ogre exception converting battle model " << model.hrc <<": " << ex.what() << std::endl;

+ 64 - 65
src/installer/KernelDataInstaller.cpp

@@ -17,6 +17,7 @@
 #include <tinyxml.h>
 #include <fstream>
 #include <iostream>
+#include <memory>
 #include "DiskImage.h"
 #include "KernelDataInstaller.h"
 #include "common/FinalFantasy7/FF7NameLookup.h"
@@ -178,6 +179,16 @@ int KernelDataInstaller::ReadAttacks(){
 
     limit_attacks_.clear();
 
+    // Limit data, from ff7.exe (file offset of the table at 0x910d94, in the .data section).
+    const int LIMIT_TABLE_OFFSET = 0x910d94 - 0x7b0000 + 0x3ae000;
+    std::unique_ptr<File> exe_file;
+    try{
+        exe_file.reset(new File(exe_path_));
+    }
+    catch (...){
+        std::cerr << "[WARNING] Can't read the data of the limits from ff7.exe." << std::endl;
+    }
+
     // The kernel has data for 128 attacks, but names and descriptions for 256. The last 128 are the
     // limit break techniques, which the characters refer to by ID (128 and up).
     for (int i = 0; i < 256; i ++){
@@ -232,6 +243,16 @@ int KernelDataInstaller::ReadAttacks(){
 
         // Limit techniques only have name and description. Both start with control codes, drop
         // everything before the first letter.
+        // The data of the limits that the characters use (128 to 183) is not in the kernel: it is a table of
+        // attack records, with the same format, in the data of ff7.exe (0x910d94, indexed by the limit ID minus
+        // 128; found from the code that ff7.exe uses to load the limits of a character, 0x5c9524).
+        File* source = &attacks_file;
+        bool limit_from_exe = false;
+        if (i >= 128 && i <= 183 && exe_file != nullptr){
+            exe_file->SetOffset(LIMIT_TABLE_OFFSET + (i - 128) * 0x1c);
+            source = exe_file.get();
+            limit_from_exe = true;
+        }
         if (i >= 128){
             for (std::string* text : {&data.name, &data.description}){
                 size_t first = text->find_first_of(
@@ -240,30 +261,32 @@ int KernelDataInstaller::ReadAttacks(){
                 else text->erase(0, first);
             }
             data.id = i;
-            limit_attacks_.push_back(data);
-            continue;
+            if (!limit_from_exe){
+                limit_attacks_.push_back(data);
+                continue;
+            }
         }
 
         // Read data from the item data section.
-        data.accuracy = attacks_file.readU8();
-        data.impact_effect = attacks_file.readU8();
-        data.hurt_anim = attacks_file.readU8();
-        data.unknown = attacks_file.readU8();
-        data.mp = attacks_file.readU16LE();
-        data.sound = attacks_file.readU16LE();
-        data.camera_single = attacks_file.readU16LE();
-        data.camera_multiple = attacks_file.readU16LE();
-        data.target_raw = attacks_file.readU8();
-        data.effect = attacks_file.readU8();
-        data.damage_raw = attacks_file.readU8();
-        data.power = attacks_file.readU8();
-        data.condition_raw = attacks_file.readU8();
-        data.status_change_raw = attacks_file.readU8();
-        data.additional_effects_raw = attacks_file.readU8();
-        data.additional_effects_mod_raw = attacks_file.readU8();
-        data.status_raw = attacks_file.readU32LE();
-        data.element_raw = attacks_file.readU16LE();
-        data.special_raw = attacks_file.readU16LE();
+        data.accuracy = source->readU8();
+        data.impact_effect = source->readU8();
+        data.hurt_anim = source->readU8();
+        data.unknown = source->readU8();
+        data.mp = source->readU16LE();
+        data.sound = source->readU16LE();
+        data.camera_single = source->readU16LE();
+        data.camera_multiple = source->readU16LE();
+        data.target_raw = source->readU8();
+        data.effect = source->readU8();
+        data.damage_raw = source->readU8();
+        data.power = source->readU8();
+        data.condition_raw = source->readU8();
+        data.status_change_raw = source->readU8();
+        data.additional_effects_raw = source->readU8();
+        data.additional_effects_mod_raw = source->readU8();
+        data.status_raw = source->readU32LE();
+        data.element_raw = source->readU16LE();
+        data.special_raw = source->readU16LE();
 
         // Derive data from the read data.
         data.id = i;
@@ -355,6 +378,8 @@ void KernelDataInstaller::WriteAttacks(std::string file_name){
           << "    dmg_formula = " << static_cast<int>(attack.damage_formula) << ",\n"
           << "    dmg_modifier = " << static_cast<int>(attack.damage_modifier) << ",\n"
           << "    power = " << static_cast<int>(attack.power) << ",\n"
+          << "    additional = {effect = " << static_cast<int>(attack.additional_effects_raw)
+          << ", modifier = " << static_cast<int>(attack.additional_effects_mod_raw) << "},\n"
           << "    restore = " << attack.restore_type << ",\n"
           << "    target = {selectable = " << attack.target.selection_enabled
           << ", default_enemy = " << attack.target.default_enemy
@@ -678,6 +703,7 @@ int KernelDataInstaller::ReadItems(){
         data.sellable = !(data.restrict_raw & (1 << 0));
         data.useable_battle = !(data.restrict_raw & (2 << 0));
         data.useable_menu = !(data.restrict_raw & (4 << 0));
+        data.throwable = !(data.restrict_raw & (8 << 0));
         if (data.target_raw == (data.target_raw | 0x01)) data.target.selection_enabled = true;
         else data.target.selection_enabled = false;
         if (data.target_raw == (data.target_raw | 0x02)) data.target.default_enemy = true;
@@ -696,9 +722,12 @@ int KernelDataInstaller::ReadItems(){
         else data.target.random = false;
         data.damage_formula = data.damage_raw >> 4; // Upper nybble.
         data.damage_modifier = data.damage_raw & 15; // Lower nybble.
-        data.status.chance = 63 - (data.status_change_raw ^ 63); // Out of 63;
-        if (data.status_change_raw == (data.status_change_raw | 0x00000080)) data.status.mode = TOGGLE;
-        else if (data.status_change_raw == (data.status_change_raw | 0x00000040)) data.status.mode = CURE;
+        // Status byte: the lower 6 bits are the chance out of 63, and the upper bits the mode (0x80
+        // toggles the statuses, 0x40 cures them, otherwise they are inflicted). The old formula
+        // wrapped around for cure and toggle items, so Antidote, Hyper... lost their statuses.
+        data.status.chance = data.status_change_raw & 0x3F;
+        if ((data.status_change_raw & 0x80) != 0) data.status.mode = TOGGLE;
+        else if ((data.status_change_raw & 0x40) != 0) data.status.mode = CURE;
         else data.status.mode = INFLICT;
         switch (data.condition_raw){
             case 0: data.restore_type = RESTORE_HP; break;
@@ -706,45 +735,13 @@ int KernelDataInstaller::ReadItems(){
             case 2: data.restore_type = RESTORE_STATUS; break;
             default: data.restore_type = RESTORE_NONE;
         }
-
-
         // In KERNEL.BIN, items that don't induce statuses actually have all statuses marked, and
-        // a chance of 255. If it's the case, skip statuses altogether.
-        if (data.status.chance <= 64){
-            // TODO: Im fairly sure that this can be done with a single-line loop...
-            // ... but I don't know how
-            if (data.status_raw == (data.status_raw | 0x00000001)) data.status.status.push_back(DEATH);
-            if (data.status_raw == (data.status_raw | 0x00000002)) data.status.status.push_back(NEAR_DEATH);
-            if (data.status_raw == (data.status_raw | 0x00000004)) data.status.status.push_back(SLEEP);
-            if (data.status_raw == (data.status_raw | 0x00000008)) data.status.status.push_back(POISONED);
-            if (data.status_raw == (data.status_raw | 0x00000010)) data.status.status.push_back(SADNESS);
-            if (data.status_raw == (data.status_raw | 0x00000020)) data.status.status.push_back(FURY);
-            if (data.status_raw == (data.status_raw | 0x00000040)) data.status.status.push_back(CONFU);
-            if (data.status_raw == (data.status_raw | 0x00000080)) data.status.status.push_back(SILENCE);
-            if (data.status_raw == (data.status_raw | 0x00000100)) data.status.status.push_back(HASTE);
-            if (data.status_raw == (data.status_raw | 0x00000200)) data.status.status.push_back(SLOW);
-            if (data.status_raw == (data.status_raw | 0x00000400)) data.status.status.push_back(STOP);
-            if (data.status_raw == (data.status_raw | 0x00000800)) data.status.status.push_back(FROG);
-            if (data.status_raw == (data.status_raw | 0x00001000)) data.status.status.push_back(SMALL);
-            if (data.status_raw == (data.status_raw | 0x00002000)) data.status.status.push_back(SLOW_NUMB);
-            if (data.status_raw == (data.status_raw | 0x00004000)) data.status.status.push_back(PETRIFY);
-            if (data.status_raw == (data.status_raw | 0x00008000)) data.status.status.push_back(REGEN);
-            if (data.status_raw == (data.status_raw | 0x00010000)) data.status.status.push_back(BARRIER);
-            if (data.status_raw == (data.status_raw | 0x00020000)) data.status.status.push_back(M_BARRIER);
-            if (data.status_raw == (data.status_raw | 0x00040000)) data.status.status.push_back(REFLECT);
-            if (data.status_raw == (data.status_raw | 0x00080000)) data.status.status.push_back(DUAL);
-            if (data.status_raw == (data.status_raw | 0x00100000)) data.status.status.push_back(SHIELD);
-            if (data.status_raw == (data.status_raw | 0x00200000)) data.status.status.push_back(D_SENTENCE);
-            if (data.status_raw == (data.status_raw | 0x00400000)) data.status.status.push_back(MANIPULATE);
-            if (data.status_raw == (data.status_raw | 0x00800000)) data.status.status.push_back(BERSERK);
-            if (data.status_raw == (data.status_raw | 0x01000000)) data.status.status.push_back(PEERLESS);
-            if (data.status_raw == (data.status_raw | 0x02000000)) data.status.status.push_back(PARALYSIS);
-            if (data.status_raw == (data.status_raw | 0x04000000)) data.status.status.push_back(DARKNESS);
-            if (data.status_raw == (data.status_raw | 0x08000000)) data.status.status.push_back(DUAL_DRAIN);
-            if (data.status_raw == (data.status_raw | 0x10000000)) data.status.status.push_back(DEATH_FORCE);
-            if (data.status_raw == (data.status_raw | 0x20000000)) data.status.status.push_back(RESIST);
-            if (data.status_raw == (data.status_raw | 0x40000000)) data.status.status.push_back(LUCKY_GIRL);
-            if (data.status_raw == (data.status_raw | 0x80000000)) data.status.status.push_back(IMPRISONED);
+        // a chance of 255. If it's the case, skip statuses altogether. The status IDs are the bit
+        // positions of the original game (4 sadness, 5 fury...).
+        if (data.status_change_raw != 0xFF && data.status_raw != 0xFFFFFFFF){
+            for (int bit = 0; bit < 32; bit ++){
+                if ((data.status_raw & (1u << bit)) != 0) data.status.status.push_back(bit);
+            }
         }
 
         // Get elements
@@ -791,7 +788,7 @@ void KernelDataInstaller::WriteItems(std::string file_name){
           << "    sell = " << item.sellable << ",\n"
           << "    battle = " << item.useable_battle << ",\n"
           << "    menu = " << item.useable_menu << ",\n"
-          << "    throw = 0,\n"
+          << "    throw = " << item.throwable << ",\n"
           << "    effect = " << static_cast<int>(item.effect) << ",\n"
           << "    dmg_formula = " << static_cast<int>(item.damage_formula) << ",\n"
           << "    dmg_modifier = " << static_cast<int>(item.damage_modifier) << ",\n"
@@ -1130,6 +1127,7 @@ int KernelDataInstaller::ReadArmors(){
         data.sellable = !(data.restrict_raw & (1 << 0));
         data.useable_battle = !(data.restrict_raw & (2 << 0));
         data.useable_menu = !(data.restrict_raw & (4 << 0));
+        data.throwable = !(data.restrict_raw & (8 << 0));
         if (data.equip_raw == (data.equip_raw | 0x0001)) data.equip.push_back(0);
         if (data.equip_raw == (data.equip_raw | 0x0002)) data.equip.push_back(1);
         if (data.equip_raw == (data.equip_raw | 0x0004)) data.equip.push_back(2);
@@ -1203,7 +1201,7 @@ void KernelDataInstaller::WriteArmors(std::string file_name){
           << "    sell = " << armor.sellable << ",\n"
           << "    battle = " << armor.useable_battle << ",\n"
           << "    menu = " << armor.useable_menu << ",\n"
-          << "    throw = 0,\n"
+          << "    throw = " << armor.throwable << ",\n"
           << "    defense = {physical = " << static_cast<int>(armor.defense) << ", magical = "
           << static_cast<int>(armor.m_defense) << "},\n"
           << "    evasion = {physical = " << static_cast<int>(armor.evasion) << ", magical = "
@@ -1313,6 +1311,7 @@ int KernelDataInstaller::ReadAccessories(){
         data.sellable = !(data.restrict_raw & (1 << 0));
         data.useable_battle = !(data.restrict_raw & (2 << 0));
         data.useable_menu = !(data.restrict_raw & (4 << 0));
+        data.throwable = !(data.restrict_raw & (8 << 0));
         if (data.status_raw == (data.status_raw | 0x00000001)) data.status.push_back(DEATH);
         if (data.status_raw == (data.status_raw | 0x00000002)) data.status.push_back(NEAR_DEATH);
         if (data.status_raw == (data.status_raw | 0x00000004)) data.status.push_back(SLEEP);
@@ -1410,7 +1409,7 @@ void KernelDataInstaller::WriteAccessories(std::string file_name){
           << "    sell = " << accessory.sellable << ",\n"
           << "    battle = " << accessory.useable_battle << ",\n"
           << "    menu = " << accessory.useable_menu << ",\n"
-          << "    throw = 0,\n"
+          << "    throw = " << accessory.throwable << ",\n"
           << "    special_effect = {";
         if (accessory.effect != 0XFF) file << static_cast<int>(accessory.effect);
         file

+ 9 - 0
src/installer/KernelDataInstaller.h

@@ -1276,6 +1276,9 @@ class KernelDataInstaller{
              */
             bool useable_menu;
 
+            /** Whether the item can be thrown (Throw command). */
+            bool throwable;
+
             /**
              * Target selection mode.
              *
@@ -1802,6 +1805,9 @@ class KernelDataInstaller{
              */
             bool useable_menu;
 
+            /** Whether the item can be thrown (Throw command). */
+            bool throwable;
+
             /**
              * The weapon battle model index.
              *
@@ -1953,6 +1959,9 @@ class KernelDataInstaller{
              */
             bool useable_menu;
 
+            /** Whether the item can be thrown (Throw command). */
+            bool throwable;
+
             /**
              * The weapon battle model index.
              *

+ 5 - 1
src/installer/data/AbFile.cpp

@@ -42,7 +42,11 @@ unsigned int AbFile::GenerateScripts(std::string model_id, std::string path) con
 
 void AbFile::Read(){
     ab_file_.SetOffset(0x68); // 104 / 0x68 is the first script index.
-    int total = is_enemy_ ? 74 : 32; // 32 for enemies, 74 for characters.
+    // 32 scripts for enemies, 74 for characters (their table of offsets ends where the first script starts:
+    // 0x68 + 74 * 4 = 400 in the files of the party). The scripts 60 and up are the ones of the limits. This
+    // was the other way around before, so the characters only had 32 scripts and the limits had no animation.
+    // The parameter is true for everything that is not a model of the party (it was only for enemies).
+    int total = is_enemy_ ? 32 : 74;
     for (int a = 0; a < total; a ++){
         scripts_.push_back(DecompileScript(ab_file_.readU16LE()));
         ab_file_.readU16LE(); // Offset are 16 bits, in 32 bit blocks. 3rd and 4th bytes discarded.

برخی فایل ها در این مقایسه diff نمایش داده نمی شوند زیرا تعداد فایل ها بسیار زیاد است