Sfoglia il codice sorgente

Merge branch 'feature/battle_module' into develop

Iñigo Valentin 2 giorni fa
parent
commit
9c26145667

+ 312 - 56
data/data/scripts/battle/battle_camera.lua

@@ -7,14 +7,16 @@
 -- and camera_multiple of the attacks. The interpreters are in ff7.exe (0x5c2341 and 0x5c3f45).
 --
 -- A script is a list of opcodes (0xd5-0xff, other values do nothing) with operands that are bytes or
--- 16 bit values (little endian, with sign). Positions are in the units of the original game, in a
--- frame with x to the side, y down and z forward (toward the enemies, for the party), and the ones
--- that follow an actor are relative to a point of it, the offsets turned with the way it faces if
--- the stream has "rotate" on. The frame of the scene is converted with
+-- 16 bit values (little endian, with sign). Positions are in the units of the original game, with x to
+-- the side, y down and z in depth (the enemies are in the negative side), and the ones that follow an
+-- actor are relative to a point of it, the offsets turned with the way it faces if the stream has
+-- "rotate" on. The frame of the scene is converted like the positions of the formations:
 --
---   scene = (x, -z, -y) / 255      (a reflection: the original frame is left handed)
+--   scene = (x, z, -y) / 255
 --
--- (the division is the one the installer uses for every coordinate of the battle). The streams run
+-- (the division is the one the installer uses for every coordinate of the battle). The facing angle of
+-- an actor in ff7.exe is the one of the direction to its target plus half a turn (0x420d5b), so the
+-- positive z of a turned offset is behind the actor. The streams run
 -- one opcode after the other until one of them waits or places the point (the ones that do are
 -- listed in YIELDS), once per tick, 15 ticks per second like the effects.
 --
@@ -95,6 +97,8 @@ function BattleCamera.new(position, look, env)
     local f = env.formation
     self.cam.pos = {f.pos[1], f.pos[2], f.pos[3]}
     self.look.pos = {f.look[1], f.look[2], f.look[3]}
+    -- The camera the script started on (opcode d9). The opcode dd changes the one of e1 and e2, not it.
+    self.base = f
     return self
 end
 
@@ -120,7 +124,7 @@ end
 --- Converts a vector of the original frame to the scene, as an offset.
 local function to_scene_offset(x, y, z)
     local k = BattleCamera.UNIT
-    return x * k, -z * k, -y * k
+    return x * k, z * k, -y * k
 end
 
 --- Converts a position of the original frame (absolute) to the scene.
@@ -130,20 +134,41 @@ end
 
 --- Position of a point of an actor, plus an offset of the original frame.
 --
+-- As in ff7.exe, the offsets of the position of the camera grow with the size of the model (0x5c6290) and
+-- turn with the way it faces if the stream has "rotate" on, and the ones of the point it looks at do
+-- neither: they only move down by the height that the model has for it (0x5c5a78). None of that applies to
+-- the center of a group of targets.
+--
+-- @param kind Stream of the offset, "pos" or "look".
 -- @param rotate If the offset turns with the way the actor faces.
-function BattleCamera:anchor(ref, point, ox, oy, oz, rotate)
+function BattleCamera:anchor(ref, point, ox, oy, oz, rotate, kind)
     local actor = self.env:actor(ref)
     if actor == nil then return nil end
-    -- The points of the original are bones. All of the used ones (0 and 10) are near the middle of
-    -- the body, so they are the middle of the actor.
-    local px, py, pz = actor.pos[1], actor.pos[2], actor.pos[3] + actor.height * 0.5
+    -- The points are ends of bones of the model. Without that data (an old install), the middle of the actor.
+    local px, py, pz
+    if actor.point ~= nil then px, py, pz = actor.point(point) end
+    if px == nil then px, py, pz = actor.pos[1], actor.pos[2], actor.pos[3] + actor.height * 0.5 end
+    if actor.group then
+        rotate = false
+    end
+    if kind == "look" then
+        oy = oy + (actor.look_height or 0)
+        rotate = false
+    elseif actor.size ~= nil then
+        local function scale(value, size)
+            -- A Small actor halves the factors, but they don't go under 256.
+            if actor.small then size = math.max(256, math.floor(size / 2)) end
+            return math.floor(value * size / 256)
+        end
+        ox, oy, oz = scale(ox, actor.size[1]), scale(oy, actor.size[2]), scale(oz, actor.size[3])
+    end
     local k = BattleCamera.UNIT
     local dx, dy, dz
     if rotate then
-        -- x is to the left of the way it faces (reflection), z forward, y down.
+        -- x is to the left of the way it faces, z behind it, y down (the rotation of 0x5c6290).
         local fx, fy = actor.forward[1], actor.forward[2]
-        dx = (-fy) * ox * k + fx * oz * k
-        dy = fx * ox * k + fy * oz * k
+        dx = (-fy) * ox * k - fx * oz * k
+        dy = fx * ox * k - fy * oz * k
         dz = -oy * k
     else
         dx, dy, dz = to_scene_offset(ox, oy, oz)
@@ -171,13 +196,51 @@ end
 local function start_follow(stream, ref, point, ox, oy, oz, ticks, rotate)
     stream.tasks[#stream.tasks + 1] = {
         type = "follow", ref = ref, point = point, off = {ox, oy, oz}, ticks = math.max(1, ticks),
-        age = 0, rotate = rotate,
+        age = 0, rotate = rotate, kind = stream.kind,
+    }
+end
+
+--- Starts an orbit of the position around the point the camera looks at (opcode f8 of the position,
+-- task 0x5c3c7d of ff7.exe).
+--
+-- All the values are the ones of the script: angles in 4096ths of a turn, distances in the original frame.
+--
+-- @param speed Angle added each tick.
+-- @param radius Horizontal distance to the point, in eighths.
+-- @param angle Starting angle.
+-- @param radius_speed Added to the radius each tick.
+-- @param y_speed Added to the height (down) of the camera each tick.
+local function start_orbit(stream, speed, radius, angle, radius_speed, y_speed, ticks)
+    stream.tasks[#stream.tasks + 1] = {
+        type = "orbit", speed = speed, radius = radius, angle = angle, radius_speed = radius_speed,
+        y_speed = y_speed, ticks = math.max(1, ticks), age = 0,
     }
 end
 
+--- The reference of the "current actor" of the opcodes (byte 0xbe40e4 of ff7.exe): the target, or
+-- the group of targets if there are several or after the opcode df.
+function BattleCamera:current_ref()
+    return self.group and "targets" or "current"
+end
+
+--- Position of one of the two views a model has for the cameras (opcode e0): the position of the
+-- camera or the point it looks at, depending on the stream. It doesn't turn or grow with the model. The
+-- height of the first view is over the ground, and the one of the second over the actor.
+--
+-- @param view 0 or 1.
+-- @return Nil if there is no data, like for a group of targets.
+function BattleCamera:view_point(ref, view, kind)
+    local actor = self.env:actor(ref)
+    if actor == nil or actor.views == nil or actor.views[view + 1] == nil then return nil end
+    local offset = actor.views[view + 1][kind]
+    local x, y, z = to_scene_offset(offset[1], offset[2], offset[3])
+    if view ~= 0 then z = z + actor.pos[3] end
+    return vec(actor.pos[1] + x, actor.pos[2] + y, z)
+end
+
 --- Places a stream at a point of an actor, now.
 function BattleCamera:place(stream, ref, point, ox, oy, oz, rotate)
-    local p = self:anchor(ref, point, ox, oy, oz, rotate)
+    local p = self:anchor(ref, point, ox, oy, oz, rotate, stream.kind)
     if p ~= nil then stream.pos = p end
 end
 
@@ -219,6 +282,9 @@ function BattleCamera:run(stream)
             end
         elseif op == 0xdc then
             stream.rotate = true
+        elseif op == 0xdf then
+            -- From now on, the "current actor" of both streams is the group of targets.
+            self.group = true
         elseif kind == "pos" and op == 0xf1 then
             stream.rotate = false
         elseif kind == "look" and op == 0xdb then
@@ -227,10 +293,15 @@ function BattleCamera:run(stream)
             stream.linear = false
         elseif kind == "pos" and op == 0xdb then
             stream.linear = true
-        elseif op == 0xe1 or op == 0xd9 or op == 0xdd then
-            -- The camera that was in use.
-            if op == 0xdd then u8(stream) end
-            local source = kind == "pos" and env.formation.pos or env.formation.look
+        elseif op == 0xdd then
+            -- Chooses the camera of the formation that e1 and e2 use, for both streams.
+            local index = u8(stream)
+            local chosen = env.formation_at ~= nil and env.formation_at(index) or nil
+            if chosen ~= nil then env.formation, self.formation_index = chosen, index end
+        elseif op == 0xe1 or op == 0xd9 then
+            -- The camera of the formation (e1), or the one that was in use before the script (d9).
+            local view = op == 0xd9 and self.base or env.formation
+            local source = kind == "pos" and view.pos or view.look
             stream.pos = {source[1], source[2], source[3]}
         elseif op == 0xe2 then
             local source = kind == "pos" and env.formation.pos or env.formation.look
@@ -238,6 +309,11 @@ function BattleCamera:run(stream)
         elseif op == 0xe6 then
             local x, y, z = s16(stream), s16(stream), s16(stream)
             start_move(stream, self:absolute(x, y, z), u8(stream))
+        elseif op == 0xe0 then
+            -- Move to a view of the current actor: view, ticks.
+            local view, ticks = u8(stream), u8(stream)
+            local target = self:view_point(self:current_ref(), view, kind)
+            if target ~= nil then start_move(stream, target, ticks) end
         elseif (kind == "pos" and op == 0xf9) or (kind == "look" and op == 0xfa) then
             local x, y, z = s16(stream), s16(stream), s16(stream)
             stream.pos = self:absolute(x, y, z)
@@ -245,13 +321,13 @@ function BattleCamera:run(stream)
             -- Move to a point of an actor, with an offset: actor (e3 and d8), point, x, y, z, ticks.
             local ref
             if op == 0xe3 then ref = actor_from_byte(u8(stream))
-            elseif op == 0xd8 then u8(stream) ref = "targets"
+            elseif op == 0xd8 then ref = {target = u8(stream) + 1}
             elseif op == 0xe4 then ref = "attacker"
-            else ref = "current" end
+            else ref = self:current_ref() end
             local point = u8(stream)
             local x, y, z = s16(stream), s16(stream), s16(stream)
             local ticks = u8(stream)
-            local target = self:anchor(ref, point, x, y, z, stream.rotate)
+            local target = self:anchor(ref, point, x, y, z, stream.rotate, stream.kind)
             if target ~= nil then start_move(stream, target, ticks) end
         elseif (kind == "pos" and (op == 0xe7 or op == 0xe9 or op == 0xeb))
           or (kind == "look" and (op == 0xe8 or op == 0xea or op == 0xec)) then
@@ -259,7 +335,7 @@ function BattleCamera:run(stream)
             local ref
             if op == 0xeb or op == 0xec then ref = actor_from_byte(u8(stream))
             elseif op == 0xe7 or op == 0xe8 then ref = "attacker"
-            else ref = "current" end
+            else ref = self:current_ref() end
             local point = u8(stream)
             local x, y, z = s16(stream), s16(stream), s16(stream)
             local ticks = u8(stream)
@@ -270,13 +346,17 @@ function BattleCamera:run(stream)
             local ref
             if (kind == "pos" and op == 0xef) or (kind == "look" and op == 0xf0) then ref = actor_from_byte(u8(stream))
             elseif (kind == "pos" and op == 0xf0) or (kind == "look" and op == 0xf9) then ref = "attacker"
-            else ref = "current" end
+            else ref = self:current_ref() end
             local point = u8(stream)
             local x, y, z = s16(stream), s16(stream), s16(stream)
             self:place(stream, ref, point, x, y, z, stream.rotate)
+        elseif kind == "pos" and op == 0xf8 then
+            local speed, radius, angle = s16(stream), s16(stream), s16(stream)
+            local radius_speed, y_speed, ticks = s16(stream), s16(stream), s16(stream)
+            start_orbit(stream, speed, radius, angle, radius_speed, y_speed, ticks)
         else
-            -- Opcodes that don't change the camera (events of the battle, the orbits f2 and f3, the
-            -- moves to the data of an actor e0, 0xf8 of the position): skip their operands.
+            -- Opcodes that don't change the camera (events of the battle) and the ones no script of the
+            -- game uses (like f2 and f3): skip their operands.
             stream.pc = stream.pc + length
         end
         if yields[op] and op ~= 0xff and op ~= 0xf4 then return end
@@ -301,8 +381,19 @@ function BattleCamera:run_tasks(stream)
                     task.start[3] + (task.target[3] - task.start[3]) * f,
                 }
             end
+        elseif task.type == "orbit" then
+            task.angle = task.angle + task.speed
+            local a = task.angle * 2 * math.pi / 4096
+            local r = task.radius * 8 * BattleCamera.UNIT
+            local center = self.look.pos
+            stream.pos = {
+                center[1] + math.sin(a) * r,
+                center[2] + math.cos(a) * r,
+                stream.pos[3] - task.y_speed * BattleCamera.UNIT,
+            }
+            task.radius = task.radius + task.radius_speed
         else
-            local p = self:anchor(task.ref, task.point, task.off[1], task.off[2], task.off[3], task.rotate)
+            local p = self:anchor(task.ref, task.point, task.off[1], task.off[2], task.off[3], task.rotate, task.kind)
             if p ~= nil then stream.pos = p end
         end
         if task.age < task.ticks then alive[#alive + 1] = task end
@@ -369,6 +460,50 @@ local function entity_info(entity)
 end
 BattleCameraController.heights = {}
 
+--- Data of the battle models for the cameras, by model name. False for the models without it.
+BattleCameraController.models = {}
+
+--- Gets the camera data of a model, written by the installer. Nil if there is none.
+local function model_data(name)
+    if name == nil then return nil end
+    local data = BattleCameraController.models[name]
+    if data == nil then
+        local chunk = loadfile("./data/scripts/battle_models/" .. name .. "_camera.lua")
+        if chunk ~= nil then chunk() end
+        data = BattleModelCameras ~= nil and BattleModelCameras[name] or false
+        BattleCameraController.models[name] = data
+    end
+    return data or nil
+end
+
+--- Describes an actor of the scene for the camera.
+--
+-- @param entity Its entity.
+-- @param side Its side, and index its place in it.
+-- @param forward The way it faces.
+local function actor_info(entity, side, index, forward)
+    local x, y, z, height = entity_info(entity)
+    local info = {pos = {x, y, z}, height = height, forward = forward({x, y, z})}
+    local ui = UiContainer.BattleUi
+    local data = model_data(ui:get_model_name(side, index))
+    if data ~= nil then
+        info.size, info.look_height, info.views = data.size, data.look_height, data.views
+        info.small = ui:has_status(side, index, BattleStatus.SMALL)
+        -- Position of a point of the model, nil if the model doesn't have it.
+        info.point = function(point)
+            local bone = data.points[point + 1]
+            if bone == nil then return nil end
+            local bx, by, bz
+            if bone == 0 then bx, by, bz = entity:get_bone_position(0)
+            elseif data.lengths[bone - 1] ~= nil then bx, by, bz = entity:get_bone_end(bone - 1, data.lengths[bone - 1])
+            end
+            if bx == nil or (bx == 0 and by == 0 and bz == 0) then return nil end
+            return bx, by, bz
+        end
+    end
+    return info
+end
+
 --- Builds the environment of the camera for an action.
 local function build_env(side, actor, target_side, targets, formation)
     local ui = UiContainer.BattleUi
@@ -376,27 +511,27 @@ local function build_env(side, actor, target_side, targets, formation)
         local e = ui:get_entity(s, index)
         return e
     end
-    -- Center of the targets (their entities) and of the attacker.
-    local function center_of(s, list)
-        local sx, sy, sz, n = 0, 0, 0, 0
-        local height = 0
+    -- Middle of the area the targets are in, on the ground.
+    local function ground_center(s, list)
+        local min_x, max_x, min_y, max_y
         for _, index in ipairs(list) do
             local e = entity_of(s, index)
             if e ~= nil then
-                local x, y, z, h = entity_info(e)
-                sx, sy, sz, n, height = sx + x, sy + y, sz + z, n + 1, math.max(height, h)
+                local x, y = entity_info(e)
+                min_x, max_x = math.min(min_x or x, x), math.max(max_x or x, x)
+                min_y, max_y = math.min(min_y or y, y), math.max(max_y or y, y)
             end
         end
-        if n == 0 then return nil end
-        return {sx / n, sy / n, sz / n}, height
+        if min_x == nil then return nil end
+        return {(min_x + max_x) / 2, (min_y + max_y) / 2, 0}
     end
     local attacker_entity = entity_of(side, actor)
-    local attacker_pos, attacker_height
+    local attacker_pos
     if attacker_entity ~= nil then
-        local x, y, z, h = entity_info(attacker_entity)
-        attacker_pos, attacker_height = {x, y, z}, h
+        local x, y, z = entity_info(attacker_entity)
+        attacker_pos = {x, y, z}
     end
-    local target_pos, target_height = center_of(target_side, targets)
+    local target_pos = ground_center(target_side, targets)
     local function direction(from, to)
         if from == nil or to == nil then return {0, -1} end
         local dx, dy = to[1] - from[1], to[2] - from[2]
@@ -404,28 +539,33 @@ local function build_env(side, actor, target_side, targets, formation)
         if l < 0.0001 then return {0, -1} end
         return {dx / l, dy / l}
     end
+    local function toward(to) return function(from) return direction(from, to) end end
     local env = {formation = formation}
     function env:actor(ref)
         if ref == "attacker" then
-            if attacker_pos == nil then return nil end
-            return {pos = attacker_pos, height = attacker_height, forward = direction(attacker_pos, target_pos)}
+            if attacker_entity == nil then return nil end
+            return actor_info(attacker_entity, side, actor, toward(target_pos))
+        elseif ref == "current" and #targets == 1 then
+            local e = entity_of(target_side, targets[1])
+            if e ~= nil then return actor_info(e, target_side, targets[1], toward(attacker_pos)) end
         elseif ref == "current" or ref == "targets" then
-            if target_pos == nil then return nil end
-            if ref == "current" then
-                -- The first target.
-                local e = entity_of(target_side, targets[1])
-                if e ~= nil then
-                    local x, y, z, h = entity_info(e)
-                    return {pos = {x, y, z}, height = h, forward = direction({x, y, z}, attacker_pos)}
-                end
-            end
-            return {pos = target_pos, height = target_height, forward = direction(target_pos, attacker_pos)}
+            -- The center of the group of targets, on the ground (0x5bfe39).
+            local center = ground_center(target_side, targets)
+            if center == nil then return nil end
+            return {
+                group = true, pos = center, height = 0, forward = direction(center, attacker_pos),
+                point = function() return center[1], center[2], center[3] end,
+            }
+        elseif type(ref) == "table" and ref.target ~= nil then
+            -- One of the targets, by its place in the list (opcode d8).
+            local index = targets[ref.target] or targets[1]
+            local e = entity_of(target_side, index)
+            if e ~= nil then return actor_info(e, target_side, index, toward(attacker_pos)) end
         elseif type(ref) == "table" then
-            local e = entity_of(ref.side == "party" and Battle.TargetGroup.PARTY or Battle.TargetGroup.ENEMIES, ref.index)
+            local ref_side = ref.side == "party" and Battle.TargetGroup.PARTY or Battle.TargetGroup.ENEMIES
+            local e = entity_of(ref_side, ref.index)
             if e == nil then return nil end
-            local x, y, z, h = entity_info(e)
-            local other = ref.side == "party" and target_pos or attacker_pos
-            return {pos = {x, y, z}, height = h, forward = direction({x, y, z}, other)}
+            return actor_info(e, ref_side, ref.index, toward(ref.side == "party" and target_pos or attacker_pos))
         end
         return nil
     end
@@ -443,6 +583,7 @@ end
 -- @return True if there is a camera.
 function BattleCameraController:start(side, actor, target_side, targets, camera_single, camera_multiple)
     self:stop(false)
+    self.from_script = false
     if Battle.is_camera_auto ~= nil and not Battle.is_camera_auto() then return false end
     if targets == nil or #targets == 0 then return false end
     local id = #targets > 1 and camera_multiple or camera_single
@@ -470,6 +611,115 @@ function BattleCameraController:start(side, actor, target_side, targets, camera_
     return true
 end
 
+--- Starts the camera of the victory: shots of the party at fixed places, which depend on the camera
+-- file of the layout of the battle (camera id -3 of ff7.exe, set at 0x42dbd7).
+--
+-- @return True if there is a camera (an old install doesn't have its data).
+function BattleCameraController:start_victory()
+    local variant = math.random(0, 2)
+    local file = self.FILE_BY_LAYOUT[battle_manager:get_layout()] or 0
+    local data = Game.BattleCameras ~= nil and Game.BattleCameras[file] or nil
+    if data == nil or data.victory_position == nil then return false end
+    local position = data.scripts[data.victory_position[variant + 1]]
+    local look = data.scripts[data.victory_look[variant + 1]]
+    if position == nil and look == nil then return false end
+    self:reset()
+    local index = UiContainer.BattleUi.camera_index or 0
+    local px, py, pz, lx, ly, lz = battle_manager:get_camera(index)
+    -- These scripts don't use any actor.
+    local env = {formation = {pos = {px, py, pz}, look = {lx, ly, lz}}, actor = function() return nil end}
+    self.camera = BattleCamera.new(position, look, env)
+    self.camera_index = index
+    print("Battle camera: victory, variant " .. tostring(variant) .. " file " .. tostring(file))
+    return true
+end
+
+--- Starts one of the camera scripts that ff7.exe has (camera id -2): the ones of the start of the
+-- battles, and the ones that the animation scripts of some enemies use. They go to a camera of the
+-- formation, which they can change.
+--
+-- @param id Number of the script.
+-- @return True if there is a camera.
+function BattleCameraController:start_script(id)
+    local data = Game.BattleCameras ~= nil and Game.BattleCameras.intro or nil
+    if data == nil or id == nil or id < 0 then return false end
+    local position = data.scripts[data.position[id + 1]]
+    local look = data.scripts[data.look[id + 1]]
+    if position == nil and look == nil then return false end
+    local function formation_at(index)
+        if index < 0 or index > 2 then return nil end
+        local px, py, pz, lx, ly, lz = battle_manager:get_camera(index)
+        return {pos = {px, py, pz}, look = {lx, ly, lz}}
+    end
+    local index = UiContainer.BattleUi.camera_index or 0
+    local env = {formation = formation_at(index), formation_at = formation_at, actor = function() return nil end}
+    self:reset()
+    self.camera = BattleCamera.new(position, look, env)
+    self.camera_index = index
+    self.from_script = true
+    return true
+end
+
+--- Starts the camera of the start of a battle: from some other place to a camera of the formation.
+-- The formation chooses the script.
+--
+-- @return True if there is a camera.
+function BattleCameraController:start_intro()
+    self:reset()
+    UiContainer.BattleUi.camera_index = 0
+    local id = battle_manager:get_intro_camera()
+    if not self:start_script(id) then return false end
+    print("Battle camera: start of the battle, script " .. tostring(id))
+    return true
+end
+
+--- Changes the camera of the formation the battle rests on, moving to it.
+--
+-- @param index 0 to 2.
+function BattleCameraController:set_view(index)
+    if index < 0 or index > 2 then return end
+    local previous = UiContainer.BattleUi.camera_index or 0
+    UiContainer.BattleUi.camera_index = index
+    self.camera_index = index
+    if self.camera ~= nil or previous == index then return end
+    local px, py, pz, lx, ly, lz = battle_manager:get_camera(previous)
+    local from = self.returning ~= nil and self.returning.to or nil
+    local cam, look = from ~= nil and from[1] or {px, py, pz}, from ~= nil and from[2] or {lx, ly, lz}
+    px, py, pz, lx, ly, lz = battle_manager:get_camera(index)
+    self.returning = {target = {{px, py, pz}, {lx, ly, lz}}, cam = cam, look = look, index = index}
+    self.accumulated = 0
+end
+
+--- Is a script of an animation still moving the camera? It goes on even with no action.
+function BattleCameraController:is_script_running()
+    return self.camera ~= nil and self.from_script == true and not self.camera:is_finished()
+end
+
+--- Moves the camera of the start of the battle, and leaves the one of the formation when it ends.
+--
+-- @param dt Seconds since the last call.
+-- @return True while it goes on.
+function BattleCameraController:update_intro(dt)
+    if self.camera == nil then return false end
+    self:update(dt)
+    if not self.camera:is_finished() then return true end
+    local index = self.camera_index or 0
+    self:reset()
+    battle_manager:set_camera(index)
+    return false
+end
+
+--- Forgets the camera in use, without moving anything.
+function BattleCameraController:reset()
+    self.camera = nil
+    self.from_script = false
+    self.returning = nil
+    self.last = nil
+    self.previous = nil
+    self.current = nil
+    self.accumulated = 0
+end
+
 --- Stops the camera and goes back to the one of the formation.
 --
 -- The original doesn't jump: every tick the camera and the point it looks at cover half of the
@@ -532,6 +782,12 @@ function BattleCameraController:update(dt)
     while self.accumulated >= 1 do
         self.accumulated = self.accumulated - 1
         self.camera:tick()
+        -- A script chose another camera of the formation: the battle stays on it.
+        local view = self.camera.formation_index
+        if view ~= nil then
+            self.camera_index = view
+            UiContainer.BattleUi.camera_index = view
+        end
         local cam, look = self.camera:get()
         self.previous = self.current
         self.current = {cam = {cam[1], cam[2], cam[3]}, look = {look[1], look[2], look[3]}}

File diff suppressed because it is too large
+ 600 - 107
data/data/scripts/battle/battle_ui.lua


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

@@ -19,6 +19,9 @@ local function get_materia_level(materia, ap)
     return level
 end
 
+--- See get_materia_level, the stats need it too.
+Characters.get_materia_level = get_materia_level
+
 --- Gets the magic, summons and enemy skills a character can use with the materia that is equipped.
 --
 -- Every ability is listed once, even if more than one materia gives it.

+ 4 - 0
data/data/scripts/field.lua

@@ -316,9 +316,13 @@ name_character = function(id)
         print("Tried to rename invalid character with ID " .. tostring(id))
         return 0
     end
+    -- Cait Sith and Vincent get their data before they are named.
+    Characters.load_recruit_record(id)
     -- While the name menu is not enabled, the character just gets its default name.
     if not UiContainer.NameMenu.enabled then
         UiContainer.NameMenu:apply_default_name(id)
+        -- The level of the character is set once it has a name.
+        Characters.join(id)
         return 0
     end
     UiContainer.NameMenu.id = id

+ 18 - 12
data/data/scripts/menu/item_menu.lua

@@ -841,28 +841,34 @@ UiContainer.ItemMenu = {
                 end
         elseif Game.Items[item].id == 71 then
             -- Power source. Can't be differenciated by other means other than ID. STR bonus + 1.
-            -- Original game caps bonus at 255. V-Gears doesn't.
-            Characters[char_id].stats.str.bonus = Characters[char_id].stats.str.bonus + 1
+            if not Characters.add_stat_bonus(char_id, "str") then
+                return false
+            end
         elseif Game.Items[item].id == 72 then
             -- Guard source. Can't be differenciated by other means other than ID. VIT bonus + 1.
-            -- Original game caps bonus at 255. V-Gears doesn't.
-            Characters[char_id].stats.vit.bonus = Characters[char_id].stats.vit.bonus + 1
+            if not Characters.add_stat_bonus(char_id, "vit") then
+                return false
+            end
         elseif Game.Items[item].id == 73 then
             -- Magic source. Can't be differenciated by other means other than ID. MAG bonus + 1.
-            -- Original game caps bonus at 255. V-Gears doesn't.
-            Characters[char_id].stats.mag.bonus = Characters[char_id].stats.mag.bonus + 1
+            if not Characters.add_stat_bonus(char_id, "mag") then
+                return false
+            end
         elseif Game.Items[item].id == 74 then
             -- Mind source. Can't be differenciated by other means other than ID. SPR bonus + 1.
-            -- Original game caps bonus at 255. V-Gears doesn't.
-            Characters[char_id].stats.spr.bonus = Characters[char_id].stats.spr.bonus + 1
+            if not Characters.add_stat_bonus(char_id, "spr") then
+                return false
+            end
         elseif Game.Items[item].id == 75 then
             -- Speed source. Can't be differenciated by other means other than ID. DEX bonus + 1.
-            -- Original game caps bonus at 255. V-Gears doesn't.
-            Characters[char_id].stats.dex.bonus = Characters[char_id].stats.dex.bonus + 1
+            if not Characters.add_stat_bonus(char_id, "dex") then
+                return false
+            end
         elseif Game.Items[item].id == 76 then
             -- Luck source. Can't be differenciated by other means other than ID. LCK bonus + 1.
-            -- Original game caps bonus at 255. V-Gears doesn't.
-            Characters[char_id].stats.lck.bonus = Characters[char_id].stats.lck.bonus + 1
+            if not Characters.add_stat_bonus(char_id, "lck") then
+                return false
+            end
         elseif Game.Items[item].id == 87 then
             -- Omnislash. Can't be differenciated by other means other than ID.
             -- Functionality hardcoded here.

+ 6 - 17
data/data/scripts/menu/menu_lib.lua

@@ -37,9 +37,8 @@ end
 
 --- Calculates how much of the way to the next level a character has done.
 --
--- Uses the EXP curve of the character (see Game.Growth.curves): the EXP needed to attain a level
--- L is Mod * (L - 1)^2 / 10, where Mod is the gradient of the curve segment for L. The character
--- stores the EXP still missing for the next level (exp_to_next).
+-- The character stores the experience still missing for the next level (exp_to_next), see
+-- Characters.exp_threshold.
 --
 -- @param character Entry of the Characters table.
 -- @return A number from 0 to 1. 0 if it can't be calculated (e.g. level 99).
@@ -48,21 +47,11 @@ UiContainer.exp_progress = function(character)
     if definition == nil or definition.curves == nil or definition.curves.exp == nil then
         return 0
     end
-    local curve = Game.Growth.curves[definition.curves.exp]
     local level = character.level
-    local target = level + 1
-    if curve == nil or target > 99 then return 0 end
-    local segment
-    if target <= 11 then segment = 0
-    elseif target <= 21 then segment = 1
-    elseif target <= 31 then segment = 2
-    elseif target <= 41 then segment = 3
-    elseif target <= 51 then segment = 4
-    elseif target <= 61 then segment = 5
-    elseif target <= 81 then segment = 6
-    else segment = 7 end
-    local span = math.floor(curve[segment].gradient * level * level / 10)
-    if span <= 0 or character.exp_to_next == nil then return 0 end
+    if level >= Characters.MAX_LEVEL or character.exp_to_next == nil then return 0 end
+    local span = Characters.exp_threshold(character.char_id, level)
+      - Characters.exp_threshold(character.char_id, level - 1)
+    if span <= 0 then return 0 end
     return math.max(0, math.min(1, 1 - character.exp_to_next / span))
 end
 

+ 4 - 0
data/data/scripts/menu/name_menu.lua

@@ -188,6 +188,8 @@ UiContainer.NameMenu = {
         if string.lower(name) == "ex-soldier" then return "Cloud" end
         -- The initial data of the game only holds "Red" for him.
         if id == 4 and string.lower(name) == "red" then return "Red XIII" end
+        -- The data of ff7.exe that he joins with spells his name wrong.
+        if id == 6 and string.lower(name) == "cait seith" then return "Cait Sith" end
         return name
     end,
 
@@ -302,6 +304,8 @@ UiContainer.NameMenu = {
         if self.chocobo == false then
             Characters[self.id].name = self.name
             export_character_names()
+            -- The level of the character is set once it has a name.
+            Characters.join(self.id)
         else
             -- TODO: Do chocobo.
         end

+ 287 - 124
data/data/scripts/system.lua

@@ -280,6 +280,15 @@ set_character_enable = function(character, enable)
         return
     end
     Characters[character].enabled = enable;
+    -- As in ff7.exe (0x61c782), a character that is hidden also leaves the party, locked or not.
+    if not enable then
+        for i = 1, 3 do
+            if Party[i] == character then
+                Party[i] = nil
+                export_party_members()
+            end
+        end
+    end
 end
 
 --- Checks if a character is enabled in the PHS.
@@ -512,124 +521,296 @@ Inventory.sort = function(criteria)
     end
 end
 
+-- Leveling up, as in ff7.exe (1998 build, functions 0x5c76d9 to 0x5c7bb1).
+
+Characters.MAX_LEVEL = 99
+Characters.MAX_EXP = 999999999
+--- Caps of the base stats that level ups give. Sources go to the stat bonus, not to the base.
+Characters.MAX_BASE_STAT = 100
+Characters.MAX_BASE_HP = 9999
+Characters.MAX_BASE_MP = 999
+
+--- Divides truncating toward zero, like the integer divisions of the original.
+local function divide(a, b)
+    local quotient = a / b
+    if quotient < 0 then return math.ceil(quotient) end
+    return math.floor(quotient)
+end
+
+--- Gets the segment of the growth curves used for a level: one every 10 levels up to 60, then one
+-- every 20.
+local function curve_segment(level)
+    if level <= 60 then return math.max(0, math.floor((level - 1) / 10)) end
+    return math.min(7, math.floor((level - 61) / 20) + 6)
+end
+
+--- Picks one of the 12 bonuses: a random number from 1 to 8 plus how far the character is behind.
+local function bonus_index(difference)
+    return math.max(0, math.min(11, math.random(1, 8) + difference))
+end
+
+--- Gets the total experience a character needs to go from a level to the next one.
+--
+-- It's the sum of gradient * n^2 / 10 for n from 1 to the level, all of them with the gradient of
+-- the segment of that level.
+--
+-- @param id Character ID.
+-- @param level The level.
+-- @return The total experience, 0 for level 0.
+Characters.exp_threshold = function(id, level)
+    local gradient = Game.Growth.curves[Game.Characters[id].curves.exp][curve_segment(level)].gradient
+    local total = 0
+    for n = 1, level do total = total + math.floor(gradient * n * n / 10) end
+    return total
+end
+
+--- Raises the base stats of a character for one level.
+--
+-- Each stat has a curve that gives the value expected at the new level; the further the character
+-- is below it, the better the bonus is likely to be.
+local function level_up(id)
+    local character = Characters[id]
+    local stats = character.stats
+    local level = character.level
+    local segment = curve_segment(level)
+    local curves = Game.Characters[id].curves
+    local function curve(name) return Game.Growth.curves[curves[name]][segment] end
+
+    for _, name in ipairs({"str", "vit", "mag", "spr", "dex", "lck"}) do
+        local stat = stats[name]
+        local value = math.max(1, stat.base)
+        local data = curve(name)
+        local expected = math.floor(data.gradient * (level + 1) / 100) + data.base
+        local gain = Game.Growth.bonus.primary[bonus_index(expected - value)]
+        stat.base = math.min(Characters.MAX_BASE_STAT, value + gain)
+    end
+
+    local hp = curve("hp")
+    local function expected_hp(n) return hp.gradient * n + hp.base * 40 end
+    local value = math.max(1, stats.hp.base)
+    local index = bonus_index(divide(expected_hp(level) * 100, value) - 100)
+    local gain = divide((expected_hp(level + 1) - expected_hp(level)) * Game.Growth.bonus.hp[index], 100)
+    stats.hp.base = math.min(Characters.MAX_BASE_HP, value + gain)
+
+    local mp = curve("mp")
+    local function expected_mp(n) return math.floor(mp.gradient * n / 10) + mp.base * 2 end
+    value = math.max(1, stats.mp.base)
+    index = bonus_index(divide(expected_mp(level) * 100, value) - 100)
+    gain = divide((expected_mp(level + 1) - expected_mp(level)) * Game.Growth.bonus.mp[index], 100)
+    stats.mp.base = math.min(Characters.MAX_BASE_MP, value + gain)
+
+    character.level = level + 1
+end
+
+--- Gives experience to a character, and levels it up as many times as it reaches.
+--
+-- The current HP and MP don't change, only the base values and the maximums.
+--
+-- @param id Character ID.
+-- @param exp Experience gained.
+-- @return The number of levels gained.
+Characters.add_exp = function(id, exp)
+    local character = Characters[id]
+    local definition = Game.Characters[id]
+    if character == nil or definition == nil or definition.curves == nil then return 0 end
+    character.exp = math.min(Characters.MAX_EXP, (character.exp or 0) + exp)
+    local first_level = character.level
+    while character.level < Characters.MAX_LEVEL
+      and character.exp >= Characters.exp_threshold(id, character.level) do
+        level_up(id)
+    end
+    if character.level < Characters.MAX_LEVEL then
+        character.exp_to_next = Characters.exp_threshold(id, character.level) - character.exp
+    else
+        character.exp_to_next = 0
+    end
+    if character.level > first_level then Characters.recalculate_stats(id) end
+    return character.level - first_level
+end
+
+--- Variable of the field scripts with the level of the characters whose level doesn't depend on
+-- the one of the party (Yuffie): bank 1, address 2.
+Characters.JOIN_LEVEL_BANK = 1
+Characters.JOIN_LEVEL_ADDRESS = 2
+
+--- Gets the average level of the available characters (in the party or enabled in the PHS), without
+-- counting one of them.
+--
+-- @param excluded ID of the character that isn't counted.
+-- @return The average, or the level of the excluded character if there is nobody else.
+Characters.average_level = function(excluded)
+    local sum, count = 0, 0
+    for id = 0, 8 do
+        if id ~= excluded and Characters[id] ~= nil and (IFMEMBQ(id) or IFPRTYQ(id)) then
+            sum = sum + Characters[id].level
+            count = count + 1
+        end
+    end
+    if count == 0 then return Characters[excluded].level end
+    return math.floor(sum / count)
+end
+
+--- Copies a table and the tables in it.
+local function copy_table(source)
+    if type(source) ~= "table" then return source end
+    local result = {}
+    for key, value in pairs(source) do result[key] = copy_table(value) end
+    return result
+end
+
+--- Gives a character the data it joins with. The slots of Cait Sith and Vincent hold young Cloud and
+-- Sephiroth at the start: ff7.exe replaces the whole slot with data of its own when the window to
+-- name them opens (0x70ec9a). Nothing happens for the other characters.
+--
+-- The availability and the lock in the party are not part of that data, and are kept.
+--
+-- @param id Character ID.
+Characters.load_recruit_record = function(id)
+    local record = Game.RecruitRecords ~= nil and Game.RecruitRecords[id] or nil
+    if record == nil or Characters[id] == nil then return end
+    local character = copy_table(record)
+    character.enabled = Characters[id].enabled
+    character.locked = Characters[id].locked
+    Characters[id] = character
+    Characters.recalculate_stats(id)
+end
+
+--- Sets the level of a character that joins, as in ff7.exe (0x5c72a6). The original does it when the
+-- window to name the character is closed (for everybody but Cloud).
+--
+-- The level is the average of the other available characters plus half of the level offset of the
+-- character. With an odd offset (Yuffie) it comes from a variable of the field scripts instead, and
+-- the character is built again from level 1. The experience of the previous level is added to the
+-- one the character has, and it levels up as usual, so it never goes down. HP and MP end up filled.
+--
+-- @param id Character ID.
+Characters.join = function(id)
+    local character = Characters[id]
+    local definition = Game.Characters[id]
+    if id == 0 or character == nil or definition == nil or definition.curves == nil then return end
+    -- The offset is a signed byte.
+    local offset = tonumber(definition.initial_level) or 0
+    if offset > 127 then offset = offset - 256 end
+    local stats = character.stats
+    local level
+    if offset % 2 == 0 then
+        level = Characters.average_level(id) + divide(offset, 2)
+    else
+        level = Banks[Characters.JOIN_LEVEL_BANK][Characters.JOIN_LEVEL_ADDRESS] or 0
+        -- It is unknown what writes the variable in a normal game: without it, the character would
+        -- be left at level 1, so the average of the party is used.
+        if level == 0 then level = Characters.average_level(id) end
+        character.level = 1
+        character.exp = 0
+        for _, name in ipairs({"str", "vit", "mag", "spr", "dex", "lck", "hp", "mp"}) do
+            stats[name].base = 1
+        end
+    end
+    level = math.max(1, math.min(Characters.MAX_LEVEL, level))
+    Characters.add_exp(id, Characters.exp_threshold(id, level - 1))
+    stats.hp.current = stats.hp.base
+    stats.mp.current = stats.mp.base
+    Characters.recalculate_stats(id)
+    print(character.name .. " joins at level " .. tostring(character.level))
+end
+
+--- Names of the primary stats.
+Characters.PRIMARY_STATS = {"str", "vit", "mag", "spr", "dex", "lck"}
+
+--- Cap of the primary stats and of the bonus that the sources give, as in ff7.exe.
+Characters.MAX_STAT = 255
+
+--- Primary stat or maximum raised by each of the Plus materia, by the ID of its ability.
+Characters.PLUS_MATERIA = {
+    [0] = "str", [1] = "vit", [2] = "mag", [3] = "spr", [4] = "dex", [5] = "lck", [8] = "hp", [9] = "mp",
+}
+
+--- Item ID of the Curse Ring, and what it adds to the stats on top of the bonuses of its data.
+Characters.CURSE_RING = 313
+Characters.CURSE_RING_BONUS = {str = 15, vit = 15, mag = 15, spr = 15, dex = 15, lck = 10}
+
+--- Uses a source on a character: one more point of bonus for a primary stat.
+--
+-- @param id Character ID.
+-- @param name Name of the stat, one of {@see Characters.PRIMARY_STATS}.
+-- @return False if the bonus is already at its cap, and nothing happens.
+Characters.add_stat_bonus = function(id, name)
+    local stat = Characters[id].stats[name]
+    if (stat.bonus or 0) >= Characters.MAX_STAT then return false end
+    stat.bonus = (stat.bonus or 0) + 1
+    Characters.recalculate_stats(id)
+    return true
+end
+
 Characters.recalculate_stats = function(id)
     -- Initialize
     local stats = Characters[id].stats
-    stats.str.total = stats.str.base
-    stats.vit.total = stats.vit.base
-    stats.mag.total = stats.mag.base
-    stats.spr.total = stats.spr.base
-    stats.dex.total = stats.dex.base
-    stats.lck.total = stats.lck.base
+    -- The primary stats start with the base value, that grows with the levels, plus the bonus that the
+    -- sources give.
+    for _, name in ipairs(Characters.PRIMARY_STATS) do
+        stats[name].total = stats[name].base + (stats[name].bonus or 0)
+    end
     stats.hp.max = stats.hp.base
     stats.mp.max = stats.mp.base
-    -- Weapon bonus. HP and MP are percents of base, the rest absolutes. The stats are keyed by name,
-    -- so they are walked with pairs (ipairs only walks the array part and found nothing).
     local weapon = Game.Items[Characters[id].weapon.id]
-    for stat, value in pairs(weapon.stats or {}) do
-        if stat == "str" then
-            stats.str.total = stats.str.total + value
-        elseif stat == "vit" then
-            stats.vit.total = stats.vit.total + value
-        elseif stat == "mag" then
-            stats.mag.total = stats.mag.total + value
-        elseif stat == "spr" then
-            stats.spr.total = stats.spr.total + value
-        elseif stat == "dex" then
-            stats.dex.total = stats.dex.total + value
-        elseif stat == "lck" then
-            stats.lck.total = stats.lck.total + value
-        elseif stat == "hp" then
-            stats.hp.max = stats.hp.max + (value * stats.hp.max / 100)
-        elseif stat == "mp" then
-            stats.mp.max = stats.mp.max + (value * stats.mp.max / 100)
-        end
-    end
-    -- Armor bonus. HP and MP are percents of bsae, the rest absolutes.
     local armor = Game.Items[Characters[id].armor.id]
-    for stat, value in pairs(armor.stats or {}) do
-        if stat == "str" then
-            stats.str.total = stats.str.total + value
-        elseif stat == "vit" then
-            stats.vit.total = stats.vit.total + value
-        elseif stat == "mag" then
-            stats.mag.total = stats.mag.total + value
-        elseif stat == "spr" then
-            stats.spr.total = stats.spr.total + value
-        elseif stat == "dex" then
-            stats.dex.total = stats.dex.total + value
-        elseif stat == "lck" then
-            stats.lck.total = stats.lck.total + value
-        elseif stat == "hp" then
-            stats.hp.max = stats.hp.max + (value * stats.hp.max / 100)
-        elseif stat == "mp" then
-            stats.mp.max = stats.mp.max + (value * stats.mp.max / 100)
-        end
-    end
-    -- Accesory bonus
-    local accessory = Game.Items[Characters[id].accessory]
-    if (accessory ~= nil) then
-        for stat, value in pairs(accessory.stats or {}) do
-            if stat == "str" then
-                stats.str.total = stats.str.total + value
-            elseif stat == "vit" then
-                stats.vit.total = stats.vit.total + value
-            elseif stat == "mag" then
-                stats.mag.total = stats.mag.total + value
-            elseif stat == "spr" then
-                stats.spr.total = stats.spr.total + value
-            elseif stat == "dex" then
-                stats.dex.total = stats.dex.total + value
-            elseif stat == "lck" then
-                stats.lck.total = stats.lck.total + value
-            elseif stat == "hp" then
-                stats.hp.max = stats.hp.max + (value * stats.hp.max / 100)
-            elseif stat == "mp" then
-                stats.mp.max = stats.mp.max + (value * stats.mp.max / 100)
+    -- Bonuses of the equipment: points added to the primary stats. They are keyed by name, so they are
+    -- walked with pairs (ipairs only walks the array part and found nothing).
+    for _, item in pairs({weapon, armor, Game.Items[Characters[id].accessory]}) do
+        for name, value in pairs(item.stats or {}) do
+            if stats[name] ~= nil and stats[name].total ~= nil then
+                stats[name].total = stats[name].total + value
             end
         end
     end
+    -- The Curse Ring has more bonuses than its data can hold, ff7.exe adds them (0x6bbb04).
+    if Characters[id].accessory == Characters.CURSE_RING then
+        for name, value in pairs(Characters.CURSE_RING_BONUS) do stats[name].total = stats[name].total + value end
+    end
     -- Get a list of materias
-    local materias = {}
-    for m = 0, 7 do
-        if Characters[id].weapon.materia[m] ~= nil then
-            table.insert(materias, Game.Materia[Characters[id].weapon.materia[m].id])
-        end
-        if Characters[id].armor.materia[m] ~= nil then
-            table.insert(materias, Game.Materia[Characters[id].armor.materia[m].id])
+    local materias, equipped_materias = {}, {}
+    for _, part in ipairs({Characters[id].weapon, Characters[id].armor}) do
+        for m = 0, 7 do
+            local equipped = part.materia[m]
+            if equipped ~= nil and Game.Materia[equipped.id] ~= nil then
+                table.insert(materias, Game.Materia[equipped.id])
+                table.insert(equipped_materias, equipped)
+            end
         end
     end
-    -- Get materia bonuses. All are percents of base.
-    for _, materia in ipairs(materias) do
-        for stat, value in pairs(materia.stats or {}) do
-            if stat == "str" then
-                stats.str.total = stats.str.total + (value * stats.str.base / 100)
-            elseif stat == "vit" then
-                stats.vit.total = stats.vit.total + (value * stats.vit.base / 100)
-            elseif stat == "mag" then
-                stats.mag.total = stats.mag.total + (value * stats.mag.base / 100)
-            elseif stat == "spr" then
-                stats.spr.total = stats.spr.total + (value * stats.spr.base / 100)
-            elseif stat == "dex" then
-                stats.dex.total = stats.dex.total + (value * stats.dex.base / 100)
-            elseif stat == "lck" then
-                stats.lck.total = stats.lck.total + (value * stats.lck.base / 100)
-            elseif stat == "hp" then
-                stats.hp.max = stats.hp.max + (value * stats.hp.max / 100)
-            elseif stat == "mp" then
-                stats.mp.max = stats.mp.max + (value * stats.mp.max / 100)
+    -- Materia changes, as in ff7.exe (0x5cd1e8 and 0x5ce487): points for the primary stats and percents
+    -- for HP and MP, that every equipped materia adds up, and the percents of the Plus materia (HP,
+    -- MP, Speed, Magic and Luck Plus).
+    local points, percents = {}, {}
+    local function add(list, name, value) list[name] = (list[name] or 0) + value end
+    for index, materia in ipairs(materias) do
+        for name, value in pairs(materia.stats or {}) do
+            if name == "hp" or name == "mp" then add(percents, name, value)
+            else add(points, name, value)
             end
         end
+        local name = materia.type == Materia.TYPE.INDEPENDENT and materia.ability ~= nil
+          and Characters.PLUS_MATERIA[materia.ability.id] or nil
+        if name ~= nil then
+            local level = math.max(1, Characters.get_materia_level(materia, equipped_materias[index].ap or 0))
+            local param = materia.ability.param
+            add(percents, name, param[level] or param[#param])
+        end
+    end
+    local function percent_of(value, name)
+        local result = value * math.min(100, percents[name] or 0) / 100
+        -- Truncated toward zero, like the integer division of the original.
+        if result < 0 then return math.ceil(result) end
+        return math.floor(result)
     end
-    -- Round down all basic stats
-    stats.str.total = math.floor(stats.str.total)
-    stats.vit.total = math.floor(stats.vit.total)
-    stats.mag.total = math.floor(stats.mag.total)
-    stats.spr.total = math.floor(stats.spr.total)
-    stats.dex.total = math.floor(stats.dex.total)
-    stats.lck.total = math.floor(stats.lck.total)
-    stats.hp.max = math.floor(stats.hp.max)
-    stats.mp.max = math.floor(stats.mp.max)
+    -- The percent of a Plus materia applies to the stat with the equipment, without the materia points.
+    for _, name in ipairs(Characters.PRIMARY_STATS) do
+        local value = math.min(Characters.MAX_STAT, stats[name].total)
+        value = value + percent_of(value, name) + (points[name] or 0)
+        stats[name].total = math.max(0, math.min(Characters.MAX_STAT, math.floor(value)))
+    end
+    stats.hp.max = math.min(Characters.MAX_BASE_HP, stats.hp.max + percent_of(stats.hp.max, "hp"))
+    stats.mp.max = math.min(Characters.MAX_BASE_MP, stats.mp.max + percent_of(stats.mp.max, "mp"))
 
     -- 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
@@ -643,24 +824,6 @@ Characters.recalculate_stats = function(id)
     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
-    if stats.vit.total < 1 then
-        stats.vit.total = 1
-    end
-    if stats.mag.total < 1 then
-        stats.mag.total = 1
-    end
-    if stats.spr.total < 1 then
-        stats.spr.total = 1
-    end
-    if stats.dex.total < 1 then
-        stats.dex.total = 1
-    end
-    if stats.lck.total < 1 then
-        stats.lck.total = 1
-    end
     if stats.hp.max < 1 then
         stats.hp.max = 1
     end
@@ -687,8 +850,8 @@ Characters.recalculate_stats = function(id)
     if stats.def < 1 then
         stats.def = 1
     end
-    if stats.eva < 1 then
-        stats.eva = 1
+    if stats.eva < 0 then
+        stats.eva = 0
     end
     if stats.matk < 1 then
         stats.matk = 1
@@ -696,8 +859,8 @@ Characters.recalculate_stats = function(id)
     if stats.mdef < 1 then
         stats.mdef = 1
     end
-    if stats.meva < 1 then
-        stats.meva = 1
+    if stats.meva < 0 then
+        stats.meva = 0
     end
 
     -- Cap current HP/MP

+ 10 - 0
doc/TODO.md

@@ -24,6 +24,16 @@ First step: play the scene with log level 3 and look at the time between the `di
 layer of mds5_4 has no such opcodes and still scrolls with the rest, and it is not known why it should
 not.
 
+## Battle: recruits that remain untested
+
+Yuffie, Vincent and Cait Sith remain untested: the level they join with (`Characters.join` in `system.lua`)
+and, for Vincent and Cait Sith, the data they get when they are named (`Characters.load_recruit_record`). The
+other characters are working fine.
+
+- Yuffie's level comes from the variable at bank 1, address 2. Only the field blackbg4 writes it, so it is not
+  known what sets it in a normal game. While it is 0 the average level of the party is used, which is not from
+  the original.
+
 ## Battle: special limits
 
 Not done yet (kernel data in ff7.exe, ids 170-176, see `get_special_limit` in `battle_ui.lua`):

+ 13 - 4
src/core/BattleManager.cpp

@@ -50,13 +50,11 @@ template<>BattleManager *Ogre::Singleton<BattleManager>::msSingleton = nullptr;
 ConfigVar cv_debug_battle_grid("debug_battle_grid", "Draw debug battle grid", "false");
 ConfigVar cv_debug_battle_axis("debug_battle_axis", "Draw debug battle axis", "false");
 
-const float BattleManager::ENEMY_SCALE = 0.0032f;
+const float BattleManager::ENEMY_SCALE = 1.0f / 255.0f;
 
 const float BattleManager::ATTACK_SCALE = 0.0032f;
 
-const float BattleManager::PARTY_SCALE = 0.0039f;
-
-const float BattleManager::SCENE_SCALE = 0.0012f;
+const float BattleManager::PARTY_SCALE = 1.0f / 255.0f;
 
 const float BattleManager::PARTY_Y = 5.0f;
 
@@ -106,6 +104,7 @@ void BattleManager::ClearBattle(){
     // TODO location_ = null;
     camera_.clear();
     initial_camera_ = 0;
+    intro_camera_ = -1;
     layout_ = LAYOUT::NORMAL;
     escape_difficulty_ = 0.0f;
     arena_battle_ = false;
@@ -636,6 +635,16 @@ void BattleManager::SetInitialCamera(const unsigned int id){
     initial_camera_ = id;
 }
 
+void BattleManager::SetIntroCamera(const int id){
+    if (module_ != Module::BATTLE){
+        LOG_ERROR("Tried to set the camera in the BattleManager, but it's not in battle mode.");
+        return;
+    }
+    intro_camera_ = id;
+}
+
+int BattleManager::ScriptGetIntroCamera() const{return intro_camera_;}
+
 void BattleManager::LoadParty(){
     if (module_ != Module::BATTLE){
         LOG_ERROR("Tried to load party in the BattleManager, but it's not in battle mode.");

+ 21 - 9
src/core/BattleManager.h

@@ -290,7 +290,6 @@ class BattleManager : public Manager, public Ogre::Singleton<BattleManager>{
           const int orientation, const char* animation
         );
 
-
         /**
          * Adds a mesh of a visual effect to the battle scene.
          *
@@ -349,7 +348,6 @@ class BattleManager : public Manager, public Ogre::Singleton<BattleManager>{
          */
         void ScriptRemoveDynamicMesh(const char* name);
 
-
         /**
          * Sets the battle layout.
          *
@@ -576,6 +574,20 @@ class BattleManager : public Manager, public Ogre::Singleton<BattleManager>{
          */
         void SetInitialCamera(const unsigned int id);
 
+        /**
+         * Sets the camera script of the start of the battle.
+         *
+         * @param[in] id ID of the script, -1 for none.
+         */
+        void SetIntroCamera(const int id);
+
+        /**
+         * Gets the camera script of the start of the battle.
+         *
+         * @return ID of the script, -1 if there is none.
+         */
+        int ScriptGetIntroCamera() const;
+
         /**
          * Changes the battle camera to one of the cameras of the formation.
          *
@@ -651,7 +663,6 @@ class BattleManager : public Manager, public Ogre::Singleton<BattleManager>{
          */
         void ClearDynamicMeshes();
 
-
         /**
          * Loads the party members into the battle.
          */
@@ -718,7 +729,8 @@ class BattleManager : public Manager, public Ogre::Singleton<BattleManager>{
         static const float SIDE_DISTANCE;
 
         /**
-         * Scale factor for battle enemy models.
+         * Scale factor for battle enemy models: the one of the positions of the battle (the original units are
+         * 255 times smaller than the ones of the scene).
          */
         static const float ENEMY_SCALE;
 
@@ -727,11 +739,6 @@ class BattleManager : public Manager, public Ogre::Singleton<BattleManager>{
          */
         static const float PARTY_SCALE;
 
-        /**
-         * Scale factor for battle background models.
-         */
-        static const float SCENE_SCALE;
-
         /**
          * Scale factor for battle attack and spell models.
          */
@@ -763,6 +770,11 @@ class BattleManager : public Manager, public Ogre::Singleton<BattleManager>{
          */
         unsigned int initial_camera_;
 
+        /**
+         * Camera script of the start of the battle.
+         */
+        int intro_camera_;
+
         /**
          * Battle layout.
          */

+ 5 - 18
src/core/CameraManager.cpp

@@ -174,12 +174,6 @@ void CameraManager::Set2DCamera(
 void CameraManager::StartBattleCamera(
   const Ogre::Vector3 position, const Ogre::Vector3 orientation
 ){
-    /*
-     * TODO: Something is wrong here. The camera look 'mostly' okay, but it's still weird.
-     * Also, there are variations and it doesn't look the same on successive calls.
-     * I thinks it's something related to the lookAt functions.
-     * Try to fix it. First, replace the deprecated calls, and see what happens.
-     */
     if (module_ != Module::BATTLE){
         LOG_ERROR("Tried to start battle camera but the CameraManager is already in battle mode");
         return;
@@ -218,15 +212,8 @@ void CameraManager::StartBattleCamera(
 }
 
 void CameraManager::SetBattleCamera(const Ogre::Vector3 position, const Ogre::Vector3 orientation){
-    camera_->resetFrustumExtents();
-    camera_->setFOVy(Ogre::Radian(Ogre::Math::PI / 4.0f));
-    camera_->setOrientation(Ogre::Quaternion::IDENTITY);
-    camera_->setPosition(position);
-    //CameraManager::getSingleton().GetCurrentCamera()->setFixedYawAxis(true, Ogre::Vector3::UNIT_Y);
-    camera_->lookAt(orientation);
-    camera_->roll(Ogre::Angle(90));
-    // Fix: compensate for the battle UI covered section of the screen.
-    camera_->move(Ogre::Vector3(0, 0, -4));
+    // The second vector is the point the camera looks at.
+    SetBattleCameraUpright(position, orientation);
 }
 
 void CameraManager::SetBattleCameraUpright(
@@ -245,9 +232,9 @@ void CameraManager::SetBattleCameraUpright(
     camera_->setFOVy(Ogre::Radian(Ogre::Math::PI / 4.0f));
     camera_->setPosition(position);
     camera_->setOrientation(Ogre::Quaternion(right, up, -direction));
-    // Compensation of the battle UI, like the other battle cameras. They move the camera 4 units
-    // down at about 60 units from the scene, so it's proportional to the distance here, because
-    // the cameras of the effects go from very far to very close.
+    // Compensation of the section of the screen that the battle UI covers: the camera moves down. It's
+    // proportional to the distance (4 units at about 60 from the scene), because the cameras of the
+    // effects go from very far to very close.
     const float distance = (look_at - position).length();
     camera_->move(Ogre::Vector3(0, 0, -0.066f * distance));
 }

+ 3 - 3
src/core/CameraManager.h

@@ -174,7 +174,7 @@ class CameraManager : public Manager, public Ogre::Singleton<CameraManager>{
         const Ogre::Vector3 ProjectPointToScreen(const Ogre::Vector3& point);
 
         /**
-         * Sets the battle camera.
+         * Sets the battle camera, like {@see SetBattleCameraUpright}.
          *
          * Unlike {@see StartBattleCamera}, it doesn't save the state of the field camera, so it
          * can be used to change the camera during a battle.
@@ -187,8 +187,8 @@ class CameraManager : public Manager, public Ogre::Singleton<CameraManager>{
         /**
          * Sets the battle camera, always with the Z axis of the scene pointing up.
          *
-         * {@see SetBattleCamera} is only upright for cameras looking toward negative X, so this
-         * one is for the cameras of the effects, that can look anywhere.
+         * It also moves the camera down to compensate for the part of the screen that the battle
+         * interface covers.
          *
          * @param[in] position Camera position.
          * @param[in] look_at Point the camera looks at.

+ 11 - 0
src/core/Entity.h

@@ -387,6 +387,17 @@ class Entity{
             return std::make_tuple(0.0f, 0.0f, 0.0f);
         }
 
+        /**
+         * Gets the position in the scene of the end of a bone of the skeleton of the entity.
+         *
+         * @param[in] bone Number of the bone.
+         * @param[in] length Length of the bone, in the units of the model.
+         * @return The position, all zeros if there is no such bone.
+         */
+        virtual std::tuple<float, float, float> ScriptGetBoneEnd(const int bone, const float length){
+            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.

+ 6 - 2
src/core/EntityManager.cpp

@@ -69,7 +69,7 @@ static const float ENCOUNTER_CHECK_FRAMES = 8.0f;
  */
 static const float ENCOUNTER_STEP_VALUE = 5.0f;
 
-const float EntityManager::SCENE_SCALE = 0.003f;
+const float EntityManager::SCENE_SCALE = 1.0f / 255.0f;
 
 const unsigned int EntityManager::BATTLE_BACKGROUND_ID = 1000;
 
@@ -527,7 +527,8 @@ void EntityManager::RemoveBattleEntity(const Ogre::String& name){
         ScriptManager::getSingleton().RemoveEntity(ScriptManager::BATTLE, name);
         battle_entity_.erase(it);
         // The entity is not deleted, as its destructor would destroy the model again, like in
-        // ClearBattle.
+        // ClearBattle. So what the model holds (a weapon) has to be destroyed here.
+        entity->ScriptAttachModel("", -1, 0.0f, 0.0f, 0.0f);
         Ogre::Root::getSingleton().getSceneManager("Scene")->destroyEntity(name);
         scene_node_->removeAndDestroyChild("Battle_" + name);
         entity->ReleaseResources();
@@ -636,6 +637,9 @@ void EntityManager::ClearBattle(){
         ScriptManager::getSingleton().RemoveEntity(
           ScriptManager::ENTITY, battle_entity_[i]->GetName()
         );
+        // The model held in a bone (a weapon) is another Ogre entity, and the next battle creates
+        // one with the same name.
+        battle_entity_[i]->ScriptAttachModel("", -1, 0.0f, 0.0f, 0.0f);
         Ogre::Root::getSingleton().getSceneManager("Scene")->destroyEntity(
           battle_entity_[i]->GetName()
         );

+ 14 - 0
src/core/EntityModel.cpp

@@ -145,6 +145,20 @@ std::tuple<float, float, float> EntityModel::ScriptGetBonePosition(const int bon
     return std::make_tuple(position.x, position.y, position.z);
 }
 
+std::tuple<float, float, float> EntityModel::ScriptGetBoneEnd(const int bone, const float length){
+    Ogre::SkeletonInstance* skeleton = model_->getSkeleton();
+    const Ogre::String name = "bone" + std::to_string(bone);
+    if (skeleton == nullptr || !skeleton->hasBone(name)) return std::make_tuple(0.0f, 0.0f, 0.0f);
+    // Bring the skeleton to the current frame of the animation.
+    model_->_updateAnimation();
+    Ogre::Bone* node = skeleton->getBone(name);
+    // The bones go along their Y axis, where their children are placed.
+    const Ogre::Vector3 end = node->_getDerivedPosition()
+      + node->_getDerivedOrientation() * (node->_getDerivedScale() * Ogre::Vector3(0, length, 0));
+    const Ogre::Vector3 position = model_->_getParentNodeFullTransform() * end;
+    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
 ){

+ 2 - 0
src/core/EntityModel.h

@@ -75,6 +75,8 @@ class EntityModel : public Entity{
 
         virtual std::tuple<float, float, float> ScriptGetBonePosition(const int bone);
 
+        virtual std::tuple<float, float, float> ScriptGetBoneEnd(const int bone, const float length);
+
         virtual bool ScriptAttachModel(
           const char* model, const int bone, const float rx, const float ry, const float rz
         );

+ 2 - 0
src/core/ScriptManagerBinds.h

@@ -139,6 +139,7 @@ void ScriptManager::InitBinds(){
       "set_alpha", &Entity::ScriptSetAlpha,
       "set_texture", &Entity::ScriptSetTexture,
       "get_bone_position", &Entity::ScriptGetBonePosition,
+      "get_bone_end", &Entity::ScriptGetBoneEnd,
       "attach_model", sol::overload(
         [](Entity& entity, const char* model, const int bone){
             return entity.ScriptAttachModel(model, bone, 0.0f, 0.0f, 0.0f);
@@ -253,6 +254,7 @@ void ScriptManager::InitBinds(){
       "set_dynamic_mesh", &BattleManager::ScriptSetDynamicMesh,
       "remove_dynamic_mesh", &BattleManager::ScriptRemoveDynamicMesh,
       "get_layout", &BattleManager::ScriptGetLayout,
+      "get_intro_camera", &BattleManager::ScriptGetIntroCamera,
       "get_attack", [](BattleManager& manager, const int id, sol::this_state state) -> sol::object{
           sol::state_view view(state);
           const AttackData* attack = manager.GetAttackData(id);

+ 9 - 0
src/core/XmlEnemyFile.cpp

@@ -50,6 +50,15 @@ void XmlEnemyFile::LoadEnemy(Enemy& enemy){
                 else if (GetString(node_stat, "id") == "spd") enemy.SetDex(value);
                 else if (GetString(node_stat, "id") == "lck") enemy.SetLck(value);
                 else if (GetString(node_stat, "id") == "eva") enemy.SetEva(value);
+                // The maximum goes first, the current value is capped to it.
+                else if (GetString(node_stat, "id") == "hp"){
+                    enemy.SetHpMax(value);
+                    enemy.SetHp(value);
+                }
+                else if (GetString(node_stat, "id") == "mp"){
+                    enemy.SetMpMax(value);
+                    enemy.SetMp(value);
+                }
                 node_stat = node_stat->NextSibling();
             }
         }

+ 4 - 3
src/core/XmlFormationFile.cpp

@@ -55,15 +55,16 @@ void XmlFormationFile::LoadFormation(){
         }
         else if (node->Type() == TiXmlNode::TINYXML_ELEMENT && node->ValueStr() == "camera"){
             BattleManager::getSingleton().SetInitialCamera(GetInt(node, "initial"));
+            BattleManager::getSingleton().SetIntroCamera(GetInt(node, "intro", -1));
             TiXmlNode* camera_node = node->FirstChild();
             while (camera_node != nullptr){
                 int id = GetInt(camera_node, "id");
                 Ogre::Vector3 pos = Ogre::Vector3(
-                  GetInt(camera_node, "x"), GetInt(camera_node, "y"), GetInt(camera_node, "z")
+                  GetFloat(camera_node, "x"), GetFloat(camera_node, "y"), GetFloat(camera_node, "z")
                 );
                 Ogre::Vector3 dir = Ogre::Vector3(
-                  GetInt(camera_node, "direction_x"), GetInt(camera_node, "direction_y"),
-                  GetInt(camera_node, "direction_z")
+                  GetFloat(camera_node, "direction_x"), GetFloat(camera_node, "direction_y"),
+                  GetFloat(camera_node, "direction_z")
                 );
                 BattleManager::getSingleton().AddCamera(id, pos, dir);
                 camera_node = camera_node->NextSibling();

+ 90 - 1
src/installer/BattleCameraScripts.h

@@ -26,6 +26,7 @@
 #include <ostream>
 #include <string>
 #include <vector>
+#include "ExeEffectCameras.h"
 
 /**
  * Reads the camera scripts of the battles (camdat0.bin, camdat1.bin and camdat2.bin of data/battle).
@@ -40,6 +41,9 @@
  * operands (bytes and 16 bit values). The lengths of the operands for each opcode of the two kinds
  * of scripts were found in the interpreter of ff7.exe (0x5c2341 for the position, 0x5c3f45 for the
  * point it looks at). A script ends with 0xff, or with 0xfe followed by 0xc0 (loop).
+ *
+ * The third pointer is the list of the scripts of the camera of the victory (the camera id -3 in the
+ * game): three for the position, one for each variant, and then three for the point it looks at.
  */
 namespace BattleCameraScripts{
 
@@ -50,6 +54,8 @@ namespace BattleCameraScripts{
     struct Set{
         std::vector<uint32_t> position;
         std::vector<uint32_t> look;
+        std::vector<uint32_t> victory_position;
+        std::vector<uint32_t> victory_look;
         std::map<uint32_t, std::vector<uint8_t>> scripts;
     };
 
@@ -183,9 +189,86 @@ namespace BattleCameraScripts{
                 list.back() = key;
             }
         }
+        const uint32_t victory = ReadU32(d, 8) - base;
+        if (victory >= d.size()) return false;
+        for (int i = 0; i < 6; ++ i){
+            const bool position = i < 3;
+            const uint32_t offset = ReadU32(d, victory + 4 * i) - base;
+            std::vector<uint8_t> script;
+            if (offset >= d.size() || !ReadScript(d, offset, position, script)) return false;
+            const uint32_t key = offset * 2 + (position ? 0 : 1);
+            set.scripts[key] = script;
+            (position ? set.victory_position : set.victory_look).push_back(key);
+        }
         return true;
     }
 
+    /**
+     * Reads the scripts of the cameras of the start of the battles (the camera id -2 in the game) from
+     * ff7.exe. There are two lists of pointers, one for the position and one for the point it looks
+     * at, indexed by the camera byte of the formation (read at 0x5c2406 and 0x5c400a in the 1998
+     * build). An entry that isn't a script has the key 0.
+     *
+     * @return False if the file couldn't be read or the scripts aren't there.
+     */
+    inline bool ReadIntro(const std::string& path, Set& set){
+        set = Set();
+        ExeEffectCameras::Image image;
+        if (!ExeEffectCameras::LoadImage(path, image)) return false;
+        const uint32_t tables[2] = {0x8f70d0, 0x8f7270};
+        const size_t count = (tables[1] - tables[0]) / 4;
+        size_t valid = 0;
+        for (int kind = 0; kind < 2; ++ kind){
+            const bool position = kind == 0;
+            std::vector<uint32_t>& list = position ? set.position : set.look;
+            const int64_t table = ExeEffectCameras::FileOffset(image.sections, tables[kind]);
+            if (table < 0) return false;
+            for (size_t i = 0; i < count; ++ i){
+                list.push_back(0);
+                const uint32_t address = ReadU32(image.data, table + 4 * i);
+                const int64_t offset = ExeEffectCameras::FileOffset(image.sections, address);
+                std::vector<uint8_t> script;
+                // They start with an opcode, and none is long.
+                if (offset < 0 || image.data[offset] < 0xd5
+                  || !ReadScript(image.data, static_cast<uint32_t>(offset), position, script)
+                  || script.size() > 512) continue;
+                const uint32_t key = static_cast<uint32_t>(offset) * 2 + (position ? 0 : 1);
+                set.scripts[key] = script;
+                list.back() = key;
+                ++ valid;
+            }
+        }
+        // Another version of the executable has other things there.
+        return valid >= count;
+    }
+
+    /**
+     * Writes the cameras of the start of the battles, after {@see WriteLua}. Game.BattleCameras.intro
+     * has the lists "position" and "look" (index = camera of the formation + 1) and the scripts.
+     */
+    inline void WriteIntroLua(std::ostream& out, const Set& set){
+        const std::string name = "Game.BattleCameras.intro";
+        out << "-- Cameras of the start of the battles, read from ff7.exe.\n"
+            << name << " = {position = {}, look = {}, scripts = {}}\n";
+        for (int kind = 0; kind < 2; ++ kind){
+            const std::vector<uint32_t>& list = kind == 0 ? set.position : set.look;
+            out << name << "." << (kind == 0 ? "position" : "look") << " = {";
+            for (size_t i = 0; i < list.size(); ++ i){
+                if (i % 16 == 0) out << "\n    ";
+                out << list[i] << ", ";
+            }
+            out << "\n}\n";
+        }
+        for (const auto& script : set.scripts){
+            out << name << ".scripts[" << script.first << "] = {";
+            for (size_t i = 0; i < script.second.size(); ++ i){
+                if (i % 24 == 0) out << "\n    ";
+                out << static_cast<int>(script.second[i]) << ", ";
+            }
+            out << "\n}\n";
+        }
+    }
+
     /**
      * Writes the sets to a Lua file. Game.BattleCameras[file] has the list "position" and "look"
      * (index = camera id * 3 + variant + 1, the value is the name of a script), and the table
@@ -195,7 +278,8 @@ namespace BattleCameraScripts{
         out << "-- Camera scripts of the battles, read from camdat0.bin, camdat1.bin and camdat2.bin.\n"
             << "-- Game.BattleCameras[file].position[camera id * 3 + variant + 1] is the name of a script in\n"
             << "-- Game.BattleCameras[file].scripts (the bytes of the script), the same for .look (the point\n"
-            << "-- the camera looks at). See scripts/battle/battle_camera.lua for the format.\n"
+            << "-- the camera looks at). .victory_position[variant + 1] and .victory_look are the ones of the\n"
+            << "-- camera of the victory. See scripts/battle/battle_camera.lua for the format.\n"
             << "Game.BattleCameras = Game.BattleCameras or {}\n";
         for (const auto& item : sets){
             const Set& set = item.second;
@@ -210,6 +294,11 @@ namespace BattleCameraScripts{
                 }
                 out << "\n}\n";
             }
+            for (int kind = 0; kind < 2; ++ kind){
+                out << name << "." << (kind == 0 ? "victory_position" : "victory_look") << " = {";
+                for (const uint32_t key : kind == 0 ? set.victory_position : set.victory_look) out << key << ", ";
+                out << "}\n";
+            }
             for (const auto& script : set.scripts){
                 out << name << ".scripts[" << script.first << "] = {";
                 for (size_t i = 0; i < script.second.size(); ++ i){

+ 81 - 7
src/installer/BattleDataInstaller.cpp

@@ -23,6 +23,7 @@
 #include <set>
 #include <cctype>
 #include <cstdio>
+#include <cstring>
 #include <cstdlib>
 #include <algorithm>
 #include <zlib.h>
@@ -593,6 +594,13 @@ unsigned int BattleDataInstaller::ConvertBattleModel(){
             // 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/");
+            if (!info.is_scene && "" != model.hrc){
+                WriteModelCamera(
+                  File(output_dir_ + "temp/battle_models/" + model.script),
+                  File(output_dir_ + "temp/battle_models/" + model.hrc + "bin"),
+                  model.id + "_" + info.name_normal
+                );
+            }
         }
 
         // Playable characters hold their weapons in battle (but Red XIII, who has none). Each one is a
@@ -901,6 +909,13 @@ void BattleDataInstaller::WriteBattleCameras(){
     }
     std::ofstream file(data_dir_ + "gamedata/battle_cameras.lua");
     BattleCameraScripts::WriteLua(file, sets);
+    // The ones of the start of the battles are in the executable.
+    BattleCameraScripts::Set intro;
+    auto exe_path = const_cast<DiskImage&>(disk_image_).filePath("ff7.exe");
+    if (exe_path != nullptr && BattleCameraScripts::ReadIntro(*exe_path, intro)){
+        BattleCameraScripts::WriteIntroLua(file, intro);
+    }
+    else std::cerr << "[WARNING] Can't read the cameras of the start of the battles from ff7.exe." << std::endl;
 }
 
 void BattleDataInstaller::WriteEffectMeshes(){
@@ -1091,6 +1106,14 @@ void BattleDataInstaller::WriteEnemies(){
         stat_eva->SetAttribute("id", "eva");
         stat_eva->SetAttribute("value", enemy.eva);
         stats->LinkEndChild(stat_eva.release());
+        std::unique_ptr<TiXmlElement> stat_hp(new TiXmlElement("stat"));
+        stat_hp->SetAttribute("id", "hp");
+        stat_hp->SetAttribute("value", enemy.hp);
+        stats->LinkEndChild(stat_hp.release());
+        std::unique_ptr<TiXmlElement> stat_mp(new TiXmlElement("stat"));
+        stat_mp->SetAttribute("id", "mp");
+        stat_mp->SetAttribute("value", enemy.mp);
+        stats->LinkEndChild(stat_mp.release());
         container->LinkEndChild(stats.release());
         std::unique_ptr<TiXmlElement> elements(new TiXmlElement("elements"));
         for (Enemy::Element element : enemy.elements){
@@ -1375,16 +1398,17 @@ void BattleDataInstaller::WriteFormations(){
         container->LinkEndChild(enemies.release());
         std::unique_ptr<TiXmlElement> cameras(new TiXmlElement("camera"));
         cameras->SetAttribute("initial", formation.initial_camera_position);
+        cameras->SetAttribute("intro", formation.intro_camera);
         int c = 0;
         for (Formation::Camera camera : formation.camera_positions){
             std::unique_ptr<TiXmlElement> camera_xml(new TiXmlElement("position"));
             camera_xml->SetAttribute("id", c);
-            camera_xml->SetAttribute("x", camera.x);
-            camera_xml->SetAttribute("y", camera.y);
-            camera_xml->SetAttribute("z", camera.z);
-            camera_xml->SetAttribute("direction_x", camera.d_x);
-            camera_xml->SetAttribute("direction_y", camera.d_y);
-            camera_xml->SetAttribute("direction_z", camera.d_z);
+            camera_xml->SetDoubleAttribute("x", camera.x);
+            camera_xml->SetDoubleAttribute("y", camera.y);
+            camera_xml->SetDoubleAttribute("z", camera.z);
+            camera_xml->SetDoubleAttribute("direction_x", camera.d_x);
+            camera_xml->SetDoubleAttribute("direction_y", camera.d_y);
+            camera_xml->SetDoubleAttribute("direction_z", camera.d_z);
             cameras->LinkEndChild(camera_xml.release());
             c ++;
         }
@@ -1622,6 +1646,54 @@ void BattleDataInstaller::GenerateRsdFiles(SpellModel model, std::string path){
     }
 }
 
+void BattleDataInstaller::WriteModelCamera(
+  File script, File skeleton, const std::string& model_name
+){
+    // The scripts of a model start with a header of 0x68 bytes, that ff7.exe copies to the data the
+    // cameras use (0x42b6a0): 16 points of the model at 0x12, the factors of the size at 0x44, two
+    // views of the model (a camera position and a point to look at) at 0x4C and the height of the point
+    // the camera looks at, at 0x64.
+    if (script.GetFileSize() < 0x68 || skeleton.GetFileSize() < 16) return;
+    skeleton.SetOffset(12);
+    const unsigned int bones = skeleton.readU32LE();
+    if (bones == 0 || skeleton.GetFileSize() < 16 + bones * 12) return;
+    std::ofstream file(data_dir_ + "scripts/battle_models/" + model_name + "_camera.lua");
+    if (!file) return;
+    file << "-- Data of the model for the cameras of the battles. A point is the end of the bone with the\n"
+      << "-- number of the point minus one (0 is the root).\n"
+      << "BattleModelCameras = BattleModelCameras or {}\n"
+      << "BattleModelCameras[\"" << model_name << "\"] = {\n    points = {";
+    script.SetOffset(0x12);
+    for (int i = 0; i < 16; i ++) file << static_cast<int>(script.readU8()) << ", ";
+    file << "},\n    size = {";
+    script.SetOffset(0x44);
+    for (int i = 0; i < 3; i ++) file << static_cast<int>(static_cast<int16_t>(script.readU16LE())) << ", ";
+    // The two views, one after the other.
+    script.SetOffset(0x4C);
+    file << "},\n    views = {";
+    for (int v = 0; v < 2; v ++){
+        for (int p = 0; p < 2; p ++){
+            file << (p == 0 ? "{pos = {" : "look = {");
+            for (int i = 0; i < 3; i ++) file << static_cast<int>(static_cast<int16_t>(script.readU16LE())) << ", ";
+            file << (p == 0 ? "}, " : "}}, ");
+        }
+    }
+    script.SetOffset(0x64);
+    file << "},\n    look_height = " << static_cast<int>(static_cast<int16_t>(script.readU16LE()))
+      << ",\n    lengths = {";
+    // The bones are the last data of the skeleton: parent, length (negative) and polygons.
+    skeleton.SetOffset(skeleton.GetFileSize() - bones * 12);
+    for (unsigned int b = 0; b < bones; b ++){
+        skeleton.readU32LE();
+        const u32 raw = skeleton.readU32LE();
+        float length = 0.0f;
+        std::memcpy(&length, &raw, sizeof(length));
+        skeleton.readU32LE();
+        file << "[" << b << "] = " << -length << ", ";
+    }
+    file << "},\n}\n";
+}
+
 void BattleDataInstaller::DecompileBattleModelHrc(
   File compiled, BattleModel model, std::string path, std::string skeleton_name
 ){
@@ -1723,7 +1795,9 @@ void BattleDataInstaller::DecompileSceneModelHrc(
         decompiled += "bone" + std::to_string(b) + "\n";
         if (b == 0) decompiled += "root\n";
         else decompiled += ("bone" + std::to_string(b - 1) + "\n");
-        decompiled += "100.000000\n";
+        // The pieces share the coordinates of the scene. A length would move each one along the depth, away
+        // from the previous one.
+        decompiled += "0.000000\n";
         decompiled += "1 " + model.p[b].substr(0, 4) + "\n\n";
     }
     std::ofstream out(path);

+ 9 - 0
src/installer/BattleDataInstaller.h

@@ -417,6 +417,15 @@ class BattleDataInstaller{
          */
         void GenerateRsdFiles(SpellModel model, std::string path);
 
+        /**
+         * Writes the data of a model that the cameras of the battles use, as a Lua script.
+         *
+         * @param[in] script The file with the animation scripts of the model.
+         * @param[in] skeleton The skeleton of the model.
+         * @param[in] model_name Name of the model, like rt_cloud.
+         */
+        void WriteModelCamera(File script, File skeleton, const std::string& model_name);
+
         /**
          * Decompiles a compiled HRC file.
          *

+ 5 - 0
src/installer/DataInstaller.cpp

@@ -301,6 +301,11 @@ float DataInstaller::Progress(){
         case KERNEL_SAVEMAP:
             write_output_line_("Extracting the initial savemap...", 2, true);
             kernel_installer_->ReadInitialSaveMap();
+            {
+                auto exe_path = disk_image_.filePath("ff7.exe");
+                if (exe_path) kernel_installer_->ReadRecruitRecords(*exe_path);
+                else write_output_line_("ff7.exe not found, Cait Sith and Vincent won't have their data.", 2, true);
+            }
             kernel_installer_->WriteInitialSaveMap(data_dir_ + "gamedata/initial_savemap.lua");
             installation_state_ = MEDIA_IMAGES;
             return CalcProgress();

+ 237 - 187
src/installer/KernelDataInstaller.cpp

@@ -15,6 +15,8 @@
 
 
 #include <tinyxml.h>
+#include <algorithm>
+#include <iterator>
 #include <fstream>
 #include <iostream>
 #include <memory>
@@ -522,6 +524,8 @@ void KernelDataInstaller::WriteCharacters(std::string file_name){
           << "        mp = " << static_cast<int>(character.curve_mp) << ",\n"
           << "        exp = " << static_cast<int>(character.curve_exp) << ",\n"
           << "    },\n"
+          << "    limit_divisors = {" << character.limit_1_div << ", " << character.limit_2_div << ", "
+          << character.limit_3_div << ", " << character.limit_4_div << "},\n"
           << "    limits = {\n"
           << "        [1] = {\n"
           << "            kills = 0,\n"
@@ -619,7 +623,7 @@ void KernelDataInstaller::ReadGrowth(){
         else growth_.curves[i].type = CURVE_EXP;
         for (int j = 0; j < 8; j ++){
             growth_.curves[i].gradient[j] = growth_file.readU8();
-            growth_.curves[i].base[j] = growth_file.readU8();
+            growth_.curves[i].base[j] = static_cast<s8>(growth_file.readU8());
         }
     }
 }
@@ -639,7 +643,7 @@ void KernelDataInstaller::WriteGrowth(std::string file_name){
         file << "Game.Growth.curves[" << i << "] = {\n";
         for (int j = 0; j < 8; j ++){
             file << "    [" << j << "] = {gradient = " << static_cast<int>(growth_.curves[i].gradient[j])
-              << ", base = " << static_cast<int>(growth_.curves[i].gradient[j]) << "},\n";
+              << ", base = " << static_cast<int>(growth_.curves[i].base[j]) << "},\n";
         }
         file << "}\n";
     }
@@ -2105,100 +2109,131 @@ void KernelDataInstaller::ReadInitialSaveMap(){
     savemap_file.WriteFile("/home/ivalentin/initialsavemap");
     // The initial savemap in KERNEL.BIN startas at 0x0054, directly into Cloud's level.
     // It skips the header (PC and PSX, checksum, preview data and window colour).
-    for (int i = 0; i < 9; i ++){
-        savemap_.characters[i].identifier = savemap_file.readU8();
-        savemap_.characters[i].level = savemap_file.readU8();
-        savemap_.characters[i].str = savemap_file.readU8();
-        savemap_.characters[i].vit = savemap_file.readU8();
-        savemap_.characters[i].mag = savemap_file.readU8();
-        savemap_.characters[i].spr = savemap_file.readU8();
-        savemap_.characters[i].dex = savemap_file.readU8();
-        savemap_.characters[i].lck = savemap_file.readU8();
-        savemap_.characters[i].str_bonus = savemap_file.readU8();
-        savemap_.characters[i].vit_bonus = savemap_file.readU8();
-        savemap_.characters[i].mag_bonus = savemap_file.readU8();
-        savemap_.characters[i].spr_bonus = savemap_file.readU8();
-        savemap_.characters[i].dex_bonus = savemap_file.readU8();
-        savemap_.characters[i].lck_bonus = savemap_file.readU8();
-        savemap_.characters[i].limit_level = savemap_file.readU8();
-        savemap_.characters[i].limit_bar = savemap_file.readU8();
-        bool name_end = false;
-        savemap_.characters[i].name = "";
-        for (int j = 0; j < 12; j ++){
-            savemap_.characters[i].name_raw[i] = savemap_file.readU8();
-            if (name_end == false){
-                if (savemap_.characters[i].name_raw[i] != 0XFF){
-                    savemap_.characters[i].name += ENGLISH_CHARS[savemap_.characters[i].name_raw[i]];
-                }
-                else name_end = true;
+    for (int i = 0; i < 9; i ++) ReadSaveMapCharacter(savemap_file, savemap_.characters[i]);
+    // The initial savemap ends up after character data, end now.
+}
+
+void KernelDataInstaller::ReadSaveMapCharacter(File& savemap_file, SaveMap::Character& character){
+    character.identifier = savemap_file.readU8();
+    character.level = savemap_file.readU8();
+    character.str = savemap_file.readU8();
+    character.vit = savemap_file.readU8();
+    character.mag = savemap_file.readU8();
+    character.spr = savemap_file.readU8();
+    character.dex = savemap_file.readU8();
+    character.lck = savemap_file.readU8();
+    character.str_bonus = savemap_file.readU8();
+    character.vit_bonus = savemap_file.readU8();
+    character.mag_bonus = savemap_file.readU8();
+    character.spr_bonus = savemap_file.readU8();
+    character.dex_bonus = savemap_file.readU8();
+    character.lck_bonus = savemap_file.readU8();
+    character.limit_level = savemap_file.readU8();
+    character.limit_bar = savemap_file.readU8();
+    bool name_end = false;
+    character.name = "";
+    for (int j = 0; j < 12; j ++){
+        character.name_raw[j] = savemap_file.readU8();
+        if (name_end == false){
+            if (character.name_raw[j] != 0XFF){
+                character.name += ENGLISH_CHARS[character.name_raw[j]];
             }
+            else name_end = true;
         }
-        savemap_.characters[i].weapon = savemap_file.readU8();
-        savemap_.characters[i].armor = savemap_file.readU8();
-        savemap_.characters[i].accessory = savemap_file.readU8();
-        savemap_.characters[i].status_raw = savemap_file.readU8();
-        if (savemap_.characters[i].status_raw == (savemap_.characters[i].status_raw | 0x10)){
-            savemap_.characters[i].sadness = true;
-            savemap_.characters[i].fury = false;
-        }
-        else if (savemap_.characters[i].status_raw == (savemap_.characters[i].status_raw | 0x20)){
-            savemap_.characters[i].sadness = false;
-            savemap_.characters[i].fury = true;
-        }
-        else{
-            savemap_.characters[i].sadness = false;
-            savemap_.characters[i].fury = false;
-        }
-        savemap_.characters[i].row_raw = savemap_file.readU8();
-        if (savemap_.characters[i].row_raw == 0xFE) savemap_.characters[i].back_row = true;
-        else savemap_.characters[i].back_row = false;
-        savemap_.characters[i].level_progress = savemap_file.readU8();
-        savemap_.characters[i].learned_limits_raw = savemap_file.readU16LE();
-        for (int j = 0; j < 4; j ++){
-            savemap_.characters[i].limits_learned[j][0] = false;
-            savemap_.characters[i].limits_learned[j][1] = false;
-        }
-        if (savemap_.characters[i].learned_limits_raw == (savemap_.characters[i].learned_limits_raw | 0x0001))
-            savemap_.characters[i].limits_learned[0][0] = true;
-        if (savemap_.characters[i].learned_limits_raw == (savemap_.characters[i].learned_limits_raw | 0x0002))
-            savemap_.characters[i].limits_learned[0][1] = true;
-        if (savemap_.characters[i].learned_limits_raw == (savemap_.characters[i].learned_limits_raw | 0x0008))
-            savemap_.characters[i].limits_learned[1][0] = true;
-        if (savemap_.characters[i].learned_limits_raw == (savemap_.characters[i].learned_limits_raw | 0x0010))
-            savemap_.characters[i].limits_learned[1][1] = true;
-        if (savemap_.characters[i].learned_limits_raw == (savemap_.characters[i].learned_limits_raw | 0x0040))
-            savemap_.characters[i].limits_learned[2][0] = true;
-        if (savemap_.characters[i].learned_limits_raw == (savemap_.characters[i].learned_limits_raw | 0x0080))
-            savemap_.characters[i].limits_learned[2][1] = true;
-        if (savemap_.characters[i].learned_limits_raw == (savemap_.characters[i].learned_limits_raw | 0x0200))
-            savemap_.characters[i].limits_learned[3][0] = true;
-        savemap_.characters[i].kills = savemap_file.readU16LE();
-        savemap_.characters[i].limit_uses[0] = savemap_file.readU16LE();
-        savemap_.characters[i].limit_uses[1] = savemap_file.readU16LE();
-        savemap_.characters[i].limit_uses[2] = savemap_file.readU16LE();
-        savemap_.characters[i].hp = savemap_file.readU16LE();
-        savemap_.characters[i].base_hp = savemap_file.readU16LE();
-        savemap_.characters[i].mp = savemap_file.readU16LE();
-        savemap_.characters[i].base_mp = savemap_file.readU16LE();
-        savemap_.characters[i].unknown = savemap_file.readU32LE();
-        savemap_.characters[i].max_hp = savemap_file.readU16LE();
-        savemap_.characters[i].max_mp = savemap_file.readU16LE();
-        savemap_.characters[i].exp = savemap_file.readU32LE();
-        for (int m = 0; m < 8; m ++){
-            savemap_.characters[i].weapon_materia[m].id = savemap_file.readU8();
-            // TODO: Identify Enemy Skill, do special treatment
-            savemap_.characters[i].weapon_materia[m].ap // WARNING: AP has only three bytes.
-              = savemap_file.readU8() + (savemap_file.readU8() << 8) + (savemap_file.readU8() << 16);
-        }
-        for (int m = 0; m < 8; m ++){
-            savemap_.characters[i].armor_materia[m].id = savemap_file.readU8();
-            // TODO: Identify Enemy Skill, do special treatment
-            savemap_.characters[i].armor_materia[m].ap // WARNING: AP has only three bytes.
-              = savemap_file.readU8() + (savemap_file.readU8() << 8) + (savemap_file.readU8() << 16);
+    }
+    character.weapon = savemap_file.readU8();
+    character.armor = savemap_file.readU8();
+    character.accessory = savemap_file.readU8();
+    character.status_raw = savemap_file.readU8();
+    if (character.status_raw == (character.status_raw | 0x10)){
+        character.sadness = true;
+        character.fury = false;
+    }
+    else if (character.status_raw == (character.status_raw | 0x20)){
+        character.sadness = false;
+        character.fury = true;
+    }
+    else{
+        character.sadness = false;
+        character.fury = false;
+    }
+    character.row_raw = savemap_file.readU8();
+    if (character.row_raw == 0xFE) character.back_row = true;
+    else character.back_row = false;
+    character.level_progress = savemap_file.readU8();
+    character.learned_limits_raw = savemap_file.readU16LE();
+    for (int j = 0; j < 4; j ++){
+        character.limits_learned[j][0] = false;
+        character.limits_learned[j][1] = false;
+    }
+    if (character.learned_limits_raw == (character.learned_limits_raw | 0x0001))
+        character.limits_learned[0][0] = true;
+    if (character.learned_limits_raw == (character.learned_limits_raw | 0x0002))
+        character.limits_learned[0][1] = true;
+    if (character.learned_limits_raw == (character.learned_limits_raw | 0x0008))
+        character.limits_learned[1][0] = true;
+    if (character.learned_limits_raw == (character.learned_limits_raw | 0x0010))
+        character.limits_learned[1][1] = true;
+    if (character.learned_limits_raw == (character.learned_limits_raw | 0x0040))
+        character.limits_learned[2][0] = true;
+    if (character.learned_limits_raw == (character.learned_limits_raw | 0x0080))
+        character.limits_learned[2][1] = true;
+    if (character.learned_limits_raw == (character.learned_limits_raw | 0x0200))
+        character.limits_learned[3][0] = true;
+    character.kills = savemap_file.readU16LE();
+    character.limit_uses[0] = savemap_file.readU16LE();
+    character.limit_uses[1] = savemap_file.readU16LE();
+    character.limit_uses[2] = savemap_file.readU16LE();
+    character.hp = savemap_file.readU16LE();
+    character.base_hp = savemap_file.readU16LE();
+    character.mp = savemap_file.readU16LE();
+    character.base_mp = savemap_file.readU16LE();
+    character.unknown = savemap_file.readU32LE();
+    character.max_hp = savemap_file.readU16LE();
+    character.max_mp = savemap_file.readU16LE();
+    character.exp = savemap_file.readU32LE();
+    for (int m = 0; m < 8; m ++){
+        character.weapon_materia[m].id = savemap_file.readU8();
+        // TODO: Identify Enemy Skill, do special treatment
+        character.weapon_materia[m].ap // WARNING: AP has only three bytes.
+          = savemap_file.readU8() + (savemap_file.readU8() << 8) + (savemap_file.readU8() << 16);
+    }
+    for (int m = 0; m < 8; m ++){
+        character.armor_materia[m].id = savemap_file.readU8();
+        // TODO: Identify Enemy Skill, do special treatment
+        character.armor_materia[m].ap // WARNING: AP has only three bytes.
+          = savemap_file.readU8() + (savemap_file.readU8() << 8) + (savemap_file.readU8() << 16);
+    }
+    character.exp_to_next = savemap_file.readU32LE();
+}
+
+void KernelDataInstaller::ReadRecruitRecords(const std::string& exe_path){
+    recruit_records_found_ = false;
+    std::ifstream exe(exe_path, std::ios::binary);
+    const std::vector<u8> data(
+      (std::istreambuf_iterator<char>(exe)), std::istreambuf_iterator<char>()
+    );
+    // The data of Cait Sith and Vincent are two character records like the ones of the savemap, one
+    // after the other (at 0x9138d0 in the 1998 build). They are found by their contents: the
+    // character IDs 6 and 7, valid levels, weapons of each one and names that end.
+    const size_t size = 0x84;
+    for (size_t offset = 0; offset + 2 * size <= data.size(); offset ++){
+        bool found = true;
+        for (int r = 0; r < 2 && found; r ++){
+            const u8* record = &data[offset + r * size];
+            const int first_weapon = r == 0 ? 101 : 114;
+            const int last_weapon = r == 0 ? 113 : 127;
+            found = record[0] == 6 + r && record[1] >= 1 && record[1] <= 99
+              && record[0x1C] >= first_weapon && record[0x1C] <= last_weapon
+              && std::find(record + 0x10, record + 0x1C, 0xFF) != record + 0x1C;
         }
-        savemap_.characters[i].exp_to_next = savemap_file.readU32LE();
+        if (!found) continue;
+        File records(&data[offset], 0, 2 * size);
+        for (int r = 0; r < 2; r ++) ReadSaveMapCharacter(records, recruit_records_[r]);
+        recruit_records_found_ = true;
+        return;
     }
-    // The initial savemap ends up after character data, end now.
+    std::cerr << "[WARNING] Can't find the data of Cait Sith and Vincent in ff7.exe." << std::endl;
 }
 
 void KernelDataInstaller::WriteInitialSaveMap(std::string file_name){
@@ -2207,106 +2242,121 @@ void KernelDataInstaller::WriteInitialSaveMap(std::string file_name){
     file.open(file_name, std::ios::out);
     if (!file) return;
     for (int c = 0; c < 9; c ++){
-        int total_count; // Utility to count in loops.
-        SaveMap::Character character = savemap_.characters[c];
-        file
-          << "Characters[" << c << "] = {\n"
-          << "    char_id = " << static_cast<int>(character.identifier) << ",\n"
-          << "    name = \"" << character.name << "\",\n"
-          << "    enabled = false,\n"
-          << "    locked = false,\n"
-          << "    level = " << static_cast<int>(character.level) << ",\n"
-          << "    kills = " << character.kills << ",\n"
-          << "    back_row = " << (character.back_row ? "true" : "false") << ",\n"
-          << "    exp = " << character.exp << ",\n"
-          << "    exp_to_next = " << character.exp_to_next << ",\n"
-          << "    stats = {\n"
-          << "        str = {base = " << static_cast<int>(character.str)
-          << ", bonus = " << static_cast<int>(character.str_bonus)
-          << ", total = " << static_cast<int>(character.str + character.str_bonus) << "},\n"
-          << "        vit = {base = " << static_cast<int>(character.vit)
-          << ", bonus = " << static_cast<int>(character.vit_bonus)
-          << ", total = " << static_cast<int>(character.vit + character.vit_bonus) << "},\n"
-          << "        mag = {base = " << static_cast<int>(character.mag)
-          << ", bonus = " << static_cast<int>(character.mag_bonus)
-          << ", total = " << static_cast<int>(character.mag + character.mag_bonus) << "},\n"
-          << "        spr = {base = " << static_cast<int>(character.spr)
-          << ", bonus = " << static_cast<int>(character.spr_bonus)
-          << ", total = " << static_cast<int>(character.spr + character.spr_bonus) << "},\n"
-          << "        dex = {base = " << static_cast<int>(character.dex)
-          << ", bonus = " << static_cast<int>(character.dex_bonus)
-          << ", total = " << static_cast<int>(character.dex + character.dex_bonus) << "},\n"
-          << "        lck = {base = " << static_cast<int>(character.lck)
-          << ", bonus = " << static_cast<int>(character.lck_bonus)
-          << ", total = " << static_cast<int>(character.lck + character.lck_bonus) << "},\n"
-          << "        hp = {current = " << character.hp  << ", base = " << character.base_hp
-          << ", max = " << character.max_hp << "},\n"
-          << "        mp = {current = " << character.mp  << ", base = " << character.base_mp
-          << ", max = " << character.max_mp << "},\n"
-          << "        atk = 0,\n"
-          << "        acc = 0,\n"
-          << "        def = 0,\n"
-          << "        eva = 0,\n"
-          << "        matk = 0,\n"
-          << "        mdef = 0,\n"
-          << "        meva = 0\n"
-          << "    },\n"
-          << "    limit = {\n"
-          << "        current = " << static_cast<int>(character.limit_level) << ",\n"
-          << "        bar = " << static_cast<int>(character.limit_bar) << ",\n"
-          << "        learned = {\n"
-          << "            [1] = {[1] = " << (character.limits_learned[0][0] == 1 ? "true" : "false")
-          << ", [2] = " << (character.limits_learned[0][1] == 1 ? "true" : "false") << "},\n"
-          << "            [2] = {[1] = " << (character.limits_learned[1][0] == 1 ? "true" : "false")
-          << ", [2] = " << (character.limits_learned[1][1] == 1 ? "true" : "false") << "},\n"
-          << "            [3] = {[1] = " << (character.limits_learned[2][0] == 1 ? "true" : "false")
-          << ", [2] = " << (character.limits_learned[2][1] == 1 ? "true" : "false") << "},\n"
-          << "            [4] = {[1] = " << (character.limits_learned[3][0] == 1 ? "true" : "false")
-          << ", [2] = " << (character.limits_learned[3][1] == 1 ? "true" : "false") << "}\n"
-          << "        },\n"
-          << "        uses = {[1] = " << character.limit_uses[0] << ", [2] = "
-          << character.limit_uses[1] << ", [3] = " << character.limit_uses[2] << ", [4] = 0}\n"
-          << "    },\n"
-          << "    weapon = {\n"
-          << "        id = " << static_cast<int>(character.weapon) + 128 << ",\n"
-          << "        materia = {";
-        total_count = 0;
-        for (int m = 0; m < 8; m ++){
-            if (character.weapon_materia[m].id < 255){
-                total_count ++;
-                file << "\n            [" << m << "] = {id = "
-                  << static_cast<int>(character.weapon_materia[m].id) << ", ap = "
-                  << character.weapon_materia[m].ap << "},";
-            }
-        }
-        if (total_count > 0) file << "\n        }\n    },\n";
-        else file << "}\n    },\n";
-        file
-          << "    armor = {\n"
-          << "        id = " << static_cast<int>(character.armor) + 256 << ",\n"
-          << "        materia = {";
-        total_count = 0;
-        for (int m = 0; m < 8; m ++){
-            if (character.armor_materia[m].id < 255){
-                total_count ++;
-                file << "\n            [" << m << "] = {id = "
-                  << static_cast<int>(character.armor_materia[m].id) << ", ap = "
-                  << character.armor_materia[m].ap << "},";
-            }
+        file << "Characters[" << c << "] = ";
+        WriteSaveMapCharacter(file, savemap_.characters[c]);
+        file << "Characters.recalculate_stats(" << c << ")\n\n";
+    }
+    if (recruit_records_found_){
+        file << "-- Data that Cait Sith and Vincent get when they join, from ff7.exe.\n"
+          << "Game.RecruitRecords = {}\n";
+        for (int r = 0; r < 2; r ++){
+            file << "Game.RecruitRecords[" << 6 + r << "] = ";
+            WriteSaveMapCharacter(file, recruit_records_[r]);
         }
-        if (total_count > 0) file << "\n        }\n    },\n";
-        else file << "}\n    },\n";
-        file << "    accessory = ";
-        if (character.accessory < 0xFF) file << static_cast<int>(character.accessory) + 288;
-        else file << "nil";
-        file << ",\n    status = {";
-        if (character.fury) file << FURY;
-        if (character.sadness) file << SADNESS;
-        file << "}\n}\nCharacters.recalculate_stats(" << c << ")\n\n";
     }
     file.close();
 }
 
+void KernelDataInstaller::WriteSaveMapCharacter(
+  std::ostream& file, const SaveMap::Character& character
+){
+    int total_count; // Utility to count in loops.
+    file
+      << "{\n"
+      << "    char_id = " << static_cast<int>(character.identifier) << ",\n"
+      << "    name = \"" << character.name << "\",\n"
+      << "    enabled = false,\n"
+      << "    locked = false,\n"
+      << "    level = " << static_cast<int>(character.level) << ",\n"
+      << "    kills = " << character.kills << ",\n"
+      << "    back_row = " << (character.back_row ? "true" : "false") << ",\n"
+      << "    exp = " << character.exp << ",\n"
+      << "    exp_to_next = " << character.exp_to_next << ",\n"
+      << "    stats = {\n"
+      << "        str = {base = " << static_cast<int>(character.str)
+      << ", bonus = " << static_cast<int>(character.str_bonus)
+      << ", total = " << static_cast<int>(character.str + character.str_bonus) << "},\n"
+      << "        vit = {base = " << static_cast<int>(character.vit)
+      << ", bonus = " << static_cast<int>(character.vit_bonus)
+      << ", total = " << static_cast<int>(character.vit + character.vit_bonus) << "},\n"
+      << "        mag = {base = " << static_cast<int>(character.mag)
+      << ", bonus = " << static_cast<int>(character.mag_bonus)
+      << ", total = " << static_cast<int>(character.mag + character.mag_bonus) << "},\n"
+      << "        spr = {base = " << static_cast<int>(character.spr)
+      << ", bonus = " << static_cast<int>(character.spr_bonus)
+      << ", total = " << static_cast<int>(character.spr + character.spr_bonus) << "},\n"
+      << "        dex = {base = " << static_cast<int>(character.dex)
+      << ", bonus = " << static_cast<int>(character.dex_bonus)
+      << ", total = " << static_cast<int>(character.dex + character.dex_bonus) << "},\n"
+      << "        lck = {base = " << static_cast<int>(character.lck)
+      << ", bonus = " << static_cast<int>(character.lck_bonus)
+      << ", total = " << static_cast<int>(character.lck + character.lck_bonus) << "},\n"
+      << "        hp = {current = " << character.hp  << ", base = " << character.base_hp
+      << ", max = " << character.max_hp << "},\n"
+      << "        mp = {current = " << character.mp  << ", base = " << character.base_mp
+      << ", max = " << character.max_mp << "},\n"
+      << "        atk = 0,\n"
+      << "        acc = 0,\n"
+      << "        def = 0,\n"
+      << "        eva = 0,\n"
+      << "        matk = 0,\n"
+      << "        mdef = 0,\n"
+      << "        meva = 0\n"
+      << "    },\n"
+      << "    limit = {\n"
+      << "        current = " << static_cast<int>(character.limit_level) << ",\n"
+      << "        bar = " << static_cast<int>(character.limit_bar) << ",\n"
+      << "        learned = {\n"
+      << "            [1] = {[1] = " << (character.limits_learned[0][0] == 1 ? "true" : "false")
+      << ", [2] = " << (character.limits_learned[0][1] == 1 ? "true" : "false") << "},\n"
+      << "            [2] = {[1] = " << (character.limits_learned[1][0] == 1 ? "true" : "false")
+      << ", [2] = " << (character.limits_learned[1][1] == 1 ? "true" : "false") << "},\n"
+      << "            [3] = {[1] = " << (character.limits_learned[2][0] == 1 ? "true" : "false")
+      << ", [2] = " << (character.limits_learned[2][1] == 1 ? "true" : "false") << "},\n"
+      << "            [4] = {[1] = " << (character.limits_learned[3][0] == 1 ? "true" : "false")
+      << ", [2] = " << (character.limits_learned[3][1] == 1 ? "true" : "false") << "}\n"
+      << "        },\n"
+      << "        uses = {[1] = " << character.limit_uses[0] << ", [2] = "
+      << character.limit_uses[1] << ", [3] = " << character.limit_uses[2] << ", [4] = 0}\n"
+      << "    },\n"
+      << "    weapon = {\n"
+      << "        id = " << static_cast<int>(character.weapon) + 128 << ",\n"
+      << "        materia = {";
+    total_count = 0;
+    for (int m = 0; m < 8; m ++){
+        if (character.weapon_materia[m].id < 255){
+            total_count ++;
+            file << "\n            [" << m << "] = {id = "
+              << static_cast<int>(character.weapon_materia[m].id) << ", ap = "
+              << character.weapon_materia[m].ap << "},";
+        }
+    }
+    if (total_count > 0) file << "\n        }\n    },\n";
+    else file << "}\n    },\n";
+    file
+      << "    armor = {\n"
+      << "        id = " << static_cast<int>(character.armor) + 256 << ",\n"
+      << "        materia = {";
+    total_count = 0;
+    for (int m = 0; m < 8; m ++){
+        if (character.armor_materia[m].id < 255){
+            total_count ++;
+            file << "\n            [" << m << "] = {id = "
+              << static_cast<int>(character.armor_materia[m].id) << ", ap = "
+              << character.armor_materia[m].ap << "},";
+        }
+    }
+    if (total_count > 0) file << "\n        }\n    },\n";
+    else file << "}\n    },\n";
+    file << "    accessory = ";
+    if (character.accessory < 0xFF) file << static_cast<int>(character.accessory) + 288;
+    else file << "nil";
+    file << ",\n    status = {";
+    if (character.fury) file << FURY;
+    if (character.sadness) file << SADNESS;
+    file << "}\n}\n";
+}
+
 std::string KernelDataInstaller::GetBasicStatName(int id){
     std::string name = "stat";
     switch (id){

+ 36 - 1
src/installer/KernelDataInstaller.h

@@ -206,6 +206,15 @@ class KernelDataInstaller{
          */
         void ReadInitialSaveMap();
 
+        /**
+         * Reads from ff7.exe the character data that Cait Sith and Vincent get when they join.
+         *
+         * Their slots of the initial savemap hold young Cloud and Sephiroth.
+         *
+         * @param[in] exe_path Path to ff7.exe.
+         */
+        void ReadRecruitRecords(const std::string& exe_path);
+
         /**
          * Saves the initial savemap to a Lua script.
          *
@@ -2523,7 +2532,7 @@ class KernelDataInstaller{
             /**
              * Curve bases.
              */
-            u8 base[8];
+            s8 base[8];
 
         };
 
@@ -2628,6 +2637,32 @@ class KernelDataInstaller{
          */
         SaveMap savemap_;
 
+        /**
+         * Reads one character record of the savemap.
+         *
+         * @param[in,out] savemap_file Data, at the start of the record.
+         * @param[out] character The character read.
+         */
+        void ReadSaveMapCharacter(File& savemap_file, SaveMap::Character& character);
+
+        /**
+         * Writes one character record as a Lua table.
+         *
+         * @param[in,out] file Target file.
+         * @param[in] character The character to write.
+         */
+        void WriteSaveMapCharacter(std::ostream& file, const SaveMap::Character& character);
+
+        /**
+         * Character data of Cait Sith and Vincent when they join.
+         */
+        SaveMap::Character recruit_records_[2];
+
+        /**
+         * True if the recruit records could be read.
+         */
+        bool recruit_records_found_ = false;
+
         /**
          * The kernel file.
          */

+ 90 - 29
src/installer/data/AbFile.cpp

@@ -15,8 +15,26 @@
 
 #include <iostream>
 #include <fstream>
+#include <map>
 #include "data/AbFile.h"
 
+namespace{
+
+    /**
+     * Number of bytes of parameters of the opcodes that aren't decompiled, found in the script
+     * interpreter of ff7.exe (0x41fb14, the handlers are listed at 0x424832). Opcodes that aren't
+     * here or in the decompiler have none. Getting one wrong turns its parameters into opcodes.
+     */
+    const std::map<u8, int> PARAMETER_BYTES = {
+        {0x90, 3}, {0x94, 5}, {0x96, 2}, {0x97, 2}, {0x98, 1}, {0x99, 6}, {0x9A, 4}, {0x9D, 1},
+        {0xA0, 1}, {0xA1, 2}, {0xA3, 1}, {0xA7, 1}, {0xA8, 2}, {0xAB, 4}, {0xAC, 1}, {0xAF, 1},
+        {0xB5, 11}, {0xBA, 2}, {0xBD, 4}, {0xBE, 1}, {0xBF, 2}, {0xC4, 3}, {0xC7, 3}, {0xC8, 5},
+        {0xCB, 8}, {0xCC, 1}, {0xCF, 8}, {0xD4, 3}, {0xD5, 8}, {0xD6, 1}, {0xD7, 2}, {0xDA, 1},
+        {0xDB, 4}, {0xDC, 3}, {0xDD, 2}, {0xDE, 2}, {0xE7, 1}, {0xE9, 3}, {0xF5, 1}, {0xF8, 1},
+        {0xFB, 4}, {0xFD, 6},
+    };
+}
+
 AbFile::AbFile(File file, bool enemy): ab_file_(file), is_enemy_(enemy){
     scripts_.clear();
     file.SetOffset(0);
@@ -53,6 +71,16 @@ void AbFile::Read(){
     }
 }
 
+u8 AbFile::ReadByte(){
+    if (ab_file_.GetCurrentOffset() >= ab_file_.GetFileSize()) return 0;
+    return ab_file_.readU8();
+}
+
+u16 AbFile::ReadWord(){
+    const u16 low = ReadByte();
+    return low | (ReadByte() << 8);
+}
+
 std::string AbFile::DecompileScript(u32 offset){
     u32 intial_offset = ab_file_.GetCurrentOffset();
     ab_file_.SetOffset(offset);
@@ -70,17 +98,19 @@ std::string AbFile::DecompileScript(u32 offset){
             end = true;
             break;
         }
+        // Some scripts that no model uses point to data that goes on to the end of the file.
+        if (ab_file_.GetCurrentOffset() >= ab_file_.GetFileSize()) break;
         total_opcodes ++;
-        u8 opcode = ab_file_.readU8();
+        u8 opcode = ReadByte();
         if (opcode >= 0x00 && opcode <= 0x8D) line << "    play_animation(" << static_cast<int>(opcode) << ")";
         else{
             switch (opcode){
                 case 0x91: // Play effect, one 1 byte parameter.
-                    line << "    play_effect(" << static_cast<int>(ab_file_.readU8()) << ")";
+                    line << "    play_effect(" << static_cast<int>(ReadByte()) << ")";
                     break;
                 case 0xA9: // Increase script counter by two. Two 1 byte parameters, ignored
-                    ab_file_.readU8();
-                    ab_file_.readU8();
+                    ReadByte();
+                    ReadByte();
                     break;
                 case 0xAA: // Unpause camera, no parameters.
                     line << "    unpause_camera()";
@@ -91,27 +121,47 @@ std::string AbFile::DecompileScript(u32 offset){
                      //   distance (2 bytes), distance from the joint.
                      //   start (1 byte), effect start.
                      //   end (1 byte), effect end.
-                    line << "    set_effect(" << static_cast<int>(ab_file_.readU8()) << ", " << ab_file_.readU16LE()
-                      << ", " << static_cast<int>(ab_file_.readU8()) << ", "
-                      << static_cast<int>(ab_file_.readU8()) << ")";
+                    line << "    set_effect(" << static_cast<int>(ReadByte()) << ", " << ReadWord()
+                      << ", " << static_cast<int>(ReadByte()) << ", "
+                      << static_cast<int>(ReadByte()) << ")";
                     break;
                 case 0xB6: // Pause camera and finish animation. One byte parameter, animation ID.
-                    line << "    pause_camera_finish_animation(" << static_cast<int>(ab_file_.readU8()) << ")";
+                    line << "    pause_camera_finish_animation(" << static_cast<int>(ReadByte()) << ")";
                     break;
                 case 0xB9: // Set camera. One byte parameter, camera ID.
-                    line << "    set_camera(" << static_cast<int>(ab_file_.readU8()) << ")";
+                    line << "    set_camera(" << static_cast<int>(ReadByte()) << ")";
                     break;
                 case 0x06:
                      // Play hurt animation, including action, effect and sound. It will not display
                      // damage and barrier effect. One byte parameter, the amount of frames to wait
                      // before starting.
-                    line << "    execute_hurt(" << static_cast<int>(ab_file_.readU8()) << ")";
+                    line << "    execute_hurt(" << static_cast<int>(ReadByte()) << ")";
+                    break;
+                case 0xBC:
+                    // Set the camera of the formation the battle rests on. One byte parameter, 0 to 2.
+                    line << "    set_formation_camera(" << static_cast<int>(ReadByte()) << ")";
                     break;
-                case 0xC1: // Jump to label set by 0xC9 (::jump::). No parameters.
-                    line << "    goto jump";
+                case 0xC1:
+                    // Jump to the label set by 0xC9 (::jump::). No parameters. It always jumps, so what
+                    // comes after it is not part of the script. The game looks for the label byte by
+                    // byte from the start, and in many scripts it is a parameter of another opcode:
+                    // then what follows it hasn't been decompiled yet, and it's done now.
+                    if (!label_set){
+                        const u32 next = ab_file_.GetCurrentOffset();
+                        ab_file_.SetOffset(offset);
+                        while (ab_file_.GetCurrentOffset() < next - 1 && ReadByte() != 0xC9){}
+                        if (ab_file_.GetCurrentOffset() < next - 1){
+                            label_set = true;
+                            line << "    ::jump::";
+                            break;
+                        }
+                        ab_file_.SetOffset(next);
+                    }
+                    line << "    goto jump\n    return 0";
+                    end = true;
                     break;
                 case 0xC2: // Show damage. One byte parameter, frames to wait before showing.
-                    line << "    execute_damage(" << static_cast<int>(ab_file_.readU8()) << ")";
+                    line << "    execute_damage(" << static_cast<int>(ReadByte()) << ")";
                     break;
                 case 0xC5:
                      // Set value from 0x800f8374 (unit fade time) as wait time for action script.
@@ -122,7 +172,7 @@ std::string AbFile::DecompileScript(u32 offset){
                      // Set value to 0x800f8374 (unit fade time) for futher use. One byte parameter,
                      // wait time. I have no idea what this is used for.
                     line
-                      << "    set_unit_fade_time(" << static_cast<int>(ab_file_.readU8()) << ")";
+                      << "    set_unit_fade_time(" << static_cast<int>(ReadByte()) << ")";
                     break;
                 case 0xC9: // Set a jump label. Only do it once per script. No prameters
                     if (!label_set){
@@ -140,8 +190,8 @@ std::string AbFile::DecompileScript(u32 offset){
                      // Jump to enemy, two parameters
                      //   (2 bytes), I don't know what it is.
                      //   (1 byte), I don't know what it is.
-                    line << "    jump_to_enemy(" << ab_file_.readU16LE() << ", "
-                      << static_cast<int>(ab_file_.readU8()) << ")";
+                    line << "    jump_to_enemy(" << ReadWord() << ", "
+                      << static_cast<int>(ReadByte()) << ")";
                     break;
                 case 0xD1:
                      // Move to enemy using function 0x800cf5bc by number of steps. Stop distance is
@@ -149,16 +199,16 @@ std::string AbFile::DecompileScript(u32 offset){
                      //   distance (2 byte), unknown.
                      //   unknown (2 bytes), unknown.
                      //   steps (1 byte), number of steps.
-                    line << "    move_to_target(" << ab_file_.readU16LE() << ", " << ab_file_.readU16LE() << ", "
-                      << static_cast<int>(ab_file_.readU8()) << ")";
+                    line << "    move_to_target(" << ReadWord() << ", " << ReadWord() << ", "
+                      << static_cast<int>(ReadByte()) << ")";
                     break;
                 case 0xD8:
                     // Play sound using attacker settings after waiting given number of frames.
                     // Two parameters:
                     //   wait (1 byte), frames to wait before the sound.
                     //   sound (2 bytes), sound ID.
-                    line << "    play_sound_for_attacker(" << static_cast<int>(ab_file_.readU8()) << ", "
-                      << ab_file_.readU16LE() <<  ")";
+                    line << "    play_sound_for_attacker(" << static_cast<int>(ReadByte()) << ", "
+                      << ReadWord() <<  ")";
                     break;
                 case 0xE5:
                     // Set initial (idle) direction for current unit according to situation. No
@@ -189,7 +239,7 @@ std::string AbFile::DecompileScript(u32 offset){
                     line << "    wait()";
                     break;
                 case 0xF4: // Set frames to wait. 1 parameter, frames to wait (1 byte).
-                    line << "    set_wait(" << static_cast<int>(ab_file_.readU8()) << ")";
+                    line << "    set_wait(" << static_cast<int>(ReadByte()) << ")";
                     break;
                 case 0xF6:
                     // Play die effect (depends on die type) if unit is dead. Used in enemy hurt
@@ -199,7 +249,7 @@ std::string AbFile::DecompileScript(u32 offset){
                 case 0xF7:
                     // After wait time ends execute hurt action, effect, sound. This will display
                     // damage and barriers effect. One byte parameter, wait time, in frames.
-                    line << "    execute_attack(" << static_cast<int>(ab_file_.readU8()) << ")";
+                    line << "    execute_attack(" << static_cast<int>(ReadByte()) << ")";
                     break;
                 case 0xFA: // Instantly set default position for units. No parameters.
                     line << "    return_position()";
@@ -213,24 +263,35 @@ std::string AbFile::DecompileScript(u32 offset){
                 case 0xF1: // Return.
                 case 0xEE: // Return.
                 case 0xFF: // Return.
-                //case 0xC1: // Return.
-                case 0xA2: // Return.
                     line << "    return 0";
                     end = true;
                     break;
                 case 0xFE:
-                    // Special return opcode. Return only if next byte is 0xC0.
+                    // Special return opcode. Return only if next byte is 0xC0. If it isn't, that byte
+                    // is the next opcode.
                     {
-                        u8 param = ab_file_.readU8();
-                        if (param == 0xC0){
+                        u32 next = ab_file_.GetCurrentOffset();
+                        if (ReadByte() == 0xC0){
                             line << "    return 0";
                             end = true;
                         }
-                        else line << "    -- 0xFE not paired with 0xC0 for return.";
+                        else{
+                            ab_file_.SetOffset(next);
+                            line << "    -- 0xFE not paired with 0xC0 for return.";
+                        }
                     }
                     break;
                 default:
-                    line << "    -- Unknown/unused opcode.";
+                    {
+                        auto length = PARAMETER_BYTES.find(opcode);
+                        if (length == PARAMETER_BYTES.end()) line << "    -- Unknown/unused opcode.";
+                        else{
+                            line << "    -- Not decompiled opcode, parameters:";
+                            for (int i = 0; i < length->second; i ++){
+                                line << " " << static_cast<int>(ReadByte());
+                            }
+                        }
+                    }
 
 
             }

+ 14 - 0
src/installer/data/AbFile.h

@@ -75,6 +75,20 @@ class AbFile{
          */
         std::string DecompileScript(u32 offset);
 
+        /**
+         * Reads the next byte of the file.
+         *
+         * @return The byte, 0 past the end of the file.
+         */
+        u8 ReadByte();
+
+        /**
+         * Reads the next two bytes of the file, little endian.
+         *
+         * @return The value, with 0 for the bytes past the end of the file.
+         */
+        u16 ReadWord();
+
         /**
          * The ab file.
          */

+ 21 - 30
src/installer/data/BattleSceneFile.cpp

@@ -49,28 +49,14 @@ void BattleSceneFile::Read(File file){
     }
     for (int c = 0; c < 4; c ++){
         for (int p = 0; p < 3; p ++){
-            // Camera 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_.camera[c].camera[p].x = file.readU16LE();
-            if (scene_.camera[c].camera[p].x > 0x7F9B) scene_.camera[c].camera[p].x -= 0xFFFF;
-            scene_.camera[c].camera[p].x /= 0xFF;
-            // Y and Z are inverted in original data.
-            scene_.camera[c].camera[p].y = file.readU16LE();
-            if (scene_.camera[c].camera[p].y > 0x7F9B) scene_.camera[c].camera[p].y -= 0xFFFF;
-            scene_.camera[c].camera[p].y /= 0xFF;
-            scene_.camera[c].camera[p].z = file.readU16LE();
-            if (scene_.camera[c].camera[p].z > 0x7F9B) scene_.camera[c].camera[p].z -= 0xFFFF;
-            scene_.camera[c].camera[p].z /= 0xFF;
-            scene_.camera[c].camera[p].d_x = file.readU16LE();
-            if (scene_.camera[c].camera[p].d_x > 0x7F9B) scene_.camera[c].camera[p].d_x -= 0xFFFF;
-            scene_.camera[c].camera[p].d_x /= 0xFF;
-            scene_.camera[c].camera[p].d_y = file.readU16LE();
-            if (scene_.camera[c].camera[p].d_y > 0x7F9B) scene_.camera[c].camera[p].d_y -= 0xFFFF;
-            scene_.camera[c].camera[p].d_y /= 0xFF;
-            scene_.camera[c].camera[p].d_z = file.readU16LE();
-            if (scene_.camera[c].camera[p].d_z > 0x7F9B) scene_.camera[c].camera[p].d_z -= 0xFFFF;
-            scene_.camera[c].camera[p].d_z /= 0xFF;
+            // 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();
     }
@@ -462,16 +448,21 @@ void BattleSceneFile::Read(File file){
         formation.location_name = LocationToString(scene_.setup[f].location);
         for (int c = 0; c < 3; c ++){
             Formation::Camera camera;
-            camera.x = scene_.camera[f].camera[c].x;
-            camera.y = scene_.camera[f].camera[c].y;
-            camera.z = scene_.camera[f].camera[c].z;
-            camera.d_x = scene_.camera[f].camera[c].d_x;
-            camera.d_y = scene_.camera[f].camera[c].d_y;
-            camera.d_z = scene_.camera[f].camera[c].d_z;
+            // 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);
         }
-        if (scene_.setup[f].camera < formation.camera_positions.size())
-            formation.initial_camera_position = scene_.setup[f].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]);

+ 12 - 7
src/installer/data/Formation.h

@@ -193,32 +193,32 @@ struct Formation{
         /**
          * X position.
          */
-        int x;
+        float x;
 
         /**
          * Y position.
          */
-        int y;
+        float y;
 
         /**
          * z position.
          */
-        int z;
+        float z;
 
         /**
          * X direction.
          */
-        int d_x;
+        float d_x;
 
         /**
          * Y direction.
          */
-        int d_y;
+        float d_y;
 
         /**
          * z direction.
          */
-        int d_z;
+        float d_z;
 
         /**
          * Constructor.
@@ -303,6 +303,11 @@ struct Formation{
      */
     int initial_camera_position;
 
+    /**
+     * Camera script of the start of the battle.
+     */
+    int intro_camera;
+
     /**
      * Indicates if the formation is an arena battle.
      */
@@ -321,7 +326,7 @@ struct Formation{
     Formation():
       id(0), next_formation(-1), escape_counter(0.0f), escapable(true), skip_victory_pose(false),
       skip_spoils(false), preemptive_disabled(false), layout(Layout::NORMAL), location(-1),
-      location_name(""), initial_camera_position(0),is_arena_battle(false)
+      location_name(""), initial_camera_position(0), intro_camera(-1),is_arena_battle(false)
     {
         enemies.clear();
         camera_positions.clear();

+ 4 - 3
src/installer/decompiler/field/instruction/FieldPartyInstruction.cpp

@@ -195,10 +195,11 @@ void FieldPartyInstruction::ProcessPRTYE(CodeGenerator* code_gen){
 }
 
 void FieldPartyInstruction::ProcessMMBUD(CodeGenerator* code_gen){
-    // Param 0 is the character, param 1 is 0 to hide it in the PHS and anything else to show it.
+    // Param 0 is 0 to hide the character in the PHS and anything else to show it, param 1 is the
+    // character (checked in the opcode handler of ff7.exe, 0x61c782).
     code_gen->AddOutputLine((
-      boost::format("set_character_enable(%1%, %2%)") % params_[0]->GetString()
-        % (params_[1]->GetUnsigned() != 0 ? "true" : "false")
+      boost::format("set_character_enable(%1%, %2%)") % params_[1]->GetString()
+        % (params_[0]->GetUnsigned() != 0 ? "true" : "false")
     ).str());
 }
 

Some files were not shown because too many files changed in this diff