Explorar o código

Merge branch 'feature/installer_cli' into develop

Iñigo Valentin hai 2 días
pai
achega
8a9ee26a0d
Modificáronse 100 ficheiros con 3788 adicións e 3161 borrados
  1. 1 1
      .github/agents/ff7-format-researcher.agent.md
  2. 1 1
      .github/copilot-instructions.md
  3. 1 1
      .github/instructions/ff7-data-formats.instructions.md
  4. 2 2
      .github/prompts/new-data-format.prompt.md
  5. 9 0
      .gitignore
  6. 0 3
      data/data/fonts/_fonts.xml
  7. 0 96
      data/data/fonts/ffvii.xml
  8. BIN=BIN
      data/data/fonts/ffvii_digits.png
  9. BIN=BIN
      data/data/fonts/ffvii_en.png
  10. BIN=BIN
      data/data/fonts/ffvii_jp.png
  11. 0 407
      data/data/fonts/ffvii_jp.xml
  12. BIN=BIN
      data/data/fonts/ffvii_menu.png
  13. BIN=BIN
      data/data/fonts/ffvii_timer.png
  14. 0 225
      doc/FFVII/1_history.html
  15. 0 42
      doc/FFVII/2_engine_basics.html
  16. 0 75
      doc/FFVII/3_1_kernel_overview.html
  17. 0 162
      doc/FFVII/Index.html
  18. BIN=BIN
      doc/FFVII/img/2_engine_basics.jpg
  19. 0 47
      doc/FFVII/style.css
  20. 259 37
      doc/INSTALL_DATA.md
  21. 9 0
      doc/TODO.md
  22. 1 0
      src/CMakeLists.txt
  23. 35 35
      src/common/File.cpp
  24. 31 18
      src/common/File.h
  25. 169 0
      src/common/InstallStamp.cpp
  26. 150 0
      src/common/InstallStamp.h
  27. 20 41
      src/common/LzsFile.cpp
  28. 49 1
      src/common/VGearsApplication.cpp
  29. 60 1
      src/common/VGearsApplication.h
  30. 16 8
      src/data/VGearsAFile.cpp
  31. 2 0
      src/data/VGearsBackgroundFile.cpp
  32. 12 2
      src/data/VGearsPFile.cpp
  33. 2 1
      src/data/VGearsPFile.h
  34. 85 104
      src/installer/BattleDataInstaller.cpp
  35. 2 2
      src/installer/BattleDataInstaller.h
  36. 4 0
      src/installer/CMakeLists.txt
  37. 753 0
      src/installer/CliInstaller.cpp
  38. 65 0
      src/installer/CliInstaller.h
  39. 62 6
      src/installer/DataInstaller.cpp
  40. 41 10
      src/installer/DataInstaller.h
  41. 17 1
      src/installer/DiskImage.cpp
  42. 4 1
      src/installer/DiskImage.h
  43. 11 3
      src/installer/ExternalTools.cpp
  44. 39 30
      src/installer/FieldDataInstaller.cpp
  45. 24 5
      src/installer/FieldTextWriter.cpp
  46. 307 0
      src/installer/InstallCommandLine.cpp
  47. 191 0
      src/installer/InstallCommandLine.h
  48. 54 0
      src/installer/InstallLayout.cpp
  49. 51 0
      src/installer/InstallLayout.h
  50. 5 2
      src/installer/InstallLog.cpp
  51. 16 0
      src/installer/InstallLog.h
  52. 362 0
      src/installer/InstallSteps.cpp
  53. 205 0
      src/installer/InstallSteps.h
  54. 56 9
      src/installer/InstallVerifier.cpp
  55. 24 1
      src/installer/InstallVerifier.h
  56. 91 290
      src/installer/MainWindow.cpp
  57. 5 5
      src/installer/MainWindow.h
  58. 3 3
      src/installer/MainWindow.ui
  59. 20 2
      src/installer/MediaDataInstaller.cpp
  60. 10 0
      src/installer/MediaDataInstaller.h
  61. 11 7
      src/installer/TexFile.cpp
  62. 217 0
      src/installer/WindowFonts.cpp
  63. 139 0
      src/installer/WindowFonts.h
  64. 2 2
      src/installer/WorldInstaller.cpp
  65. 1 9
      src/installer/WorldInstaller.h
  66. 55 70
      src/installer/common/BinGZipFile.cpp
  67. 17 3
      src/installer/common/BinGZipFile.h
  68. 0 8
      src/installer/data/BattleSceneFile.cpp
  69. 6 3
      src/installer/data/DaFile.cpp
  70. 1 1
      src/installer/data/DaFile.h
  71. 3 3
      src/installer/data/Enemy.h
  72. BIN=BIN
      src/installer/decompiler/test/branches.dmp
  73. 0 5
      src/installer/decompiler/test/branches.txt
  74. BIN=BIN
      src/installer/decompiler/test/break-do-while.dmp
  75. 0 14
      src/installer/decompiler/test/break-do-while.txt
  76. BIN=BIN
      src/installer/decompiler/test/break-do-while2.dmp
  77. 0 15
      src/installer/decompiler/test/break-do-while2.txt
  78. BIN=BIN
      src/installer/decompiler/test/break-while.dmp
  79. 0 15
      src/installer/decompiler/test/break-while.txt
  80. BIN=BIN
      src/installer/decompiler/test/bug_fixes.dat
  81. 0 554
      src/installer/decompiler/test/cfg_test.cpp
  82. 0 217
      src/installer/decompiler/test/codegen.cpp
  83. BIN=BIN
      src/installer/decompiler/test/continue-do-while.dmp
  84. 0 14
      src/installer/decompiler/test/continue-do-while.txt
  85. BIN=BIN
      src/installer/decompiler/test/continue-do-while2.dmp
  86. 0 15
      src/installer/decompiler/test/continue-do-while2.txt
  87. BIN=BIN
      src/installer/decompiler/test/continue-while.dmp
  88. 0 15
      src/installer/decompiler/test/continue-while.txt
  89. 0 147
      src/installer/decompiler/test/disassembler/pasc.cpp
  90. 0 39
      src/installer/decompiler/test/disassembler/pasc.h
  91. 0 33
      src/installer/decompiler/test/disassembler/subopcode.cpp
  92. 0 38
      src/installer/decompiler/test/disassembler/subopcode.h
  93. 0 227
      src/installer/decompiler/test/disassembler_test.cpp
  94. BIN=BIN
      src/installer/decompiler/test/do-while-in-while.dmp
  95. 0 20
      src/installer/decompiler/test/do-while-in-while.txt
  96. BIN=BIN
      src/installer/decompiler/test/do-while.dmp
  97. 0 7
      src/installer/decompiler/test/do-while.txt
  98. BIN=BIN
      src/installer/decompiler/test/ff7.dat
  99. BIN=BIN
      src/installer/decompiler/test/ff7_all_opcodes.dat
  100. BIN=BIN
      src/installer/decompiler/test/ff7_all_opcodes_OLD.dat

+ 1 - 1
.github/agents/ff7-format-researcher.agent.md

@@ -14,7 +14,7 @@ You are a specialist at investigating FF7 binary formats in the V-Gears codebase
 
 ## Approach
 
-1. Check the format documentation in `doc/code/FFVII/` first.
+1. Check the format documentation in [the FF7 wiki at wiki.ffrtt.ru](https://wiki.ffrtt.ru/index.php/FF7) and in the header comments of existing parsers first.
 2. Find the relevant parser triplet in `src/data/` (`*File`, `*FileSerializer`, `*FileManager`) and read the serializer for the authoritative byte layout.
 3. For installer/decompiler questions, read `src/installer/` and the matching instruction classes under `src/installer/decompiler/`.
 4. Cross-check with the test suite in `test/` — tests often show minimal usage examples.

+ 1 - 1
.github/copilot-instructions.md

@@ -19,7 +19,7 @@ V-Gears is a free, cross-platform reimplementation of the Final Fantasy VII engi
 - LuaJIT is a system dependency.
 - `test/` — Boost.Test suite mirroring `src/` paths; sources are listed manually in `test/CMakeLists.txt`.
 - `data/` — runtime configuration only (Ogre plugins/resources cfgs). Not game data.
-- `doc/` — all guides; `doc/code/FFVII/` documents the original binary formats.
+- `doc/` — all guides. The original binary formats are documented in the header comments of the parsers and in [the FF7 wiki at wiki.ffrtt.ru](https://wiki.ffrtt.ru/index.php/FF7).
 - `_OLD/` — legacy q-gears code kept for reference. Do not modify or reuse without asking.
 
 ## Build and Test

+ 1 - 1
.github/instructions/ff7-data-formats.instructions.md

@@ -13,7 +13,7 @@ Most formats in `src/data/` follow this structure — mirror it when adding form
 - `XFileSerializer` — reads/writes the binary layout (derives from `VGearsSerializer`).
 - `XFileManager` — Ogre `ResourceManager` integration (singleton + `Resource`).
 
-Format documentation lives in [doc/code/FFVII/](../../../doc/code/FFVII/). Check there and at existing similar parsers (e.g. `src/data/worldmap/TxzFile*`) before writing a new one.
+Format documentation lives in [the FF7 wiki at wiki.ffrtt.ru](https://wiki.ffrtt.ru/index.php/FF7) and in the header comments of the parsers. Check there and at existing similar parsers (e.g. `src/data/worldmap/TxzFile*`) before writing a new one.
 
 ## Installer Gotchas (verified, don't regress)
 

+ 2 - 2
.github/prompts/new-data-format.prompt.md

@@ -7,7 +7,7 @@ argument-hint: "Format name and target directory, e.g. 'XYZ in src/data/worldmap
 Scaffold a new FF7 binary format parser for the format named by the user:
 
 1. Research first:
-   - Check `doc/code/FFVII/` for documentation of the format.
+   - Check [the FF7 wiki at wiki.ffrtt.ru](https://wiki.ffrtt.ru/index.php/FF7) for documentation of the format.
    - Read the most similar existing triplet in `src/data/` (e.g. `TxzFile.h/.cpp`, `TxzFileSerializer.h/.cpp`, `TxzFileManager.h/.cpp` in `src/data/worldmap/`) and mirror its structure, base classes, and Doxygen comment style exactly.
 2. Create the triplet in the requested directory:
    - `XFile` — passive data container for the parsed format.
@@ -15,5 +15,5 @@ Scaffold a new FF7 binary format parser for the format named by the user:
    - `XFileManager` — Ogre `ResourceManager` singleton integration, matching the existing pattern.
 3. Follow `doc/STYLE.md` strictly: C++14, `PascalCase` types, `snake_case` variables with trailing underscore for members, `#pragma once`, correct include order.
 4. Register the new sources in the appropriate `src/CMakeLists.txt` source list (no globbing — add them explicitly, in the same grouped style as neighboring entries).
-5. Do not add or reference original game data; document the binary layout from `doc/code/FFVII/` knowledge in the header comments instead.
+5. Do not add or reference original game data; document the binary layout in the header comments instead.
 6. Build the affected target to verify it compiles.

+ 9 - 0
.gitignore

@@ -30,3 +30,12 @@ src/installer/MainWindow.ui.autosave
 
 # Generated from MainWindow.ui at build time.
 src/installer/ui_MainWindow.h
+
+# Built by the installer from the game data.
+data/data/fonts/ffvii_en.png
+data/data/fonts/ffvii_menu.png
+data/data/fonts/ffvii_digits.png
+data/data/fonts/ffvii_timer.png
+
+# Old decompiler tests, not built. Kept locally only, some fixtures are game data.
+src/installer/decompiler/test/

+ 0 - 3
data/data/fonts/_fonts.xml

@@ -1,10 +1,7 @@
 <?xml version="1.0" encoding="ISO-8859-1"?>
 <fonts>
     <font file_name="ffvii_en.xml" />
-    <font file_name="ffvii_jp.xml" />
     <font file_name="ffvii_menu.xml" />
     <font file_name="ffvii_digits.xml" />
     <font file_name="ffvii_timer.xml" />
-    <font file_name="ffvii.xml" />
-    <font file_name="ffvii.xml" />
 </fonts>

+ 0 - 96
data/data/fonts/ffvii.xml

@@ -1,96 +0,0 @@
-<font name="FFVIIFont" language="English" image="ffvii_en.png" image_size="256 256" height="16">
-    <char name=" " x="0" y="0" width="12" height="12" pre="0" post="-9" />
-    <char name="!" x="12" y="0" width="12" height="12" pre="2" post="-7" />
-    <char name="&quot;" x="24" y="0" width="12" height="12" pre="2" post="-4" />
-    <char name="#" x="36" y="0" width="12" height="12" pre="0" post="-2" />
-    <char name="$" x="48" y="0" width="12" height="12" pre="0" post="-5" />
-    <char name="%" x="60" y="0" width="12" height="12" pre="0" post="-2" />
-    <char name="&amp;" x="72" y="0" width="12" height="12" pre="0" post="-3" />
-    <char name="'" x="84" y="0" width="12" height="12" pre="0" post="-9" />
-    <char name="(" x="96" y="0" width="12" height="12" pre="2" post="-4" />
-    <char name=")" x="108" y="0" width="12" height="12" pre="2" post="-4" />
-    <char name="*" x="120" y="0" width="12" height="12" pre="0" post="-5" />
-    <char name="+" x="132" y="0" width="12" height="12" pre="0" post="-5" />
-    <char name="," x="144" y="0" width="12" height="12" pre="1" post="-5" />
-    <char name="-" x="156" y="0" width="12" height="12" pre="0" post="-7" />
-    <char name="." x="168" y="0" width="12" height="12" pre="1" post="-6" />
-    <char name="/" x="180" y="0" width="12" height="12" pre="0" post="-6" />
-    <char name="0" x="192" y="0" width="12" height="12" pre="0" post="-4" />
-    <char name="1" x="204" y="0" width="12" height="12" pre="2" post="-5" />
-    <char name="2" x="216" y="0" width="12" height="12" pre="0" post="-4" />
-    <char name="3" x="228" y="0" width="12" height="12" pre="0" post="-4" />
-    <char name="4" x="240" y="0" width="12" height="12" pre="0" post="-4" />
-    <char name="5" x="0" y="12" width="12" height="12" pre="0" post="-4" />
-    <char name="6" x="12" y="12" width="12" height="12" pre="0" post="-4" />
-    <char name="7" x="24" y="12" width="12" height="12" pre="0" post="-4" />
-    <char name="8" x="36" y="12" width="12" height="12" pre="0" post="-4" />
-    <char name="9" x="48" y="12" width="12" height="12" pre="0" post="-4" />
-    <char name=":" x="60" y="12" width="12" height="12" pre="2" post="-7" />
-    <char name=";" x="72" y="12" width="12" height="12" pre="0" post="-8" />
-    <char name="&lt;" x="84" y="12" width="12" height="12" pre="0" post="-5" />
-    <char name="=" x="96" y="12" width="12" height="12" pre="0" post="-4" />
-    <char name=">" x="108" y="12" width="12" height="12" pre="0" post="-5" />
-    <char name="?" x="120" y="12" width="12" height="12" pre="1" post="-5" />
-    <char name="@" x="132" y="12" width="12" height="12" pre="0" post="-2" />
-    <char name="A" x="144" y="12" width="12" height="12" pre="0" post="-3" />
-    <char name="B" x="156" y="12" width="12" height="12" pre="0" post="-5" />
-    <char name="C" x="168" y="12" width="12" height="12" pre="0" post="-4" />
-    <char name="D" x="180" y="12" width="12" height="12" pre="0" post="-4" />
-    <char name="E" x="192" y="12" width="12" height="12" pre="0" post="-5" />
-    <char name="F" x="204" y="12" width="12" height="12" pre="0" post="-5" />
-    <char name="G" x="216" y="12" width="12" height="12" pre="0" post="-4" />
-    <char name="H" x="228" y="12" width="12" height="12" pre="0" post="-4" />
-    <char name="I" x="240" y="12" width="12" height="12" pre="0" post="-9" />
-    <char name="J" x="0" y="24" width="12" height="12" pre="0" post="-6" />
-    <char name="K" x="12" y="24" width="12" height="12" pre="0" post="-5" />
-    <char name="L" x="24" y="24" width="12" height="12" pre="0" post="-5" />
-    <char name="M" x="36" y="24" width="12" height="12" pre="0" post="-1" />
-    <char name="N" x="48" y="24" width="12" height="12" pre="0" post="-4" />
-    <char name="O" x="60" y="24" width="12" height="12" pre="0" post="-3" />
-    <char name="P" x="72" y="24" width="12" height="12" pre="0" post="-5" />
-    <char name="Q" x="84" y="24" width="12" height="12" pre="0" post="-3" />
-    <char name="R" x="96" y="24" width="12" height="12" pre="0" post="-5" />
-    <char name="S" x="108" y="24" width="12" height="12" pre="0" post="-5" />
-    <char name="T" x="120" y="24" width="12" height="12" pre="0" post="-5" />
-    <char name="U" x="132" y="24" width="12" height="12" pre="0" post="-4" />
-    <char name="V" x="144" y="24" width="12" height="12" pre="0" post="-3" />
-    <char name="W" x="156" y="24" width="12" height="12" pre="0" post="-1" />
-    <char name="X" x="168" y="24" width="12" height="12" pre="0" post="-4" />
-    <char name="Y" x="180" y="24" width="12" height="12" pre="0" post="-3" />
-    <char name="Z" x="192" y="24" width="12" height="12" pre="0" post="-5" />
-    <char name="[" x="204" y="24" width="12" height="12" pre="0" post="-8" />
-    <char name="\" x="216" y="24" width="12" height="12" pre="0" post="-6" />
-    <char name="]" x="228" y="24" width="12" height="12" pre="0" post="-8" />
-    <char name="^" x="240" y="24" width="12" height="12" pre="0" post="-5" />
-    <char name="_" x="0" y="36" width="12" height="12" pre="0" post="-4" />
-    <char name="`" x="12" y="36" width="12" height="12" pre="0" post="-8" />
-    <char name="a" x="24" y="36" width="12" height="12" pre="0" post="-5" />
-    <char name="b" x="36" y="36" width="12" height="12" pre="0" post="-5" />
-    <char name="c" x="48" y="36" width="12" height="12" pre="0" post="-6" />
-    <char name="d" x="60" y="36" width="12" height="12" pre="0" post="-5" />
-    <char name="e" x="72" y="36" width="12" height="12" pre="0" post="-5" />
-    <char name="f" x="84" y="36" width="12" height="12" pre="0" post="-6" />
-    <char name="g" x="96" y="36" width="12" height="12" pre="0" post="-5" />
-    <char name="h" x="108" y="36" width="12" height="12" pre="0" post="-5" />
-    <char name="i" x="120" y="36" width="12" height="12" pre="0" post="-9" />
-    <char name="j" x="132" y="36" width="12" height="12" pre="0" post="-8" />
-    <char name="k" x="144" y="36" width="12" height="12" pre="0" post="-6" />
-    <char name="l" x="156" y="36" width="12" height="12" pre="0" post="-9" />
-    <char name="m" x="168" y="36" width="12" height="12" pre="0" post="-1" />
-    <char name="n" x="180" y="36" width="12" height="12" pre="0" post="-5" />
-    <char name="o" x="192" y="36" width="12" height="12" pre="0" post="-5" />
-    <char name="p" x="204" y="36" width="12" height="12" pre="0" post="-5" />
-    <char name="q" x="216" y="36" width="12" height="12" pre="0" post="-5" />
-    <char name="r" x="228" y="36" width="12" height="12" pre="0" post="-7" />
-    <char name="s" x="240" y="36" width="12" height="12" pre="0" post="-6" />
-    <char name="t" x="0" y="48" width="12" height="12" pre="0" post="-6" />
-    <char name="u" x="12" y="48" width="12" height="12" pre="0" post="-5" />
-    <char name="v" x="24" y="48" width="12" height="12" pre="0" post="-5" />
-    <char name="w" x="36" y="48" width="12" height="12" pre="0" post="-1" />
-    <char name="x" x="48" y="48" width="12" height="12" pre="0" post="-5" />
-    <char name="y" x="60" y="48" width="12" height="12" pre="0" post="-5" />
-    <char name="z" x="72" y="48" width="12" height="12" pre="0" post="-6" />
-    <char name="…" x="12" y="96" width="12" height="12" pre="0" post="-3" />
-    <char name="“" x="120" y="96" width="12" height="12" pre="0" post="-6" />
-    <char name="”" x="132" y="96" width="12" height="12" pre="0" post="-6" />
-</font>

BIN=BIN
data/data/fonts/ffvii_digits.png


BIN=BIN
data/data/fonts/ffvii_en.png


BIN=BIN
data/data/fonts/ffvii_jp.png


+ 0 - 407
data/data/fonts/ffvii_jp.xml

@@ -1,407 +0,0 @@
-<font name="FFVIIFont" language="Japanese" image="ffvii_jp.png" image_size="512 256" height="16">
-    <char name="バ" x="0" y="0" width="12" height="12" pre="0" post="1" />
-    <char name="ば" x="12" y="0" width="12" height="12" pre="0" post="1" />
-    <char name="ビ" x="24" y="0" width="12" height="12" pre="0" post="-1" />
-    <char name="び" x="36" y="0" width="12" height="12" pre="0" post="1" />
-    <char name="ブ" x="48" y="0" width="12" height="12" pre="0" post="0" />
-    <char name="ぶ" x="60" y="0" width="12" height="12" pre="0" post="1" />
-    <char name="ベ" x="72" y="0" width="12" height="12" pre="0" post="0" />
-    <char name="ボ" x="96" y="0" width="12" height="12" pre="0" post="0" />
-    <char name="ぼ" x="108" y="0" width="12" height="12" pre="0" post="1" />
-    <char name="ガ" x="120" y="0" width="12" height="12" pre="0" post="0" />
-    <char name="が" x="132" y="0" width="12" height="12" pre="0" post="0" />
-    <char name="ギ" x="144" y="0" width="12" height="12" pre="0" post="-1" />
-    <char name="ぎ" x="156" y="0" width="12" height="12" pre="0" post="0" />
-    <char name="グ" x="168" y="0" width="12" height="12" pre="0" post="0" />
-    <char name="ぐ" x="180" y="0" width="12" height="12" pre="0" post="-2" />
-    <char name="ゲ" x="192" y="0" width="12" height="12" pre="0" post="0" />
-    <char name="げ" x="204" y="0" width="12" height="12" pre="0" post="0" />
-    <char name="ゴ" x="216" y="0" width="12" height="12" pre="0" post="0" />
-    <char name="ご" x="228" y="0" width="12" height="12" pre="0" post="-1" />
-    <char name="ザ" x="240" y="0" width="12" height="12" pre="0" post="1" />
-    <char name="ざ" x="0" y="12" width="12" height="12" pre="0" post="-1" />
-    <char name="ジ" x="12" y="12" width="12" height="12" pre="0" post="0" />
-    <char name="じ" x="24" y="12" width="12" height="12" pre="0" post="-3" />
-    <char name="ズ" x="36" y="12" width="12" height="12" pre="0" post="0" />
-    <char name="ず" x="48" y="12" width="12" height="12" pre="0" post="0" />
-    <char name="ゼ" x="60" y="12" width="12" height="12" pre="0" post="0" />
-    <char name="ぜ" x="72" y="12" width="12" height="12" pre="0" post="1" />
-    <char name="ゾ" x="84" y="12" width="12" height="12" pre="0" post="-2" />
-    <char name="ぞ" x="96" y="12" width="12" height="12" pre="0" post="0" />
-    <char name="ダ" x="108" y="12" width="12" height="12" pre="0" post="0" />
-    <char name="だ" x="120" y="12" width="12" height="12" pre="0" post="0" />
-    <char name="ヅ" x="156" y="12" width="12" height="12" pre="0" post="0" />
-    <char name="デ" x="180" y="12" width="12" height="12" pre="0" post="0" />
-    <char name="で" x="192" y="12" width="12" height="12" pre="0" post="0" />
-    <char name="ド" x="204" y="12" width="12" height="12" pre="0" post="-4" />
-    <char name="ど" x="216" y="12" width="12" height="12" pre="0" post="-1" />
-    <char name="パ" x="240" y="12" width="12" height="12" pre="0" post="1" />
-    <char name="ぱ" x="0" y="24" width="12" height="12" pre="0" post="0" />
-    <char name="ピ" x="12" y="24" width="12" height="12" pre="0" post="-2" />
-    <char name="プ" x="36" y="24" width="12" height="12" pre="0" post="0" />
-    <char name="ぷ" x="48" y="24" width="12" height="12" pre="0" post="0" />
-    <char name="ペ" x="60" y="24" width="12" height="12" pre="0" post="0" />
-    <char name="ポ" x="84" y="24" width="12" height="12" pre="0" post="-1" />
-    <char name="0" x="108" y="24" width="12" height="12" pre="0" post="-4" />
-    <char name="1" x="120" y="24" width="12" height="12" pre="2" post="-6" />
-    <char name="2" x="132" y="24" width="12" height="12" pre="0" post="-4" />
-    <char name="3" x="144" y="24" width="12" height="12" pre="0" post="-4" />
-    <char name="4" x="156" y="24" width="12" height="12" pre="0" post="-3" />
-    <char name="5" x="168" y="24" width="12" height="12" pre="0" post="-4" />
-    <char name="6" x="180" y="24" width="12" height="12" pre="0" post="-4" />
-    <char name="7" x="192" y="24" width="12" height="12" pre="0" post="-5" />
-    <char name="8" x="204" y="24" width="12" height="12" pre="0" post="-4" />
-    <char name="9" x="216" y="24" width="12" height="12" pre="0" post="-4" />
-    <char name="、" x="228" y="24" width="12" height="12" pre="1" post="-5" />
-    <char name="。" x="240" y="24" width="12" height="12" pre="1" post="-3" />
-    <char name=" " x="0" y="36" width="12" height="12" pre="0" post="-4" />
-    <char name="ハ" x="12" y="36" width="12" height="12" pre="0" post="0" />
-    <char name="は" x="24" y="36" width="12" height="12" pre="0" post="-1" />
-    <char name="ヒ" x="36" y="36" width="12" height="12" pre="0" post="-3" />
-    <char name="ひ" x="48" y="36" width="12" height="12" pre="0" post="-1" />
-    <char name="フ" x="60" y="36" width="12" height="12" pre="0" post="-2" />
-    <char name="ふ" x="72" y="36" width="12" height="12" pre="0" post="0" />
-    <char name="ヘ" x="84" y="36" width="12" height="12" pre="0" post="0" />
-    <char name="へ" x="96" y="36" width="12" height="12" pre="0" post="0" />
-    <char name="ホ" x="108" y="36" width="12" height="12" pre="0" post="-1" />
-    <char name="ほ" x="120" y="36" width="12" height="12" pre="0" post="-1" />
-    <char name="カ" x="132" y="36" width="12" height="12" pre="0" post="-2" />
-    <char name="か" x="144" y="36" width="12" height="12" pre="0" post="0" />
-    <char name="キ" x="156" y="36" width="12" height="12" pre="0" post="-2" />
-    <char name="き" x="168" y="36" width="12" height="12" pre="0" post="-2" />
-    <char name="ク" x="180" y="36" width="12" height="12" pre="0" post="-2" />
-    <char name="く" x="192" y="36" width="12" height="12" pre="0" post="-4" />
-    <char name="ケ" x="204" y="36" width="12" height="12" pre="0" post="-1" />
-    <char name="け" x="216" y="36" width="12" height="12" pre="0" post="-1" />
-    <char name="コ" x="228" y="36" width="12" height="12" pre="0" post="-2" />
-    <char name="こ" x="240" y="36" width="12" height="12" pre="0" post="-3" />
-    <char name="サ" x="0" y="48" width="12" height="12" pre="0" post="-1" />
-    <char name="さ" x="12" y="48" width="12" height="12" pre="0" post="-2" />
-    <char name="シ" x="24" y="48" width="12" height="12" pre="0" post="-1" />
-    <char name="し" x="36" y="48" width="12" height="12" pre="0" post="-3" />
-    <char name="ス" x="48" y="48" width="12" height="12" pre="0" post="-2" />
-    <char name="す" x="60" y="48" width="12" height="12" pre="0" post="-1" />
-    <char name="セ" x="72" y="48" width="12" height="12" pre="0" post="-1" />
-    <char name="せ" x="84" y="48" width="12" height="12" pre="0" post="-1" />
-    <char name="ソ" x="96" y="48" width="12" height="12" pre="0" post="-3" />
-    <char name="そ" x="108" y="48" width="12" height="12" pre="0" post="-2" />
-    <char name="タ" x="120" y="48" width="12" height="12" pre="0" post="-2" />
-    <char name="た" x="132" y="48" width="12" height="12" pre="0" post="-1" />
-    <char name="チ" x="144" y="48" width="12" height="12" pre="0" post="-1" />
-    <char name="ち" x="156" y="48" width="12" height="12" pre="0" post="-2" />
-    <char name="ツ" x="168" y="48" width="12" height="12" pre="0" post="-2" />
-    <char name="つ" x="180" y="48" width="12" height="12" pre="0" post="-1" />
-    <char name="テ" x="192" y="48" width="12" height="12" pre="0" post="-1" />
-    <char name="て" x="204" y="48" width="12" height="12" pre="0" post="-2" />
-    <char name="ト" x="216" y="48" width="12" height="12" pre="0" post="-6" />
-    <char name="と" x="228" y="48" width="12" height="12" pre="0" post="-3" />
-    <char name="ウ" x="240" y="48" width="12" height="12" pre="0" post="-2" />
-    <char name="う" x="0" y="60" width="12" height="12" pre="0" post="-2" />
-    <char name="ア" x="12" y="60" width="12" height="12" pre="0" post="-1" />
-    <char name="あ" x="24" y="60" width="12" height="12" pre="0" post="0" />
-    <char name="イ" x="36" y="60" width="12" height="12" pre="0" post="-2" />
-    <char name="い" x="48" y="60" width="12" height="12" pre="0" post="-1" />
-    <char name="エ" x="60" y="60" width="12" height="12" pre="0" post="-1" />
-    <char name="え" x="72" y="60" width="12" height="12" pre="0" post="-1" />
-    <char name="オ" x="84" y="60" width="12" height="12" pre="0" post="-1" />
-    <char name="お" x="96" y="60" width="12" height="12" pre="0" post="0" />
-    <char name="ナ" x="108" y="60" width="12" height="12" pre="0" post="-2" />
-    <char name="な" x="120" y="60" width="12" height="12" pre="0" post="0" />
-    <char name="ニ" x="132" y="60" width="12" height="12" pre="0" post="-1" />
-    <char name="に" x="144" y="60" width="12" height="12" pre="0" post="-2" />
-    <char name="ぬ" x="168" y="60" width="12" height="12" pre="0" post="0" />
-    <char name="ネ" x="180" y="60" width="12" height="12" pre="0" post="-1" />
-    <char name="ね" x="192" y="60" width="12" height="12" pre="0" post="0" />
-    <char name="ノ" x="204" y="60" width="12" height="12" pre="0" post="-3" />
-    <char name="の" x="216" y="60" width="12" height="12" pre="0" post="-1" />
-    <char name="マ" x="228" y="60" width="12" height="12" pre="0" post="-2" />
-    <char name="ま" x="240" y="60" width="12" height="12" pre="0" post="0" />
-    <char name="ミ" x="0" y="72" width="12" height="12" pre="0" post="-3" />
-    <char name="み" x="12" y="72" width="12" height="12" pre="0" post="0" />
-    <char name="ム" x="24" y="72" width="12" height="12" pre="0" post="-1" />
-    <char name="む" x="36" y="72" width="12" height="12" pre="0" post="-1" />
-    <char name="メ" x="48" y="72" width="12" height="12" pre="0" post="-2" />
-    <char name="め" x="60" y="72" width="12" height="12" pre="0" post="-1" />
-    <char name="モ" x="72" y="72" width="12" height="12" pre="0" post="-1" />
-    <char name="も" x="84" y="72" width="12" height="12" pre="0" post="-2" />
-    <char name="ラ" x="96" y="72" width="12" height="12" pre="0" post="-2" />
-    <char name="ら" x="108" y="72" width="12" height="12" pre="0" post="-3" />
-    <char name="リ" x="120" y="72" width="12" height="12" pre="0" post="-4" />
-    <char name="り" x="132" y="72" width="12" height="12" pre="0" post="-4" />
-    <char name="ル" x="144" y="72" width="12" height="12" pre="0" post="-1" />
-    <char name="る" x="156" y="72" width="12" height="12" pre="0" post="-2" />
-    <char name="レ" x="168" y="72" width="12" height="12" pre="0" post="-4" />
-    <char name="れ" x="180" y="72" width="12" height="12" pre="0" post="-1" />
-    <char name="ロ" x="192" y="72" width="12" height="12" pre="0" post="-3" />
-    <char name="ろ" x="204" y="72" width="12" height="12" pre="0" post="-2" />
-    <char name="ヤ" x="216" y="72" width="12" height="12" pre="0" post="-1" />
-    <char name="や" x="228" y="72" width="12" height="12" pre="0" post="-1" />
-    <char name="ユ" x="240" y="72" width="12" height="12" pre="0" post="-1" />
-    <char name="よ" x="24" y="84" width="12" height="12" pre="0" post="-2" />
-    <char name="ワ" x="36" y="84" width="12" height="12" pre="0" post="-2" />
-    <char name="わ" x="48" y="84" width="12" height="12" pre="0" post="0" />
-    <char name="ン" x="60" y="84" width="12" height="12" pre="0" post="-2" />
-    <char name="ん" x="72" y="84" width="12" height="12" pre="0" post="-1" />
-    <char name="を" x="96" y="84" width="12" height="12" pre="0" post="-2" />
-    <char name="ッ" x="108" y="84" width="12" height="12" pre="0" post="-3" />
-    <char name="っ" x="120" y="84" width="12" height="12" pre="0" post="-4" />
-    <char name="ャ" x="132" y="84" width="12" height="12" pre="0" post="-3" />
-    <char name="ゃ" x="144" y="84" width="12" height="12" pre="0" post="-3" />
-    <char name="ュ" x="156" y="84" width="12" height="12" pre="0" post="-3" />
-    <char name="ゅ" x="168" y="84" width="12" height="12" pre="0" post="-3" />
-    <char name="ョ" x="180" y="84" width="12" height="12" pre="0" post="-5" />
-    <char name="ょ" x="192" y="84" width="12" height="12" pre="0" post="-4" />
-    <char name="ァ" x="204" y="84" width="12" height="12" pre="0" post="-4" />
-    <char name="ぁ" x="216" y="84" width="12" height="12" pre="0" post="-3" />
-    <char name="ィ" x="228" y="84" width="12" height="12" pre="0" post="-4" />
-    <char name="ゥ" x="0" y="96" width="12" height="12" pre="0" post="-5" />
-    <char name="ェ" x="24" y="96" width="12" height="12" pre="0" post="-3" />
-    <char name="ぇ" x="36" y="96" width="12" height="12" pre="0" post="-4" />
-    <char name="ぉ" x="60" y="96" width="12" height="12" pre="0" post="-2" />
-    <char name="!" x="72" y="96" width="12" height="12" pre="2" post="-7" />
-    <char name="?" x="84" y="96" width="12" height="12" pre="1" post="-3" />
-    <char name="『" x="96" y="96" width="12" height="12" pre="2" post="-3" />
-    <char name="』" x="108" y="96" width="12" height="12" pre="2" post="-2" />
-    <char name="A" x="144" y="96" width="12" height="12" pre="0" post="-2" />
-    <char name="B" x="156" y="96" width="12" height="12" pre="0" post="-3" />
-    <char name="C" x="168" y="96" width="12" height="12" pre="0" post="-3" />
-    <char name="D" x="180" y="96" width="12" height="12" pre="0" post="-3" />
-    <char name="E" x="192" y="96" width="12" height="12" pre="0" post="-3" />
-    <char name="F" x="204" y="96" width="12" height="12" pre="0" post="-3" />
-    <char name="G" x="216" y="96" width="12" height="12" pre="0" post="-3" />
-    <char name="H" x="228" y="96" width="12" height="12" pre="0" post="-3" />
-    <char name="I" x="240" y="96" width="12" height="12" pre="2" post="-7" />
-    <char name="J" x="0" y="108" width="12" height="12" pre="0" post="-5" />
-    <char name="K" x="12" y="108" width="12" height="12" pre="0" post="-4" />
-    <char name="L" x="24" y="108" width="12" height="12" pre="0" post="-3" />
-    <char name="M" x="36" y="108" width="12" height="12" pre="0" post="-1" />
-    <char name="N" x="48" y="108" width="12" height="12" pre="0" post="-3" />
-    <char name="O" x="60" y="108" width="12" height="12" pre="0" post="-3" />
-    <char name="P" x="72" y="108" width="12" height="12" pre="0" post="-3" />
-    <char name="Q" x="84" y="108" width="12" height="12" pre="0" post="-2" />
-    <char name="R" x="96" y="108" width="12" height="12" pre="0" post="-3" />
-    <char name="S" x="108" y="108" width="12" height="12" pre="0" post="-3" />
-    <char name="T" x="120" y="108" width="12" height="12" pre="0" post="-1" />
-    <char name="・" x="204" y="108" width="12" height="12" pre="2" post="-6" />
-    <char name="ー" x="228" y="108" width="12" height="12" pre="0" post="-3" />
-    <char name="~" x="240" y="108" width="12" height="12" pre="0" post="1" />
-    <char name="…" x="0" y="120" width="12" height="12" pre="0" post="0" />
-    <char name="【" x="60" y="120" width="12" height="12" pre="0" post="-6" />
-    <char name="】" x="72" y="120" width="12" height="12" pre="0" post="-6" />
-    <char name="「" x="132" y="120" width="12" height="12" pre="2" post="-4" />
-    <char name="」" x="144" y="120" width="12" height="12" pre="2" post="-4" />
-    <char name="(" x="156" y="120" width="12" height="12" pre="2" post="-4" />
-    <char name=")" x="168" y="120" width="12" height="12" pre="2" post="-4" />
-    <char name="大" x="108" y="132" width="12" height="12" pre="0" post="1" />
-    <char name="爆" x="132" y="144" width="12" height="12" pre="0" post="1" />
-    <char name="使" x="144" y="144" width="12" height="12" pre="0" post="1" />
-    <char name="破" x="0" y="156" width="12" height="12" pre="0" post="1" />
-    <char name="晄" x="12" y="156" width="12" height="12" pre="0" post="1" />
-    <char name="撃" x="24" y="156" width="12" height="12" pre="0" post="1" />
-    <char name="武" x="120" y="156" width="12" height="12" pre="0" post="1" />
-    <char name="神" x="132" y="156" width="12" height="12" pre="0" post="1" />
-    <char name="風" x="168" y="156" width="12" height="12" pre="0" post="1" />
-    <char name="気" x="192" y="156" width="12" height="12" pre="0" post="1" />
-    <char name="守" x="12" y="168" width="12" height="12" pre="0" post="1" />
-    <char name="命" x="36" y="168" width="12" height="12" pre="0" post="1" />
-    <char name="動" x="60" y="168" width="12" height="12" pre="0" post="1" />
-    <char name="面" x="132" y="168" width="12" height="12" pre="0" post="1" />
-    <char name="合" x="180" y="168" width="12" height="12" pre="0" post="1" />
-    <char name="明" x="228" y="168" width="12" height="12" pre="0" post="1" />
-    <char name="抜" x="12" y="180" width="12" height="12" pre="0" post="1" />
-    <char name="一" x="108" y="180" width="12" height="12" pre="0" post="1" />
-    <char name="者" x="132" y="180" width="12" height="12" pre="0" post="1" />
-    <char name="羅" x="168" y="180" width="12" height="12" pre="0" post="1" />
-    <char name="備" x="216" y="180" width="12" height="12" pre="0" post="1" />
-    <char name="器" x="228" y="180" width="12" height="12" pre="0" post="1" />
-    <char name="魔" x="0" y="192" width="12" height="12" pre="0" post="1" />
-    <char name="法" x="12" y="192" width="12" height="12" pre="0" post="1" />
-    <char name="出" x="72" y="192" width="12" height="12" pre="0" post="1" />
-    <char name="持" x="84" y="192" width="12" height="12" pre="0" post="1" />
-    <char name="相" x="96" y="192" width="12" height="12" pre="0" post="1" />
-    <char name="手" x="108" y="192" width="12" height="12" pre="0" post="1" />
-    <char name="確" x="132" y="192" width="12" height="12" pre="0" post="1" />
-    <char name="方" x="240" y="192" width="12" height="12" pre="0" post="1" />
-    <char name="行" x="0" y="204" width="12" height="12" pre="0" post="1" />
-    <char name="定" x="24" y="204" width="12" height="12" pre="0" post="1" />
-    <char name="前" x="60" y="204" width="12" height="12" pre="0" post="1" />
-    <char name="真" x="72" y="204" width="12" height="12" pre="0" post="1" />
-    <char name="覚" x="96" y="204" width="12" height="12" pre="0" post="1" />
-    <char name="列" x="108" y="204" width="12" height="12" pre="0" post="1" />
-    <char name="後" x="120" y="204" width="12" height="12" pre="0" post="1" />
-    <char name="回" x="192" y="204" width="12" height="12" pre="0" post="1" />
-    <char name="続" x="216" y="204" width="12" height="12" pre="0" post="1" />
-    <char name="敵" x="228" y="204" width="12" height="12" pre="0" post="1" />
-    <char name="尾" x="36" y="216" width="12" height="12" pre="0" post="1" />
-    <char name="興" x="120" y="216" width="12" height="12" pre="0" post="0" />
-    <char name="弾" x="240" y="216" width="12" height="12" pre="0" post="1" />
-    <char name="時" x="36" y="228" width="12" height="12" pre="0" post="1" />
-    <char name="戦" x="72" y="228" width="12" height="12" pre="0" post="1" />
-    <char name="冷" x="144" y="228" width="12" height="12" pre="0" post="1" />
-    <char name="質" x="240" y="228" width="12" height="12" pre="0" post="1" />
-    <char name="反" x="36" y="240" width="12" height="12" pre="0" post="1" />
-    <char name="目" x="60" y="240" width="12" height="12" pre="0" post="-2" />
-    <char name="力" x="96" y="240" width="12" height="12" pre="0" post="0" />
-    <char name="兵" x="180" y="240" width="12" height="12" pre="0" post="1" />
-    <char name="花" x="280" y="0" width="12" height="12" pre="0" post="1" />
-    <char name="下" x="352" y="0" width="12" height="12" pre="0" post="1" />
-    <char name="入" x="376" y="0" width="12" height="12" pre="0" post="1" />
-    <char name="先" x="388" y="0" width="12" height="12" pre="0" post="1" />
-    <char name="不" x="400" y="0" width="12" height="12" pre="0" post="1" />
-    <char name="子" x="412" y="0" width="12" height="12" pre="0" post="1" />
-    <char name="供" x="424" y="0" width="12" height="12" pre="0" post="1" />
-    <char name="屋" x="436" y="0" width="12" height="12" pre="0" post="1" />
-    <char name="階" x="256" y="12" width="12" height="12" pre="0" post="1" />
-    <char name="部" x="292" y="12" width="12" height="12" pre="0" post="1" />
-    <char name="場" x="316" y="12" width="12" height="12" pre="0" post="1" />
-    <char name="仲" x="340" y="12" width="12" height="12" pre="0" post="1" />
-    <char name="間" x="352" y="12" width="12" height="12" pre="0" post="1" />
-    <char name="限" x="388" y="12" width="12" height="12" pre="0" post="1" />
-    <char name="何" x="472" y="12" width="12" height="12" pre="0" post="1" />
-    <char name="料" x="496" y="12" width="12" height="12" pre="0" post="1" />
-    <char name="上" x="268" y="24" width="12" height="12" pre="0" post="1" />
-    <char name="事" x="292" y="24" width="12" height="12" pre="0" post="1" />
-    <char name="奥" x="400" y="24" width="12" height="12" pre="0" post="1" />
-    <char name="初" x="448" y="24" width="12" height="12" pre="0" post="1" />
-    <char name="村" x="460" y="24" width="12" height="12" pre="0" post="1" />
-    <char name="車" x="484" y="36" width="12" height="12" pre="0" post="1" />
-    <char name="螺" x="328" y="48" width="12" height="12" pre="0" post="1" />
-    <char name="具" x="412" y="48" width="12" height="12" pre="0" post="1" />
-    <char name="状" x="304" y="60" width="12" height="12" pre="0" post="1" />
-    <char name="態" x="316" y="60" width="12" height="12" pre="0" post="1" />
-    <char name="開" x="448" y="60" width="12" height="12" pre="0" post="1" />
-    <char name="同" x="292" y="72" width="12" height="12" pre="0" post="1" />
-    <char name="速" x="304" y="72" width="12" height="12" pre="0" post="1" />
-    <char name="遅" x="316" y="72" width="12" height="12" pre="0" post="1" />
-    <char name="味" x="376" y="72" width="12" height="12" pre="0" post="1" />
-    <char name="倍" x="424" y="72" width="12" height="12" pre="0" post="1" />
-    <char name="人" x="484" y="72" width="12" height="12" pre="0" post="1" />
-    <char name="今" x="496" y="72" width="12" height="12" pre="0" post="1" />
-    <char name="当" x="280" y="84" width="12" height="12" pre="0" post="-1" />
-    <char name="飛" x="316" y="84" width="12" height="12" pre="0" post="1" />
-    <char name="以" x="328" y="84" width="12" height="12" pre="0" post="1" />
-    <char name="外" x="340" y="84" width="12" height="12" pre="0" post="1" />
-    <char name="身" x="388" y="84" width="12" height="12" pre="0" post="1" />
-    <char name="旋" x="412" y="84" width="12" height="12" pre="0" post="1" />
-    <char name="機" x="460" y="84" width="12" height="12" pre="0" post="1" />
-    <char name="械" x="472" y="84" width="12" height="12" pre="0" post="1" />
-    <char name="炉" x="496" y="84" width="12" height="12" pre="0" post="1" />
-    <char name="新" x="256" y="96" width="12" height="12" pre="0" post="1" />
-    <char name="両" x="268" y="96" width="12" height="12" pre="0" post="1" />
-    <char name="本" x="280" y="96" width="12" height="12" pre="0" post="1" />
-    <char name="君" x="292" y="96" width="12" height="12" pre="0" post="1" />
-    <char name="内" x="316" y="96" width="12" height="12" pre="0" post="1" />
-    <char name="作" x="328" y="96" width="12" height="12" pre="0" post="1" />
-    <char name="警" x="340" y="96" width="12" height="12" pre="0" post="1" />
-    <char name="特" x="352" y="96" width="12" height="12" pre="0" post="1" />
-    <char name="穴" x="400" y="96" width="12" height="12" pre="0" post="1" />
-    <char name="足" x="472" y="96" width="12" height="12" pre="0" post="1" />
-    <char name="長" x="352" y="108" width="12" height="12" pre="0" post="1" />
-    <char name="塔" x="388" y="108" width="12" height="12" pre="0" post="1" />
-    <char name="見" x="472" y="108" width="12" height="12" pre="0" post="1" />
-    <char name="元" x="304" y="120" width="12" height="12" pre="0" post="1" />
-    <char name="終" x="352" y="120" width="12" height="12" pre="0" post="1" />
-    <char name="名" x="388" y="120" width="12" height="12" pre="0" post="1" />
-    <char name="成" x="436" y="120" width="12" height="12" pre="0" post="1" />
-    <char name="記" x="280" y="132" width="12" height="12" pre="0" post="1" />
-    <char name="選" x="304" y="132" width="12" height="12" pre="0" post="1" />
-    <char name="番" x="316" y="132" width="12" height="12" pre="0" post="1" />
-    <char name="街" x="328" y="132" width="12" height="12" pre="0" post="1" />
-    <char name="墓" x="448" y="132" width="12" height="12" pre="0" post="1" />
-    <char name="心" x="460" y="132" width="12" height="12" pre="0" post="1" />
-    <char name="道" x="268" y="144" width="12" height="12" pre="0" post="1" />
-    <char name="巻" x="328" y="144" width="12" height="12" pre="0" post="1" />
-    <char name="予" x="460" y="144" width="12" height="12" pre="0" post="1" />
-    <char name="落" x="484" y="144" width="12" height="12" pre="0" post="1" />
-    <char name="日" x="328" y="156" width="12" height="12" pre="0" post="-2" />
-    <char name="口" x="436" y="156" width="12" height="12" pre="0" post="0" />
-    <char name="温" x="340" y="168" width="12" height="12" pre="0" post="1" />
-    <char name="走" x="400" y="168" width="12" height="12" pre="0" post="1" />
-    <char name="危" x="484" y="168" width="12" height="12" pre="0" post="1" />
-    <char name="言" x="304" y="180" width="12" height="12" pre="0" post="1" />
-    <char name="失" x="400" y="180" width="12" height="12" pre="0" post="1" />
-    <char name="敗" x="412" y="180" width="12" height="12" pre="0" post="1" />
-    <char name="押" x="364" y="192" width="12" height="12" pre="0" post="1" />
-    <char name="教" x="412" y="192" width="12" height="12" pre="0" post="1" />
-    <char name="参" x="328" y="204" width="12" height="12" pre="0" post="1" />
-    <char name="知" x="340" y="204" width="12" height="12" pre="0" post="1" />
-    <char name="聞" x="352" y="204" width="12" height="12" pre="0" post="1" />
-    <char name="仕" x="376" y="204" width="12" height="12" pre="0" post="1" />
-    <char name="別" x="388" y="204" width="12" height="12" pre="0" post="1" />
-    <char name="集" x="400" y="204" width="12" height="12" pre="0" post="1" />
-    <char name="信" x="412" y="204" width="12" height="12" pre="0" post="1" />
-    <char name="用" x="424" y="204" width="12" height="12" pre="0" post="1" />
-    <char name="早" x="292" y="216" width="12" height="12" pre="0" post="1" />
-    <char name="話" x="352" y="216" width="12" height="12" pre="0" post="1" />
-    <char name="帰" x="364" y="216" width="12" height="12" pre="0" post="1" />
-    <char name="売" x="424" y="216" width="12" height="12" pre="0" post="1" />
-    <char name="浮" x="436" y="216" width="12" height="12" pre="0" post="1" />
-    <char name="加" x="460" y="216" width="12" height="12" pre="0" post="1" />
-    <char name="約" x="484" y="216" width="12" height="12" pre="0" post="1" />
-    <char name="礼" x="256" y="228" width="12" height="12" pre="0" post="1" />
-    <char name="束" x="268" y="228" width="12" height="12" pre="0" post="1" />
-    <char name="男" x="292" y="228" width="12" height="12" pre="0" post="1" />
-    <char name="立" x="340" y="228" width="12" height="12" pre="0" post="1" />
-    <char name="俺" x="364" y="228" width="12" height="12" pre="0" post="1" />
-    <char name="私" x="412" y="228" width="12" height="12" pre="0" post="1" />
-    <char name="倒" x="448" y="228" width="12" height="12" pre="0" post="1" />
-    <char name="休" x="460" y="228" width="12" height="12" pre="0" post="1" />
-    <char name="助" x="256" y="240" width="12" height="12" pre="0" post="1" />
-    <char name="説" x="412" y="240" width="12" height="12" pre="0" post="1" />
-    <char name="柱" x="448" y="240" width="12" height="12" pre="0" post="1" />
-    <char name="伝" x="12" y="132" width="12" height="12" pre="0" post="1" />
-    <char name="探" x="36" y="132" width="12" height="12" pre="0" post="1" />
-    <char name="苦" x="192" y="132" width="12" height="12" pre="0" post="1" />
-    <char name="困" x="216" y="132" width="12" height="12" pre="0" post="1" />
-    <char name="客" x="24" y="144" width="12" height="12" pre="0" post="1" />
-    <char name="夫" x="144" y="144" width="12" height="12" pre="0" post="1" />
-    <char name="貸" x="228" y="144" width="12" height="12" pre="0" post="1" />
-    <char name="期" x="240" y="144" width="12" height="12" pre="0" post="1" />
-    <char name="保" x="48" y="156" width="12" height="12" pre="0" post="1" />
-    <char name="帯" x="60" y="156" width="12" height="12" pre="0" post="1" />
-    <char name="向" x="108" y="156" width="12" height="12" pre="0" post="1" />
-    <char name="襲" x="144" y="156" width="12" height="12" pre="0" post="1" />
-    <char name="次" x="168" y="156" width="12" height="12" pre="0" post="1" />
-    <char name="素" x="192" y="156" width="12" height="12" pre="0" post="1" />
-    <char name="買" x="72" y="168" width="12" height="12" pre="0" post="0" />
-    <char name="幼" x="120" y="168" width="12" height="12" pre="0" post="1" />
-    <char name="禁" x="0" y="180" width="12" height="12" pre="0" post="1" />
-    <char name="店" x="156" y="180" width="12" height="12" pre="0" post="1" />
-    <char name="緊" x="204" y="180" width="12" height="12" pre="0" post="1" />
-    <char name="研" x="216" y="180" width="12" height="12" pre="0" post="1" />
-    <char name="暇" x="0" y="192" width="12" height="12" pre="0" post="1" />
-    <char name="駅" x="84" y="192" width="12" height="12" pre="0" post="1" />
-    <char name="製" x="132" y="204" width="12" height="12" pre="0" post="1" />
-    <char name="録" x="240" y="204" width="12" height="12" pre="0" post="1" />
-    <char name="協" x="120" y="216" width="12" height="12" pre="0" post="1" />
-    <char name="脱" x="204" y="216" width="12" height="12" pre="0" post="1" />
-    <char name="躍" x="228" y="216" width="12" height="12" pre="0" post="1" />
-    <char name="到" x="36" y="228" width="12" height="12" pre="0" post="1" />
-    <char name="功" x="36" y="240" width="12" height="12" pre="0" post="1" />
-    <char name="酒" x="156" y="240" width="12" height="12" pre="0" post="1" />
-    <char name="給" x="292" y="132" width="12" height="12" pre="0" post="1" />
-    <char name="断" x="340" y="132" width="12" height="12" pre="0" post="1" />
-    <char name="油" x="376" y="132" width="12" height="12" pre="0" post="1" />
-    <char name="僕" x="400" y="132" width="12" height="12" pre="0" post="1" />
-    <char name="存" x="412" y="132" width="12" height="12" pre="0" post="1" />
-    <char name="例" x="472" y="144" width="12" height="12" pre="0" post="1" />
-    <char name="増" x="400" y="156" width="12" height="12" pre="0" post="1" />
-    <char name="貴" x="496" y="168" width="12" height="12" pre="0" post="1" />
-    <char name="噂" x="328" y="180" width="12" height="12" pre="0" post="1" />
-    <char name="壱" x="340" y="180" width="12" height="12" pre="0" post="1" />
-    <char name="侵" x="268" y="192" width="12" height="12" pre="0" post="1" />
-    <char name="謝" x="436" y="192" width="12" height="12" pre="0" post="1" />
-    <char name="価" x="484" y="192" width="12" height="12" pre="0" post="1" />
-    <char name="欠" x="496" y="192" width="12" height="12" pre="0" post="1" />
-    <char name="寄" x="256" y="204" width="12" height="12" pre="0" post="1" />
-    <char name="忙" x="268" y="204" width="12" height="12" pre="0" post="1" />
-    <char name="五" x="292" y="204" width="12" height="12" pre="0" post="1" />
-    <char name="度" x="400" y="204" width="12" height="12" pre="0" post="1" />
-    <char name="誘" x="460" y="204" width="12" height="12" pre="0" post="1" />
-    <char name="輩" x="496" y="204" width="12" height="12" pre="0" post="1" />
-    <char name="試" x="316" y="216" width="12" height="12" pre="0" post="1" />
-    <char name="牲" x="484" y="216" width="12" height="12" pre="0" post="1" />
-    <char name="秀" x="472" y="228" width="12" height="12" pre="0" post="1" />
-    <char name="軽" x="496" y="228" width="12" height="12" pre="0" post="1" />
-    <char name="刻" x="472" y="240" width="12" height="12" pre="0" post="1" />
-</font>

BIN=BIN
data/data/fonts/ffvii_menu.png


BIN=BIN
data/data/fonts/ffvii_timer.png


+ 0 - 225
doc/FFVII/1_history.html

@@ -1,225 +0,0 @@
-<html>
-    <head>
-        <link rel="stylesheet" href="style.css"/>
-    </head>
-    <body>
-        <h2>Preface</h2>
-        <p>
-            On January 31st, 1997, Final Fantasy VII was released to the
-            Japanese public. This single game both revolutionized and raised
-            the bar of Japanese style console role playing games. It success
-            was so staggering, it placed Squaresoft firmly on top the the the
-            genre, displacing the Dragon Quest series created by the rival Enix
-            company.
-        </p>
-        <p>
-            The story of how this game came to be has a story more expansive
-            than the game itself. It starts, as most stories do, with its
-            prequel.
-        </p>
-        <h2>Squaresoft and the "Big N"</h2>
-        <p>
-            In 1994, Squaresoft released Final Fantasy VI in Japan through an
-            exclusive contract with Nintendo. The game was for the Super
-            Famicom, or more internationally known as the Super Nintendo
-            Entertainment System. This game was a massive best-seller, and the
-            powers that be decided to have the game "cross the pond" as it were
-            for the U.S. audiences.
-        </p>
-        <p>
-            Sadly, as Nintendo had exclusive distribution rights to all games
-            in the United States, the decision was made to alter the game. The
-            traditional Final Fantasy logo was changed to one American
-            audiences were more used to. The sequel number was also dropped
-            from VI to III. Nintendo had only released two Final Fantasy games
-            in the states. Part I for the NES, and Part IV for the SNES (Part
-            IV was actually going to be a NES game, but was ported up in the
-            middle of it's development. That, however is another story). The
-            game was also edited for content. Several silly things like a
-            programmers room and a porno book were removed. All in all the
-            sales were modest, but it was nowhere near the success that the
-            game enjoyed in Japan.
-        </p>
-        <p>
-            It was often said that the U.S. market was not appropriate for
-            Japanese-style RPGs.
-        </p>
-        <p>
-            After the release of FF6 in the U.S., Nintendo started work on a
-            new video game system. Codenamed the "Ultra 64" it was boasting a
-            new 3D graphics core and a CD-ROM format for it's games. At the
-            time, Nintendo and Sony were working together to create the
-            "PlayStation Expansion" (PSX) CDROM system as an add-on to the
-            Super Nintendo. It was also rumored that this technology was going
-            to be in the Ultra 64 system as well.
-        </p>
-        <p>
-            Squaresoft decided that movie-like role playing games that took
-            advantage of this new multimedia technology was the future. They
-            invested billions of yen into SGI workstations when it was learned
-            that the Ultra 64 was going to use a 64 bit R4300 MIPS
-            architecture. A new threaded 3D engine was developed for the Final
-            Fantasy series. A demo of the new technology was created on their
-            new development systems. It was a simple battle engine using the
-            characters from FF6. It was assumed that this would be the
-            beginnings of FF7 for the Ultra 64.
-        </p>
-        <p>
-            Then the rug was pulled out from under Square's feet by Nintendo.
-        </p>
-        <p>
-            Nintendo and Sony had a falling out. An issue came about when both
-            companies disagreed over who got to license the games for the new
-            CD-ROM systems. Sony wanted control, but Nintendo balked. Nintendo
-            also had problems as Sony was already making the sound chip for the
-            SNES which was difficult to program for. Nintendo wanted more
-            control.
-        </p>
-        <p>
-            Nintendo went behind Sony and asked Phillips for assistance, as
-            they also could license CD-ROM technology. When Sony found out that
-            Nintendo was going to someone else, (and a foreign one at that!),
-            it was the last straw and pulled their technology. They also
-            convinced Phillips, Matsushita, NEC, and Pioneer not to license any
-            optical drive technology to Nintendo either.
-        </p>
-        <p>
-            Going alone, Sony decided to take their popular System 11 arcade
-            boards, tack on a CD-ROM and called it the Playstation.
-        </p>
-        <p>
-            Nintendo, without a drive system, quietly disclosed to their third
-            parties that the Ultra 64 was going to be cartridge based. The
-            maximum limit that any game could be was 32 megabytes. Squaresoft
-            was now in a bind, they had invested millions of yen into creating
-            a movie-like RPG experience and now had to cut it down to fit on a
-            cartridge. When it was revealed that the PSX would also be using a
-            MIPS CPU, Square abandoned Nintendo and gained an exclusive
-            distribution contract with Sony. The groundwork for Final Fantasy
-            VII was now laid and could continue unobstructed.
-        </p>
-        <h2>The Production</h2>
-        <p>
-            Halfway through the production of Final Fantasy VII, two very
-            important things happened. First a second team was spun off to
-            start production of Final Fantasy VIII. This allowed a staggered
-            development cycle were when one game one done, another would be
-            half done, cutting production time in half. Also half way through
-            production, Hironobu Sakaguchi, the producer, learned that his
-            mother Aki had died. Sakaguchi drew on this death and altered the
-            story in a radical way. It now revolved around life and death and
-            the earth.
-        </p>
-        <h2>The Release</h3>
-        <p>
-            The game was shipped to stores in Japan January 31, 1997, but not
-            without a few problems. First, the game was incomplete. A few
-            scenes were not able to run correctly before release. Also the
-            extra bosses were not added in time. These were minor issues that
-            no one missed, and were later fixed in the U.S. version.
-        </p>
-        <p>
-            In the States, a demo of FF7 was released with the game
-            "Tobal No.1". It was a modified version of the first part of the
-            game using characters not available until later. It was also the
-            first release in the states that called the game by it's proper
-            number. It was also the first time American audiences saw a true
-            Final Fantasy logo. The game was released in the the states
-            September 3rd, 1997. This release fixed several bugs, included the
-            missing bosses, and the nonworking scenes were added properly.
-        </p>
-        <p>
-            Later, Japan got a re-release of the expanded U.S. version, along
-            with a scene viewer and other bonus content. This was called "Final
-            Fantasy VII International"
-        </p>
-        <h2>The PC Port</span></h2>
-        <p>
-            With the wild success of FF7, Square's shareholders were beginning
-            to pressure the company to start diversifying their products. At
-            the time, Square was only making games exclusively for Sony, and
-            limiting their market. It also became apparent that their older
-            games were not suitable for more modern systems. Even Final Fantasy
-            VI, the game previous, was fixed to a single platform and could not
-            be adapted easily to other computer systems. Square made the choice
-            to update their old games to modern programming languages and
-            platforms. They also decided to port Final Fantasy VII to the PC.
-        </p>
-        <p>
-            Square chose Eidos of the publisher for their PC ports. At the time
-            Eidos has successfully handled the conversion and release of Core's
-            widely popular "Tomb Raider" game from the PSX to PC. Having
-            experience in marketing and distributing PSX to PC conversions, the
-            company seemed to be the right choice.
-        </p>
-        <p>
-            In the beginning, however, the PC port suffered many problems. When
-            the contract programmers received the FF7 source code from Square,
-            it was a horrible state of atrophy. When work started on the port,
-            it was soon discovered that they had received an earlier, buggy
-            version of the program. Work had to stop while Square accumulated a
-            later version. It was also discovered that the people and equipment
-            used to create the backgrounds for FF7, were now being used for FF8
-            and FF9. There was no way to re-render the backgrounds and the port
-            team was forced to use the original low color/low resolution PSX
-            dependencies. The movies faired worse. Squaresoft never rendered
-            high resolution versions of the movies. The movie format was
-            incompatible with Microsoft's DirectX system, so it was decided to
-            convert the compressed PSX movies to one more native to a PC
-            platform. This caused disastrous results. The movies were now a
-            copy of a copy of a low resolution render.
-        </p>
-        <p>
-            Square also refused to have anything added. It was to be a straight
-            port of the PSX version with the same exact interface. Concessions
-            were only made to text input. The game could run in a "high
-            resolution" mode of 640x480, which isn't really a lot in terms of
-            PC resolution. It was also limited to 15-bit color.
-        </p>
-        <p>
-            More problems arose. The PSX had the ability to use different color
-            depths on the screen at the same time. Many graphical effects
-            depended on this ability. Many PC graphic cards did not have the
-            ability to use color look up tables when placed into high color
-            modes. This caused the game to go into a low resolution software
-            renderer if this functionality wasn't available. FF7 was also
-            designed for 15 bit graphics. This caused noticeable color
-            banding on a PC screen. The sound architecture is also wildly
-            different and suffered as well.
-        </p>
-        <p>
-            The PC port was released in June of 1998. It was late, buggy, and
-            not very well ported. The game initially was incompatible with
-            Cyrix and AMD CPUs, to which Eidos technical support simply refused
-            to support at first. Many people with high-end graphic cards found
-            themselves forced into a software renderer due to a lack of a color
-            lookup system. Movies played upside down, or crashed the system all
-            together, as it used a 3rd-party renderer. The only solution Eido
-            came up with was to offer a save game past the crash point,
-            destroying hours of work by the user. Many sound cards were not
-            designed for MIDI playback and the software player used too much in
-            the way of resources, slowing the whole system. The initial
-            keyboard configuration was grossly unintuitive, using only the
-            numeric keypad. Many laptops without one couldn't even use the game
-            as you had to use the number pad to access the configuration
-            menu... and the box was ugly.
-        </p>
-        <p>
-            Eidos was dropped when Final Fantasy VIII for the PC was released.
-        </p>
-        <h2>Where are they now?</h3>
-        <p>
-            The PC port is now out of print and does not run on the Windows NT
-            type kernels due to some farflung misallocated pointers. Many now
-            play FF7 via PSX emulation. With this way of playing the game,
-            graphic modes higher than 1024x768 resolution, 32-bit color, and
-            texture filtering, can all be used. The PSX version is also stable
-            and for the most part, bug free. The engine has continued to be
-            built upon. It has also been used in other non-Final Fantasy games
-            such as "Parasite Eve", which was the first to support full body
-            textures before FF8. The PC port is still supported by a small band
-            of users. Unofficial patches have also been released with varying
-            degrees of success. Not bad for a little engine that could.
-        </p>
-    </body>
-</html>

+ 0 - 42
doc/FFVII/2_engine_basics.html

@@ -1,42 +0,0 @@
-<html>
-    <head>
-        <link rel="stylesheet" href="style.css"/>
-    </head>
-    <body>
-        <h2>The Engine Basics</h2>
-        <h3>Parts of the Engine</h3>
-        <p>
-            The engine used to power Final Fantasy 7 is split into several
-            modules. This allowed the programming team to break apart into very
-            distinct groups. It also created a very diverse game playing
-            environment. It also allowed the artists to only have to work
-            within their own module, keeping the artwork as dynamic as
-            possible.
-        </p>
-        <p>
-            The module system allowed for a single point of entry into, and
-            exit out of, each distinct part of the game. The PSX, which the
-            game was originally developed for, had very limited resources. With
-            only 1 megabyte of video ram and 2 megabytes of system ram, data
-            had to be banked in and out efficiently. Modules were a clean way
-            to dump whole parts of the engine to make way for other parts.
-        </p>
-        <p>
-            The core system is made up of six modules. They are called the
-            kernel, field, menu, world map, battle, and mini game. They are
-            arranged in the following order.
-        </p>
-        <p>
-            <img src='img/2_engine_basics.jpg'/>
-        </p>
-        <h3>Generic Program Flow</h3>
-        <p>
-            Not every module is accessible by every other module. There is a
-            distinct flow between them. For example, you can not access the
-            menu from battle, much to the chagrin of the poor user who had
-            forgotten to equip some last minute item. The field module, second
-            only to the kernel, drives the game. It includes a powerful
-            scripting system that can call any module within the game.
-        </p>
-    </body>
-</html>

+ 0 - 75
doc/FFVII/3_1_kernel_overview.html

@@ -1,75 +0,0 @@
-<html>
-    <head>
-        <link rel="stylesheet" href="style.css"/>
-    </head>
-    <body>
-        <h2>Kernel Overview</h2>
-        <h3>History</h3>
-        <p>
-            The kernel is a throwback to the very first Final Fantasy game for
-            the Nintendo's original 8 bit system. The NES could only natively
-            read 32 kilobytes of program ROM. To get around this incredible
-            limitation, Nintendo developed "memory mappers" that allowed parts
-            of the program to be switched out, or "banked" and replaced with
-            other parts stored on the game cartridge.
-        </p>
-        <p>
-            FF1 used Nintendo's "Memory Manager Controller #1" (MMC1) . This
-            controller split the game into sixteen sections, each 16 kilobytes
-            long. (The maximum an MMC1 program could be was 256K). This
-            controller also split the accessible memory from the cartridge into
-            two 16K sections. The top 16K was bankable. The bottom 16K could
-            never be switched out and stayed in memory until you removed the
-            cartridge.
-        </p>
-        <p>
-            The original FF1 kernel was located in this bottom 16K of memory.
-        </p>
-        <p>
-            First and foremost the kernel contained the main program loop. It
-            handled all the low level functions for the game. Some of these
-            included controlling interrupts, banking in and out the appropriate
-            part of the game, jumping control to a particular module, playing
-            the music, and other tasks.
-        </p>
-        <p>
-            As the Final Fantasy franchise grew, so did the size of the games.
-            They all still retained the kernel/module system. During the
-            backporting process, this did cause a few headaches. For example,
-            Final Fantasy 6 was originally developed for the Super Nintendo.
-            When it's menu module was banked in, it was done with electronic
-            bank switching. The later PSX port banked the data from the CD-ROM,
-            which caused an unexpected lag that one wasn't used to. On the PC
-            version for FF7, them menu system was simply integrated into the
-            main executable.
-        </p>
-        <h3>Kernel Functionality</h3>
-        <p>
-            The Kernel is a threaded multitasking program that manages the
-            whole system. It uses a simple software based memory manager that
-            handles both RAM and video memory for all the modules in the game.
-            Assisting the kernel are many statically linked Psy-Q libraries. In
-            the case of the PC port, the Psy-Q libs were replaced with a PC
-            equivalent. For example the SEQ player was replaced with a MIDI
-            player, Both accomplish the same tasks, just with different formats
-            and execution strategies. The table below is a generic
-            representation of how the kernel sits in relation to the other
-            aspects of the program.
-
-        </p>
-        <p>
-            <table id='kernel-functionality'>
-                <tr><td>User</td></tr>
-                <tr><td>Module</td></tr>
-                <tr>
-                    <td>
-                        Kernel
-                        <span id='kernel-psyq'>Psy-Q libraries</span>
-                    </td>
-                </tr>
-                <tr><td>PSX BIOS</td></tr>
-                <tr><td>Hardware</td></tr>
-            </table>
-        </p>
-    </body>
-</html>

+ 0 - 162
doc/FFVII/Index.html

@@ -1,162 +0,0 @@
-<html>
-    <head>
-        <link rel="stylesheet" href="style.css"/>
-    </head>
-    <body>
-        <h1>FF7</h1>
-        <p>This is a Stub article. A Wiki version of Gears should go here. For more information, select the "discussion" tab above so we can best architecture the data. For those who want to start converting, download the <a rel="nofollow" class="external text" href="https://wiki.ffrtt.ru/gears.pdf">Gears pdf</a> <a href="/index.php?title=User:Halkun" title="User:Halkun">Halkun</a> 20:18, 5 Mar 2005 (CST)
-        </p>
-        <h2>Contents</h2>
-        <ul class='no_bullet'>
-            <li><span class='index_num'>1</span> <a href="1_history.html" title="History">History</a></li>
-            <li>
-                <span class='index_num'>2</span>
-                <a href="/index.php?title=FF7/Engine_basics" title="Engine basics">Engine Basics</a>
-                <ul class='no_bullet'>
-                    <li><span class='index_num'>2.1</span> Parts of the Engine</li>
-                    <li><span class='index_num'>2.2</span> Generic Program Flow</li>
-                </ul>
-            </li>
-            <li>
-                <span class='index_num'>3</span>
-                <a href="/index.php?title=FF7/Kernel" title="Kernel">The Kernel</a>
-                <ul class='no_bullet'>
-                    <li>
-                        <span class='index_num'>3.1</span>
-                        <a href="/index.php?title=FF7/Kernel/Overview" title="Kernel/Overview">Kernel Overview</a>
-                        <ul class='no_bullet'>
-                            <li><span class='index_num'>3.1.1</span> History</li>
-                            <li><span class='index_num'>3.1.2</span> Kernel Functionality</li>
-                        </ul>
-                    </li>
-                    <li>
-                        <span class='index_num'>3.2</span>
-                        <a href="/index.php?title=FF7/Kernel/Memory_management" title="Kernel/Memory management">Memory Management</a>
-                        <ul class='no_bullet'>
-                            <li><span class='index_num'>3.2.1</span> RAM Management</li>
-                            <li><span class='index_num'>3.2.2</span> VRAM Management</li>
-                            <li><span class='index_num'>3.2.3</span> PSX CD-ROM management</li>
-                        </ul>
-                    </li>
-                    <li>
-                        <span class='index_num'>3.3</span>
-                        <a href="/index.php?title=FF7/Kernel/Kernel.bin" title="Kernel/Kernel.bin">Kernel.bin</a>
-                        <ul class='no_bullet'>
-                            <li><span class='index_num'>3.3.1</span> The KERNEL.BIN Archive</li>
-                            <li><span class='index_num'>3.3.1</span> The KERNEL2.BIN Archive</li>
-                        </ul>
-                    </li>
-                    <li>
-                        <span class='index_num'>3.4</span>
-                        <a href="/index.php?title=FF7/Kernel/Low_level_libraries" title="Kernel/Low level libraries">Low Level Libraries</a>
-                        <ul class='no_bullet'>
-                            <li><span class='index_num'>3.4.1</span> PC to PSX comparison</li>
-                            <li>
-                                <span class='index_num'>3.4.2</span> Data Archives
-                                <ul class='no_bullet'>
-                                    <li><span class='index_num'>3.4.2.1</span> BIN Archive data format</li>
-                                    <li><span class='index_num'>3.4.2.2</span> <a href="/index.php?title=FF7/LZSS_format" title="LZSS format"> LZSS Archives</a></li>
-                                    <li><span class='index_num'>3.4.2.3</span> <a href="/index.php?title=FF7/LGP_format" title="LGP format"> LGP Archives</a></li>
-                                </ul>
-                            </li>
-                            <li>
-                                <span class='index_num'>3.5</span> Textures
-                                <ul class='no_bullet'>
-                                    <li><span class='index_num'>3.5.1</span> <a href="/index.php?title=PSX/TIM_format" title="PSX/TIM format"> TIM texture data format for PSX</a></li>
-                                    <li><span class='index_num'>3.5.2</span> <a href="/index.php?title=FF7/TEX_format" title="TEX format"> TEX texture data format for the PC</a></li>
-                                </ul>
-                            </li>
-                            <li>
-                                <span class='index_num'>3.6</span>File formats for 3D models
-                                <ul class='no_bullet'>
-                                    <li><span class='index_num'>3.6.1</span> <a href="/index.php?title=FF7/Kernel/Low_level_libraries#Model_formats_for_PSX" title="Kernel/Low level libraries">Model Formats for PSX</a></li>
-                                    <li><span class='index_num'>3.6.2</span> Model Formats for PC</li>
-                                </ul>
-                            </li>
-                        </ul>
-                    </li>
-                </ul>
-            </li>
-            <li>
-                <span class='index_num'>4</span>
-                <a href="/index.php?title=FF7/Menu_Module" title="Menu Module">The Menu Module</a>
-                <ul class='no_bullet'>
-                    <li><span class='index_num'>4.1</span> Menu Overview</li>
-                    <li><span class='index_num'>4.2</span> Menu Initialization</li>
-                    <li><span class='index_num'>4.3</span> Menu Modules</li>
-                    <li><span class='index_num'>4.4</span> Calling the various menus</li>
-                    <li><span class='index_num'>4.5</span> Menu dependencies</li>
-                    <li><span class='index_num'>4.6</span> <a href="/index.php?title=FF7/Savemap" title="Savemap">The Save Game format</a></li>
-                </ul>
-            </li>
-            <li>
-                <span class='index_num'>5</span>
-                <a href="/index.php?title=FF7/Field_Module" title="Field Module"> The Field Module</a>
-                <ul class='no_bullet'>
-                    <li><span class='index_num'>5.1</span> Field Overview</li>
-                    <li>
-                        <span class='index_num'>5.2</span> Field Format (PC)
-                        <ul class='no_bullet'>
-                            <li><span class='index_num'>5.2.1</span> General PC Field File Format</li>
-                            <li><span class='index_num'>5.2.1</span> PC Field File Header</li>
-                            <li><span class='index_num'>5.2.1</span> File Section Details</li>
-                        </ul>
-                    </li>
-                    <li>
-                        <span class='index_num'>5.3</span>
-                        <a href="/index.php?title=FF7/Field_Module#Field_Format_.28PSX.29" title="Field Module">Field Format (PSX)</a>
-                        <ul class='no_bullet'>
-                            <li><span class='index_num'>5.3.1</span> <a href="/index.php?title=FF7/Field_Module#PSX_DAT_Format" title="Field Module">PSX DAT Format</a></li>
-                            <li><span class='index_num'>5.3.2</span> <a href="/index.php?title=FF7/Field_Module#PSX_MIM_Format" title="Field Module">PSX MIM Format</a></li>
-                            <li><span class='index_num'>5.3.3</span> <a href="/index.php?title=FF7/Field_Module#PSX_BSX_Format" title="Field Module">PSX BSX Format</a></li>
-                            <li><span class='index_num'>5.3.4</span> <a href="/index.php?title=FF7/Field_Module#PSX_BCX_Format" title="Field Module">PSX BCX Format</a></li>
-                        </ul>
-                    </li>
-                </ul>
-            </li>
-            <li>
-                <span class='index_num'>6</span> The Battle Module
-                <ul class='no_bullet'>
-                    <li><span class='index_num'>6.1</span> Battle Overview</li>
-                    <li><span class='index_num'>6.2</span> <a href="/index.php?title=FF7/Battle/Battle_Mechanics" title="Battle/Battle Mechanics"> Battle Mechanics</a></li>
-                    <li><span class='index_num'>6.3</span> <a href="/index.php?title=FF7/Battle/Battle_Field" title="Battle/Battle Field"> Battle Field</a></li>
-                    <li>
-                        <span class='index_num'>6.4</span>
-                        <a href="/index.php?title=FF7/Battle/Battle_Scenes" title="Battle/Battle Scenes"> Battle Scenes (scene.bin)</a>
-                        <ul class='no_bullet'>
-                            <li><span class='index_num'>6.4.1</span> <a href="/index.php?title=FF7/Battle/Battle_Scenes/Battle_Script" title="Battle/Battle Scenes/Battle Script"> Battle Scripts</a></li>
-                        </ul>
-                    </li>
-                    <li><span class='index_num'>6.5</span> <a href="/index.php?title=FF7/Playstation_Battle_Model_Format" class="mw-redirect" title="Playstation Battle Model Format"> Battle Models (PSX)</a></li>
-                    <li><span class='index_num'>6.6</span> <a href="/index.php?title=FF7/Battle/Battle_Animation_(PC)" title="Battle/Battle Animation (PC)"> Battle Animation (PC)</a></li>
-                </ul>
-            </li>
-            <li>
-                <span class='index_num'>7</span>
-                <a href="/index.php?title=FF7/WorldMap_Module" title="WorldMap Module"> The World Map Module</a>
-                <ul class='no_bullet'>
-                    <li><span class='index_num'>7.1</span> <a href="/index.php?title=FF7/World_Map/BSZ" title="World Map/BSZ"> World Map BSZ model file format (PSX)</a></li>
-                    <li><span class='index_num'>7.2</span> <a href="/index.php?title=FF7/World_Map/TXZ" title="World Map/TXZ"> World Map TXZ file format (PSX)</a></li>
-                    <li><span class='index_num'>7.3</span> <a href="/index.php?title=FF7/WorldMap_Module/Script" title="WorldMap Module/Script"> World Map Script Engine</a></li>
-                </ul>
-            </li>
-            <li>
-                <span class='index_num'>8</span> Sound
-                <ul class='no_bullet'>
-                    <li>
-                        <span class='index_num'>8.1</span>
-                        <a href="/index.php?title=FF7/PSX/PSX_Sound" title="PSX/PSX Sound">PSX Sound</a>
-                        <ul class='no_bullet'>
-                            <li><span class='index_num'>8.1.1</span> <a href="/index.php?title=FF7/PSX/Sound/Overview" title="PSX/Sound/Overview">Overview</a></li>
-                            <li><span class='index_num'>8.1.2</span> <a href="/index.php?title=FF7/PSX/Sound/INSTRx.DAT" title="PSX/Sound/INSTRx.DAT">INSTRx.DAT</a></li>
-                            <li><span class='index_num'>8.1.3</span> <a href="/index.php?title=FF7/PSX/Sound/INSTRx.ALL" title="PSX/Sound/INSTRx.ALL">INSTRx.ALL</a></li>
-                            <li><span class='index_num'>8.1.4</span> <a href="/index.php?title=FF7/PSX/Sound/AKAO_sequence" title="PSX/Sound/AKAO sequence">AKAO sequence</a></li>
-                            <li><span class='index_num'>8.1.5</span> <a href="/index.php?title=FF7/PSX/Sound/Code_Map" title="PSX/Sound/Code Map">Code Map</a></li>
-                        </ul>
-                    </li>
-                    <li><span class='index_num'>8.2</span> PC Sound</li>
-                </ul>
-            </li>
-        </ul>
-    </body>
-</html>

BIN=BIN
doc/FFVII/img/2_engine_basics.jpg


+ 0 - 47
doc/FFVII/style.css

@@ -1,47 +0,0 @@
-body{
-    background-color: #000000;
-    color: #ffffff;
-    max-width: 80em;
-    margin: auto;
-}
-
-a{
-    color: #0000ff;
-}
-
-a:hover{
-    color: #6666ff;
-}
-
-a{
-    color: #cc00ff;
-}
-
-ul.no_bullet{
-    list-style-type: none;
-}
-
-ul.no_bullet li span.index_num{
-    font-family: monospace;
-    margin-right: 8px;
-    font-size: 1.2em;
-    color: #999;
-    font-weight: bold;
-}
-
-table#kernel-functionality{
-    margin: auto;
-    border-collapse: collapse;
-}
-
-table#kernel-functionality td{
-    border: 2px solid #ffffff;
-    text-align: center;
-}
-
-table#kernel-functionality td span#kernel-psyq{
-    display: block;
-    margin: 0.5em 0.5em 0.2em 4.2em;
-    padding: 0.2em;
-    border: 2px solid #ffffff;
-}

+ 259 - 37
doc/INSTALL_DATA.md

@@ -1,84 +1,306 @@
 # <img src="../v-gears.png" alt="V-Gears" width="50"/> V-Gears Data Installation Guide
 
-## What you need
+V-Gears doesn't include any of the data of Final Fantasy VII. `v-gears-installer` reads it from your own copy of the game and converts it to the formats V-Gears uses. It can be used with a window or from the command line, and both install in the same way.
+
+## TL;DR
+
+You need the ISO image of the PC install disk, and FFmpeg and TiMidity for the audio (for example `sudo apt install ffmpeg timidity`).
+
+**With the window:** run `v-gears-installer`, select the ISO in **Final Fantasy VII ISO file**, and click **Install data**.
+
+**From the command line:**
 
-To install the Final Fantasy VII game data you need your own copy of the PC version of the game. The installer reads the **ISO image of the install disk** directly, so there is nothing to extract by hand. It extracts what it needs to `<installation directory>/original_data/` and converts it from there.
+```Bash
+v-gears-installer --iso ff7install.iso
+```
+
+Either way, everything is installed to the directory the game reads (`~/.v-gears/`, or `%USERPROFILE%\v-gears\` on Windows), and you can [run V-Gears](RUN.md "Run V-Gears") when it finishes. For the videos, run it again with each of the game disks 1, 2 and 3 (see [Extract the videos](#extract-the-videos)).
 
-If you also want the videos, you need the ISO images of the PC game disks 1, 2 and 3 (see [Extract the videos](#extract-the-videos)). The disks of the PlayStation versions are not supported.
+## Contents
 
-## FFmpeg and TiMidity
+- [What you need](#what-you-need)
+- [The installation directory](#the-installation-directory)
+- [Install with the window](#install-with-the-window)
+- [Install from the command line](#install-from-the-command-line)
+- [What can be installed](#what-can-be-installed)
+- [Options](#options)
+- [Extract the videos](#extract-the-videos)
+- [Verify an installation](#verify-an-installation)
+- [Troubleshooting](#troubleshooting)
+
+## What you need
 
-The installer converts the sound effects, the music and the videos with two external programs (the videos only need FFmpeg):
+- **The ISO image of the install disk** of the PC version of the game. The installer reads the image directly: there is nothing to extract by hand. The disks of the PlayStation versions are not supported.
+- **The ISO images of the PC game disks 1, 2 and 3**, only if you want the videos (see [Extract the videos](#extract-the-videos)).
+- **FFmpeg and TiMidity**, for the sound effects, the music and the videos (see [FFmpeg and TiMidity](#ffmpeg-and-timidity)).
+- **Free disk space:** a full installation uses about 1 GB. While installing, the installer needs about 3 GB plus the size of the ISO, and it checks that the space is there before it starts.
 
-- [FFmpeg](https://ffmpeg.org/download.html "FFmpeg") converts the sound effects, encodes the music and converts the videos.
+### FFmpeg and TiMidity
+
+The installer converts the audio and the videos with two external programs:
+
+- [FFmpeg](https://ffmpeg.org/download.html "FFmpeg") converts the sound effects, encodes the music and converts the videos. It must be able to write Ogg files (it needs the Vorbis encoder).
 - [TiMidity](https://timidity.sourceforge.net/#download "TiMidity") plays the original MIDI music so FFmpeg can encode it. Only the music needs it.
 
-The silence at the end of each music track (the reverberation that TiMidity renders after the last note) is removed when the music is encoded. The scripts that wait for a track to end, such as the jingle of the inns, would wait for it otherwise, and the files are smaller.
+In most GNU/Linux distributions both are available as packages:
+
+| Distribution | Command |
+|---|---|
+| Debian, Ubuntu | `sudo apt install ffmpeg timidity` |
+| Fedora | `sudo dnf install ffmpeg timidity++` |
+| Arch | `sudo pacman -S ffmpeg timidity++` |
+| macOS (Homebrew) | `brew install ffmpeg timidity` |
+
+On Windows, download a build of FFmpeg and copy `ffmpeg.exe` to a `tools` folder next to the installer, or in the installation directory. TiMidity++ also needs its `timidity.cfg` and the instrument files next to `timidity.exe`.
+
+The installer looks for each program in this order:
+
+1. The program you chose: with **Locate…** in the window (the choice is remembered), or with `--ffmpeg` and `--timidity` in the command line.
+2. A `tools` folder in the installation directory, then one next to the installer, then the folder of the installer itself.
+3. The system `PATH`.
+
+Every program is run once to check that it works. If one that the installation needs is missing, the installer says so before it starts, and what you would lose without it. The rest can be installed without the audio. To add it later, install the programs and run the installer again with only the sound effects and the music selected.
+
+The silence at the end of each music track (the reverberation that TiMidity renders after the last note) is removed when the music is encoded. Otherwise, the scripts that wait for a track to end, such as the jingle of the inns, would wait for the silence too.
+
+## The installation directory
 
-You don't have to configure anything if they are installed. The installer looks for them, in this order:
+The installation directory holds the configuration, the converted game data and the saves, and it is where the game runs. By default it is the one the game reads its data from:
 
-1. The program you chose with **Locate…**. The choice is remembered.
-2. A `tools` folder inside the installation directory, or next to the installer. On Windows, the easiest way is to copy `ffmpeg.exe` there.
-3. The system `PATH`. In most GNU/Linux distributions both are available as packages (for example, `sudo apt install ffmpeg timidity`).
+| System | Default directory |
+|---|---|
+| GNU/Linux, macOS | `~/.v-gears/` |
+| Windows | `%USERPROFILE%\v-gears\` |
 
-The window shows what the installer found (`Audio tools: FFmpeg ✓ … · TiMidity ✓ …`). Every program is run once to check that it works, and FFmpeg must be able to write ogg files (it needs the Vorbis encoder). On Windows, TiMidity also needs its `timidity.cfg` and the instrument files next to `timidity.exe`.
+It is created if it doesn't exist. After an installation it has:
 
-If a program that the installation needs is missing, the installer tells you before it starts. The message says what you would lose, and you can:
+| Path | What it is |
+|---|---|
+| `plugins.cfg`, `resources.cfg` | The configuration of V-Gears and Ogre. |
+| `data/` | The game data: the V-Gears files (scripts, screens, fonts...) and the converted game data. |
+| `data/config/config.cfg` | The configuration of the game (controls, options). An installation never replaces it if it exists. |
+| `data/video/` | The videos, if you extracted them. |
+| `save/` | The saved games, written by the game. |
+| `temp/world_models/` | World map data that the game reads. |
+| `install.info` | The record of the installations: the parts installed, with which version of the installer, and whether the last installation finished. See [Verify an installation](#verify-an-installation). |
+| `installer.log` | The log of the last installation. |
+| `install.log` | The log of Ogre during the last installation. |
 
-- **Locate…** the program in your system.
-- **Get it…**: open its download page.
-- **Check again**, for when you have just installed it.
-- **Continue without** it. The rest is installed normally, and the sound effects, the music, the videos, or any of them, are left out. The extracted `.wav` and `.mid` files stay in `~/.v-gears/data/audio/`, and the indexes only list the files that exist.
-- **Cancel** the installation.
+During the installation the installer also extracts the install disk to `original_data/`, and writes temporary files to `temp/`. They are deleted at the end, unless you keep them with [Preserve original data](#preserve-original-data).
 
-To add the missing audio later, install the programs and run the installer again with only the sound effects and the music selected (the *Media only* option, or *Custom*).
+## Install with the window
 
-## Launch the Installer
+Start the installer without arguments:
 
 ```Bash
 ~/V-Gears/build/bin/v-gears-installer
 ```
 
-It can be started from any directory. When the installation starts, it works from the installation directory.
+It can be started from any directory.
 
-## Run the Installer
-
-1. In **Import data source**, select the ISO image of the install disk. The installer tells you if the image is valid.
-2. In **VGears installation directory**, select where to install, for example `~/.v-gears/`. It will be created if it doesn't exist. It holds the configuration and the converted data, and it is where the game runs.
-3. (Optional) Select **Show advanced options** to choose what to install (see below). The defaults install everything. If the directory doesn't have the V-Gears files yet (configuration, scripts, screens, fonts...), leave **Copy V-Gears data files** checked, and the installer copies them there from the `data/` folder of the repository (`share/v-gears/` in an installed package). The engine also copies them by itself the first time it runs.
+1. In **Final Fantasy VII ISO file**, select the ISO image of the install disk. The installer tells you if the image is valid and supported.
+2. In **VGears installation directory**, select where to install (see [The installation directory](#the-installation-directory)). The installer remembers it.
+3. Optionally, select **Show advanced options** to choose what to install and how (see [What can be installed](#what-can-be-installed) and [Options](#options)). The defaults install everything, and the estimate under the options shows about how much disk space it will use.
 4. Click **Install data**.
 
-Before extracting anything, the installer checks that everything is in place: that the ISO is valid, that the directory is writable and has enough free space (about 3 GB plus the size of the ISO), and that the FFmpeg and TiMidity programs it needs can be used (see below). If something is wrong it tells you and doesn't start.
+The **Audio tools** line shows whether FFmpeg and TiMidity were found, with a **Locate…** link for each.
 
-The log shows the progress. Problems are shown in color (red for errors, orange for warnings), and the full log is written to `installer.log` in the installation directory. Don't be discouraged by some warnings about skipped fields or models, they are known limitations of the converter. The installation is finished when the progress bar reaches 100% and the window can be closed again.
+Before extracting anything, the installer checks that everything is in place: that the ISO is valid, that the directory is writable and has enough free space, that the V-Gears data files and the Ogre plugins can be found, and that the audio tools work. If something is wrong, it tells you what and doesn't start.
 
-An installation can only be done once per installer window. To install again, close the installer and open it again. The estimate under the options shows about how much disk space it will use.
+The progress bar and the log show how the installation goes. Problems are shown in color: red for errors, orange for warnings. Some warnings about skipped fields or models are expected: they are known limitations of the converter. The installation is finished when the bar reaches 100%.
 
 When it finishes:
 
-- **Verify install** checks that the installation directory has everything the game needs, and lists what is missing, grouped by part. If you skipped a part on purpose, its files are expected to be missing.
+- **Verify install** checks that the directory has everything the game needs (see [Verify an installation](#verify-an-installation)).
 - **Launch game** starts V-Gears from the installation directory.
 
+You can install again, or extract the videos of another disk, without closing the window.
+
+## Install from the command line
+
+Any installation option makes the installer work from the command line, without its window. The simplest installation installs everything to the default directory:
+
+```Bash
+v-gears-installer --iso ff7install.iso
+```
+
+The command line installer doesn't need a display, so it can be used over SSH, in a container or in a script. In a terminal it shows a progress bar with what it is doing, and writes the warnings (in orange) and the errors (in red) above it. When the output goes to a file or a pipe, it writes a line for each percent and every message, without colors. Set `NO_COLOR` to turn the colors off in a terminal too.
+
+When it finishes, it writes the number of errors and warnings, the first errors, and where the full log is.
+
+### Examples
+
+```Bash
+# Everything, to another directory.
+v-gears-installer --iso ff7install.iso --output ~/games/v-gears
+
+# Only the field maps and their models (and the kernel data they need).
+v-gears-installer --iso ff7install.iso --preset fields
+
+# The battle data, plus the music.
+v-gears-installer --iso ff7install.iso --preset battle --with music
+
+# Everything except the music.
+v-gears-installer --iso ff7install.iso --without music
+
+# Only some parts.
+v-gears-installer --iso ff7install.iso --preset custom --with kernel,fields,field-models
+
+# Start again from nothing, and don't stop on warnings (for scripts).
+v-gears-installer --iso ff7install.iso --clean --yes
+
+# Add the videos of a game disk to an installation.
+v-gears-installer --iso FF7DISC1.iso
+
+# Check an installation.
+v-gears-installer --verify --output ~/games/v-gears
+```
+
+### Arguments
+
+| Argument | What it does |
+|---|---|
+| `-i`, `--iso <file>` | The disk image. The install disk installs the game; game disks 1, 2 and 3 only add their videos to an installation. |
+| `-o`, `--output <dir>` | The installation directory. Default: the one the game reads (see [The installation directory](#the-installation-directory)). |
+| `-p`, `--preset <name>` | What to install: `everything` (the default), `fields`, `world-map`, `battle`, `media` or `custom`. `custom` starts with nothing. See [Presets](#presets). |
+| `--with <parts>` | Install these parts too, separated by commas. See [Parts](#parts). |
+| `--without <parts>` | Don't install these parts, separated by commas. The parts that need them are left out too. |
+| `--clean` | Delete the data of a previous installation first. See [Clean install](#clean-install). |
+| `--keep-originals` | Keep the extracted disk, the temporary files and the original audio and images. See [Preserve original data](#preserve-original-data). |
+| `--no-copy-data` | Don't copy the V-Gears data files. See [Copy V-Gears data files](#copy-v-gears-data-files). |
+| `--data-dir <dir>` | The V-Gears `data` folder to copy. Default: looked for next to the installer and in the system. |
+| `--ffmpeg <file>` | Path to FFmpeg. Default: looked for as explained in [FFmpeg and TiMidity](#ffmpeg-and-timidity). |
+| `--timidity <file>` | Path to TiMidity. Looked for like FFmpeg. |
+| `-y`, `--yes` | Continue when there are warnings or the audio tools are missing. Without it, the installer stops where the window would ask. |
+| `--strict` | End with exit status 3 if the installation finished with errors in its log. Useful in scripts that must not accept a partial installation. |
+| `--verify` | Check an installation instead of installing. See [Verify an installation](#verify-an-installation). |
+| `--list-parts` | List the parts that can be installed. |
+| `--cli` | Use the command line, not the window. Any of the options above already implies it. |
+| `-h`, `--help` | Show the usage. |
+| `-v`, `--version` | Show the version. |
+
+`--option=value` works too, for example `--preset=fields`.
+
+The window and the command line don't share settings: the command line doesn't use the FFmpeg and TiMidity programs you chose with **Locate…** in the window.
+
+### Exit status
+
+| Status | Meaning |
+|---|---|
+| `0` | The installation, the extraction or the verification went well. An installation that finished with some errors in its log still returns 0, unless `--strict` is given. |
+| `1` | It failed, or it stopped because of a warning or a missing audio tool (use `--yes` to continue anyway), or the verification found something missing. |
+| `2` | The command line is wrong. |
+| `3` | With `--strict`: the installation finished, but there are errors in its log. |
+| `130` | The installation was interrupted (Ctrl+C). The installation directory is incomplete until you install again. |
+
+## What can be installed
+
+### Parts
+
+| Window option | Command line part | What it is | Needs |
+|---|---|---|---|
+| Extract game data | `kernel` | The kernel data: items, materia, characters, the initial savemap, the fonts. | |
+| Extract field maps | `fields` | The field maps, their scripts, backgrounds and texts. | |
+| Extract field 3D models | `field-models` | The models of the characters in the fields. | `fields` |
+| Extract world map data | `world-map` | The world map. | the field maps, installed now or before |
+| Extract world map 3D models | `world-map-models` | The models of the world map. | `world-map` |
+| Extract battle data | `battle-data` | The battle scenes, enemies, formations, attacks and encounters. | |
+| Extract battle models | `battle-models` | The battle models and animations, and the spell effects. | |
+| Extract images | `images` | The images of the menus and the windows. | |
+| Extract sound effects | `sounds` | The sound effects. | FFmpeg |
+| Extract music tracks | `music` | The music. | FFmpeg and TiMidity |
+| Extract videos | `videos` | The videos. They are not on the install disk: see [Extract the videos](#extract-the-videos). | FFmpeg |
+
+A part can't be chosen without what it needs. In the window its option is disabled, and in the command line `--with field-models` alone is an error. When a part is removed, the parts that need it are removed too.
+
+### Presets
+
+| Window | Command line | Parts |
+|---|---|---|
+| Everything | `everything` | All of them. |
+| Field maps and models | `fields` | `kernel`, `fields`, `field-models` |
+| World map only | `world-map` | `world-map`, `world-map-models` |
+| Battle data and models | `battle` | `kernel`, `battle-data`, `battle-models` |
+| Media only (images, sounds, music, videos) | `media` | `images`, `sounds`, `music` |
+| Custom | `custom` | None: choose them yourself. |
+
+In the window the options can only be changed by hand with *Custom*. In the command line, `--with` and `--without` change any preset. For a later installation it's useful to install only what you need, for example only the fields, which is a few minutes faster.
+
+The world map scripts need the field maps. To install only the world map, install the fields first, or together with it.
+
+## Options
+
+### Copy V-Gears data files
+
+Window: **Copy V-Gears data files** (on by default). Command line: on unless `--no-copy-data`.
+
+Copies the files that come with V-Gears (configuration, scripts, screens, fonts...) to the installation directory. They are taken from the `data/` folder of the repository, or `share/v-gears/` in an installed package. In the command line, `--data-dir` chooses another folder.
+
+The game configuration (`data/config/config.cfg`) is only copied if the installation doesn't have it yet, so your settings are kept. Without this option, the installation directory must already have the V-Gears files.
+
+### Clean install
+
+Window: **Clean install** (off by default). Command line: `--clean`.
+
+Before installing, deletes what a previous installation wrote: the converted game data in `data/`, the temporary files in `temp/` and the extracted disk in `original_data/`. A new installation then starts from nothing, without old files of parts you don't install this time.
+
+It keeps:
+
+- The saved games (`save/`).
+- The controls (`controls.cfg`), the configuration of the game (`data/config/`) and the rest of the files in the root of the installation directory, such as `plugins.cfg` and the logs.
+- The videos (`data/video/`), because they come from the game disks and the install disk can't put them back.
+
+It needs **Copy V-Gears data files**, because the V-Gears files in `data/` are deleted too. It only deletes in a directory that is a V-Gears installation (it has `plugins.cfg` and `resources.cfg`). The window asks before deleting anything.
+
+### Preserve original data
+
+Window: **Preserve original data** (off by default). Command line: `--keep-originals`.
+
+To convert the game, the installer extracts the install disk and some original files: the WAV sound effects, the MIDI music, the TEX images and the temporary files of the models. V-Gears doesn't use them, so they are deleted when the installation is complete. This option keeps them, for example to study the original files. It uses about 1 GB more.
+
+The temporary files of the world map (`temp/world_models/`) are always kept, because the game reads them.
+
 ## Extract the videos
 
-The videos are not on the install disk, but on the PC game disks 1, 2 and 3. To get them, run the installer once for each disk: select the disk's ISO as the data source and the same installation directory, and click 'Install data'. The installer detects a game disk, extracts only its videos to `<installation directory>/data/video/` and doesn't touch anything else. Several disks have the same videos, so those already installed are skipped. Unlike the full installation, it can be repeated with the same installer window.
+The videos are not on the install disk, but on the PC game disks 1, 2 and 3. To get them, run the installer once for each disk, with the same installation directory:
+
+- In the window, select the disk's ISO and click **Install data**.
+- In the command line, run `v-gears-installer --iso FF7DISC1.iso` (and the same for the other two disks).
 
-The engine can't decode the original AVI files (Duck TrueMotion 2 codec), so the installer uses FFmpeg to convert each video to a folder of JPEG frames, an `.ogg` sound track (if the video has sound) and a `movie.xml` with the frame count and frame rate. Movies that carry camera data for the field background also get a `camera.cam` file. They are played by the engine's movie player, which draws the frames and plays the sound. FFmpeg is therefore needed to install the videos.
+The installer detects a game disk, extracts only its videos to `data/video/` and doesn't touch anything else. Several disks have the same videos, so those already installed are skipped. The options don't apply to a game disk, and `--clean` can't be used with one.
+
+The engine can't decode the original AVI files (Duck TrueMotion 2 codec), so the installer uses FFmpeg to convert each video to a folder of JPEG frames, an `.ogg` sound track (if the video has sound) and a `movie.xml` with the frame count and the frame rate. The videos that carry camera data for the field background also get a `camera.cam` file. The engine's movie player draws the frames and plays the sound. FFmpeg is therefore needed to install the videos.
 
 <!-- TODO(review): confirm the exact output layout under data/video/ (folder per movie, file names) after a fresh install, and which movies play in game. -->
 
 ## Battle data
 
-The battle installation extracts the battle scenes, enemy and formation data, the attacks, the field and world map encounter tables, and the battle models and animations. It also extracts the visual assets of the spell effects (`magic.lgp`): the meshes and textures of the effects and the sprite lists, which the battle scripts use to recreate the original spell effects. If you installed before these were added, run the installer again with the battle options selected (*Battle* preset or *Custom*) to get them.
+The battle installation extracts the battle scenes, the enemy and formation data, the attacks, the field and world map encounter tables, and the battle models and animations. It also extracts the visual assets of the spell effects (`magic.lgp`): the meshes and textures of the effects and the sprite lists, which the battle scripts use to recreate the original spell effects. If you installed before these were added, run the installer again with the battle parts selected (the *Battle data and models* preset, or `--preset battle`) to get them.
 
 <!-- TODO(review): list of spells with effects (currently the Fire, Ice, Bolt and Cure families) and the reinstall requirement should be re-checked against the current state of battle_fx.lua. -->
 
-## Advanced options
+## Verify an installation
+
+**Verify install** in the window, or `v-gears-installer --verify` in the command line (with `--output` for a directory other than the default), checks that the installation directory has everything the game needs. It lists what is missing, grouped by part.
+
+It only checks that the files exist, it doesn't open them. If you skipped a part on purpose (for example the music), its files are expected to be missing. The Ogre plugins listed in `plugins.cfg` are looked for where the game looks for them: the installation directory, the directory of the game, and the Ogre directories of the system.
+
+It also reads `install.info`, the record that the installer keeps of the installations, and reports:
+
+- An installation that didn't finish, because it was interrupted (Ctrl+C, closing the window) or it failed.
+- The parts that were converted by an older installer: when a new version of the installer converts something differently, the parts installed before have to be installed again. Installing only those parts is enough.
+- An installation without a record, made before the installer kept one. Its data may be outdated.
+
+The game checks the same record when it starts, and writes a warning if the data has to be installed again.
 
-The installer has a list of advanced options, under **Show advanced options**. They have tooltips with short explanations of what they do. For a fresh installation there is usually no need to change them: the *Everything* option installs it all.
+## Troubleshooting
 
-*What to install* has ready-made sets of options. Choose *Custom* to pick them one by one. For later installations it's useful to choose only what you need (for example, only the fields), which shortens the installation by a few minutes.
+- **The installation can't start.** The installer lists what is wrong. The most common problems are an ISO that isn't the PC install disk, a directory without enough free space, and missing Ogre plugins.
+- **The sounds or the music are missing.** FFmpeg or TiMidity were not found or didn't work. Install them and run the installer again with only the sound effects and the music.
+- **Warnings and errors in the log.** Some fields and models are skipped by known limitations of the converter, and some original files are dummies. A few dozen warnings and errors are normal. The full log is in `installer.log`, and the log of Ogre in `install.log`.
+- **Old or wrong files after reinstalling.** Install again with **Clean install** (`--clean`).
+- **The game says the data must be installed again.** The last installation didn't finish, or some parts were installed by an older installer. Run `v-gears-installer --verify` to see which, and install them again.
 
 ## Next steps
 
-- [Run V-Gears](RUN.md "Run V-Gears")
+- [Run V-Gears](RUN.md "Run V-Gears")

+ 9 - 0
doc/TODO.md

@@ -130,3 +130,12 @@ remembers of the original). Not done:
 - The records 38 and 39 also have a Warship scene in `world_function_64`; it is not known which fields lead to them and they
   were not tested. The last move of record 37 (direction 176, facing 48) is a plain move without turning.
 - The vehicles may run at 15 frames per second as well (their speeds were tuned by eye).
+
+## Fonts: possible improvements
+
+The fonts are built by the installer from WINDOW.BIN (see `WindowFonts`) and drawn as a texture atlas: the PNG is loaded once, each letter is a quad with its cell as texture coordinates, and the geometry is only rebuilt when the text or the position changes. Converting the fonts to TTF was considered and discarded: an engine that loads TTF files rasterizes them into the same kind of atlas, the FF7 font is a two colour pixel font (glyph and shadow) that an outline format can't keep, and the installer would need a font writing library. Possible improvements, not planned yet:
+
+- `UiFont::GetCharData` searches the list of characters for every letter each time the geometry is rebuilt. An array indexed by the character code would make it a direct lookup.
+- The PC version has a font twice the resolution (24x24 cells) in `usfont_a_h.tex` and `usfont_b_h.tex` of menu_us.lgp, split in two textures. The installer could merge them in one image and write the XML for it, for sharper text at high resolutions.
+- The installer could write `ffvii_en.xml` from the width table in WINDOW.BIN (third file, one byte per character: 3 bits of lead, 5 bits of width) instead of keeping it by hand. The XML in the repository matches the table except for `! " , . : ?`, which were made tighter by hand.
+- Loading TTF files makes sense only to support fonts made by users, not for the fonts of the game.

+ 1 - 0
src/CMakeLists.txt

@@ -594,6 +594,7 @@ set(VGEARS_SOURCE_FILES
     common/LzsFile.cpp
     common/TypeDefine.cpp
     common/DataDirectory.cpp
+    common/InstallStamp.cpp
     common/OgrePlugins.cpp
     common/VGearsApplication.cpp
     common/VGearsManualObject.cpp

+ 35 - 35
src/common/File.cpp

@@ -17,72 +17,72 @@
 #include <string.h>
 #include "common/File.h"
 #include "common/FileSystem.h"
+#include <algorithm>
+#include <cstring>
 #include "core/Logger.h"
 
-File::File(const Ogre::String& file):
-  file_name_(file),
-  buffer_(nullptr),
-  buffer_size_(0),
-  offset_(0)
-{
+File::File(){}
+
+File::File(const Ogre::String& file): file_name_(file){
     LOG_TRIVIAL("Loading file: " + file_name_ + "\n");
-    buffer_size_ = FileSystem::GetFileSize(file_name_);
-    buffer_ = static_cast<u8*>(malloc(sizeof(u8) * buffer_size_));
-    if (!FileSystem::ReadFile(file_name_, buffer_, 0, buffer_size_))
+    // Zeroed, so a file that can't be read is empty data, not whatever was in memory.
+    buffer_.assign(FileSystem::GetFileSize(file_name_), 0);
+    if (!buffer_.empty() && !FileSystem::ReadFile(file_name_, buffer_.data(), 0, buffer_.size()))
         LOG_TRIVIAL("Warning: " + file_name_ + " not found!\n");
 }
 
-File::File(const File* file, u32 offset, u32 length):
-  buffer_(nullptr), buffer_size_(length), offset_(offset)
-{
+File::File(const File* file, u32 offset, u32 length){
     assert(file != nullptr);
     file_name_ = file->GetFileName();
-    buffer_ = static_cast<u8*>(malloc(sizeof(u8) * buffer_size_));
-    file->GetFileBuffer(buffer_, offset_, buffer_size_);
+    // The fragment is a file of its own: it is read from its start.
+    buffer_.assign(length, 0);
+    if (length > 0) file->GetFileBuffer(buffer_.data(), offset, length);
 }
 
-File::File(const u8* buffer, u32 offset, u32 length):
-  file_name_("BUFFER"), buffer_(nullptr), buffer_size_(length), offset_(offset)
-{
+File::File(const u8* buffer, u32 offset, u32 length): file_name_("BUFFER"){
     assert(buffer != nullptr);
-    buffer_ = static_cast<u8*>(malloc(sizeof(u8) * buffer_size_));
-    memcpy(buffer_, buffer + offset, buffer_size_);
+    buffer_.assign(buffer + offset, buffer + offset + length);
 }
 
 File::File(const File* file){
     assert(file != nullptr);
-    buffer_size_ = file->GetFileSize();
-    file_name_   = file->GetFileName();
-    buffer_ = static_cast<u8*>(malloc(sizeof(u8) * buffer_size_));
-    file->GetFileBuffer(buffer_, 0, buffer_size_);
+    file_name_ = file->GetFileName();
+    buffer_ = file->buffer_;
 }
 
-File::~File(){/*free(buffer_);*/}
+File::~File(){}
 
 void File::WriteFile(const Ogre::String& file) const{
-    FileSystem::WriteNewFile(file, buffer_, buffer_size_);
+    FileSystem::WriteNewFile(file, buffer_.data(), static_cast<u32>(buffer_.size()));
 }
 
 const Ogre::String& File::GetFileName() const{return file_name_;}
 
-u32 File::GetFileSize() const{return buffer_size_;}
+u32 File::GetFileSize() const{return static_cast<u32>(buffer_.size());}
 
 void File::GetFileBuffer(u8* buffer, const u32 &start, const u32 &length) const{
-    memcpy(buffer, buffer_ + start, length);
+    // What is past the end of the file is read as zeros.
+    const u32 size = GetFileSize();
+    const u32 available = start < size ? std::min(length, size - start) : 0;
+    if (available > 0) memcpy(buffer, buffer_.data() + start, available);
+    if (available < length) memset(buffer + available, 0, length - available);
 }
 
-u8 File::GetU8(u32 offset) const{return *(buffer_ + offset);}
+// Many of the original files are read past their end by the parsers (truncated animations, headers of the
+// last entry of an archive...). Those bytes are read as zeros, instead of whatever is in memory after the file.
+
+u8 File::GetU8(u32 offset) const{return offset < buffer_.size() ? buffer_[offset] : 0;}
 
 u16 File::GetU16LE(u32 offset) const{
-    return (buffer_ + offset)[0] | ((buffer_ + offset)[1] << 8);
+    return GetU8(offset) | (GetU8(offset + 1) << 8);
 }
 
 u32 File::GetU32LE(u32 offset) const{
     return
-      (buffer_ + offset)[0]
-      | ((buffer_ + offset)[1] << 8)
-      | ((buffer_ + offset)[2] << 16)
-      | ((buffer_ + offset)[3] << 24);
+      static_cast<u32>(GetU8(offset))
+      | (static_cast<u32>(GetU8(offset + 1)) << 8)
+      | (static_cast<u32>(GetU8(offset + 2)) << 16)
+      | (static_cast<u32>(GetU8(offset + 3)) << 24);
 }
 
 u8 File::readU8(){
@@ -106,6 +106,6 @@ u32 File::readU32LE(){
 u32 File::GetCurrentOffset(){return offset_;}
 
 void File::SetOffset(u32 offset){
-    if (offset < buffer_size_) offset_ = offset;
-    else offset_ = buffer_size_ - 1;
+    if (offset < buffer_.size()) offset_ = offset;
+    else offset_ = buffer_.empty() ? 0 : GetFileSize() - 1;
 }

+ 31 - 18
src/common/File.h

@@ -15,6 +15,7 @@
 
 #pragma once
 
+#include <vector>
 #include <OgreString.h>
 #include "common/TypeDefine.h"
 
@@ -25,6 +26,11 @@ class File{
 
     public:
 
+        /**
+         * Creates an empty file.
+         */
+        File();
+
         /**
          * Opens a file.
          *
@@ -37,7 +43,7 @@ class File{
          *
          * @param[in] file Pointer to the file.
          */
-        File(const File* file);
+        explicit File(const File* file);
 
         /**
          * Loads a file fragment.
@@ -62,6 +68,26 @@ class File{
          */
         virtual ~File();
 
+        /**
+         * Copies a file, with its own copy of the data.
+         */
+        File(const File& file) = default;
+
+        /**
+         * Moves a file.
+         */
+        File(File&& file) = default;
+
+        /**
+         * Copies a file, with its own copy of the data.
+         */
+        File& operator=(const File& file) = default;
+
+        /**
+         * Moves a file.
+         */
+        File& operator=(File&& file) = default;
+
         /**
          * Writes the contents of the buffer to a file.
          *
@@ -149,10 +175,7 @@ class File{
         /**
          * Checks the current offset of the file.
          *
-         * Default is 0. Can be set on instantiation with {@see
-         * File(const File* file, u32 offset, u32 length)} or {@see
-         * File(const u8* buffer, u32 offset, u32 length)} and advanced with
-         * {@see readU8}, {@see readU16LE} or {@see readU32LE}
+         * Default is 0. It is advanced with {@see readU8}, {@see readU16LE} or {@see readU32LE}.
          */
         u32 GetCurrentOffset();
 
@@ -176,22 +199,12 @@ class File{
         /**
          * Current offset of the file.
          *
-         * Default is 0. Can be set on instantiation with {@see
-         * File(const File* file, u32 offset, u32 length)} or {@see
-         * File(const u8* buffer, u32 offset, u32 length)} and advanced with
-         * {@see readU8}, {@see readU16LE} or {@see readU32LE}
+         * Default is 0. It is advanced with {@see readU8}, {@see readU16LE} or {@see readU32LE}.
          */
         u32 offset_ = 0;
 
         /**
-         * The file buffer.
-         *
-         * It contains the file data.
-         */
-        u8* buffer_;
-
-        /**
-         * The allocated size of {@see buffer_}.
+         * The file data. Each file has its own copy, freed with the file.
          */
-        u32 buffer_size_;
+        std::vector<u8> buffer_;
 };

+ 169 - 0
src/common/InstallStamp.cpp

@@ -0,0 +1,169 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <algorithm>
+#include <ctime>
+#include <fstream>
+#include <set>
+#include <sstream>
+#include "common/InstallStamp.h"
+
+namespace VGears{
+
+    namespace InstallStamp{
+
+        namespace bfs = boost::filesystem;
+
+        const char* const FILE_NAME = "install.info";
+
+        namespace{
+
+            /**
+             * Joins a list with commas.
+             */
+            std::string Join(const std::vector<std::string>& items){
+                std::string joined;
+                for (const std::string& item : items) joined += (joined.empty() ? "" : ",") + item;
+                return joined;
+            }
+
+            /**
+             * Splits a list separated by commas, skipping empty items.
+             */
+            std::vector<std::string> Split(const std::string& list){
+                std::vector<std::string> items;
+                std::stringstream stream(list);
+                std::string item;
+                while (std::getline(stream, item, ',')) if (!item.empty()) items.push_back(item);
+                return items;
+            }
+
+            /**
+             * Removes the spaces at both ends.
+             */
+            std::string Trim(std::string text){
+                const auto space = [](unsigned char c){return std::isspace(c) != 0;};
+                while (!text.empty() && space(text.back())) text.pop_back();
+                while (!text.empty() && space(text.front())) text.erase(0, 1);
+                return text;
+            }
+        }
+
+        bool Read(const bfs::path& directory, Stamp& stamp){
+            stamp = Stamp();
+            std::ifstream file((directory / FILE_NAME).string());
+            if (!file.is_open()) return false;
+            std::string line;
+            while (std::getline(file, line)){
+                line = Trim(line);
+                if (line.empty() || line[0] == '#') continue;
+                const size_t equal = line.find('=');
+                if (equal == std::string::npos) continue;
+                const std::string key = Trim(line.substr(0, equal));
+                const std::string value = Trim(line.substr(equal + 1));
+                if (key == "complete") stamp.complete = value == "1";
+                else if (key == "installer") stamp.installer = value;
+                else if (key == "date") stamp.date = value;
+                else if (key == "disk") stamp.disk = value;
+                else if (key == "installing") stamp.installing = Split(value);
+                else if (key.compare(0, 5, "part.") == 0 && key.size() > 5){
+                    int version = 0;
+                    try{version = std::stoi(value);}
+                    catch (...){version = 0;}
+                    stamp.parts[key.substr(5)] = version;
+                }
+            }
+            return true;
+        }
+
+        bool Write(const bfs::path& directory, const Stamp& stamp){
+            std::ofstream file((directory / FILE_NAME).string(), std::ios::out | std::ios::trunc);
+            if (!file.is_open()) return false;
+            file << "# Record of the installations of the game data, written by v-gears-installer.\n"
+                 << "# The game and the verifier read it to know if the data must be installed again.\n"
+                 << "complete=" << (stamp.complete ? 1 : 0) << "\n"
+                 << "installer=" << stamp.installer << "\n"
+                 << "date=" << stamp.date << "\n"
+                 << "disk=" << stamp.disk << "\n";
+            if (!stamp.installing.empty()) file << "installing=" << Join(stamp.installing) << "\n";
+            for (const auto& part : stamp.parts) file << "part." << part.first << "=" << part.second << "\n";
+            return static_cast<bool>(file);
+        }
+
+        void Start(
+          Stamp& stamp, const std::vector<std::string>& parts, const std::string& installer,
+          const std::string& date, const std::string& disk
+        ){
+            // The parts of an installation that didn't finish, and are not installed again now, are not usable.
+            if (!stamp.complete){
+                for (const std::string& part : stamp.installing){
+                    if (std::find(parts.begin(), parts.end(), part) == parts.end()) stamp.parts[part] = 0;
+                }
+            }
+            stamp.complete = false;
+            stamp.installing = parts;
+            stamp.installer = installer;
+            stamp.date = date;
+            stamp.disk = disk;
+        }
+
+        void Finish(Stamp& stamp){
+            for (const std::string& part : stamp.installing) stamp.parts[part] = DATA_VERSION;
+            stamp.installing.clear();
+            stamp.complete = true;
+        }
+
+        std::vector<std::string> Outdated(const Stamp& stamp){
+            std::set<std::string> outdated;
+            for (const auto& part : stamp.parts) if (part.second < DATA_VERSION) outdated.insert(part.first);
+            if (!stamp.complete) outdated.insert(stamp.installing.begin(), stamp.installing.end());
+            return std::vector<std::string>(outdated.begin(), outdated.end());
+        }
+
+        std::vector<std::string> Problems(const bfs::path& directory, bool* found){
+            std::vector<std::string> problems;
+            Stamp stamp;
+            const bool read = Read(directory, stamp);
+            if (found != nullptr) *found = read;
+            if (!read) return problems;
+            if (!stamp.complete){
+                problems.push_back(
+                  "The last installation (" + stamp.date + ") didn't finish: it was interrupted or it failed. "
+                  "Install the data again."
+                );
+            }
+            std::vector<std::string> old;
+            for (const auto& part : stamp.parts){
+                const bool interrupted = std::find(stamp.installing.begin(), stamp.installing.end(), part.first)
+                  != stamp.installing.end();
+                if (part.second < DATA_VERSION && !(interrupted && !stamp.complete)) old.push_back(part.first);
+            }
+            if (!old.empty()){
+                problems.push_back(
+                  "These parts were installed by an older installer, or their installation didn't finish, and must be "
+                  "installed again: " + Join(old) + "."
+                );
+            }
+            return problems;
+        }
+
+        std::string Now(){
+            const std::time_t now = std::time(nullptr);
+            char text[32];
+            std::strftime(text, sizeof(text), "%Y-%m-%d %H:%M:%S", std::localtime(&now));
+            return text;
+        }
+    }
+}

+ 150 - 0
src/common/InstallStamp.h

@@ -0,0 +1,150 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#pragma once
+
+#include <map>
+#include <string>
+#include <vector>
+#include <boost/filesystem.hpp>
+
+namespace VGears{
+
+    /**
+     * The record of the installations of the game data in a directory (install.info).
+     *
+     * The installer writes it when an installation starts, as unfinished, and again when it finishes. It says what
+     * was installed and with which version of the converted data, so the game and the verifier can tell when an
+     * installation didn't finish, or when a part was converted by an older installer and must be installed again.
+     */
+    namespace InstallStamp{
+
+        /**
+         * Version of the converted data.
+         *
+         * Increase it when the installer converts something differently, so the installations made before have to
+         * be done again. The parts installed with an older version are reported as outdated.
+         *
+         * - 1: First version of the record.
+         */
+        const int DATA_VERSION = 1;
+
+        /**
+         * Name of the file, in the installation directory.
+         */
+        extern const char* const FILE_NAME;
+
+        /**
+         * What the record says.
+         */
+        struct Stamp{
+
+            /**
+             * True if the last installation finished.
+             */
+            bool complete = false;
+
+            /**
+             * Version of the installer that made the last installation.
+             */
+            std::string installer;
+
+            /**
+             * When the last installation started, as "YYYY-MM-DD HH:MM:SS".
+             */
+            std::string date;
+
+            /**
+             * The disk of the last installation.
+             */
+            std::string disk;
+
+            /**
+             * The installed parts (as in the command line of the installer, like "fields"), with the version of
+             * the data they were installed with. 0 if their installation didn't finish.
+             */
+            std::map<std::string, int> parts;
+
+            /**
+             * The parts of the installation that is in progress, or that didn't finish.
+             */
+            std::vector<std::string> installing;
+        };
+
+        /**
+         * Reads the record of a directory.
+         *
+         * @param[in] directory The installation directory.
+         * @param[out] stamp What it says.
+         * @return False if there is no record.
+         */
+        bool Read(const boost::filesystem::path& directory, Stamp& stamp);
+
+        /**
+         * Writes the record of a directory.
+         *
+         * @param[in] directory The installation directory.
+         * @param[in] stamp What to write.
+         * @return False if it can't be written.
+         */
+        bool Write(const boost::filesystem::path& directory, const Stamp& stamp);
+
+        /**
+         * Starts an installation: the record says it is in progress.
+         *
+         * The parts installed before are kept. The ones of an installation that didn't finish, and are not
+         * installed again now, are marked as not installed (version 0).
+         *
+         * @param[in,out] stamp The record of the directory. Empty if there was none.
+         * @param[in] parts The parts that will be installed.
+         * @param[in] installer Version of the installer.
+         * @param[in] date When the installation starts.
+         * @param[in] disk The disk.
+         */
+        void Start(
+          Stamp& stamp, const std::vector<std::string>& parts, const std::string& installer,
+          const std::string& date, const std::string& disk
+        );
+
+        /**
+         * Finishes an installation: its parts are installed with the current version of the data.
+         *
+         * @param[in,out] stamp The record of the directory.
+         */
+        void Finish(Stamp& stamp);
+
+        /**
+         * Gets the parts installed with an older version of the data, or whose installation didn't finish.
+         *
+         * @param[in] stamp The record.
+         * @return The names of the parts, sorted.
+         */
+        std::vector<std::string> Outdated(const Stamp& stamp);
+
+        /**
+         * Describes what is wrong with the installation of a directory, according to its record.
+         *
+         * @param[in] directory The installation directory.
+         * @param[out] found True if there is a record. It can be null.
+         * @return One sentence for each problem. Empty if there is none, or if there is no record.
+         */
+        std::vector<std::string> Problems(const boost::filesystem::path& directory, bool* found = nullptr);
+
+        /**
+         * Gets the current date and time, as written in the record.
+         */
+        std::string Now();
+    }
+}

+ 20 - 41
src/common/LzsFile.cpp

@@ -39,68 +39,47 @@ LzsFile::LzsFile(File* pFile): File(pFile){
 LzsFile::~LzsFile(){}
 
 void LzsFile::ExtractLzs(){
+    const u32 input_size = GetFileSize();
     u32 input_length = GetU32LE(0) + 4;
-    if (input_length != buffer_size_){
+    if (input_length != input_size){
         LOG_TRIVIAL("Warning: extract failed, this is not lzs!\n");
         return;
     }
-    u32 extract_size = (buffer_size_ + 255) & ~255;
-    u8* extractbuffer_ = static_cast<u8*>(malloc(extract_size));
-    unsigned int inputoffset_ = 4;
-    int outputoffset_ = 0;
+    std::vector<u8> output;
+    output.reserve((input_size + 255) & ~255);
+    unsigned int input_offset = 4;
     u8 control_byte = 0;
     u8 control_bit = 0;
-    while (inputoffset_ < buffer_size_){
+    while (input_offset < input_size){
         if (control_bit == 0){
-            control_byte = (static_cast<u8*>(buffer_))[inputoffset_ ++];
+            control_byte = GetU8(input_offset ++);
             control_bit = 8;
         }
-
-        if (control_byte & 1){
-            (static_cast<u8*>(extractbuffer_))[outputoffset_ ++] =
-              (static_cast<u8*>(buffer_))[inputoffset_ ++];
-            if (outputoffset_ == extract_size){
-                extract_size += 256;
-                extractbuffer_ = static_cast<u8*>(realloc(extractbuffer_, extract_size));
-            }
-        }
+        if (control_byte & 1) output.push_back(GetU8(input_offset ++));
         else{
-            u8 reference1 = (static_cast<u8*>(buffer_))[inputoffset_++];
-            u8 reference2 = (static_cast<u8*>(buffer_))[inputoffset_++];
-            u16 referenceoffset_ = reference1 | ((reference2 & 0xF0) << 4);
+            u8 reference1 = GetU8(input_offset ++);
+            u8 reference2 = GetU8(input_offset ++);
+            u16 reference_offset = reference1 | ((reference2 & 0xF0) << 4);
             u8 reference_length = (reference2 & 0xF) + 3;
-            int realoffset_
-              = outputoffset_ - ((outputoffset_ - 18 - referenceoffset_) & 0xFFF);
+            const int output_offset = static_cast<int>(output.size());
+            int real_offset = output_offset - ((output_offset - 18 - reference_offset) & 0xFFF);
             for (int j = 0; j < reference_length; ++ j){
-                if (realoffset_ < 0){
-                    (static_cast<u8*>(extractbuffer_))[outputoffset_++] = 0;
-                }
-                else{
-                    (static_cast<u8*>(extractbuffer_))[outputoffset_++] =
-                      (static_cast<u8*>(extractbuffer_))[realoffset_];
-                }
-                if (outputoffset_ == extract_size){
-                    extract_size += 256;
-                    extractbuffer_ =
-                      static_cast<u8*>(realloc(extractbuffer_, extract_size));
-                }
-                ++ realoffset_;
+                // Before the start of the data, or the byte that is being written: 0.
+                if (real_offset < 0 || real_offset >= static_cast<int>(output.size())) output.push_back(0);
+                else output.push_back(output[real_offset]);
+                ++ real_offset;
             }
         }
         control_byte >>= 1;
         control_bit --;
     }
-    free(buffer_);
-    // the real buffer size and mBufferSize will be a bit different
-    buffer_ = extractbuffer_;
-    buffer_size_ = outputoffset_;
+    buffer_ = std::move(output);
 }
 
 std::vector<VGears::uint8> LzsBuffer::Decompress(
   const std::vector<VGears::uint8>& buffer
 ){
+    if (buffer.empty()) return std::vector<VGears::uint8>();
     LzsFile tmp(static_cast<const u8*>(buffer.data()), 0, buffer.size());
-    std::vector<VGears::uint8> ret(tmp.buffer_size_);
-    ret.assign(tmp.buffer_, tmp.buffer_ + tmp.buffer_size_);
-    return ret;
+    return std::vector<VGears::uint8>(tmp.buffer_.begin(), tmp.buffer_.end());
 }

+ 49 - 1
src/common/VGearsApplication.cpp

@@ -41,6 +41,11 @@
 #include "data/VGearsTriggersFile.h"
 #include "data/VGearsMapListFile.h"
 #include "Version.h"
+#include "common/InstallStamp.h"
+#include <OgreControllerManager.h>
+#include <OgreDefaultHardwareBufferManager.h>
+#include <OgreMaterialManager.h>
+#include <OgreMeshManager.h>
 
 /**
  * Application singleton.
@@ -134,7 +139,38 @@ namespace VGears{
         return true;
     }
 
-    void Application::loadPlugins(){
+    bool Application::initOgreHeadless(){
+        if (_initialized) return false;
+        _initialized = true;
+        _headless = true;
+        // Ogre writes its messages to the log file only, not to the terminal: the programs that convert data have
+        // their own output. Created before the root, which then doesn't create its own log.
+        if (Ogre::LogManager::getSingletonPtr() == nullptr){
+            _log_manager = std::make_unique<Ogre::LogManager>();
+            _log_manager->createLog(log_filename_, true, false, false);
+        }
+        // No plugins file is passed to Ogre: the plugins are looked for in several places, see loadPlugins.
+        _root = std::make_unique<Ogre::Root>("", config_filename_, log_filename_);
+        loadPlugins(true);
+        _overlay_system = std::make_unique<Ogre::OverlaySystem>();
+        Ogre::LogManager::getSingleton().getDefaultLog()->setLogDetail(Ogre::LL_BOREME);
+        // Without a render system nobody creates the hardware buffer manager, and meshes need one.
+        _buffer_manager = std::make_unique<Ogre::DefaultHardwareBufferManager>();
+        // What Ogre::Root::initialise and the render system do, except what needs a graphics driver: the
+        // controllers (used by animated materials), a texture manager for the textures named by the materials,
+        // the default material that new materials copy, and the built-in meshes.
+        if (Ogre::ControllerManager::getSingletonPtr() == nullptr)
+            _controller_manager = std::make_unique<Ogre::ControllerManager>();
+        _texture_manager = std::make_unique<Ogre::DefaultTextureManager>();
+        Ogre::MaterialManager::getSingleton().initialise();
+        Ogre::MeshManager::getSingleton()._initialise();
+        registerArchiveFactories();
+        loadResourcesConfig();
+        initComponents();
+        return true;
+    }
+
+    void Application::loadPlugins(bool skip_render_systems){
         const bfs::path plugins_file(bfs::absolute(bfs::path(plugins_filename_)));
         OgrePlugins::Config config;
         if (!OgrePlugins::ReadConfig(plugins_file, config))
@@ -148,6 +184,10 @@ namespace VGears{
           + std::to_string(OGRE_VERSION_PATCH)
         );
         for (const String& name : config.plugins){
+            if (skip_render_systems && name.compare(0, 13, "RenderSystem_") == 0){
+                Ogre::LogManager::getSingleton().logMessage("Not loading Ogre plugin " + name + ": no render system");
+                continue;
+            }
             const bfs::path file(OgrePlugins::Find(name, directories, ogre_version));
             if (file.empty()){
                 String searched;
@@ -290,6 +330,14 @@ namespace VGears{
             return false;
         }
         std::cout << "Data directory: " << data_directory.directory.string() << std::endl;
+        // The record of the installations says if the game data must be installed again.
+        bool recorded = false;
+        for (const std::string& problem : InstallStamp::Problems(data_directory.directory, &recorded))
+            std::cout << "Warning: " << problem << std::endl;
+        if (!recorded && bfs::exists(data_directory.directory / "data" / "fields" / "_fields.xml", ec)){
+            std::cout << "Warning: the game data was installed by an older version of v-gears-installer, and may be "
+              "outdated. Install it again with v-gears-installer." << std::endl;
+        }
         return true;
     }
 

+ 60 - 1
src/common/VGearsApplication.h

@@ -17,6 +17,10 @@
 
 #include <OgreRoot.h>
 #include <OgreOverlaySystem.h>
+#include <OgreHardwareBufferManager.h>
+#include <OgreLogManager.h>
+#include <OgreControllerManager.h>
+#include <OgreTextureManager.h>
 #include <memory>
 #include "TypeDefine.h"
 
@@ -65,6 +69,26 @@ namespace VGears{
              */
             bool initOgre(bool hideWindow = false);
 
+            /**
+             * Initializes Ogre without a render system, for programs that only convert data.
+             *
+             * No window is created, so no display or graphics driver is needed. The render system plugins in the
+             * plugins file are not loaded, and meshes and skeletons are kept in system memory (see
+             * Ogre::DefaultHardwareBufferManager). Materials can name textures, but no texture is created (see
+             * Ogre::DefaultTextureManager). Nothing can be rendered.
+             *
+             * @return True if the system was succesfully initiated, false if there were errors or it was already
+             * initialized.
+             */
+            bool initOgreHeadless();
+
+            /**
+             * Tells if Ogre was initialized without a render system (see {@see initOgreHeadless}).
+             *
+             * @return True if there is no render system.
+             */
+            bool IsHeadless() const{return _headless;}
+
             /**
              * Retrieves the Ogre system main component.
              *
@@ -144,9 +168,10 @@ namespace VGears{
              *
              * Each plugin is looked for in the directories given by {@see OgrePlugins::SearchDirectories}.
              *
+             * @param[in] skip_render_systems True to not load the render system plugins.
              * @throws std::runtime_error If the plugins file can't be read or a plugin is not found.
              */
-            void loadPlugins(void);
+            void loadPlugins(bool skip_render_systems = false);
 
             /**
              * Loads the resource configuration from  the file.
@@ -285,11 +310,45 @@ namespace VGears{
              */
             bool _initialized = false;
 
+            /**
+             * True if Ogre was initialized without a render system.
+             */
+            bool _headless = false;
+
+            /**
+             * Hardware buffer manager used without a render system, that keeps the buffers in system memory.
+             *
+             * It is declared before the root so it is destroyed after it: the meshes, destroyed with the root,
+             * notify the buffer manager when their buffers are released.
+             */
+            std::unique_ptr<Ogre::HardwareBufferManager> _buffer_manager;
+
+            /**
+             * Log manager created without a render system, so Ogre's messages only go to the log file.
+             *
+             * The root uses it instead of creating its own. Declared before the root so it is destroyed after it.
+             */
+            std::unique_ptr<Ogre::LogManager> _log_manager;
+
+            /**
+             * Controller manager used without a render system, if the root didn't create one.
+             *
+             * Declared before the root for the same reason as the buffer manager.
+             */
+            std::unique_ptr<Ogre::ControllerManager> _controller_manager;
+
             /**
              * Ogre main component.
              */
             std::unique_ptr<Ogre::Root> _root;
 
+            /**
+             * Texture manager used without a render system. Materials can name textures, but no texture is created.
+             *
+             * Declared after the root so it is destroyed before it, as the texture manager of a render system is.
+             */
+            std::unique_ptr<Ogre::TextureManager> _texture_manager;
+
             /**
              *The ogre overlay system.
              */

+ 16 - 8
src/data/VGearsAFile.cpp

@@ -109,15 +109,23 @@ namespace VGears{
             key_frame->setTranslate(ConvertRootTranslation(frame->root_translation, flip_forward_axis));
             SetFrameRotation(key_frame, frame->root_rotation);
         }
+        // Some models of the original game use animations made for a model with more bones (Barret in southmk2,
+        // Yuffie in trnad_4...). The bones are matched by their position, and the ones the skeleton doesn't have
+        // are left out.
+        // The extra bones are not at the end: Tifa's skeleton, whose animations Barret uses, has the hair and an
+        // armour bone in the middle, so the bones after them get the rotations of other bones. Like the original
+        // engine, which has no bone names. These scenes looked right in the game (southmk2, trnad_4, kuro_7,
+        // spipe_2...), so matching the bones by name is not needed for now.
+        const uint32 skeleton_bones = skeleton->getNumBones() > 0 ? skeleton->getNumBones() - 1 : 0;
+        if (bone_count_ > skeleton_bones){
+            Ogre::LogManager::getSingleton().logMessage(
+              "[WARNING] The animation " + name + " has " + std::to_string(bone_count_) + " bones, and the skeleton "
+              + skeleton->getName() + " " + std::to_string(skeleton_bones) + ": the other "
+              + std::to_string(bone_count_ - skeleton_bones) + " are not animated.", Ogre::LML_CRITICAL
+            );
+        }
         for(uint32 i(0); i < bone_count_; ++ i){
-            if (i + 1 >= skeleton->getNumBones()){
-                // TODO: Figure out why this happens/fix it.
-                LOG_ERROR(
-                  "Bone " + std::to_string(i + 1) + "  is out of bounds "
-                  + std::to_string(skeleton->getNumBones()) + " for: " + name
-                  + " in: " + skeleton->getName()
-                );
-            }
+            if (i + 1 >= skeleton->getNumBones()) continue;
             else{
                 bone = skeleton->getBone(i + 1);
                 track = anim->createNodeTrack(track_handle ++, bone);

+ 2 - 0
src/data/VGearsBackgroundFile.cpp

@@ -114,6 +114,8 @@ namespace VGears{
         );
         Ogre::MemoryDataStream *buffer(new Ogre::MemoryDataStream(memory_size));
         uint32 *color(reinterpret_cast<uint32*>(buffer->getPtr()));
+        // The tiles don't fill the image: what they don't cover must be transparent, not whatever was in memory.
+        memset(color, 0, memory_size);
 
         int dst_x(0), dst_y(0);
         int dst_x_16(0), dst_y_16(0);

+ 12 - 2
src/data/VGearsPFile.cpp

@@ -16,6 +16,7 @@
 #include <iostream>
 #include <OgreBone.h>
 #include <OgreLogManager.h>
+#include <OgreMaterialManager.h>
 #include <OgreStringConverter.h>
 #include "data/VGearsPFile.h"
 #include "common/VGearsStringUtil.h"
@@ -135,7 +136,7 @@ namespace VGears{
             const String sub_name(
               bone_name + "/" + rsd_base + "/" + Ogre::StringConverter::toString(g)
             );
-            AddGroup(groups_[g], mo, sub_name, material_base_name, skeleton->getBone(bone_name));
+            AddGroup(groups_[g], mo, sub_name, material_base_name, rsd->getGroup(), skeleton->getBone(bone_name));
         }
     }
 
@@ -151,13 +152,22 @@ namespace VGears{
 
     void PFile::AddGroup(
       const Group &group, ManualObject &mo, const String &sub_name,
-      const String &material_base_name, const Ogre::Bone *bone
+      const String &material_base_name, const String &material_group, const Ogre::Bone *bone
     ) const{
         size_t material_index(0);
         if (group.has_texture) material_index = group.texture_index + 1;
         String material_name(
           material_base_name + "/" + Ogre::StringConverter::toString(material_index)
         );
+        // A group can use a texture that its RSD file doesn't list (some battle effects get it from the effect
+        // that uses them). Without a material the group would have none at all: use the one without texture.
+        if (material_index > 0 && !Ogre::MaterialManager::getSingleton().resourceExists(material_name, material_group)){
+            Ogre::LogManager::getSingleton().logMessage(
+              "[WARNING] The group " + sub_name + " uses the texture " + Ogre::StringConverter::toString(group.texture_index)
+              + ", which " + material_base_name + " doesn't have: it has no texture.", Ogre::LML_CRITICAL
+            );
+            material_name = material_base_name + "/0";
+        }
         const uint16 bone_handle(bone->getHandle());
         const Ogre::Vector3 bone_position(GetPosition(bone));
         size_t index(0);

+ 2 - 1
src/data/VGearsPFile.h

@@ -371,11 +371,12 @@ namespace VGears{
              * @param[in,out] mo The object to add to the group.
              * @param[in] sub_name Name for mo.
              * @param[in] material_base_name Name of the material for mo.
+             * @param[in] material_group Resource group of the materials.
              * @param[in] bone The bone to assign to bo.
              */
             virtual void AddGroup(
               const Group &group, ManualObject &mo, const String &sub_name,
-              const String &material_base_name, const Ogre::Bone *bone
+              const String &material_base_name, const String &material_group, const Ogre::Bone *bone
             ) const;
 
             /**

+ 85 - 104
src/installer/BattleDataInstaller.cpp

@@ -145,7 +145,7 @@ unsigned int BattleDataInstaller::InitializeSpellModels(){
 
 unsigned int BattleDataInstaller::ProcessScene(){
     if (next_scene_ >= scenes_uncompressed_.size()) return total_scenes_;
-    File* scene_file = scenes_uncompressed_[next_scene_];
+    File* scene_file = scenes_uncompressed_[next_scene_].get();
     if (scene_file == NULL){
         // Keep battle IDs stable: an unreadable scene still takes its 4 battle slots.
         std::cout << "Warning: scene " << next_scene_ << " could not be extracted." << std::endl;
@@ -412,7 +412,6 @@ unsigned int BattleDataInstaller::ProcessSpellModel(){
         magic_lgp_files_[next_model_to_process_].WriteFile(
           output_dir_ + "temp/spell_models/" + p_name
         );
-        std::cout << "[BONE RENAMED] " << fname << " --> " << p_name << std::endl;
         bool found = false;
         for (int m = 0; m < spell_models_.size(); m ++){
             if (spell_models_[m].id == id){
@@ -673,13 +672,11 @@ unsigned int BattleDataInstaller::ConvertSpellModel(){
 
         // Decompile the .hrc file (if any)
         if (model.hrc != ""){
-            std::cout << "[DECOMPILE] " << output_dir_ + "temp/spell_models/" + model.hrc << std::endl;
             DecompileSpellModelHrc(
               File(output_dir_ + "temp/spell_models/" + model.hrc), model,
               output_dir_ + "temp/spell_models/" + info.name_normal + ".hrc", model.id
             );
             model.hrc = info.name_normal + ".hrc";
-            std::cout << "    TO: " << (output_dir_ + "temp/spell_models/" + info.name_normal + ".hrc") << std::endl;
         }
         GenerateRsdFiles(model, output_dir_ + "temp/spell_models/");
 
@@ -697,7 +694,6 @@ unsigned int BattleDataInstaller::ConvertSpellModel(){
 
         // Export meshes thet have an .hrc skeleton.
         if (model.hrc != ""){
-            std::cout << "[EXPORT MESH] " << model.hrc << std::endl;
             Ogre::ResourcePtr hrc = VGears::HRCFileManager::GetSingleton().load(model.id + ".hrc", "FFVII");
             Ogre::String base_name;
             VGears::StringUtil::splitBase(model.hrc, base_name);
@@ -790,6 +786,9 @@ unsigned int BattleDataInstaller::InitializeEffectModels(){
         if (it != index.end()){found_folder = ""; return it->second;}
         return static_cast<size_t>(-1);
     };
+    // The folders that have each file, for the textures of the models of the root.
+    std::map<std::string, std::vector<std::string>> texture_folders;
+    for (const auto& entry : index) if (!entry.first.first.empty()) texture_folders[entry.first.second].push_back(entry.first.first);
     std::set<std::string> written;
     auto write = [&](size_t f, const std::string& name){
         if (written.insert(name).second) magic_lgp_files_[f].WriteFile(dir + name);
@@ -817,33 +816,67 @@ unsigned int BattleDataInstaller::InitializeEffectModels(){
         std::string p_folder;
         size_t p_index = find(folder, ply + ".p", p_folder);
         if (p_index == static_cast<size_t>(-1)) continue;
-        const std::string key = key_of(folder);
-        EffectModel model;
-        model.name = key + "_" + EffectSafeName(EffectStem(rsd_name));
         const std::string p_name = key_of(p_folder) + "_" + EffectSafeName(ply) + ".p";
         write(p_index, p_name);
-        std::string rsd = "@RSD940102\nPLY=" + p_name.substr(0, p_name.size() - 2) + ".PLY\n";
-        rsd += "MAT=" + model.name + ".MAT\nGRP=" + model.name + ".GRP\n";
-        std::vector<std::string> tex_names;
-        for (const std::string& t : tex){
-            std::string t_folder;
-            size_t t_index = find(folder, t + ".tex", t_folder);
-            if (t_index == static_cast<size_t>(-1)) continue;
-            const std::string t_name = key_of(t_folder) + "_" + EffectSafeName(t) + ".tex";
-            write(t_index, t_name);
-            tex_names.push_back(t_name);
-        }
-        rsd += "NTEX=" + std::to_string(tex_names.size()) + "\n";
-        for (size_t t = 0; t < tex_names.size(); t ++){
-            rsd += "TEX[" + std::to_string(t) + "]=" + tex_names[t].substr(0, tex_names[t].size() - 4) + ".TIM\n";
+        const std::string stem = EffectSafeName(EffectStem(rsd_name));
+        // Tells if a texture is in a folder, or in the archive root.
+        const auto has_texture = [&](const std::string& texture_folder, const std::string& t){
+            std::string found;
+            return find(texture_folder, t + ".tex", found) != static_cast<size_t>(-1);
+        };
+        // Writes a model with the textures of a folder. The textures keep their place in the list, so the
+        // polygons get the texture they use even if one is missing.
+        const auto add_model = [&](const std::string& name, const std::string& texture_folder){
+            EffectModel model;
+            model.name = name;
+            std::string rsd = "@RSD940102\nPLY=" + p_name.substr(0, p_name.size() - 2) + ".PLY\n";
+            rsd += "MAT=" + model.name + ".MAT\nGRP=" + model.name + ".GRP\n";
+            std::vector<std::string> tex_names;
+            for (const std::string& t : tex){
+                std::string t_folder;
+                const size_t t_index = find(texture_folder, t + ".tex", t_folder);
+                if (t_index == static_cast<size_t>(-1)){
+                    std::cerr << "[WARNING] The texture " << t << " of the effect model " << model.name
+                      << " is not in magic.lgp." << std::endl;
+                    tex_names.push_back(key_of(texture_folder) + "_" + EffectSafeName(t) + ".tex");
+                    continue;
+                }
+                const std::string t_name = key_of(t_folder) + "_" + EffectSafeName(t) + ".tex";
+                write(t_index, t_name);
+                tex_names.push_back(t_name);
+            }
+            rsd += "NTEX=" + std::to_string(tex_names.size()) + "\n";
+            for (size_t t = 0; t < tex_names.size(); t ++){
+                rsd += "TEX[" + std::to_string(t) + "]=" + tex_names[t].substr(0, tex_names[t].size() - 4) + ".TIM\n";
+            }
+            model.textures = tex_names;
+            std::ofstream(dir + model.name + ".rsd") << rsd;
+            // A model with a single bone, with the mesh.
+            std::ofstream(dir + model.name + ".hrc")
+              << ":HEADER_BLOCK 2\n:SKELETON " << model.name << "\n:BONES 1\n\nbone0\nroot\n0.000000\n1 "
+              << model.name << "\n\n";
+            effect_models_.push_back(model);
+        };
+        bool complete = true;
+        for (const std::string& t : tex) complete = complete && has_texture(folder, t);
+        // The models of the archive root are shared by several effects, and each effect has its own version of
+        // their textures in its folder (exp_1.tex is in five, all different). There is a model for each folder
+        // that has all of them, named after the folder like the models of the folders.
+        std::vector<std::string> variants;
+        if (!complete && folder.empty()){
+            std::set<std::string> candidates;
+            for (const std::string& t : tex){
+                const auto found = texture_folders.find(t + ".tex");
+                if (found != texture_folders.end()) candidates.insert(found->second.begin(), found->second.end());
+            }
+            for (const std::string& candidate : candidates){
+                bool all = true;
+                for (const std::string& t : tex) all = all && has_texture(candidate, t);
+                if (all) variants.push_back(candidate);
+            }
         }
-        model.textures = tex_names;
-        std::ofstream(dir + model.name + ".rsd") << rsd;
-        // A model with a single bone, with the mesh.
-        std::ofstream(dir + model.name + ".hrc")
-          << ":HEADER_BLOCK 2\n:SKELETON " << model.name << "\n:BONES 1\n\nbone0\nroot\n0.000000\n1 "
-          << model.name << "\n\n";
-        effect_models_.push_back(model);
+        if (variants.empty()) add_model(key_of(folder) + "_" + stem, folder);
+        else for (const std::string& variant : variants) add_model(key_of(variant) + "_" + stem, variant);
     }
     res_mgr_->removeResourceLocation(dir, "FFVII");
     res_mgr_->addResourceLocation(dir, "FileSystem", "FFVII", true, true);
@@ -861,6 +894,8 @@ unsigned int BattleDataInstaller::ConvertEffectModel(){
             const std::string path = data_dir_ + "models/battle/effects/"
               + texture.substr(0, texture.size() - 4) + ".png";
             if (boost::filesystem::exists(path)) continue;
+            // A texture that is not in magic.lgp is already reported.
+            if (!boost::filesystem::exists(output_dir_ + "temp/effects/" + texture)) continue;
             try{
                 TexFile tex(output_dir_ + "temp/effects/" + texture);
                 tex.SavePng(path);
@@ -1486,87 +1521,29 @@ std::string BattleDataInstaller::BuildAttackFileName(Attack attack){
     return file_name;
 }
 
-File* BattleDataInstaller::ExtractGZipScene(File file){
-    u32 offset = 0;
-    u8* file_buffer = static_cast<u8*>(malloc(file.GetFileSize()));
-    file.GetFileBuffer(file_buffer, 0, file.GetFileSize());
-    u32 extract_size = 256 * 1024;
-    u8* extract_buffer = static_cast<u8*>(malloc(extract_size));
-    int ret;
-    z_stream strm;
-    strm.zalloc = Z_NULL; // Used to allocate the internal state.
-    strm.zfree = Z_NULL; // Used to free the internal state.
-    strm.opaque = Z_NULL; // Private data object passed to zalloc and zfree.
-    strm.next_in = file_buffer + offset; //Next input byte.
-    strm.avail_in = file.GetFileSize() - offset; // Number of bytes available at next_in.
-    strm.next_out = extract_buffer; // Next output byte should be put there.
-    strm.avail_out = extract_size; // Remaining free space at next_out.
-    ret = inflateInit2(&strm, 15 + 32);
-    if (ret != Z_OK){
-        switch (ret){
-            case Z_MEM_ERROR:
-                inflateEnd(&strm);
-                std::cout << "Warning: inflateInit2 - Z_MEM_ERROR in file " << file.GetFileName() << std::endl;
-                break;
-            case Z_STREAM_ERROR:
-                inflateEnd(&strm);
-                std::cout << "Warning: inflateInit2 - Z_STREAM_ERROR in file " << file.GetFileName() << std::endl;
-                break;
-            default:
-                inflateEnd(&strm);
-                std::cout << "Warning: inflateInit2 - unknown error in file " << file.GetFileName() << std::endl;
-        }
-        return NULL;
+std::unique_ptr<File> BattleDataInstaller::ExtractGZipScene(const File& file){
+    std::vector<u8> compressed(file.GetFileSize());
+    if (!compressed.empty()) file.GetFileBuffer(compressed.data(), 0, compressed.size());
+    std::vector<u8> out;
+    std::string error;
+    if (compressed.empty() || !BinGZipFile::Inflate(compressed.data(), compressed.size(), out, error) || out.empty()){
+        std::cout << "Warning: " << (error.empty() ? "empty data" : error) << " in file " << file.GetFileName() << std::endl;
+        return nullptr;
     }
-    do{
-        if (strm.next_out == NULL){
-            inflateEnd(&strm);
-            std::cout << "Warning: strm.next_out == NULL in file " << file.GetFileName() << std::endl;
-            return NULL;
-        }
-        ret = inflate(&strm, Z_NO_FLUSH);
-        assert(ret != Z_STREAM_ERROR);
-        switch (ret){
-            case Z_NEED_DICT:
-                inflateEnd(&strm);
-                std::cout << "Warning: inflate - Z_NEED_DICT in file " << file.GetFileName() << std::endl;
-                return NULL;
-            case Z_DATA_ERROR:
-                inflateEnd(&strm);
-                std::cout << "Warning: inflate - Z_DATA_ERROR in file " << file.GetFileName() << std::endl;
-                return NULL;
-            case Z_MEM_ERROR:
-                inflateEnd(&strm);
-                std::cout << "Warning: inflate - Z_MEM_ERROR in file " << file.GetFileName() << std::endl;
-                return NULL;
-        }
-        if (ret != Z_STREAM_END){
-            extract_buffer = static_cast<u8*>(realloc(extract_buffer, extract_size * 2));
-            if (extract_buffer == NULL){
-                inflateEnd(&strm);
-                //std::cout << "Warning: extract_buffer == NULL in file "
-                //  << file.GetFileName() << std::endl;
-                return NULL;
-            }
-            strm.next_out = static_cast<u8*>(extract_buffer + extract_size);
-            strm.avail_out = extract_size;
-            extract_size *= 2;
-        }
-    } while (ret != Z_STREAM_END);
-    extract_size = extract_size - strm.avail_out;
-    (void)inflateEnd(&strm);
-    if (ret != Z_STREAM_END){
-        std::cout << "Warning: ret != Z_STREAM_END in file " << file.GetFileName() << std::endl;
-        return NULL;
-    }
-    File* out_file = new File(extract_buffer, 0, extract_size);
-    return out_file;
+    return std::make_unique<File>(out.data(), 0, static_cast<u32>(out.size()));
 }
 
 void BattleDataInstaller::ExportMesh(const std::string outdir, const Ogre::MeshPtr &mesh){
     VGears::String base_mesh_name;
     VGears::StringUtil::splitFull(mesh->getName(), base_mesh_name);
     MakeMaterialsUnique(mesh, outdir + base_mesh_name);
+    // A model without geometry (enemy 15, Eye, has only a skeleton and animations) has no bounds, and Ogre
+    // doesn't export a mesh without them. It is exported as an empty mesh at the origin.
+    // Ogre also wants a radius that is not 0, so the bounds are a tiny box.
+    if (mesh->getBounds().isNull() || mesh->getBoundingSphereRadius() <= 0){
+        mesh->_setBounds(Ogre::AxisAlignedBox(Ogre::Vector3(-0.01f), Ogre::Vector3(0.01f)), false);
+        mesh->_setBoundingSphereRadius(0.02f);
+    }
     Ogre::MeshSerializer mesh_serializer;
     Ogre::SkeletonPtr skeleton(mesh->getSkeleton());
     Ogre::SkeletonSerializer skeleton_serializer;
@@ -1576,6 +1553,7 @@ void BattleDataInstaller::ExportMesh(const std::string outdir, const Ogre::MeshP
     mesh->setSkeletonName(outdir + base_mesh_name + ".skeleton");
     mesh_serializer.exportMesh(mesh.get(), data_dir_ + "models/battle/" + outdir + mesh->getName());
     Ogre::MaterialSerializer mat_ser;
+    bool queued = false;
     std::set<std::string> textures;
     Ogre::Mesh::SubMeshList sub_meshes = mesh->getSubMeshes();
     for (Ogre::SubMesh* sub_mesh : sub_meshes){
@@ -1603,10 +1581,13 @@ void BattleDataInstaller::ExportMesh(const std::string outdir, const Ogre::MeshP
         }
         if (std::count(battle_materials_.begin(), battle_materials_.end(), sub_mesh->getMaterialName()) == 0){
             mat_ser.queueForExport(mat);
+            queued = true;
             battle_materials_.push_back(sub_mesh->getMaterialName());
         }
     }
-    mat_ser.exportQueued(data_dir_ + "models/battle/" + outdir + base_mesh_name + VGears::EXT_MATERIAL);
+    // Ogre throws if there is nothing to export (a mesh without geometry, or whose materials are already exported).
+    if (queued)
+        mat_ser.exportQueued(data_dir_ + "models/battle/" + outdir + base_mesh_name + VGears::EXT_MATERIAL);
 }
 
 void BattleDataInstaller::GenerateRsdFiles(BattleModel model, std::string path){

+ 2 - 2
src/installer/BattleDataInstaller.h

@@ -360,7 +360,7 @@ class BattleDataInstaller{
          * @return Uncompressed file. NULL if errors were encountered (they will
          * be logged to console).
          */
-        File* ExtractGZipScene(File file);
+        std::unique_ptr<File> ExtractGZipScene(const File& file);
 
         /**
          * Constructs a file name for the XML file to save an enemy to.
@@ -517,7 +517,7 @@ class BattleDataInstaller{
         /**
          * List of uncompressed scenes.
          */
-        std::vector<File*> scenes_uncompressed_;
+        std::vector<std::unique_ptr<File>> scenes_uncompressed_;
 
         /**
          * Processed scenes.

+ 4 - 0
src/installer/CMakeLists.txt

@@ -8,13 +8,16 @@ find_package(Qt5 COMPONENTS Core REQUIRED)
 set(INSTALLER_SOURCE_FILES
     main.cpp
     BattleDataInstaller.cpp
+    CliInstaller.cpp
     DataInstaller.cpp
     DiskImage.cpp
     FieldDataInstaller.cpp
     FieldTextWriter.cpp
+    InstallCommandLine.cpp
     InstallLayout.cpp
     InstallLog.cpp
     InstallOptions.cpp
+    InstallSteps.cpp
     ExternalTools.cpp
     InstallVerifier.cpp
     VideoFiles.cpp
@@ -26,6 +29,7 @@ set(INSTALLER_SOURCE_FILES
     ScopedLgp.cpp
     TexFile.cpp
     VGearsUtility.cpp
+    WindowFonts.cpp
     WorldInstaller.cpp
     common/BinGZipFile.cpp
     common/DrawSkeleton.cpp

+ 753 - 0
src/installer/CliInstaller.cpp

@@ -0,0 +1,753 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <cmath>
+#include <cstdio>
+#include <csignal>
+#include <cstdlib>
+#include <algorithm>
+#include <memory>
+#include <mutex>
+#ifdef _WIN32
+#include <io.h>
+#include <windows.h>
+#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
+#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
+#endif
+#else
+#include <sys/ioctl.h>
+#include <unistd.h>
+#endif
+#include <QtCore/QCoreApplication>
+#include <QtCore/QDir>
+#include <QtCore/QFile>
+#include <QtCore/QFileInfo>
+#include "CliInstaller.h"
+#include "DataInstaller.h"
+#include "DiskImage.h"
+#include "ExternalTools.h"
+#include "InstallLayout.h"
+#include "InstallLog.h"
+#include "InstallSteps.h"
+#include "InstallVerifier.h"
+
+#ifndef VGEARS_INSTALLER_VERSION
+#define VGEARS_INSTALLER_VERSION "unknown"
+#endif
+
+namespace{
+
+    // The messages are written with stdio, not with std::cout or std::cerr: while the installation log is open it
+    // captures those streams, and the progress and the summary don't belong in the log.
+
+    /**
+     * Writes a line to the standard output.
+     */
+    void Print(const std::string& text){
+        std::fputs((text + "\n").c_str(), stdout);
+        std::fflush(stdout);
+    }
+
+    /**
+     * Writes a line to the standard error.
+     */
+    void PrintError(const std::string& text){
+        std::fflush(stdout);
+        std::fputs((text + "\n").c_str(), stderr);
+        std::fflush(stderr);
+    }
+
+    /**
+     * Writes a list of problems to the standard error.
+     *
+     * @param[in] title Line written before the list.
+     * @param[in] problems The problems.
+     */
+    void PrintList(const std::string& title, const QStringList& problems){
+        PrintError(title);
+        for (const QString& problem : problems) PrintError("  - " + problem.toStdString());
+    }
+
+    /**
+     * Tells if the standard output is a terminal, where a line can be redrawn.
+     */
+    bool IsTerminal(){
+#ifdef _WIN32
+        return _isatty(_fileno(stdout)) != 0;
+#else
+        return isatty(fileno(stdout)) != 0;
+#endif
+    }
+
+    /**
+     * Gets the width of the terminal, in columns.
+     */
+    size_t TerminalWidth(){
+#ifdef _WIN32
+        CONSOLE_SCREEN_BUFFER_INFO info;
+        if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info))
+            return static_cast<size_t>(info.srWindow.Right - info.srWindow.Left + 1);
+#else
+        winsize size;
+        if (ioctl(fileno(stdout), TIOCGWINSZ, &size) == 0 && size.ws_col > 0) return size.ws_col;
+#endif
+        return 80;
+    }
+
+    /**
+     * Tells if the messages can be coloured: the output is a terminal that understands colours, and the user didn't
+     * turn them off (https://no-color.org).
+     */
+    bool CanColour(){
+        if (!IsTerminal() || std::getenv("NO_COLOR") != nullptr) return false;
+#ifdef _WIN32
+        // The Windows console only understands the colour codes if it is asked to.
+        HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
+        DWORD mode = 0;
+        if (!GetConsoleMode(console, &mode)) return false;
+        return SetConsoleMode(console, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING) != 0;
+#else
+        const char* term = std::getenv("TERM");
+        return term == nullptr || std::string(term) != "dumb";
+#endif
+    }
+
+    /**
+     * Colours a message by its severity: orange for warnings, red for errors.
+     *
+     * @param[in] level The severity.
+     * @param[in] text The message.
+     * @param[in] colour False to leave it as it is.
+     */
+    std::string Coloured(InstallLog::Level level, const std::string& text, bool colour){
+        if (!colour || level == InstallLog::INFO) return text;
+        return (level == InstallLog::ERROR_LEVEL ? "\x1b[31m" : "\x1b[38;5;208m") + text + "\x1b[0m";
+    }
+
+    /**
+     * Shows the progress of an installation, and its problems.
+     *
+     * In a terminal, the progress is a single line at the bottom, redrawn in place, with the percent, a bar and
+     * what the installer is doing. The warnings and the errors are written above it as they happen. The rest of
+     * the messages are only in the installation log. The warnings are orange and the errors red, if the terminal
+     * can show colours.
+     *
+     * Elsewhere (the output is a file or a pipe) the log writes every message, and the progress is a line for each
+     * percent.
+     *
+     * The problems can come from other threads (the audio conversions), so everything is drawn with a lock.
+     */
+    class ProgressDisplay{
+
+        public:
+
+            ProgressDisplay(): interactive_(IsTerminal()), colour_(CanColour()){}
+
+            /**
+             * Colours a message by its severity, if the terminal can show colours.
+             */
+            std::string Colour(InstallLog::Level level, const std::string& text) const{
+                return Coloured(level, text, colour_);
+            }
+
+            ~ProgressDisplay(){Detach();}
+
+            /**
+             * Gets the messages of the installation log, which must be open.
+             */
+            void Attach(){
+                if (!interactive_) return;
+                InstallLog& log = InstallLog::Get();
+                log.SetEcho(false);
+                log.SetSink([this](InstallLog::Level level, const std::string& message){
+                    if (level == InstallLog::INFO) SetStatus(message);
+                    else Message(Colour(level, message));
+                });
+            }
+
+            /**
+             * Stops getting the messages of the installation log, and leaves the progress line as it is.
+             */
+            void Detach(){
+                if (!interactive_) return;
+                InstallLog::Get().SetSink(nullptr);
+                std::lock_guard<std::mutex> lock(mutex_);
+                if (drawn_ > 0) std::fputs("\n", stdout);
+                std::fflush(stdout);
+                drawn_ = 0;
+            }
+
+            /**
+             * Shows the progress, if it has gone up since it was last shown.
+             *
+             * @param[in] progress The progress [0-100].
+             */
+            void SetProgress(float progress){
+                const int percent = std::max(0, std::min(100, static_cast<int>(std::floor(progress))));
+                std::lock_guard<std::mutex> lock(mutex_);
+                // The progress of an installation doesn't go back.
+                if (percent <= percent_) return;
+                percent_ = percent;
+                if (interactive_) Draw();
+                else{
+                    char line[32];
+                    std::snprintf(line, sizeof(line), "[%3d%%]", percent);
+                    Print(line);
+                }
+            }
+
+            /**
+             * Shows what the installer is doing.
+             *
+             * In a terminal it is the text of the progress line. Elsewhere it is written as a line, if it changed.
+             */
+            void SetStatus(const std::string& status){
+                std::lock_guard<std::mutex> lock(mutex_);
+                if (status == status_) return;
+                status_ = status;
+                if (interactive_) Draw();
+                else Print(status);
+            }
+
+            /**
+             * Ends the progress line, so what is written next starts on a line of its own.
+             */
+            void EndLine(){
+                if (!interactive_) return;
+                std::lock_guard<std::mutex> lock(mutex_);
+                if (drawn_ > 0) std::fputs("\n", stdout);
+                std::fflush(stdout);
+                drawn_ = 0;
+            }
+
+        private:
+
+            /**
+             * Writes a message above the progress line.
+             */
+            void Message(const std::string& message){
+                std::lock_guard<std::mutex> lock(mutex_);
+                Clear();
+                std::fputs((message + "\n").c_str(), stdout);
+                Draw();
+            }
+
+            /**
+             * Erases the progress line. The lock must be held.
+             */
+            void Clear(){
+                if (drawn_ == 0) return;
+                std::fputs(("\r" + std::string(drawn_, ' ') + "\r").c_str(), stdout);
+                drawn_ = 0;
+            }
+
+            /**
+             * Draws the progress line over the previous one. The lock must be held.
+             */
+            void Draw(){
+                // One column less than the terminal, so the line never wraps.
+                const size_t width = std::max<size_t>(TerminalWidth(), 20) - 1;
+                const int percent = std::max(percent_, 0);
+                char head[16];
+                std::snprintf(head, sizeof(head), "[%3d%%] ", percent);
+                std::string line = head;
+                size_t columns = line.size();
+                // The bar, if there is room for it and some of the status.
+                const size_t bar = width >= 60 ? 30 : (width >= 40 ? 15 : 0);
+                if (bar > 0){
+                    const size_t full = bar * static_cast<size_t>(percent) / 100;
+#ifdef _WIN32
+                    line += std::string(full, '#') + std::string(bar - full, '-');
+#else
+                    for (size_t i = 0; i < bar; ++ i) line += i < full ? "\u2588" : "\u2591";
+#endif
+                    line += " ";
+                    columns += bar + 1;
+                }
+                std::string status = status_;
+                if (columns + status.size() > width){
+                    status = status.substr(0, width > columns + 3 ? width - columns - 3 : 0);
+                    // Don't cut a UTF-8 character.
+                    while (!status.empty() && (static_cast<unsigned char>(status.back()) & 0xC0) == 0x80)
+                        status.pop_back();
+                    if (!status.empty() && (static_cast<unsigned char>(status.back()) & 0x80)) status.pop_back();
+                    status += "...";
+                }
+                line += status;
+                columns += status.size();
+                // Written over the previous line, padded to cover what is left of it.
+                std::string out = "\r" + line;
+                if (columns < drawn_) out += std::string(drawn_ - columns, ' ');
+                std::fputs(out.c_str(), stdout);
+                std::fflush(stdout);
+                drawn_ = columns;
+            }
+
+            /**
+             * True if the output is a terminal.
+             */
+            const bool interactive_;
+
+            /**
+             * True if the messages are coloured.
+             */
+            const bool colour_;
+
+            /**
+             * The last percent shown, -1 if none.
+             */
+            int percent_ = -1;
+
+            /**
+             * What the installer is doing.
+             */
+            std::string status_;
+
+            /**
+             * Columns of the progress line on the screen, 0 if there is none.
+             */
+            size_t drawn_ = 0;
+
+            /**
+             * Lock for the drawing.
+             */
+            std::mutex mutex_;
+    };
+
+    /**
+     * Opens the installation log in the installation directory, and shows its messages in the display.
+     */
+    void OpenInstallLog(const QString& output, bool append, ProgressDisplay& display){
+        InstallLog::Get().Open((output + "installer.log").toStdString(), append);
+        display.Attach();
+    }
+
+    /**
+     * Closes the installation log, and writes a summary of the problems.
+     *
+     * @return The number of errors in the log.
+     */
+    size_t CloseInstallLog(ProgressDisplay& display){
+        InstallLog& log = InstallLog::Get();
+        log.EndStep();
+        display.Detach();
+        const size_t errors = log.Count(InstallLog::ERROR_LEVEL);
+        const size_t warnings = log.Count(InstallLog::WARNING);
+        const std::string path = log.Path();
+        log.Close();
+        Print("");
+        Print(std::to_string(errors) + " error(s), " + std::to_string(warnings) + " warning(s).");
+        for (const std::string& message : log.First(InstallLog::ERROR_LEVEL, 10))
+            Print("  " + display.Colour(InstallLog::ERROR_LEVEL, message));
+        if (errors > 10) Print("  ...");
+        Print("The full log is in " + path);
+        return errors;
+    }
+
+    /**
+     * Checks that the audio tools the installation needs can be used.
+     *
+     * @param[in] options What is installed.
+     * @param[in] output The installation directory.
+     * @param[in] yes True to continue without the tools.
+     * @return True if the installation can go on.
+     */
+    bool CheckTools(const InstallOptions& options, const QString& output, bool yes){
+        const ExternalTools::Locations& locations = ExternalTools::CurrentLocations();
+        const InstallRules::ToolNeeds needs = InstallRules::ToolsNeeded(options);
+        const ExternalTools::Tool ffmpeg = needs.ffmpeg ? ExternalTools::FindFfmpeg(locations) : ExternalTools::Tool();
+        const ExternalTools::Tool timidity
+          = needs.timidity ? ExternalTools::FindTimidity(locations) : ExternalTools::Tool();
+        const bool missing_ffmpeg = needs.ffmpeg && !ffmpeg.usable;
+        const bool missing_timidity = needs.timidity && !timidity.usable;
+        if (needs.ffmpeg && ffmpeg.usable) Print("FFmpeg: " + ffmpeg.path + " (" + ExternalTools::ShortVersion(ffmpeg) + ")");
+        if (needs.timidity && timidity.usable)
+            Print("TiMidity: " + timidity.path + " (" + ExternalTools::ShortVersion(timidity) + ")");
+        const std::vector<std::string> consequences
+          = InstallRules::ToolConsequences(options, !missing_ffmpeg, !missing_timidity);
+        if (consequences.empty()) return true;
+
+        QStringList reasons;
+        if (missing_ffmpeg) reasons << QString::fromStdString("FFmpeg: " + ffmpeg.problem);
+        if (missing_timidity) reasons << QString::fromStdString("TiMidity: " + timidity.problem);
+        QStringList lost;
+        for (const std::string& line : consequences) lost << QString::fromStdString(line);
+        PrintList("The installer needs programs it can't use:", reasons);
+        PrintList("Without them:", lost);
+        if (yes) return true;
+        PrintError("");
+        PrintError("Install them, copy them to " + QDir::toNativeSeparators(output + "tools").toStdString()
+          + ", or give their paths with --ffmpeg and --timidity.");
+#if defined(_WIN32)
+        PrintError("Windows: download a build of FFmpeg (ffmpeg.exe) from https://ffmpeg.org/download.html. "
+          "TiMidity++ also needs its timidity.cfg and instrument files next to timidity.exe.");
+#elif defined(__APPLE__)
+        PrintError("macOS: brew install ffmpeg timidity");
+#else
+        PrintError("Debian, Ubuntu: sudo apt install ffmpeg timidity");
+        PrintError("Fedora: sudo dnf install ffmpeg timidity++");
+        PrintError("Arch: sudo pacman -S ffmpeg timidity++");
+#endif
+        PrintError("To install without them, use --yes.");
+        return false;
+    }
+
+    /**
+     * Extracts the videos of a game disk.
+     *
+     * @param[in] disk_image The game disk.
+     * @param[in] output The installation directory.
+     * @param[in] strict True to end with an error status if the log has errors.
+     * @return The exit status.
+     */
+    int ExtractVideos(DiskImage& disk_image, const QString& output, bool strict){
+        const QStringList errors = InstallSteps::CheckVideoOutput(output);
+        if (!errors.isEmpty()){
+            PrintList("The extraction can't start:", errors);
+            return CliInstaller::EXIT_FAILED;
+        }
+        // The installation log of a previous run is kept.
+        ProgressDisplay progress;
+        OpenInstallLog(output, true, progress);
+        InstallLog::Get().Add("Extracting the videos of " + disk_image.getId() + "...");
+        int extracted = 0;
+        int skipped = 0;
+        bool ok = false;
+        try{
+            ok = disk_image.extractVideos(
+              output.toStdString() + "data/", [&progress](float value){progress.SetProgress(value);},
+              [](const std::string& message){InstallLog::Get().Add(message);}, &extracted, &skipped
+            );
+            if (ok) InstallSteps::ConvertMovies(output.toStdString() + "data/video/");
+        }
+        catch (const std::exception& ex){
+            InstallLog::Get().Add(std::string("[ERROR] Video extraction failed: ") + ex.what());
+            ok = false;
+        }
+        if (ok){
+            progress.SetProgress(100);
+            InstallSteps::MarkVideosInstalled(output);
+            InstallLog::Get().Add(
+              "Videos extracted: " + std::to_string(extracted) + " new, " + std::to_string(skipped)
+              + " already installed."
+            );
+        }
+        else InstallLog::Get().Add("[ERROR] Some videos could not be extracted.");
+        const size_t logged_errors = CloseInstallLog(progress);
+        if (!ok) return CliInstaller::EXIT_FAILED;
+        return strict && logged_errors > 0 ? CliInstaller::EXIT_ERRORS : CliInstaller::EXIT_OK;
+    }
+
+    /**
+     * Installs the game from the install disk.
+     *
+     * @param[in] arguments The command line.
+     * @param[in] disk_image The install disk.
+     * @param[in] output The installation directory.
+     * @return The exit status.
+     */
+    int Install(const InstallCommandLine::Arguments& arguments, DiskImage& disk_image, const QString& output){
+        const InstallOptions& options = arguments.options;
+        bool anything = false;
+        for (const InstallCommandLine::Part& part : InstallCommandLine::Parts()) anything |= options.*(part.option);
+        if (!anything){
+            PrintError("Nothing to install. Choose a preset, or parts with --with.");
+            return CliInstaller::EXIT_USAGE;
+        }
+        Print("Installing:");
+        for (const InstallCommandLine::Part& part : InstallCommandLine::Parts())
+            if (options.*(part.option)) Print("  - " + std::string(part.description));
+
+        // The V-Gears data folder to copy.
+        QString game_data;
+        if (arguments.copy_data){
+            game_data = arguments.data_dir.empty()
+              ? InstallSteps::FindGameDataDir() : QDir::cleanPath(QString::fromStdString(arguments.data_dir));
+            if (game_data.isEmpty()){
+                PrintError("The V-Gears 'data' folder was not found. Give it with --data-dir.");
+                return CliInstaller::EXIT_FAILED;
+            }
+            Print("V-Gears data files: " + QDir::toNativeSeparators(game_data).toStdString());
+        }
+
+        // Check everything that can be checked before touching the disk.
+        InstallSteps::PreflightResult preflight
+          = InstallSteps::RunPreflight(
+          disk_image, output, arguments.copy_data, game_data, arguments.clean
+        );
+        for (
+          const std::string& problem
+          : InstallRules::Problems(
+            options, !arguments.clean && QFile::exists(output + "data/fields/_fields.xml")
+          )
+        ) preflight.errors << QString::fromStdString(problem);
+        if (!preflight.errors.isEmpty()){
+            PrintList("The installation can't start:", preflight.errors);
+            return CliInstaller::EXIT_FAILED;
+        }
+        if (!preflight.warnings.isEmpty()){
+            PrintList("Warnings:", preflight.warnings);
+            if (!arguments.yes){
+                PrintError("To install anyway, use --yes.");
+                return CliInstaller::EXIT_FAILED;
+            }
+        }
+        // The audio is converted with external programs: say now, before anything is extracted, if they are missing.
+        if (!CheckTools(options, output, arguments.yes)) return CliInstaller::EXIT_FAILED;
+
+        // Everything is checked: the previous installation can be deleted.
+        if (arguments.clean){
+            const std::string root = output.toStdString();
+            if (!InstallLayout::IsInstallation(root)) Print("Nothing to clean: there is no installation in the directory.");
+            else{
+                Print("Deleting the previous installation (the saves, the controls, the game configuration and the "
+                  "videos are kept)...");
+                const InstallLayout::CleanResult cleaned = InstallLayout::CleanInstallation(root);
+                if (!cleaned.errors.empty()){
+                    QStringList errors;
+                    for (const std::string& error : cleaned.errors) errors << QString::fromStdString(error);
+                    PrintList("The previous installation could not be deleted:", errors);
+                    return CliInstaller::EXIT_FAILED;
+                }
+                Print("Deleted " + std::to_string(cleaned.removed) + " files and folders.");
+            }
+        }
+
+        // From here on, the installation directory is being changed: until it finishes, the record says so.
+        InstallSteps::MarkInstallStarted(output, options, disk_image.getId());
+
+        // The progress of the whole installation: the extraction, the copy and the conversion (see
+        // InstallSteps::OverallProgress).
+        ProgressDisplay progress;
+        // Ends the progress line before writing why the installation stops.
+        const auto fail = [&progress](const std::string& message){
+            progress.EndLine();
+            PrintError(message);
+            return CliInstaller::EXIT_FAILED;
+        };
+        progress.SetStatus("Extracting the install disk...");
+        if (!disk_image.extractImage(output.toStdString(), [&progress](float value){
+              progress.SetProgress(InstallSteps::OverallProgress(InstallSteps::Phase::EXTRACT, value));
+            })) return fail("Failed to extract the ISO image.");
+        if (disk_image.getContentPath().empty()) return fail("The extracted data path is invalid.");
+        const std::vector<std::string> missing_files = InstallSteps::MissingRequiredFiles(disk_image);
+        if (!missing_files.empty()){
+            progress.EndLine();
+            QStringList names;
+            for (const std::string& file : missing_files) names << QString::fromStdString(file);
+            PrintList("Some of the required files were not found among the extracted data:", names);
+            return CliInstaller::EXIT_FAILED;
+        }
+        // Copy the V-Gears data files (scripts, screens, fonts...) to the installation directory.
+        if (arguments.copy_data){
+            progress.SetStatus("Copying the V-Gears data files...");
+            if (!InstallSteps::CopyDirectory(game_data, output, [&progress](float value){
+                  progress.SetProgress(InstallSteps::OverallProgress(InstallSteps::Phase::COPY, value));
+                })) return fail("Failed to copy the V-Gears data files to the installation directory.");
+        }
+        // The installer's Ogre setup loads plugins.cfg and resources.cfg from the working directory (and writes
+        // install.log there), so run from the installation directory.
+        if (!QFile::exists(output + "plugins.cfg") || !QFile::exists(output + "resources.cfg"))
+            return fail("The installation directory must contain plugins.cfg and resources.cfg. Don't use --no-copy-data.");
+        if (!QDir::setCurrent(output)) return fail("Could not enter the installation directory.");
+
+        OpenInstallLog(output, false, progress);
+        if (options.videos){
+            InstallLog::Get().Add(
+              "[WARNING] The install disk has no videos. To extract them, run the installer again with game disk 1, "
+              "2 or 3 as the ISO."
+            );
+        }
+        const DataInstaller::AdvancedOptions advanced
+          = InstallSteps::ToAdvancedOptions(options, arguments.keep_originals);
+        const auto write_line = [](const std::string line, int, bool){InstallLog::Get().Add(line);};
+        std::string error;
+        try{
+            DataInstaller installer(disk_image, QDir::toNativeSeparators(output).toStdString(), advanced, write_line);
+            float value = 0;
+            while (value < 100){
+                value = installer.Progress();
+                progress.SetProgress(InstallSteps::OverallProgress(InstallSteps::Phase::CONVERT, value));
+            }
+        }
+        catch (const std::exception& ex){
+            error = ex.what();
+        }
+        catch (...){
+            error = "Unknown error";
+        }
+        if (!error.empty()) InstallLog::Get().Add("[ERROR] Installation failed: " + error);
+        else InstallSteps::MarkInstallFinished(output);
+        const size_t errors = CloseInstallLog(progress);
+        if (!error.empty()) return CliInstaller::EXIT_FAILED;
+        Print("Installation finished in " + QDir::toNativeSeparators(output).toStdString());
+        if (arguments.strict && errors > 0){
+            Print("It finished with errors, and --strict was given: the exit status is 3.");
+            return CliInstaller::EXIT_ERRORS;
+        }
+        return CliInstaller::EXIT_OK;
+    }
+
+    /**
+     * Gets the installation directory of the command line, or the default one.
+     *
+     * @return The directory, normalized. Empty if there is none.
+     */
+    QString OutputDir(const InstallCommandLine::Arguments& arguments){
+        const QString dir = arguments.output.empty()
+          ? InstallSteps::DefaultInstallDir() : QString::fromStdString(arguments.output);
+        return dir.isEmpty() ? QString() : InstallSteps::NormalizeOutputDir(dir);
+    }
+
+    /**
+     * Verifies an installation.
+     *
+     * @return The exit status.
+     */
+    int Verify(const InstallCommandLine::Arguments& arguments){
+        const QString output = OutputDir(arguments);
+        if (output.isEmpty() || !QDir(output).exists()){
+            PrintError("The installation directory does not exist: " + output.toStdString());
+            return CliInstaller::EXIT_FAILED;
+        }
+        const QString game_data = arguments.data_dir.empty()
+          ? InstallSteps::FindGameDataDir() : QString::fromStdString(arguments.data_dir);
+        Print("Verifying " + QDir::toNativeSeparators(output).toStdString() + "...");
+        const VerifyResult result = VerifyInstallation(
+          output.toStdString(), game_data.toStdString(), InstallSteps::PluginSearch()
+        );
+        if (result.Ok()){
+            Print("Everything the game needs is installed (" + std::to_string(result.checked) + " checks).");
+            return CliInstaller::EXIT_OK;
+        }
+        std::string group;
+        for (const VerifyProblem& problem : result.problems){
+            if (problem.group != group){
+                group = problem.group;
+                Print(group + ":");
+            }
+            Print("  - " + problem.message);
+        }
+        Print(
+          std::to_string(result.problems.size()) + " problem(s) in " + std::to_string(result.checked) + " checks. If "
+          "you skipped a part of the installation on purpose (for example the music), its files are expected to be "
+          "missing."
+        );
+        return CliInstaller::EXIT_FAILED;
+    }
+
+}
+
+namespace{
+
+    /**
+     * Ends the program when it is interrupted (Ctrl+C) or asked to end.
+     *
+     * The progress line is ended, and the user is told that the installation didn't finish: the record of the
+     * installation directory already says so. Only what is safe in a signal handler is used.
+     */
+    extern "C" void OnInterrupt(int){
+        static const char message[] = "\n\nInterrupted: the installation didn't finish. Run the installer again.\n";
+#ifdef _WIN32
+        _write(2, message, sizeof(message) - 1);
+#else
+        const ssize_t written = write(2, message, sizeof(message) - 1);
+        (void)written;
+#endif
+        std::_Exit(CliInstaller::EXIT_INTERRUPTED);
+    }
+
+}
+
+namespace CliInstaller{
+
+    int Run(const InstallCommandLine::Arguments& arguments, const std::string& program){
+        switch (arguments.mode){
+            case InstallCommandLine::Mode::HELP:
+                std::fputs(InstallCommandLine::Usage(program).c_str(), stdout);
+                return EXIT_OK;
+            case InstallCommandLine::Mode::VERSION:
+                Print("V-Gears Installer " + std::string(VGEARS_INSTALLER_VERSION));
+                return EXIT_OK;
+            case InstallCommandLine::Mode::LIST_PARTS:
+                for (const InstallCommandLine::Part& part : InstallCommandLine::Parts()){
+                    char line[128];
+                    std::snprintf(line, sizeof(line), "%-18s %s", part.name, part.description);
+                    Print(line);
+                }
+                return EXIT_OK;
+            case InstallCommandLine::Mode::INVALID:
+                PrintError(arguments.error);
+                PrintError("Run '" + program + " --help' for the usage.");
+                return EXIT_USAGE;
+            case InstallCommandLine::Mode::VERIFY:
+                return Verify(arguments);
+            case InstallCommandLine::Mode::INSTALL:
+                std::signal(SIGINT, OnInterrupt);
+                std::signal(SIGTERM, OnInterrupt);
+                break;
+            case InstallCommandLine::Mode::GUI:
+                PrintError("The installer window can't be opened from the command line installer.");
+                return EXIT_USAGE;
+        }
+
+        const QString output = OutputDir(arguments);
+        if (output.isEmpty()){
+            PrintError("No installation directory: give one with --output.");
+            return EXIT_USAGE;
+        }
+        Print("Installation directory: " + QDir::toNativeSeparators(output).toStdString());
+
+        // The paths given must be the programs, and work.
+        if (!arguments.ffmpeg.empty()){
+            const ExternalTools::Tool tool = ExternalTools::ProbeFfmpeg(arguments.ffmpeg);
+            if (!tool.usable){
+                PrintError("FFmpeg can't be used: " + tool.problem);
+                return EXIT_FAILED;
+            }
+        }
+        if (!arguments.timidity.empty()){
+            const ExternalTools::Tool tool = ExternalTools::ProbeTimidity(arguments.timidity);
+            if (!tool.usable){
+                PrintError("TiMidity can't be used: " + tool.problem);
+                return EXIT_FAILED;
+            }
+        }
+        InstallSteps::SetToolLocations(output, arguments.ffmpeg, arguments.timidity);
+
+        if (!QFileInfo(QString::fromStdString(arguments.iso)).isReadable()){
+            PrintError("The ISO image can't be read: " + arguments.iso);
+            return EXIT_FAILED;
+        }
+        // The working directory changes during installation, so the path must be absolute.
+        DiskImage disk_image(QFileInfo(QString::fromStdString(arguments.iso)).absoluteFilePath().toStdString());
+        Print("Disk: " + disk_image.getId());
+        if (!disk_image.isValid()){
+            PrintError("The ISO is not a valid Final Fantasy VII image: " + disk_image.getErrorMessage());
+            return EXIT_FAILED;
+        }
+        // A game disk only has videos: extract them, without the rest of the installation.
+        if (disk_image.isVideoDisk()){
+            if (arguments.clean){
+                PrintError("--clean is for the install disk: a game disk only adds its videos to an installation.");
+                return EXIT_USAGE;
+            }
+            Print("Game disk: only its videos will be extracted.");
+            return ExtractVideos(disk_image, output, arguments.strict);
+        }
+        return Install(arguments, disk_image, output);
+    }
+
+}

+ 65 - 0
src/installer/CliInstaller.h

@@ -0,0 +1,65 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#pragma once
+
+#include <string>
+#include "InstallCommandLine.h"
+
+/**
+ * The installer without its window: it installs, or verifies an installation, from the command line.
+ *
+ * It does the same steps as the installer window (see InstallSteps), and writes the same installer.log. Where the
+ * window asks, it stops, unless the user said to continue with --yes.
+ */
+namespace CliInstaller{
+
+    /**
+     * Exit status when everything went well.
+     */
+    const int EXIT_OK = 0;
+
+    /**
+     * Exit status when the installation or the verification failed.
+     */
+    const int EXIT_FAILED = 1;
+
+    /**
+     * Exit status when the command line is wrong.
+     */
+    const int EXIT_USAGE = 2;
+
+    /**
+     * Exit status when the installation finished with errors in its log, with --strict.
+     */
+    const int EXIT_ERRORS = 3;
+
+    /**
+     * Exit status when the installation is interrupted (Ctrl+C), as usual: 128 plus the number of SIGINT.
+     */
+    const int EXIT_INTERRUPTED = 130;
+
+    /**
+     * Does what the command line asks.
+     *
+     * A QCoreApplication must exist. The mode of the arguments must not be GUI.
+     *
+     * @param[in] arguments The parsed command line.
+     * @param[in] program Name of the program, for the usage text.
+     * @return The exit status.
+     */
+    int Run(const InstallCommandLine::Arguments& arguments, const std::string& program);
+
+}

+ 62 - 6
src/installer/DataInstaller.cpp

@@ -19,6 +19,10 @@
 #include "InstallLayout.h"
 #include "InstallLog.h"
 #include "DiskImage.h"
+#include "data/VGearsAFileManager.h"
+#include "data/VGearsHRCFileManager.h"
+#include "data/VGearsPFileManager.h"
+#include "data/VGearsRSDFileManager.h"
 
 float DataInstaller::LINE_SCALE_FACTOR = 0.0078124970964f;
 
@@ -34,10 +38,17 @@ DataInstaller::DataInstaller(
   disk_image_(disk_image), output_dir_(output_dir), data_dir_(InstallLayout::DataDir(output_dir)),
   options_(options), write_output_line_(write_output_line)
 {
-    if (!application_.initOgre(true)) throw std::runtime_error("Ogre init failure");
+    // The installer only converts data, so it needs no render system, no window and no display.
+    if (!application_.initOgreHeadless()) throw std::runtime_error("Ogre init failure");
     Ogre::Log* default_log(Ogre::LogManager::getSingleton().getDefaultLog());
     assert( default_log );
     default_log->setLogDetail(Ogre::LL_LOW);
+    // Ogre's messages only go to its own log (install.log, see Application::initOgreHeadless). Most are expected
+    // while converting (meshes without a skeleton yet, materials without a render system), and in the terminal and
+    // installer.log they hide the messages of the installer. The problems that V-Gears itself writes to that log
+    // (LOG_ERROR and LOG_WARNING) are passed to the installation log.
+    default_log->setDebugOutputEnabled(false);
+    default_log->addListener(&ogre_problems_);
 
     // Assign weights.
     for (int i = IDLE; i < STATE_COUNT; i ++) step_weight_[i] = 1;
@@ -55,7 +66,16 @@ DataInstaller::DataInstaller(
     step_weight_[FIELD_CONVERT_MODELS] = 3;
 }
 
-DataInstaller::~DataInstaller(){}
+DataInstaller::~DataInstaller(){
+    Ogre::Log* default_log = Ogre::LogManager::getSingletonPtr() ? Ogre::LogManager::getSingleton().getDefaultLog() : nullptr;
+    if (default_log) default_log->removeListener(&ogre_problems_);
+}
+
+void DataInstaller::OgreProblems::messageLogged(
+  const Ogre::String& message, Ogre::LogMessageLevel, bool, const Ogre::String&, bool&
+){
+    if (message.compare(0, 7, "[ERROR]") == 0 || message.compare(0, 9, "[WARNING]") == 0) InstallLog::Get().Add(message);
+}
 
 const char* DataInstaller::StepGroup(int state){
     if (state >= FIELD_CONVERT_MODELS_INIT && state <= FIELD_CONVERT_MODELS)
@@ -109,7 +129,7 @@ float DataInstaller::Progress(){
                         );
             battle_installer_ = std::make_unique<BattleDataInstaller>(disk_image_, output_dir_, application_.ResMgr());
             world_installer_ = std::make_unique<WorldInstaller>(
-              disk_image_, output_dir_, options_.keep_originals, application_.ResMgr()
+              disk_image_, output_dir_, application_.ResMgr()
             );
             installation_state_ = BATTLE_SCENES_INIT;
             return CalcProgress();
@@ -170,6 +190,7 @@ float DataInstaller::Progress(){
             if (cur_substep_ >= substeps_) installation_state_ = BATTLE_MODELS_CONVERT_INIT;
             return CalcProgress();
         case BATTLE_MODELS_CONVERT_INIT:
+            UseModelParts("temp/battle_models/");
             cur_substep_ = 0;
             substeps_ =  battle_installer_->ConvertBattleModelsInit();
             installation_state_ = BATTLE_MODELS_CONVERT;
@@ -199,6 +220,7 @@ float DataInstaller::Progress(){
             if (cur_substep_ >= substeps_) installation_state_ = SPELL_MODELS_CONVERT_INIT;
             return CalcProgress();
         case SPELL_MODELS_CONVERT_INIT:
+            UseModelParts("temp/spell_models/");
             cur_substep_ = 0;
             substeps_ =  battle_installer_->ConvertSpellModelsInit();
             installation_state_ = SPELL_MODELS_CONVERT;
@@ -209,6 +231,7 @@ float DataInstaller::Progress(){
             return CalcProgress();
         case EFFECT_MODELS_INIT:
             write_output_line_("Extracting battle effects...", 2, true);
+            UseModelParts("temp/effects/");
             substeps_ = battle_installer_->InitializeEffectModels();
             cur_substep_ = 0;
             installation_state_ = EFFECT_MODELS_CONVERT;
@@ -310,6 +333,10 @@ float DataInstaller::Progress(){
             installation_state_ = MEDIA_IMAGES;
             return CalcProgress();
         case MEDIA_IMAGES:
+            // The fonts are always needed, even if the rest of the images are skipped.
+            write_output_line_("Extracting fonts...", 2, true);
+            if (!media_installer_->InstallFonts())
+                write_output_line_("WARNING: Couldn't read WINDOW.BIN, the game won't be able to show text.", 2, true);
             // Skip images if option is set.
             if (!options_.images){
                 write_output_line_("Skipping images installation...", 2, true);
@@ -439,6 +466,7 @@ float DataInstaller::Progress(){
                 return CalcProgress();
             }
             write_output_line_("Converting field models...", 2, true);
+            UseModelParts("temp/char/");
             field_model_names_ = field_installer_->ConvertModelsInit();
             substeps_ = field_model_names_.size();
             cur_substep_ = 0;
@@ -460,6 +488,7 @@ float DataInstaller::Progress(){
                 return CalcProgress();
             }
             write_output_line_("Extracting world map data...", 2, true);
+            UseModelParts("temp/world_models/");
             substeps_ = world_installer_->Initialize();
             cur_substep_ = 0;
             installation_state_ = WM_MATERIALS;
@@ -506,7 +535,7 @@ float DataInstaller::Progress(){
                 }
             }
             write_output_line_("Cleaning up...", 2, true);
-            if (!options_.keep_originals) CleanInstall();
+            if (!options_.keep_originals) RemoveOriginals();
             installation_state_ = DONE;
             return CalcProgress();
         case DONE:
@@ -535,6 +564,31 @@ const float DataInstaller::CalcProgress(){
     return progress;
 }
 
+void DataInstaller::UseModelParts(const std::string& temp_dir){
+    Ogre::ResourceGroupManager& res_mgr = Ogre::ResourceGroupManager::getSingleton();
+    // Only the files of the parts are released: each of them removes what it made (an HRC file its mesh and its
+    // skeleton, an RSD file its materials). Ogre's clearResourceGroup can't be used: it removes those too, and then
+    // their owners fail to remove them.
+    std::vector<Ogre::ResourceManager*> managers = {
+      &VGears::HRCFileManager::GetSingleton(), &VGears::RSDFileManager::GetSingleton(),
+      &VGears::PFileManager::GetSingleton(), &VGears::AFileManager::GetSingleton()
+    };
+    for (Ogre::ResourceManager* manager : managers){
+        std::vector<Ogre::ResourceHandle> handles;
+        auto it = manager->getResourceIterator();
+        while (it.hasMoreElements()){
+            const Ogre::ResourcePtr resource = it.getNext();
+            if (resource->getGroup() == "FFVII") handles.push_back(resource->getHandle());
+        }
+        for (const Ogre::ResourceHandle handle : handles){
+            if (manager->getByHandle(handle)) manager->remove(handle);
+        }
+    }
+    for (const std::string& dir : {"temp/char/", "temp/battle_models/", "temp/spell_models/", "temp/effects/", "temp/world_models/"}){
+        if (dir != temp_dir) res_mgr.removeResourceLocation(output_dir_ + dir, "FFVII");
+    }
+}
+
 void DataInstaller::CreateDirectories(){
     for (const std::string& dir : InstallLayout::DataSubdirs()) CreateDir(dir);
     CreateDir("temp", true);
@@ -567,10 +621,12 @@ void DataInstaller::CreateDirectories(){
     fields_lgp_ = std::make_unique<ScopedLgp>(application_.getRoot(), *fields_lgp_path, "LGP", "FFVIIFields");
 }
 
-void DataInstaller::CleanInstall(){
+void DataInstaller::RemoveOriginals(){
+    boost::system::error_code ec;
     // The game itself reads some of the temp directories, so only the rest are removed.
     for (const std::string& dir : InstallLayout::RemovableTempSubdirs())
-        boost::filesystem::remove_all(InstallLayout::TempDir(output_dir_) + dir + "/");
+        boost::filesystem::remove_all(InstallLayout::TempDir(output_dir_) + dir + "/", ec);
+    boost::filesystem::remove_all(InstallLayout::OriginalDataDir(output_dir_), ec);
 }
 
 void DataInstaller::CreateDir(const std::string& path, bool in_root){

+ 41 - 10
src/installer/DataInstaller.h

@@ -18,6 +18,7 @@
 #include <string>
 #include <vector>
 #include <iostream>
+#include <OgreLog.h>
 #include "common/VGearsApplication.h"
 #include "DiskImage.h"
 #include "FieldDataInstaller.h"
@@ -95,15 +96,11 @@ class DataInstaller{
             bool wm_models;
 
             /**
-             * Option to keep original data after installation.
+             * Option to keep the original data after installation: the extracted install disk, the temporary
+             * files and the original files of the converted sounds, music and images.
              */
             bool keep_originals;
 
-            /**
-             * Option to perform a clean installation.
-             */
-            bool clean_install;
-
         };
 
         /**
@@ -165,9 +162,10 @@ class DataInstaller{
         void CreateDirectories();
 
         /**
-         * Cleans up after the installation is complete.
+         * Removes the original data once the installation is complete: the extracted install disk and the
+         * temporary files the game doesn't read.
          */
-        void CleanInstall();
+        void RemoveOriginals();
 
         /**
          * Installation steps.
@@ -472,15 +470,30 @@ class DataInstaller{
          */
         static const char* StepGroup(int state);
 
+        /**
+         * Prepares the resources for the conversion of a kind of models.
+         *
+         * The parts of the models of every kind (field, battle, spells, effects, world map) are in the same resource
+         * group, and many have the same names in different kinds (the field part cbba.rsd and the battle part
+         * cbba.rsd). Ogre keeps every loaded resource by name, so a model would get the part of another kind of
+         * model, loaded before, or the part of another kind left in its temporary folder by a previous installation
+         * in the same directory. This releases the parts loaded before, and leaves in the group only the temporary
+         * folder of the models that will be converted.
+         *
+         * @param[in] temp_dir Temporary folder of the models, relative to the installation directory
+         * ("temp/char/").
+         */
+        void UseModelParts(const std::string& temp_dir);
+
         /**
          * Substeps in the current installation step.
          */
-        int substeps_;
+        int substeps_ = 0;
 
         /**
          * Current substep in the current installation step.
          */
-        int cur_substep_;
+        int cur_substep_ = 0;
 
         /**
          * Weight of each installation step.
@@ -527,6 +540,24 @@ class DataInstaller{
          */
         VGears::Application application_;
 
+        /**
+         * Passes the problems that V-Gears writes to Ogre's log to the installation log.
+         */
+        class OgreProblems : public Ogre::LogListener{
+
+            public:
+
+                void messageLogged(
+                  const Ogre::String& message, Ogre::LogMessageLevel lml, bool mask_debug,
+                  const Ogre::String& log_name, bool& skip_message
+                ) override;
+        };
+
+        /**
+         * Listener of Ogre's log. Declared after the application, so it is destroyed before Ogre.
+         */
+        OgreProblems ogre_problems_;
+
         /**
          * LGP archive with field data.
          */

+ 17 - 1
src/installer/DiskImage.cpp

@@ -561,7 +561,19 @@ DiskImage::DiskImage(std::string path) : DiskImage() {
 
 DiskImage::~DiskImage(){};
 
-bool DiskImage::extractImage(std::string installation_path){
+bool DiskImage::extractImage(std::string installation_path, const std::function<void(float)>& progress){
+    // The progress is how much of the image has been read, reported when it goes up by a percent. The reader can go
+    // back to read some parts again, so it only goes up.
+    const qint64 image_size = QFileInfo(QString::fromStdString(path)).size();
+    int last_percent = -1;
+    const auto report = [&](qint64 done){
+        if (!progress || image_size <= 0) return;
+        const int percent = static_cast<int>(std::min<qint64>(100, 100 * done / image_size));
+        if (percent <= last_percent) return;
+        last_percent = percent;
+        progress(static_cast<float>(percent));
+    };
+    report(0);
     struct archive* a;
     struct archive* ext;
     struct archive_entry* entry;
@@ -653,6 +665,7 @@ bool DiskImage::extractImage(std::string installation_path){
                     std::cerr << "Error writing data block: " << archive_error_string(ext) << std::endl;
                     break;
                 }
+                report(archive_filter_bytes(a, -1));
             }
         }
         archive_write_finish_entry(ext);
@@ -809,6 +822,7 @@ bool DiskImage::extractImage(std::string installation_path){
                                 }
                                 out_file.write(chunk.data(), got);
                                 remaining -= static_cast<uint32_t>(got);
+                                report(image_file.tellg());
                             }
                         }
                     }
@@ -825,6 +839,7 @@ bool DiskImage::extractImage(std::string installation_path){
 
         content_path = data_dir;
         is_extracted = true;
+        if (progress) progress(100);
         return true;
     }
 
@@ -846,6 +861,7 @@ bool DiskImage::extractImage(std::string installation_path){
 
     content_path = data_dir;
     is_extracted = true;
+    if (progress) progress(100);
     return true;
 }
 

+ 4 - 1
src/installer/DiskImage.h

@@ -215,9 +215,12 @@ struct DiskImage{
          * path.
          *
          * @param[in] installation_path The v-gears installation directory.
+         * @param[in] progress Receives the progress [0-100]. It can be empty.
          * @return True if the extraction was successful, false otherwise.
          */
-        bool extractImage(std::string installation_path);
+        bool extractImage(
+          std::string installation_path, const std::function<void(float)>& progress = std::function<void(float)>()
+        );
 
         /**
          * Finds a file in the extracted content of the disk image.

+ 11 - 3
src/installer/ExternalTools.cpp

@@ -251,7 +251,12 @@ namespace ExternalTools{
     }
 
     std::vector<std::string> FfmpegArguments(const std::string& input, const std::string& output){
-        return {"-hide_banner", "-loglevel", "panic", "-y", "-i", input, output};
+        // Bit exact: without it the Ogg stream serial number is random, so every installation writes different
+        // files.
+        return {
+          "-hide_banner", "-loglevel", "panic", "-y", "-i", input, "-fflags", "+bitexact", "-flags:a", "+bitexact",
+          output
+        };
     }
 
     std::vector<std::string> FfmpegStdinArguments(const std::string& output){
@@ -263,7 +268,7 @@ namespace ExternalTools{
         return {
           "-hide_banner", "-loglevel", "panic", "-y", "-i", "-", "-af",
           "areverse,silenceremove=start_periods=1:start_duration=0:start_threshold=-50dB"
-          ":start_silence=0.3:detection=peak,areverse",
+          ":start_silence=0.3:detection=peak,areverse", "-fflags", "+bitexact", "-flags:a", "+bitexact",
           output
         };
     }
@@ -317,7 +322,10 @@ namespace ExternalTools{
         // The sound. Some movies have none.
         const std::string ogg = directory + "/" + name + ".ogg";
         const RunResult sound = Run(
-          ffmpeg, {"-hide_banner", "-loglevel", "panic", "-y", "-i", input, "-vn", ogg}, -1
+          ffmpeg,
+          {"-hide_banner", "-loglevel", "panic", "-y", "-i", input, "-vn", "-fflags", "+bitexact", "-flags:a",
+           "+bitexact", ogg},
+          -1
         );
         if (!sound.started || !sound.finished || sound.exit_code != 0 || fs::file_size(ogg, ec) == 0 || ec)
             fs::remove(ogg, ec);

+ 39 - 30
src/installer/FieldDataInstaller.cpp

@@ -223,18 +223,8 @@ bool FieldDataInstaller::IsAFieldFile(const Ogre::String& resource_name){
 }
 
 bool FieldDataInstaller::WillCrash(const Ogre::String& resource_name){
-    if (
-      resource_name == "bugin1a" // crashes in back ground image generation
-      || resource_name == "fr_e" // Background image crash
-      || resource_name == "las4_2" // Background image crash
-      || resource_name == "las4_3" // Background image crash
-      || resource_name == "lastmap" // Background image crash
-      || resource_name == "md_e1" // Background image crash
-      || resource_name == "trnad_3" // Background image crash
-      || resource_name == "bonevil2" // stof
-      || resource_name == "coloin1" // boost::bad_format_string: format-string is ill-formed
-      || resource_name == "elmin4_2" // boost::bad_format_string: format-string is ill-formed
-    ) return true;
+    // No field is known to crash at the moment.
+    (void)resource_name;
     return false;
 }
 
@@ -571,13 +561,11 @@ void FieldDataInstaller::ConvertModels(std::string model_name){
         if (VGears::HRCFileManager::GetSingleton().resourceExists(model->first, "FFVII"))
             VGears::HRCFileManager::GetSingleton().remove(model->first, "FFVII");
         write_output_line_("[ERROR] Ogre exception converting model " + model->first + ": " + ex.what());
-        std::cerr << "[ERROR] Ogre exception converting model " << model->first <<": " << ex.what() << std::endl;
     }
     catch (const std::exception& ex){
         if (VGears::HRCFileManager::GetSingleton().resourceExists(model->first, "FFVII"))
             VGears::HRCFileManager::GetSingleton().remove(model->first, "FFVII");
         write_output_line_("[ERROR] Exception converting model " + model->first + ": " + ex.what());
-        std::cerr << "[ERROR] Exception converting model " << model->first << ": " << ex.what() << std::endl;
     }
 }
 
@@ -728,21 +716,15 @@ void FieldDataInstaller::PcFieldToVGearsField(VGears::FLevelFilePtr& field){
             try{field_text_writer_.Write(raw_field_data, field->getName());}
             catch (const std::out_of_range& ex){
                 write_output_line_("[ERROR] Failed to read texts from field " + field->getName() + ": " + ex.what());
-                std::cerr << "[ERROR] Failed to read texts from field "
-                  << field->getName() << ": " << ex.what() << std::endl;
             }
             field_text_writer_.End();
         }
         else{
             write_output_line_("[ERROR] Failed to open script file from field " + field->getName() + " for writing.");
-            std::cerr << "[ERROR] Failed to open script file from field "
-              << field->getName() << "for writing." << std::endl;
         }
     }
     catch (const ::DecompilerException& ex){
         write_output_line_("[ERROR] Internal decompiler error in field " + field->getName() + ": " + ex.what());
-        std::cerr << "[ERROR] Internal decompiler error in field "
-          << field->getName() << ": " << ex.what() << std::endl;
     }
     // Write out the map file which links all the other files together for a given field.
     {
@@ -836,16 +818,43 @@ void FieldDataInstaller::PcFieldToVGearsField(VGears::FLevelFilePtr& field){
                 // complex. Now "get the Z value of the triangle with that ID". Note that ID
                 // actually just means index.
                 unsigned int triangle_index = static_cast<unsigned int>(gateway.destination.z);
-                if (triangle_index >= field->GetWalkmesh()->GetTriangles().size()){
-                    write_output_line_(
-                      "[WARNING] In field " + field->getName() + ": Map jump triangle ("
-                      + std::to_string(triangle_index) + ") out of bounds ("
-                      + std::to_string(field->GetWalkmesh()->GetTriangles().size()) + ")"
-                    );
-                    std::cerr << "[WARNING] In field " << field->getName()
-                      << ": Map jump triangle (" << triangle_index << ") out of bounds ("
-                      << field->GetWalkmesh()->GetTriangles().size() << ")" << std::endl;
-                    triangle_index = 0;
+                const auto& triangles = field->GetWalkmesh()->GetTriangles();
+                if (triangle_index >= triangles.size()){
+                    // Some map jumps of the original scripts have a triangle that is not in the walkmesh (pillar_3
+                    // to mds6_22). The one under the position is used instead, in the units the walkmesh is
+                    // written in.
+                    const float scale = GetFieldScaleFactor(this_field_id);
+                    const float x = gateway.destination.x / downscaler_next;
+                    const float y = gateway.destination.y / downscaler_next;
+                    const auto side = [x, y](const Ogre::Vector3& a, const Ogre::Vector3& b){
+                        return (x - b.x) * (a.y - b.y) - (a.x - b.x) * (y - b.y);
+                    };
+                    size_t under = triangles.size();
+                    for (size_t t = 0; t < triangles.size() && under == triangles.size(); t ++){
+                        const Ogre::Vector3 a = triangles[t].a / scale, b = triangles[t].b / scale;
+                        const Ogre::Vector3 c = triangles[t].c / scale;
+                        const float d1 = side(a, b), d2 = side(b, c), d3 = side(c, a);
+                        const bool negative = d1 < 0 || d2 < 0 || d3 < 0, positive = d1 > 0 || d2 > 0 || d3 > 0;
+                        if (!(negative && positive)) under = t;
+                    }
+                    const SpawnPointDb::Record& record = spawn_point_records[i];
+                    const std::string source = record.from_script
+                      ? "the script " + record.entity_name + ":" + record.script_function_name + " (address "
+                        + std::to_string(record.gateway_index_or_map_jump_address) + ")"
+                      : "the door " + std::to_string(record.gateway_index_or_map_jump_address);
+                    // Only reported when the position is not on the walkmesh either: those jumps are of the debug
+                    // rooms (blackbg1, blackbg4) or of scenes that place the player themselves.
+                    if (under == triangles.size()){
+                        write_output_line_(
+                          "[WARNING] In field " + field->getName() + ": the entrance from "
+                          + map_list_.at(record.field_id) + " (" + source + ") is on the walkmesh triangle "
+                          + std::to_string(triangle_index) + ", which the walkmesh doesn't have (it has "
+                          + std::to_string(triangles.size()) + "), at (" + std::to_string(gateway.destination.x) + ", "
+                          + std::to_string(gateway.destination.y) + "), which is not on the walkmesh."
+                        );
+                        triangle_index = 0;
+                    }
+                    else triangle_index = static_cast<unsigned int>(under);
                 }
                 const float z_of_triangle_with_id
                   = field->GetWalkmesh()->GetTriangles().at(triangle_index).a.z / GetFieldScaleFactor(this_field_id);

+ 24 - 5
src/installer/FieldTextWriter.cpp

@@ -37,12 +37,22 @@ void FieldTextWriter::Begin(std::string file_name){
 }
 
 u16 FieldTextWriter::GetU16LE(u32 offset){
-    if (offset+1 >= data_.size()) throw std::out_of_range("");
+    if (offset+1 >= data_.size()){
+        throw std::out_of_range(
+          "reading past the end of the script section (" + std::to_string(offset) + " of " + std::to_string(data_.size())
+          + " bytes)"
+        );
+    }
     return *reinterpret_cast<u16*>(&data_[offset]);
 }
 
 u8 FieldTextWriter::GetU8(u32 offset){
-    if (offset >= data_.size()) throw std::out_of_range("");
+    if (offset >= data_.size()){
+        throw std::out_of_range(
+          "reading past the end of the script section (" + std::to_string(offset) + " of " + std::to_string(data_.size())
+          + " bytes)"
+        );
+    }
     return data_[offset];
 }
 
@@ -64,8 +74,15 @@ void FieldTextWriter::Write(const std::vector<u8>& script_section_buffer, std::s
     if (tag_open_){
         logger_->Log("[ERROR exception]");
         logger_->Log("</dialog>\n");
+        tag_open_ = false;
     }
-    u16 dialogCount = GetU16LE(offset_to_sector + offset_to_dialogs);
+    // A field without texts can have its table of texts at the end of the section, with no room for it (nivgate3,
+    // nivl_4), or with bytes that are not a table (las4_42).
+    const u32 table = offset_to_sector + offset_to_dialogs;
+    if (table + 2 > data_.size()) return;
+    const auto fits = [this, table](u32 count){return table + 2 + count * 2 <= data_.size();};
+    u16 dialogCount = GetU16LE(table);
+    if (!fits(dialogCount)) dialogCount = 0;
     // The first string comes right after the table of offsets, so its offset says how many strings
     // there are. A field with 256 of them has a count that doesn't fit (it is read as 0), and the
     // field would have no texts at all.
@@ -73,7 +90,7 @@ void FieldTextWriter::Write(const std::vector<u8>& script_section_buffer, std::s
         const u16 first_offset = GetU16LE(offset_to_sector + offset_to_dialogs + 0x02);
         if (first_offset >= 0x02 && (first_offset % 2) == 0){
             const u16 count_from_table = (first_offset - 0x02) / 2;
-            if (count_from_table > dialogCount) dialogCount = count_from_table;
+            if (count_from_table > dialogCount && fits(count_from_table)) dialogCount = count_from_table;
         }
     }
     for (u16 i = 0; i <dialogCount; ++ i){
@@ -91,7 +108,9 @@ void FieldTextWriter::Write(const std::vector<u8>& script_section_buffer, std::s
         int colour_opened = 0;
         // Number of the next variable code of the dialog (see MPARA and MPRA2 in the scripts).
         int variable_count = 0;
-        for (unsigned char temp = 0x00;; ++ offset){
+        // A text ends with 0xFF, or at the end of the section: the empty texts of some fields have no end mark
+        // (life, life2).
+        for (unsigned char temp = 0x00; offset < data_.size(); ++ offset){
             temp = GetU8(offset);
             if (temp == 0xFF) break;
             if (temp == 0xE0 && english == true){

+ 307 - 0
src/installer/InstallCommandLine.cpp

@@ -0,0 +1,307 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <sstream>
+#include "InstallCommandLine.h"
+
+namespace{
+
+    /**
+     * Name of a preset in the command line, and the preset.
+     */
+    struct PresetName{
+        const char* name;
+        InstallPreset preset;
+    };
+
+    const PresetName kPresets[] = {
+      {"everything", InstallPreset::EVERYTHING},
+      {"fields", InstallPreset::FIELDS},
+      {"world-map", InstallPreset::WORLD_MAP},
+      {"battle", InstallPreset::BATTLE},
+      {"media", InstallPreset::MEDIA},
+      {"custom", InstallPreset::CUSTOM}
+    };
+
+    /**
+     * Splits a comma separated list, skipping empty items.
+     */
+    std::vector<std::string> SplitList(const std::string& list){
+        std::vector<std::string> items;
+        std::stringstream stream(list);
+        std::string item;
+        while (std::getline(stream, item, ',')) if (!item.empty()) items.push_back(item);
+        return items;
+    }
+
+    /**
+     * Finds a part by name.
+     *
+     * @return The part, or nullptr if there is no part with that name.
+     */
+    const InstallCommandLine::Part* FindPart(const std::string& name){
+        for (const InstallCommandLine::Part& part : InstallCommandLine::Parts()) if (name == part.name) return &part;
+        return nullptr;
+    }
+
+    /**
+     * Gets the names of the parts, separated by commas.
+     */
+    std::string PartNames(){
+        std::string names;
+        for (const InstallCommandLine::Part& part : InstallCommandLine::Parts())
+            names += (names.empty() ? "" : ", ") + std::string(part.name);
+        return names;
+    }
+
+    /**
+     * Gets the names of the presets, separated by commas.
+     */
+    std::string PresetNames(){
+        std::string names;
+        for (const PresetName& preset : kPresets) names += (names.empty() ? "" : ", ") + std::string(preset.name);
+        return names;
+    }
+
+    /**
+     * Marks the command line as wrong.
+     */
+    InstallCommandLine::Arguments Invalid(const std::string& error){
+        InstallCommandLine::Arguments arguments;
+        arguments.mode = InstallCommandLine::Mode::INVALID;
+        arguments.error = error;
+        return arguments;
+    }
+
+}
+
+namespace InstallCommandLine{
+
+    const std::vector<Part>& Parts(){
+        static const std::vector<Part> parts = {
+          {"kernel", "Kernel data: items, materia, characters...", &InstallOptions::kernel},
+          {"fields", "Field maps", &InstallOptions::fields},
+          {"field-models", "Field 3D models (needs fields)", &InstallOptions::field_models},
+          {"world-map", "World map", &InstallOptions::wm},
+          {"world-map-models", "World map 3D models (needs world-map)", &InstallOptions::wm_models},
+          {"battle-data", "Battle scenes", &InstallOptions::battle_data},
+          {"battle-models", "Battle 3D models", &InstallOptions::battle_models},
+          {"images", "Images", &InstallOptions::images},
+          {"sounds", "Sound effects (needs FFmpeg)", &InstallOptions::sounds},
+          {"music", "Music (needs TiMidity and FFmpeg)", &InstallOptions::music},
+          {"videos", "Videos (only from game disks 1, 2 and 3; needs FFmpeg)", &InstallOptions::videos}
+        };
+        return parts;
+    }
+
+    Arguments Parse(const std::vector<std::string>& args){
+        Arguments arguments;
+        bool cli = false;
+        bool verify = false;
+        bool list_parts = false;
+        bool help = false;
+        bool version = false;
+        bool preset_given = false;
+        std::vector<std::string> added;
+        std::vector<std::string> removed;
+        std::vector<std::string> unknown;
+        for (size_t i = 0; i < args.size(); ++ i){
+            std::string arg = args[i];
+            // "--option=value" is the same as "--option value".
+            std::string inline_value;
+            bool has_inline_value = false;
+            const size_t equals = arg.find('=');
+            if (arg.compare(0, 2, "--") == 0 && equals != std::string::npos){
+                inline_value = arg.substr(equals + 1);
+                arg = arg.substr(0, equals);
+                has_inline_value = true;
+            }
+            // Reads the value of an option. Returns false if it is missing.
+            std::string value;
+            const auto take_value = [&](){
+                if (has_inline_value){
+                    value = inline_value;
+                    return true;
+                }
+                if (i + 1 >= args.size()) return false;
+                value = args[++ i];
+                return true;
+            };
+            const auto needs_value = [&](const std::string& name){return "Missing value for " + name + ".";};
+
+            if (arg == "--cli") cli = true;
+            else if (arg == "--verify") verify = cli = true;
+            else if (arg == "--list-parts") list_parts = true;
+            else if (arg == "-h" || arg == "--help") help = true;
+            else if (arg == "-v" || arg == "--version") version = true;
+            else if (arg == "-y" || arg == "--yes") arguments.yes = cli = true;
+            else if (arg == "--no-copy-data"){
+                arguments.copy_data = false;
+                cli = true;
+            }
+            else if (arg == "--keep-originals"){
+                arguments.keep_originals = true;
+                cli = true;
+            }
+            else if (arg == "--clean"){
+                arguments.clean = true;
+                cli = true;
+            }
+            else if (arg == "--strict"){
+                arguments.strict = true;
+                cli = true;
+            }
+            else if (arg == "-i" || arg == "--iso"){
+                if (!take_value()) return Invalid(needs_value(arg));
+                arguments.iso = value;
+                cli = true;
+            }
+            else if (arg == "-o" || arg == "--output"){
+                if (!take_value()) return Invalid(needs_value(arg));
+                arguments.output = value;
+                cli = true;
+            }
+            else if (arg == "--data-dir"){
+                if (!take_value()) return Invalid(needs_value(arg));
+                arguments.data_dir = value;
+                cli = true;
+            }
+            else if (arg == "--ffmpeg"){
+                if (!take_value()) return Invalid(needs_value(arg));
+                arguments.ffmpeg = value;
+                cli = true;
+            }
+            else if (arg == "--timidity"){
+                if (!take_value()) return Invalid(needs_value(arg));
+                arguments.timidity = value;
+                cli = true;
+            }
+            else if (arg == "-p" || arg == "--preset"){
+                if (!take_value()) return Invalid(needs_value(arg));
+                bool found = false;
+                for (const PresetName& preset : kPresets){
+                    if (value == preset.name){
+                        arguments.preset = preset.preset;
+                        found = true;
+                    }
+                }
+                if (!found) return Invalid("Unknown preset '" + value + "'. The presets are: " + PresetNames() + ".");
+                preset_given = cli = true;
+            }
+            else if (arg == "--with" || arg == "--without"){
+                if (!take_value()) return Invalid(needs_value(arg));
+                for (const std::string& name : SplitList(value)){
+                    if (FindPart(name) == nullptr)
+                        return Invalid("Unknown part '" + name + "'. The parts are: " + PartNames() + ".");
+                    (arg == "--with" ? added : removed).push_back(name);
+                }
+                cli = true;
+            }
+            else unknown.push_back(args[i]);
+        }
+
+        // Requests for information are answered whatever else is in the command line.
+        if (help){
+            arguments.mode = Mode::HELP;
+            return arguments;
+        }
+        if (version){
+            arguments.mode = Mode::VERSION;
+            return arguments;
+        }
+        if (list_parts){
+            arguments.mode = Mode::LIST_PARTS;
+            return arguments;
+        }
+        // Without installer options, the window is opened, and Qt gets the rest of the arguments.
+        if (!cli){
+            arguments.mode = Mode::GUI;
+            return arguments;
+        }
+        if (!unknown.empty()) return Invalid("Unknown argument '" + unknown.front() + "'.");
+
+        // The parts: those of the preset, plus those added, minus those removed. Like in the window, the presets
+        // don't include the videos: they are not on the install disk, and the game disks only have videos.
+        arguments.options = InstallRules::Preset(arguments.preset, false);
+        for (const std::string& name : added) arguments.options.*(FindPart(name)->option) = true;
+        for (const std::string& name : removed) arguments.options.*(FindPart(name)->option) = false;
+        const InstallOptions selectable = InstallRules::Selectable(arguments.options);
+        for (const std::string& name : added){
+            const Part* part = FindPart(name);
+            if (arguments.options.*(part->option) && !(selectable.*(part->option)))
+                return Invalid("The part '" + name + "' can't be installed: " + part->description + ".");
+        }
+        InstallRules::ApplyDependencies(arguments.options);
+
+        if (verify){
+            if (!arguments.iso.empty()) return Invalid("--verify checks an installation, it doesn't take an ISO.");
+            if (preset_given || !added.empty() || !removed.empty())
+                return Invalid("--verify checks everything; it doesn't take a preset or parts.");
+            if (arguments.clean) return Invalid("--verify checks an installation, it doesn't delete it.");
+            arguments.mode = Mode::VERIFY;
+            return arguments;
+        }
+        if (arguments.iso.empty()) return Invalid("No ISO image given. Use --iso <file>.");
+        arguments.mode = Mode::INSTALL;
+        return arguments;
+    }
+
+    std::string Usage(const std::string& program){
+        std::stringstream usage;
+        usage
+          << "Usage:\n"
+          << "  " << program << "                      Open the installer window.\n"
+          << "  " << program << " --cli --iso <file> [options]\n"
+          << "                                         Install from the command line.\n"
+          << "  " << program << " --verify [--output <dir>]\n"
+          << "                                         Check that an installation has everything the game needs.\n"
+          << "\n"
+          << "Installation options:\n"
+          << "  -i, --iso <file>         The disk image. The install disk installs the game; game disks 1, 2\n"
+          << "                           and 3 only add their videos to an installation.\n"
+          << "  -o, --output <dir>       Installation directory. Default: the one the game reads.\n"
+          << "  -p, --preset <name>      What to install: " << PresetNames() << ".\n"
+          << "                           Default: everything. 'custom' starts with nothing.\n"
+          << "      --with <parts>       Install these parts too (comma separated).\n"
+          << "      --without <parts>    Don't install these parts (comma separated).\n"
+          << "      --no-copy-data       Don't copy the V-Gears data files: the installation directory\n"
+          << "                           must already have them.\n"
+          << "      --data-dir <dir>     The V-Gears 'data' folder to copy. Default: looked for next to\n"
+          << "                           the installer and in the system.\n"
+          << "      --clean              Delete the data of a previous installation first. The saves, the\n"
+          << "                           controls, the game configuration and the videos are kept.\n"
+          << "      --keep-originals     Keep the original data once converted: the extracted disk, the\n"
+          << "                           temporary files and the original sounds, music and images.\n"
+          << "      --ffmpeg <file>      Path to FFmpeg. Default: looked for in the 'tools' folder of the\n"
+          << "                           installation and of the installer, then in the PATH.\n"
+          << "      --timidity <file>    Path to TiMidity. Looked for like FFmpeg.\n"
+          << "  -y, --yes                Continue when there are warnings or the audio tools are missing.\n"
+          << "      --strict             End with status 3 if the installation finished with errors in its log.\n"
+          << "\n"
+          << "Other options:\n"
+          << "      --cli                Use the command line, not the window. Implied by any option above.\n"
+          << "      --list-parts         List the parts that can be installed.\n"
+          << "  -h, --help               Show this help.\n"
+          << "  -v, --version            Show the version.\n"
+          << "\n"
+          << "Parts: " << PartNames() << ".\n"
+          << "\n"
+          << "Exit status: 0 if everything went well, 1 if the installation or the verification failed,\n"
+          << "2 if the command line is wrong, 3 if it finished with errors and --strict was given, 130 if it\n"
+          << "was interrupted.\n";
+        return usage.str();
+    }
+
+}

+ 191 - 0
src/installer/InstallCommandLine.h

@@ -0,0 +1,191 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#pragma once
+
+#include <string>
+#include <vector>
+#include "InstallOptions.h"
+
+/**
+ * Command line of the installer.
+ *
+ * Without arguments the installer opens its window. With "--cli", or any of the installation options, it installs
+ * from the command line instead.
+ */
+namespace InstallCommandLine{
+
+    /**
+     * What the installer must do.
+     */
+    enum class Mode{
+
+        /**
+         * Open the installer window.
+         */
+        GUI,
+
+        /**
+         * Install from the command line.
+         */
+        INSTALL,
+
+        /**
+         * Verify an installation from the command line.
+         */
+        VERIFY,
+
+        /**
+         * Print the list of installable parts.
+         */
+        LIST_PARTS,
+
+        /**
+         * Print the usage.
+         */
+        HELP,
+
+        /**
+         * Print the version.
+         */
+        VERSION,
+
+        /**
+         * The command line is wrong. The error is in Arguments::error.
+         */
+        INVALID
+    };
+
+    /**
+     * The parsed command line.
+     */
+    struct Arguments{
+
+        /**
+         * What to do.
+         */
+        Mode mode = Mode::GUI;
+
+        /**
+         * Why the command line is wrong, when the mode is INVALID.
+         */
+        std::string error;
+
+        /**
+         * Path of the disk image.
+         */
+        std::string iso;
+
+        /**
+         * Installation directory. Empty to use the default one.
+         */
+        std::string output;
+
+        /**
+         * The preset the options start from.
+         */
+        InstallPreset preset = InstallPreset::EVERYTHING;
+
+        /**
+         * The parts to install: the preset, with the parts added and removed by the user.
+         */
+        InstallOptions options;
+
+        /**
+         * True to copy the V-Gears data files (configuration, scripts...) to the installation directory.
+         */
+        bool copy_data = true;
+
+        /**
+         * Path to the V-Gears data folder to copy. Empty to look for it.
+         */
+        std::string data_dir;
+
+        /**
+         * True to keep the original data after converting it: the extracted install disk, the temporary files and
+         * the original sounds, music and images.
+         */
+        bool keep_originals = false;
+
+        /**
+         * True to delete the data of a previous installation in the directory first.
+         */
+        bool clean = false;
+
+        /**
+         * True to end with an error status when the installation finished with errors in its log.
+         */
+        bool strict = false;
+
+        /**
+         * Path to FFmpeg. Empty to look for it.
+         */
+        std::string ffmpeg;
+
+        /**
+         * Path to TiMidity. Empty to look for it.
+         */
+        std::string timidity;
+
+        /**
+         * True to continue when there are warnings or the audio tools are missing, instead of stopping.
+         */
+        bool yes = false;
+    };
+
+    /**
+     * Name and description of an installable part.
+     */
+    struct Part{
+
+        /**
+         * Name used in the command line.
+         */
+        const char* name;
+
+        /**
+         * Description shown to the user.
+         */
+        const char* description;
+
+        /**
+         * The option of the part.
+         */
+        bool InstallOptions::* option;
+    };
+
+    /**
+     * Gets the installable parts.
+     */
+    const std::vector<Part>& Parts();
+
+    /**
+     * Parses the command line.
+     *
+     * Arguments that are not installer options are left for Qt when the window is opened (for example "-platform"),
+     * and are an error from the command line.
+     *
+     * @param[in] args The arguments, without the program name.
+     */
+    Arguments Parse(const std::vector<std::string>& args);
+
+    /**
+     * Gets the usage text.
+     *
+     * @param[in] program Name of the program.
+     */
+    std::string Usage(const std::string& program);
+
+}

+ 54 - 0
src/installer/InstallLayout.cpp

@@ -13,10 +13,64 @@
  * GNU General Public License for more details.
  */
 
+#include <algorithm>
+#include <boost/filesystem.hpp>
+#include "common/InstallStamp.h"
 #include "InstallLayout.h"
 
 namespace InstallLayout{
 
+    namespace{
+
+        /**
+         * Removes a file or a directory with its contents, and counts what was removed.
+         */
+        void Remove(const boost::filesystem::path& path, CleanResult& result){
+            boost::system::error_code ec;
+            const auto removed = boost::filesystem::remove_all(path, ec);
+            if (ec) result.errors.push_back(path.string() + ": " + ec.message());
+            else result.removed += removed;
+        }
+
+    }
+
+    std::string OriginalDataDir(const std::string& root){return root + "original_data/";}
+
+    const std::vector<std::string>& CleanInstallKeptDataDirs(){
+        static const std::vector<std::string> dirs = {"config", "video"};
+        return dirs;
+    }
+
+    bool IsInstallation(const std::string& root){
+        boost::system::error_code ec;
+        return boost::filesystem::is_regular_file(root + "plugins.cfg", ec)
+          && boost::filesystem::is_regular_file(root + "resources.cfg", ec);
+    }
+
+    CleanResult CleanInstallation(const std::string& root){
+        namespace fs = boost::filesystem;
+        CleanResult result;
+        if (!IsInstallation(root)) return result;
+        boost::system::error_code ec;
+        if (fs::exists(OriginalDataDir(root), ec)) Remove(OriginalDataDir(root), result);
+        if (fs::exists(TempDir(root), ec)) Remove(TempDir(root), result);
+        // The record of the installations describes what was just deleted.
+        if (fs::exists(root + VGears::InstallStamp::FILE_NAME, ec)) Remove(root + VGears::InstallStamp::FILE_NAME, result);
+        const fs::path data(DataDir(root));
+        if (fs::is_directory(data, ec)){
+            const std::vector<std::string>& kept = CleanInstallKeptDataDirs();
+            std::vector<fs::path> entries;
+            for (fs::directory_iterator it(data, ec), end; !ec && it != end; it.increment(ec))
+                entries.push_back(it->path());
+            if (ec) result.errors.push_back(data.string() + ": " + ec.message());
+            for (const fs::path& entry : entries){
+                if (std::find(kept.begin(), kept.end(), entry.filename().string()) == kept.end())
+                    Remove(entry, result);
+            }
+        }
+        return result;
+    }
+
     std::string DataDir(const std::string& root){return root + "data/";}
 
     std::string TempDir(const std::string& root){return root + "temp/";}

+ 51 - 0
src/installer/InstallLayout.h

@@ -62,6 +62,57 @@ namespace InstallLayout{
      */
     std::vector<std::string> RemovableTempSubdirs();
 
+    /**
+     * Gets the directory where the installation disk is extracted.
+     *
+     * Its files are only read while installing.
+     *
+     * @param[in] root Installation directory, ending with '/'.
+     */
+    std::string OriginalDataDir(const std::string& root);
+
+    /**
+     * Directories of the game data (in <installation directory>/data) that a clean installation keeps: the
+     * configuration of the game, and the videos, which come from the game disks, not from the install disk.
+     */
+    const std::vector<std::string>& CleanInstallKeptDataDirs();
+
+    /**
+     * Tells if a directory is a V-Gears installation: it has the configuration files the installer copies.
+     *
+     * @param[in] root The directory, ending with '/'.
+     */
+    bool IsInstallation(const std::string& root);
+
+    /**
+     * Result of cleaning an installation.
+     */
+    struct CleanResult{
+
+        /**
+         * Number of files and directories removed.
+         */
+        unsigned long long removed = 0;
+
+        /**
+         * What could not be removed.
+         */
+        std::vector<std::string> errors;
+    };
+
+    /**
+     * Deletes what a previous installation wrote, so a new one starts from nothing.
+     *
+     * It removes the extracted disk, the temporary files, the record of the installations (install.info) and the
+     * game data, except the directories in
+     * {@see CleanInstallKeptDataDirs}. The rest of the installation directory (saves, controls, the configuration
+     * files of V-Gears and Ogre, logs) is kept. A directory that is not an installation ({@see IsInstallation}) is
+     * not touched.
+     *
+     * @param[in] root Installation directory, ending with '/'.
+     */
+    CleanResult CleanInstallation(const std::string& root);
+
     /**
      * Directories the game registers as resource locations, relative to the installation directory.
      */

+ 5 - 2
src/installer/InstallLog.cpp

@@ -49,7 +49,7 @@ class InstallLog::Tee : public std::streambuf{
             std::string line;
             {
                 std::lock_guard<std::mutex> lock(mutex_);
-                original_->sputc(static_cast<char>(c));
+                if (log_.echo_) original_->sputc(static_cast<char>(c));
                 if (c == '\n') line.swap(line_);
                 else line_ += static_cast<char>(c);
             }
@@ -100,8 +100,11 @@ void InstallLog::Close(){
     tee_err_.reset();
     std::lock_guard<std::mutex> lock(mutex_);
     if (file_.is_open()) file_.close();
+    echo_ = true;
 }
 
+void InstallLog::SetEcho(bool echo){echo_ = echo;}
+
 void InstallLog::SetSink(Sink sink){
     std::lock_guard<std::mutex> lock(mutex_);
     sink_ = std::move(sink);
@@ -127,7 +130,7 @@ void InstallLog::Add(const std::string& message, bool show){
         if (show) sink = sink_;
     }
     // Echo to the terminal without capturing the message again.
-    if (tee_out_) tee_out_->WriteOriginal(message + "\n");
+    if (tee_out_ && echo_) tee_out_->WriteOriginal(message + "\n");
     if (sink) sink(level, message);
 }
 

+ 16 - 0
src/installer/InstallLog.h

@@ -16,6 +16,7 @@
 #pragma once
 
 #include <fstream>
+#include <atomic>
 #include <functional>
 #include <iostream>
 #include <memory>
@@ -72,6 +73,16 @@ class InstallLog{
          */
         void SetSink(Sink sink);
 
+        /**
+         * Sets if the messages and the captured standard streams are written to the terminal.
+         *
+         * They are by default. A program that draws its own output (the progress line of the command line
+         * installer) turns it off and shows the messages it gets in the sink. Closing the log turns it on again.
+         *
+         * @param[in] echo True to write to the terminal.
+         */
+        void SetEcho(bool echo);
+
         /**
          * Adds a message.
          *
@@ -127,6 +138,11 @@ class InstallLog{
         void AddCaptured(const std::string& line);
 
         mutable std::mutex mutex_;
+
+        /**
+         * True to write the messages and the captured streams to the terminal.
+         */
+        std::atomic<bool> echo_{true};
         std::ofstream file_;
         std::string path_;
         Sink sink_;

+ 362 - 0
src/installer/InstallSteps.cpp

@@ -0,0 +1,362 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <algorithm>
+#include <iostream>
+#include <boost/filesystem.hpp>
+#include <QtCore/QCoreApplication>
+#include <QtCore/QDir>
+#include <QtCore/QDirIterator>
+#include <QtCore/QFile>
+#include <QtCore/QFileInfo>
+#include <QtCore/QObject>
+#include <QtCore/QStorageInfo>
+#include <OgrePrerequisites.h>
+#include "common/DataDirectory.h"
+#include "common/OgrePlugins.h"
+#include "ExternalTools.h"
+#include "common/InstallStamp.h"
+#include "InstallCommandLine.h"
+#include "InstallLog.h"
+#include "InstallSteps.h"
+#include "MovieCamera.h"
+
+#ifndef VGEARS_INSTALLER_VERSION
+#define VGEARS_INSTALLER_VERSION "unknown"
+#endif
+
+#ifndef VGEARS_OGRE_PLUGIN_DIR
+#define VGEARS_OGRE_PLUGIN_DIR ""
+#endif
+
+namespace{
+
+    /**
+     * Minimum free space needed besides the ISO extraction: converted data, intermediate files and logs.
+     */
+    const qint64 kRequiredFreeSpace = 3LL * 1024 * 1024 * 1024;
+
+    /**
+     * Free space needed to extract the videos of a game disk.
+     */
+    const qint64 kRequiredVideoSpace = 1024LL * 1024 * 1024;
+
+    /**
+     * Checks that a directory can be created and written, and that it has enough free space.
+     *
+     * @param[in] output The directory, ending with '/'.
+     * @param[in] needed Free space needed, in bytes.
+     * @param[out] errors The problems found are added here.
+     */
+    void CheckWritable(const QString& output, qint64 needed, QStringList& errors){
+        if (!QDir().mkpath(output)){
+            errors << QObject::tr("The installation directory can't be created: %1").arg(output);
+            return;
+        }
+        QFile probe(output + ".v-gears-write-test");
+        if (!probe.open(QIODevice::WriteOnly))
+            errors << QObject::tr("The installation directory is not writable: %1").arg(output);
+        else{
+            probe.close();
+            probe.remove();
+        }
+        const QStorageInfo storage(output);
+        if (storage.isValid() && storage.bytesAvailable() < needed){
+            errors << QObject::tr("Not enough free space in %1: %2 MB available, about %3 MB needed.")
+              .arg(storage.rootPath()).arg(storage.bytesAvailable() / (1024 * 1024)).arg(needed / (1024 * 1024));
+        }
+    }
+
+    /**
+     * Names of the plugins in the plugins.cfg of a folder that the game won't find.
+     *
+     * The game looks for them in the same places (see VGears::OgrePlugins::SearchDirectories), so they don't need to
+     * be copied to the installation directory.
+     */
+    QStringList MissingOgrePlugins(const QString& source_dir){
+        namespace bfs = boost::filesystem;
+        QStringList missing;
+        const bfs::path dir(source_dir.toStdString());
+        VGears::OgrePlugins::Config config;
+        if (!VGears::OgrePlugins::ReadConfig(dir / "plugins.cfg", config)) return missing;
+        const std::vector<bfs::path> directories = VGears::OgrePlugins::SearchDirectories(
+          dir, config.folder, bfs::path(QCoreApplication::applicationDirPath().toStdString()), VGEARS_OGRE_PLUGIN_DIR
+        );
+        const std::string version = std::to_string(OGRE_VERSION_MAJOR) + "." + std::to_string(OGRE_VERSION_MINOR)
+          + "." + std::to_string(OGRE_VERSION_PATCH);
+        for (const std::string& name : config.plugins){
+            if (VGears::OgrePlugins::Find(name, directories, version).empty()) missing << QString::fromStdString(name);
+        }
+        return missing;
+    }
+
+}
+
+namespace InstallSteps{
+
+    QString DefaultInstallDir(){
+        const boost::filesystem::path dir = VGears::DataDirectory::DefaultDirectory();
+        return dir.empty() ? QString() : QDir::fromNativeSeparators(QString::fromStdString(dir.string()));
+    }
+
+    QString NormalizeOutputDir(const QString& dir){
+        QString output = QDir::fromNativeSeparators(dir);
+        if (QDir::isRelativePath(output)) output = QDir(output).absolutePath();
+        if (!output.endsWith("/")) output += "/";
+        return output;
+    }
+
+    QString FindGameDataDir(){
+        // The same places the game copies its files from when the data directory is empty, then the current directory.
+        std::vector<boost::filesystem::path> candidates = VGears::DataDirectory::TemplateCandidates(
+          boost::filesystem::path(QCoreApplication::applicationDirPath().toStdString())
+        );
+        candidates.emplace_back((QDir::currentPath() + "/data").toStdString());
+        candidates.emplace_back((QDir::currentPath() + "/../data").toStdString());
+        const boost::filesystem::path found = VGears::DataDirectory::FindTemplate(candidates, boost::filesystem::path());
+        return found.empty() ? QString() : QDir::cleanPath(QString::fromStdString(found.string()));
+    }
+
+    PreflightResult RunPreflight(
+      DiskImage& disk_image, const QString& output, bool copy_data, const QString& game_data_dir, bool clean
+    ){
+        PreflightResult result;
+        // A clean installation deletes the V-Gears data files too, so they must be copied again.
+        if (clean && !copy_data){
+            result.errors << QObject::tr(
+              "A clean installation deletes the V-Gears data files of the installation directory too: enable 'Copy "
+              "V-Gears data files'."
+            );
+        }
+        const QString iso_path = QString::fromStdString(disk_image.getPath());
+
+        // Input.
+        if (iso_path.isEmpty()) result.errors << QObject::tr("No ISO image selected.");
+        else if (!QFileInfo(iso_path).isReadable())
+            result.errors << QObject::tr("The ISO image can't be read: %1").arg(iso_path);
+        else if (!disk_image.isValid())
+            result.errors << QObject::tr("The selected ISO is not a valid Final Fantasy VII image.");
+        else if (!disk_image.isSupported())
+            result.warnings << QString::fromStdString(disk_image.getWarningMessage());
+
+        // Output: it must be creatable and writable, with room for the extracted ISO plus the converted data.
+        CheckWritable(
+          output, kRequiredFreeSpace + (iso_path.isEmpty() ? 0 : QFileInfo(iso_path).size()), result.errors
+        );
+
+        // Configuration and plugins.
+        if (copy_data){
+            if (
+              game_data_dir.isEmpty() || !QFile::exists(game_data_dir + "/plugins.cfg")
+              || !QDir(game_data_dir + "/data").exists()
+            ){
+                result.errors << QObject::tr(
+                  "The V-Gears 'data' folder was not found (it must contain plugins.cfg and a data folder)."
+                );
+            }
+            else{
+                const QStringList missing = MissingOgrePlugins(game_data_dir);
+                if (!missing.isEmpty()){
+                    result.errors << QObject::tr("Ogre plugins not found in the data folder or the system: %1")
+                      .arg(missing.join(", "));
+                }
+            }
+        }
+        else{
+            if (!QFile::exists(output + "plugins.cfg") || !QFile::exists(output + "resources.cfg")){
+                result.errors << QObject::tr(
+                  "The installation directory has no plugins.cfg and resources.cfg. Enable 'Copy V-Gears data files'."
+                );
+            }
+            else{
+                const QStringList missing = MissingOgrePlugins(output);
+                if (!missing.isEmpty()){
+                    result.errors << QObject::tr(
+                      "Ogre plugins not found in the installation directory or the system: %1"
+                    ).arg(missing.join(", "));
+                }
+            }
+        }
+        return result;
+    }
+
+    VerifyPlugins PluginSearch(){
+        VerifyPlugins search;
+        search.executable_dir = QCoreApplication::applicationDirPath().toStdString();
+        search.ogre_version = std::to_string(OGRE_VERSION_MAJOR) + "." + std::to_string(OGRE_VERSION_MINOR) + "."
+          + std::to_string(OGRE_VERSION_PATCH);
+        return search;
+    }
+
+    QStringList CheckVideoOutput(const QString& output){
+        QStringList errors;
+        CheckWritable(output, kRequiredVideoSpace, errors);
+        return errors;
+    }
+
+    bool CopyDirectory(const QString& src, const QString& dst, const std::function<void(float)>& progress){
+        const QDir src_dir(src);
+        if (!QDir().mkpath(dst)) return false;
+        bool ok = true;
+        // The files are listed first, to know the progress.
+        QStringList files;
+        QDirIterator it(src, QDir::Files | QDir::NoDotAndDotDot, QDirIterator::Subdirectories);
+        while (it.hasNext()) files << it.next();
+        if (progress) progress(0);
+        for (int f = 0; f < files.size(); ++ f){
+            if (progress) progress(100.0f * f / files.size());
+            const QString& file = files[f];
+            const QString relative = src_dir.relativeFilePath(file);
+            const QString target = dst + "/" + relative;
+            if (relative.startsWith("data/config/") && QFile::exists(target)) continue;
+            QDir().mkpath(QFileInfo(target).absolutePath());
+            if (QFile::exists(target)) QFile::remove(target);
+            if (!QFile::copy(file, target)){
+                std::cout << "Could not copy " << file.toStdString() << " to " << target.toStdString() << std::endl;
+                ok = false;
+            }
+        }
+        if (progress) progress(100);
+        return ok;
+    }
+
+    float OverallProgress(Phase phase, float progress){
+        const float value = std::max(0.0f, std::min(100.0f, progress));
+        switch (phase){
+            case Phase::EXTRACT: return value * 0.05f;
+            case Phase::COPY: return 5.0f + value * 0.01f;
+            case Phase::CONVERT: return 6.0f + value * 0.94f;
+        }
+        return value;
+    }
+
+    std::vector<std::string> MissingRequiredFiles(DiskImage& disk_image){
+        // TODO: Enumerate files or find some better way to do this.
+        static const std::vector<std::string> required_files = {
+          "data/field/char.lgp",
+          "data/field/flevel.lgp",
+          "data/kernel/KERNEL.BIN",
+          "data/menu/menu_us.lgp",
+          "data/sound/audio.fmt",
+          "data/sound/audio.dat",
+          "data/music/music.idx",
+          "data/midi/midi.lgp",
+          "data/battle/scene.bin",
+          "data/battle/battle.lgp",
+          "data/battle/magic.lgp",
+          "data/wm/WM0.MAP",
+          "data/wm/WM2.MAP",
+          "data/wm/WM3.MAP",
+          "data/wm/world_us.lgp",
+          "ff7.exe"
+        };
+        std::vector<std::string> missing;
+        for (const std::string& file : required_files){
+            if (!disk_image.filePath(file)) missing.push_back(file);
+        }
+        return missing;
+    }
+
+    void ConvertMovies(const std::string& video_dir){
+        const ExternalTools::Tool ffmpeg = ExternalTools::FindFfmpeg(ExternalTools::CurrentLocations());
+        if (!ffmpeg.usable){
+            InstallLog::Get().Add(
+              "[WARNING] FFmpeg can't be used, so the videos are not converted and the game can't play them: "
+              + ffmpeg.problem
+            );
+            return;
+        }
+        QDir directory(QString::fromStdString(video_dir));
+        for (const QString& file : directory.entryList({"*.avi"}, QDir::Files)){
+            const std::string name = QFileInfo(file).completeBaseName().toStdString();
+            const std::string destination = video_dir + name;
+            if (QFileInfo::exists(QString::fromStdString(destination + "/movie.xml"))) continue;
+            InstallLog::Get().Add("Converting " + name + ".avi...");
+            std::string error;
+            if (ExternalTools::ConvertMovie(
+                  ffmpeg.path, video_dir + file.toStdString(), destination, name,
+                  MovieCamera::LoadCamera(video_dir + "moviecam.lgp", name), &error
+                ))
+                InstallLog::Get().Add("Converted " + name);
+            else InstallLog::Get().Add("[WARNING] Could not convert " + name + ": " + error);
+        }
+    }
+
+    void SetToolLocations(const QString& install_dir, const std::string& ffmpeg, const std::string& timidity){
+        QString dir = QDir::fromNativeSeparators(install_dir);
+        if (!dir.isEmpty() && !dir.endsWith("/")) dir += "/";
+        ExternalTools::Locations& tools = ExternalTools::CurrentLocations();
+        tools.ffmpeg = ffmpeg;
+        tools.timidity = timidity;
+        const QString app_dir = QCoreApplication::applicationDirPath();
+        tools.directories.clear();
+        if (!dir.isEmpty()) tools.directories.push_back((dir + "tools").toStdString());
+        tools.directories.push_back((app_dir + "/tools").toStdString());
+        tools.directories.push_back(app_dir.toStdString());
+    }
+
+    std::vector<std::string> PartNames(const InstallOptions& options){
+        std::vector<std::string> names;
+        for (const InstallCommandLine::Part& part : InstallCommandLine::Parts()){
+            if (options.*(part.option) && part.option != &InstallOptions::videos) names.push_back(part.name);
+        }
+        return names;
+    }
+
+    void MarkInstallStarted(const QString& output, const InstallOptions& options, const std::string& disk){
+        const boost::filesystem::path dir(output.toStdString());
+        VGears::InstallStamp::Stamp stamp;
+        VGears::InstallStamp::Read(dir, stamp);
+        VGears::InstallStamp::Start(stamp, PartNames(options), VGEARS_INSTALLER_VERSION, VGears::InstallStamp::Now(), disk);
+        if (!VGears::InstallStamp::Write(dir, stamp))
+            std::cout << "[WARNING] The installation record can't be written in " << dir.string() << std::endl;
+    }
+
+    void MarkInstallFinished(const QString& output){
+        const boost::filesystem::path dir(output.toStdString());
+        VGears::InstallStamp::Stamp stamp;
+        VGears::InstallStamp::Read(dir, stamp);
+        VGears::InstallStamp::Finish(stamp);
+        if (!VGears::InstallStamp::Write(dir, stamp))
+            std::cout << "[WARNING] The installation record can't be written in " << dir.string() << std::endl;
+    }
+
+    void MarkVideosInstalled(const QString& output){
+        const boost::filesystem::path dir(output.toStdString());
+        VGears::InstallStamp::Stamp stamp;
+        // Without a record there is no installation to add the videos to: one is made, marked as finished.
+        if (!VGears::InstallStamp::Read(dir, stamp)) stamp.complete = true;
+        stamp.parts["videos"] = VGears::InstallStamp::DATA_VERSION;
+        VGears::InstallStamp::Write(dir, stamp);
+    }
+
+    DataInstaller::AdvancedOptions ToAdvancedOptions(const InstallOptions& options, bool keep_originals){
+        DataInstaller::AdvancedOptions advanced;
+        advanced.battle_data = options.battle_data;
+        advanced.battle_models = options.battle_models;
+        advanced.kernel = options.kernel;
+        advanced.images = options.images;
+        advanced.sounds = options.sounds;
+        advanced.music = options.music;
+        advanced.videos = false;
+        advanced.fields = options.fields;
+        advanced.field_models = options.fields && options.field_models;
+        advanced.wm = options.wm;
+        advanced.wm_models = options.wm && options.wm_models;
+        advanced.keep_originals = keep_originals;
+        return advanced;
+    }
+
+}

+ 205 - 0
src/installer/InstallSteps.h

@@ -0,0 +1,205 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#pragma once
+
+#include <functional>
+#include <string>
+#include <vector>
+#include <QtCore/QString>
+#include <QtCore/QStringList>
+#include "DataInstaller.h"
+#include "DiskImage.h"
+#include "InstallOptions.h"
+#include "InstallVerifier.h"
+
+/**
+ * Steps of an installation that don't depend on the user interface.
+ *
+ * They are shared by the installer window and the command line installer, so both install in the same way.
+ */
+namespace InstallSteps{
+
+    /**
+     * Result of the checks done before starting an installation.
+     */
+    struct PreflightResult{
+
+        /**
+         * Problems that prevent the installation.
+         */
+        QStringList errors;
+
+        /**
+         * Problems that the user can choose to ignore.
+         */
+        QStringList warnings;
+    };
+
+    /**
+     * Gets the default installation directory, the one the game reads its data from.
+     */
+    QString DefaultInstallDir();
+
+    /**
+     * Normalizes an installation directory: absolute, with '/' separators, and ending with '/'.
+     *
+     * The working directory changes during installation, so the path must be absolute.
+     */
+    QString NormalizeOutputDir(const QString& dir);
+
+    /**
+     * Finds the V-Gears "data" folder shipped with the game.
+     *
+     * It contains the configuration files and plugins (copied to the installation directory) and a "data" subfolder
+     * with the game data (copied to <installation directory>/data).
+     *
+     * @return Path of the folder, or an empty string if it can't be found.
+     */
+    QString FindGameDataDir();
+
+    /**
+     * Checks that an installation can succeed before anything is extracted or written.
+     *
+     * @param[in] disk_image The selected disk image.
+     * @param[in] output Absolute installation directory, ending with '/'.
+     * @param[in] copy_data True if the V-Gears data files will be copied.
+     * @param[in] game_data_dir The V-Gears "data" folder to copy (only used if copy_data is true).
+     * @param[in] clean True if the data of a previous installation will be deleted first.
+     */
+    PreflightResult RunPreflight(
+      DiskImage& disk_image, const QString& output, bool copy_data, const QString& game_data_dir, bool clean
+    );
+
+    /**
+     * Checks that the videos of a game disk can be extracted to a directory.
+     *
+     * Only the output directory is needed: no plugins, no configuration, no Ogre.
+     *
+     * @param[in] output Absolute installation directory, ending with '/'.
+     * @return The problems found. Empty if the extraction can start.
+     */
+    QStringList CheckVideoOutput(const QString& output);
+
+    /**
+     * Gets where the verifier looks for the Ogre plugins: next to this program, with the Ogre version V-Gears was
+     * built with.
+     */
+    VerifyPlugins PluginSearch();
+
+    /**
+     * Recursively copies a directory, overwriting existing files.
+     *
+     * The configuration of the game (data/config) is only copied if it isn't there: the user may have changed it.
+     *
+     * @param[in] src The directory to copy.
+     * @param[in] dst Where to copy it.
+     * @param[in] progress Receives the progress [0-100]. It can be empty.
+     * @return True if every file was copied.
+     */
+    bool CopyDirectory(
+      const QString& src, const QString& dst,
+      const std::function<void(float)>& progress = std::function<void(float)>()
+    );
+
+    /**
+     * Phases of an installation, for its progress.
+     */
+    enum class Phase{EXTRACT, COPY, CONVERT};
+
+    /**
+     * Gets the progress of a whole installation from the progress of one of its phases.
+     *
+     * The phases take a part of the progress that is about the part of the time they take: the extraction of the
+     * disk the first 5%, the copy of the V-Gears data files 1%, and the conversion the rest.
+     *
+     * @param[in] phase The phase.
+     * @param[in] progress Progress of the phase [0-100].
+     * @return Progress of the installation [0-100].
+     */
+    float OverallProgress(Phase phase, float progress);
+
+    /**
+     * Gets the files the installer needs that are not in an extracted install disk.
+     *
+     * @param[in] disk_image The disk image, already extracted.
+     * @return Paths of the missing files, relative to the disk. Empty if everything is there.
+     */
+    std::vector<std::string> MissingRequiredFiles(DiskImage& disk_image);
+
+    /**
+     * Converts the movies in a folder to what the game plays: frames and sound. The game can't
+     * decode the original videos. The movies that already have a converted folder are skipped,
+     * and the originals are kept so they are not extracted again.
+     *
+     * @param[in] video_dir Folder with the extracted movies.
+     */
+    void ConvertMovies(const std::string& video_dir);
+
+    /**
+     * Sets where FFmpeg and TiMidity are looked for.
+     *
+     * The order is: the paths given, a "tools" folder in the installation directory, a "tools" folder next to the
+     * installer, the installer folder, and the system PATH.
+     *
+     * @param[in] install_dir The installation directory. It can be empty.
+     * @param[in] ffmpeg Path to FFmpeg chosen by the user. It can be empty.
+     * @param[in] timidity Path to TiMidity chosen by the user. It can be empty.
+     */
+    void SetToolLocations(const QString& install_dir, const std::string& ffmpeg, const std::string& timidity);
+
+    /**
+     * Gets the names of the parts an installation installs, as in the command line ("fields"...).
+     *
+     * The videos are not installed from the install disk, so they are not included.
+     */
+    std::vector<std::string> PartNames(const InstallOptions& options);
+
+    /**
+     * Records in the installation directory that an installation has started (see VGears::InstallStamp).
+     *
+     * Until it is marked as finished, the game and the verifier say that the installation didn't finish.
+     *
+     * @param[in] output The installation directory, ending with '/'.
+     * @param[in] options What is installed.
+     * @param[in] disk The disk.
+     */
+    void MarkInstallStarted(const QString& output, const InstallOptions& options, const std::string& disk);
+
+    /**
+     * Records in the installation directory that the installation has finished.
+     *
+     * @param[in] output The installation directory, ending with '/'.
+     */
+    void MarkInstallFinished(const QString& output);
+
+    /**
+     * Records in the installation directory that the videos of a game disk are installed.
+     *
+     * @param[in] output The installation directory, ending with '/'.
+     */
+    void MarkVideosInstalled(const QString& output);
+
+    /**
+     * Converts the options of an installation to the options of the data installer.
+     *
+     * Videos are not installed by the data installer: they are extracted from the game disks.
+     *
+     * @param[in] options The options of the installation.
+     * @param[in] keep_originals True to keep the original data after converting it.
+     */
+    DataInstaller::AdvancedOptions ToAdvancedOptions(const InstallOptions& options, bool keep_originals);
+
+}

+ 56 - 9
src/installer/InstallVerifier.cpp

@@ -15,6 +15,15 @@
 
 #include "InstallVerifier.h"
 #include <boost/filesystem.hpp>
+#include "common/InstallStamp.h"
+#include "common/OgrePlugins.h"
+
+/**
+ * Directory with the Ogre plugins, found when V-Gears was built. Set by CMake (VGEARS_OGRE_PLUGIN_DIR).
+ */
+#ifndef VGEARS_OGRE_PLUGIN_DIR
+#define VGEARS_OGRE_PLUGIN_DIR ""
+#endif
 
 namespace fs = boost::filesystem;
 
@@ -41,15 +50,32 @@ namespace{
             }
 
             /**
-             * A file whose name starts with a prefix (a library with a version number) must exist in a directory.
+             * The Ogre plugins listed in plugins.cfg must be found where the game looks for them.
+             *
+             * @param[in] group The group of the problems.
+             * @param[in] search Where to look for them.
              */
-            void FileWithPrefix(const std::string& group, const std::string& dir, const std::string& prefix){
-                ++ result_.checked;
+            void OgrePlugins(const std::string& group, const VerifyPlugins& search){
+                if (search.ogre_version.empty()) return;
+                namespace plugins = VGears::OgrePlugins;
+                const fs::path file(root_ + "plugins.cfg");
                 boost::system::error_code ec;
-                for (fs::directory_iterator it(root_ + dir, ec), end; !ec && it != end; it.increment(ec)){
-                    if (it->path().filename().string().compare(0, prefix.size(), prefix) == 0) return;
+                // A missing plugins.cfg is already reported.
+                if (!fs::is_regular_file(file, ec)) return;
+                ++ result_.checked;
+                plugins::Config config;
+                if (!plugins::ReadConfig(file, config)){
+                    Fail(group, "plugins.cfg can't be read");
+                    return;
+                }
+                const std::vector<fs::path> directories = plugins::SearchDirectories(
+                  file.parent_path(), config.folder, fs::path(search.executable_dir), VGEARS_OGRE_PLUGIN_DIR
+                );
+                for (const std::string& name : config.plugins){
+                    ++ result_.checked;
+                    if (plugins::Find(name, directories, search.ogre_version).empty())
+                        Fail(group, "the Ogre plugin " + name + " is not in the installation directory or the system");
                 }
-                Fail(group, "no " + prefix + "* file in " + (dir.empty() ? "the installation directory" : dir));
             }
 
             /**
@@ -93,16 +119,32 @@ namespace{
 
 }
 
-VerifyResult VerifyInstallation(const std::string& root, const std::string& reference_dir){
+VerifyResult VerifyInstallation(
+  const std::string& root, const std::string& reference_dir, const VerifyPlugins& plugins
+){
     VerifyResult result;
     Checker check(root, result);
 
+    // The record of the installations: whether the last one finished, and whether a part is outdated.
+    const std::string installation = "Installation";
+    ++ result.checked;
+    bool recorded = false;
+    for (const std::string& problem : VGears::InstallStamp::Problems(fs::path(root), &recorded))
+        result.problems.push_back({installation, problem});
+    if (!recorded){
+        result.problems.push_back({
+          installation, "there is no record of the installation: it was made by an older installer, whose data may "
+          "be outdated. Install the data again."
+        });
+    }
+
     // Configuration, plugins and the files of the repository, which the game always needs.
     const std::string config = "Configuration";
     check.File(config, "plugins.cfg");
     check.File(config, "resources.cfg");
-    check.FileWithPrefix(config, "", "RenderSystem_GL");
-    check.FileWithPrefix(config, "", "Codec_STBI");
+    // The plugins don't have to be in the installation directory: the game also looks for them next to its
+    // executable and in the system.
+    check.OgrePlugins(config, plugins);
     const std::string game = "Game files";
     for (const char* file : {
       "data/config/config.cfg", "data/system/system.fontdef", "data/system/system.lua", "data/system/system.material",
@@ -183,5 +225,10 @@ VerifyResult VerifyInstallation(const std::string& root, const std::string& refe
     check.Files(music, "data/audio/musics", ".ogg", 50);
     const std::string images = "Images";
     check.Files(images, "data/images/icons", "", 1);
+    // Fonts, built from WINDOW.BIN. They are installed even when images are not.
+    const std::string fonts = "Fonts";
+    for (const char* file : {
+      "data/fonts/ffvii_en.png", "data/fonts/ffvii_menu.png", "data/fonts/ffvii_digits.png", "data/fonts/ffvii_timer.png"
+    }) check.File(fonts, file);
     return result;
 }

+ 24 - 1
src/installer/InstallVerifier.h

@@ -55,6 +55,25 @@ struct VerifyResult{
     bool Ok() const{return problems.empty();}
 };
 
+/**
+ * How the Ogre plugins of an installation are looked for.
+ *
+ * They are looked for where the game looks for them (see VGears::OgrePlugins::SearchDirectories): the installation
+ * directory, the directory of the game executable and the system.
+ */
+struct VerifyPlugins{
+
+    /**
+     * Directory of the running program, usually the same as the game's. It can be empty.
+     */
+    std::string executable_dir;
+
+    /**
+     * The Ogre version, as "major.minor.patch": the plugins have it in their file names. Empty to not check them.
+     */
+    std::string ogre_version;
+};
+
 /**
  * Checks that an installation has everything the game needs.
  *
@@ -64,5 +83,9 @@ struct VerifyResult{
  * @param[in] root Installation directory.
  * @param[in] reference_dir V-Gears "data" folder of the game (the one copied to the installation). If not empty,
  * every file in it must exist in the installation too. It can be empty.
+ * @param[in] plugins Where the Ogre plugins listed in plugins.cfg are looked for. Without the Ogre version, the
+ * plugins are not checked.
  */
-VerifyResult VerifyInstallation(const std::string& root, const std::string& reference_dir = "");
+VerifyResult VerifyInstallation(
+  const std::string& root, const std::string& reference_dir = "", const VerifyPlugins& plugins = VerifyPlugins()
+);

+ 91 - 290
src/installer/MainWindow.cpp

@@ -45,193 +45,12 @@
 #include "InstallLayout.h"
 #include "InstallLog.h"
 #include "InstallOptions.h"
+#include "InstallSteps.h"
 #include "InstallVerifier.h"
 #include "MainWindow.h"
 #include "MovieCamera.h"
 #include <ui_MainWindow.h>
 
-namespace{
-
-    /**
-     * Converts the movies in a folder to what the game plays: frames and sound. The game can't
-     * decode the original videos. The movies that already have a converted folder are skipped,
-     * and the originals are kept so they are not extracted again.
-     *
-     * @param[in] video_dir Folder with the extracted movies.
-     */
-    void ConvertMovies(const std::string& video_dir){
-        const ExternalTools::Tool ffmpeg = ExternalTools::FindFfmpeg(ExternalTools::CurrentLocations());
-        if (!ffmpeg.usable){
-            InstallLog::Get().Add(
-              "[WARNING] FFmpeg can't be used, so the videos are not converted and the game can't play them: "
-              + ffmpeg.problem
-            );
-            return;
-        }
-        QDir directory(QString::fromStdString(video_dir));
-        for (const QString& file : directory.entryList({"*.avi"}, QDir::Files)){
-            const std::string name = QFileInfo(file).completeBaseName().toStdString();
-            const std::string destination = video_dir + name;
-            if (QFileInfo::exists(QString::fromStdString(destination + "/movie.xml"))) continue;
-            InstallLog::Get().Add("Converting " + name + ".avi...");
-            std::string error;
-            if (ExternalTools::ConvertMovie(
-                  ffmpeg.path, video_dir + file.toStdString(), destination, name,
-                  MovieCamera::LoadCamera(video_dir + "moviecam.lgp", name), &error
-                ))
-                InstallLog::Get().Add("Converted " + name);
-            else InstallLog::Get().Add("[WARNING] Could not convert " + name + ": " + error);
-        }
-    }
-}
-
-/**
- * Indicates if an installer has already been created.
- */
-static bool installer_created = false;
-
-/**
- * Finds the V-Gears "data" folder shipped with the game.
- *
- * It contains the configuration files and plugins (copied to the installation directory) and a "data" subfolder with
- * the game data (copied to <installation directory>/data).
- *
- * @return Path of the folder, or an empty string if it can't be found.
- */
-static QString FindGameDataDir(){
-    // The same places the game copies its files from when the data directory is empty, then the current directory.
-    std::vector<boost::filesystem::path> candidates = VGears::DataDirectory::TemplateCandidates(
-      boost::filesystem::path(QCoreApplication::applicationDirPath().toStdString())
-    );
-    candidates.emplace_back((QDir::currentPath() + "/data").toStdString());
-    candidates.emplace_back((QDir::currentPath() + "/../data").toStdString());
-    const boost::filesystem::path found = VGears::DataDirectory::FindTemplate(candidates, boost::filesystem::path());
-    return found.empty() ? QString() : QDir::cleanPath(QString::fromStdString(found.string()));
-}
-
-#ifndef VGEARS_OGRE_PLUGIN_DIR
-#define VGEARS_OGRE_PLUGIN_DIR ""
-#endif
-
-/**
- * Names of the plugins in the plugins.cfg of a folder that the game won't find.
- *
- * The game looks for them in the same places (see VGears::OgrePlugins::SearchDirectories), so they don't need to be
- * copied to the installation directory.
- */
-static QStringList MissingOgrePlugins(const QString& source_dir){
-    namespace bfs = boost::filesystem;
-    QStringList missing;
-    const bfs::path dir(source_dir.toStdString());
-    VGears::OgrePlugins::Config config;
-    if (!VGears::OgrePlugins::ReadConfig(dir / "plugins.cfg", config)) return missing;
-    const std::vector<bfs::path> directories = VGears::OgrePlugins::SearchDirectories(
-      dir, config.folder, bfs::path(QCoreApplication::applicationDirPath().toStdString()), VGEARS_OGRE_PLUGIN_DIR
-    );
-    const std::string version = std::to_string(OGRE_VERSION_MAJOR) + "." + std::to_string(OGRE_VERSION_MINOR) + "."
-      + std::to_string(OGRE_VERSION_PATCH);
-    for (const std::string& name : config.plugins){
-        if (VGears::OgrePlugins::Find(name, directories, version).empty()) missing << QString::fromStdString(name);
-    }
-    return missing;
-}
-
-/**
- * Minimum free space needed besides the ISO extraction: converted data, intermediate files and logs.
- */
-static const qint64 kRequiredFreeSpace = 3LL * 1024 * 1024 * 1024;
-
-/**
- * Result of the checks done before starting an installation.
- */
-struct PreflightResult{
-    QStringList errors;
-    QStringList warnings;
-};
-
-/**
- * Checks that an installation can succeed before anything is extracted or written.
- *
- * @param[in] disk_image The selected disk image.
- * @param[in] output Absolute installation directory, ending with '/'.
- * @param[in] copy_data True if the V-Gears data files will be copied.
- * @param[in] game_data_dir The V-Gears "data" folder to copy (only used if copy_data is true).
- */
-static PreflightResult RunPreflight(
-  DiskImage& disk_image, const QString& output, bool copy_data, const QString& game_data_dir
-){
-    PreflightResult result;
-    const QString iso_path = QString::fromStdString(disk_image.getPath());
-
-    // Input.
-    if (iso_path.isEmpty()) result.errors << QObject::tr("No ISO image selected.");
-    else if (!QFileInfo(iso_path).isReadable()) result.errors << QObject::tr("The ISO image can't be read: %1").arg(iso_path);
-    else if (!disk_image.isValid()) result.errors << QObject::tr("The selected ISO is not a valid Final Fantasy VII image.");
-    else if (!disk_image.isSupported()) result.warnings << QString::fromStdString(disk_image.getWarningMessage());
-
-    // Output: it must be creatable and writable.
-    if (!QDir().mkpath(output)) result.errors << QObject::tr("The installation directory can't be created: %1").arg(output);
-    else{
-        QFile probe(output + ".v-gears-write-test");
-        if (!probe.open(QIODevice::WriteOnly)) result.errors << QObject::tr("The installation directory is not writable: %1").arg(output);
-        else{
-            probe.close();
-            probe.remove();
-        }
-        // Free space: the extracted ISO plus the converted data.
-        QStorageInfo storage(output);
-        const qint64 needed = kRequiredFreeSpace + (iso_path.isEmpty() ? 0 : QFileInfo(iso_path).size());
-        if (storage.isValid() && storage.bytesAvailable() < needed){
-            result.errors << QObject::tr("Not enough free space in %1: %2 MB available, about %3 MB needed.")
-              .arg(storage.rootPath()).arg(storage.bytesAvailable() / (1024 * 1024)).arg(needed / (1024 * 1024));
-        }
-    }
-
-    // Configuration and plugins.
-    if (copy_data){
-        if (game_data_dir.isEmpty() || !QFile::exists(game_data_dir + "/plugins.cfg") || !QDir(game_data_dir + "/data").exists())
-            result.errors << QObject::tr("The V-Gears 'data' folder was not found (it must contain plugins.cfg and a data folder).");
-        else{
-            const QStringList missing = MissingOgrePlugins(game_data_dir);
-            if (!missing.isEmpty())
-                result.errors << QObject::tr("Ogre plugins not found in the data folder or the system: %1").arg(missing.join(", "));
-        }
-    }
-    else{
-        if (!QFile::exists(output + "plugins.cfg") || !QFile::exists(output + "resources.cfg"))
-            result.errors << QObject::tr("The installation directory has no plugins.cfg and resources.cfg. Enable 'Copy V-Gears data files'.");
-        else{
-            const QStringList missing = MissingOgrePlugins(output);
-            if (!missing.isEmpty())
-                result.errors << QObject::tr("Ogre plugins not found in the installation directory or the system: %1").arg(missing.join(", "));
-        }
-    }
-    return result;
-}
-
-/**
- * Recursively copies a directory, overwriting existing files.
- *
- * @return True if every file was copied.
- */
-static bool CopyDirectory(const QString& src, const QString& dst){
-    const QDir src_dir(src);
-    if (!QDir().mkpath(dst)) return false;
-    bool ok = true;
-    QDirIterator it(src, QDir::Files | QDir::NoDotAndDotDot, QDirIterator::Subdirectories);
-    while (it.hasNext()){
-        const QString file = it.next();
-        const QString target = dst + "/" + src_dir.relativeFilePath(file);
-        QDir().mkpath(QFileInfo(target).absolutePath());
-        if (QFile::exists(target)) QFile::remove(target);
-        if (!QFile::copy(file, target)){
-            std::cout << "Could not copy " << file.toStdString() << " to " << target.toStdString() << std::endl;
-            ok = false;
-        }
-    }
-    return ok;
-}
-
 MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), main_window_(new Ui::MainWindow){
     main_window_->setupUi(this);
     main_window_->advancedOptions->setVisible(main_window_->chk_advanced_options->isChecked());
@@ -302,6 +121,8 @@ void MainWindow::InitSettings(void){
 }
 
 void MainWindow::OpenInstallLog(const QString& dir, bool append){
+    // A new installation starts with an empty log window.
+    if (!append) main_window_->data_log->clear();
     InstallLog& install_log = InstallLog::Get();
     install_log.Open((dir + "installer.log").toStdString(), append);
     install_log.SetSink([this](InstallLog::Level level, const std::string& message){
@@ -411,7 +232,9 @@ void MainWindow::on_btn_verify_clicked(){
         QMessageBox::warning(this, tr("Verify install"), tr("The installation directory does not exist: %1").arg(dir));
         return;
     }
-    const VerifyResult result = VerifyInstallation(dir.toStdString(), FindGameDataDir().toStdString());
+    const VerifyResult result = VerifyInstallation(
+      dir.toStdString(), InstallSteps::FindGameDataDir().toStdString(), InstallSteps::PluginSearch()
+    );
     // The game can start if its configuration and the V-Gears data files are there.
     bool can_launch = true;
     QString text;
@@ -520,12 +343,13 @@ void MainWindow::on_actionHelp_triggered(){
       "<li>Click <b>Install data</b>. The log shows the progress. Problems are shown in color and also written to "
       "<code>installer.log</code> in the installation directory.</li>"
       "</ol>"
-      "<p>The installation can only be done once per window. To install again, close the installer and open it "
-      "again.</p>"
       "<h3>Options</h3>"
       "<p>Select <b>Show advanced options</b> to choose what to install. <b>What to install</b> offers ready-made "
       "sets; choose <b>Custom</b> to pick the options by hand. Some options need others (for example the field "
-      "models need the field maps). <b>Clean install</b> deletes the data of a previous installation first. The "
+      "models need the field maps). <b>Clean install</b> deletes the data of a previous installation first; the "
+      "saves, the controls, the game configuration and the videos are kept. <b>Preserve original data</b> keeps "
+      "what the installer extracts and no longer needs (the install disk, temporary files and the original "
+      "sounds, music and images); without it, that is deleted at the end. The "
       "estimate under the options shows about how much disk space it needs.</p>"
       "<p>With <b>Copy V-Gears data files</b> the installer also copies the files that come with V-Gears (scripts, "
       "screens, fonts and configuration) to the installation directory.</p>"
@@ -615,10 +439,7 @@ void MainWindow::on_btn_data_run_clicked(){
         return;
     }
     // Normalize the output path.
-    QString output = QDir::fromNativeSeparators(main_window_->line_data_dst->text());
-    if (!output.endsWith("/")) output += "/";
-    // The working directory changes during installation, so the path must be absolute.
-    if (QDir::isRelativePath(output)) output = QDir(output).absolutePath() + "/";
+    const QString output = InstallSteps::NormalizeOutputDir(main_window_->line_data_dst->text());
 
     // A game disk only has videos: extract them, without the rest of the installation.
     if (disk_image_.isValid() && disk_image_.isVideoDisk()){
@@ -630,7 +451,7 @@ void MainWindow::on_btn_data_run_clicked(){
     const bool copy_data = main_window_->chk_copy_data->checkState() == Qt::Checked;
     QString game_data;
     if (copy_data){
-        game_data = FindGameDataDir();
+        game_data = InstallSteps::FindGameDataDir();
         if (game_data.isEmpty()){
             game_data = QFileDialog::getExistingDirectory(
               this, tr("Select the V-Gears 'data' folder to copy"), QCoreApplication::applicationDirPath()
@@ -639,9 +460,13 @@ void MainWindow::on_btn_data_run_clicked(){
         }
     }
 
-    // Check everything that can be checked before touching the disk.
-    PreflightResult preflight = RunPreflight(disk_image_, output, copy_data, game_data);
-    for (const std::string& problem : InstallRules::Problems(CurrentOptions(), QFile::exists(output + "data/fields/_fields.xml")))
+    // Check everything that can be checked before touching the disk. A clean installation deletes the field maps
+    // that are already installed.
+    const bool clean = main_window_->chk_clean_install->checkState() == Qt::Checked;
+    InstallSteps::PreflightResult preflight
+      = InstallSteps::RunPreflight(disk_image_, output, copy_data, game_data, clean);
+    const bool fields_installed = !clean && QFile::exists(output + "data/fields/_fields.xml");
+    for (const std::string& problem : InstallRules::Problems(CurrentOptions(), fields_installed))
         preflight.errors << QString::fromStdString(problem);
     if (!preflight.errors.isEmpty()){
         QMessageBox::critical(
@@ -659,8 +484,44 @@ void MainWindow::on_btn_data_run_clicked(){
     }
     // The audio is converted with external programs: say now, before anything is extracted, if they are missing.
     if (!ResolveMissingTools(CurrentOptions())) return;
+    // Everything is checked: the previous installation can be deleted.
+    if (clean && InstallLayout::IsInstallation(output.toStdString())){
+        const auto answer = QMessageBox::warning(
+          this, tr("Clean install"),
+          tr("The data of the installation in %1 will be deleted before installing. The saves, the controls, the "
+             "game configuration and the videos are kept.\n\nContinue?").arg(QDir::toNativeSeparators(output)),
+          QMessageBox::Yes | QMessageBox::No, QMessageBox::No
+        );
+        if (answer != QMessageBox::Yes) return;
+        const InstallLayout::CleanResult cleaned = InstallLayout::CleanInstallation(output.toStdString());
+        if (!cleaned.errors.empty()){
+            QStringList errors;
+            for (const std::string& error : cleaned.errors) errors << QString::fromStdString(error);
+            QMessageBox::critical(
+              this, tr("Clean install"),
+              tr("The previous installation could not be deleted:\n\n- %1").arg(errors.join("\n- "))
+            );
+            return;
+        }
+        main_window_->data_log->append(tr("Deleted the previous installation (%1 files and folders).").arg(cleaned.removed));
+    }
+    // From here on, the installation directory is being changed: until it finishes, the record says so.
+    install_dir_ = output;
+    InstallSteps::MarkInstallStarted(output, CurrentOptions(), disk_image_.getId());
     {
-        bool extraction_success = disk_image_.extractImage(output.toStdString());
+        // The extraction and the copy run here, in the window's thread: the progress is shown as they go, and the
+        // window is repainted, without taking the clicks (nothing can be started twice).
+        main_window_->data_progress_bar->setValue(0);
+        const auto show_phase = [this](InstallSteps::Phase phase, const QString& text){
+            return [this, phase, text](float value){
+                ShowProgress(InstallSteps::OverallProgress(phase, value));
+                main_window_->label_progress->setText(text);
+                QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
+            };
+        };
+        bool extraction_success = disk_image_.extractImage(
+          output.toStdString(), show_phase(InstallSteps::Phase::EXTRACT, tr("Extracting the install disk..."))
+        );
         if (!extraction_success) {
             QMessageBox::critical(this, tr("Extraction error"), tr("Failed to extract ISO file."));
             return;
@@ -673,44 +534,25 @@ void MainWindow::on_btn_data_run_clicked(){
       }
       if (!input.endsWith("/")) input += "/";
 
-        // TODO: Enumerate files or find some better way to do this.
-        const std::vector<std::string> required_files = {
-          "data/field/char.lgp",
-          "data/field/flevel.lgp",
-          "data/kernel/KERNEL.BIN",
-          "data/menu/menu_us.lgp",
-          "data/sound/audio.fmt",
-          "data/sound/audio.dat",
-          "data/music/music.idx",
-          "data/midi/midi.lgp",
-          "data/battle/scene.bin",
-          "data/battle/battle.lgp",
-          "data/battle/magic.lgp",
-          "data/wm/WM0.MAP",
-          "data/wm/WM2.MAP",
-          "data/wm/WM3.MAP",
-          "data/wm/world_us.lgp",
-          "ff7.exe"
-        };
-
         // Ensure required files are in the input dir
-        for (auto& file : required_files){
-            std::cout << "Checking for required file: " << file << std::endl;
-            const auto matched_file = disk_image_.filePath(file);
-            if (!matched_file){
-                QMessageBox::critical(
-                  this, tr("Missing input file"),
-                  tr("Some of the required files were not found among the extracted data.\n\nMake sure that the file '")
-                    + file.c_str() + tr("' is in the extracted data.")
-                );
-                return;
-            }
+        const std::vector<std::string> missing_files = InstallSteps::MissingRequiredFiles(disk_image_);
+        if (!missing_files.empty()){
+            QStringList names;
+            for (const std::string& file : missing_files) names << QString::fromStdString(file);
+            QMessageBox::critical(
+              this, tr("Missing input file"),
+              tr("Some of the required files were not found among the extracted data.\n\nMake sure that these "
+                 "files are in the extracted data:\n\n%1").arg(names.join("\n"))
+            );
+            return;
         }
         // Copy the V-Gears data files (scripts, screens, fonts...) to the installation directory.
         if (copy_data){
             main_window_->data_log->append(tr("Copying data files from %1...").arg(game_data));
             // Everything in the folder goes to the installation directory, and its "data" subfolder to <dir>/data.
-            if (!CopyDirectory(game_data, output)){
+            if (!InstallSteps::CopyDirectory(
+              game_data, output, show_phase(InstallSteps::Phase::COPY, tr("Copying the V-Gears data files..."))
+            )){
                 QMessageBox::critical(
                   this, tr("Copy error"), tr("Failed to copy the V-Gears data files to the installation directory.")
                 );
@@ -733,41 +575,21 @@ void MainWindow::on_btn_data_run_clicked(){
             QMessageBox::critical(this, tr("Output error"), tr("Could not enter the installation directory."));
             return;
         }
-        if (installer_created){
-            // Due to the use of singletons, the installer can't be re-run.
-            // TODO: Verify that this is true, and if so, try to fix it.
-            QMessageBox::critical(
-              this, tr("Error"), tr("Please, fix the errors, and then close the installer before trying again.")
-            );
-            return;
-        }
         // Collect every message of the installation in one place: the log file, the log window and the summary.
         UpdateToolLocations(output);
         OpenInstallLog(output, false);
         // Start data conversion
         try{
             // Parse advanced options.
-            DataInstaller::AdvancedOptions options;
-            options.battle_data = (Qt::Checked == main_window_->chk_battle_data->checkState());
-            options.battle_models = (Qt::Checked == main_window_->chk_battle_models->checkState());
-            options.kernel = (Qt::Checked == main_window_->chk_kernel->checkState());
-            options.images = (Qt::Checked == main_window_->chk_images->checkState());
-            options.sounds = (Qt::Checked == main_window_->chk_sounds->checkState());
-            options.music = (Qt::Checked == main_window_->chk_music->checkState());
-            options.videos = false;
+            DataInstaller::AdvancedOptions options = InstallSteps::ToAdvancedOptions(
+              CurrentOptions(), Qt::Checked == main_window_->chk_keep_original->checkState()
+            );
             if (Qt::Checked == main_window_->chk_videos->checkState()){
                 InstallLog::Get().Add(
                   "[WARNING] The install disk has no videos. To extract them, select game disk 1, 2 or 3 as the "
-                  "ISO and install again (with a new installer window)."
+                  "ISO and install again."
                 );
             }
-            options.fields = (Qt::Checked == main_window_->chk_fields->checkState());
-            options.field_models = options.fields && (Qt::Checked == main_window_->chk_field_models->checkState());
-            options.wm = (Qt::Checked == main_window_->chk_wm->checkState());
-            options.wm_models = options.wm && (Qt::Checked == main_window_->chk_wm_models->checkState());
-            options.keep_originals = (Qt::Checked == main_window_->chk_keep_original->checkState());
-            installer_created = true;
-            install_started_ = true;
             const std::string output_path = QDir::toNativeSeparators(output).toStdString();
             const auto write_line = [this](const std::string log_line, int level, bool as_progress = false){
                 InstallLog::Get().Add(log_line);
@@ -778,9 +600,9 @@ void MainWindow::on_btn_data_run_clicked(){
                     );
                 }
             };
-            // The installation runs in a worker thread so the window stays responsive. Ogre, and the OpenGL context
-            // it creates, belong to the thread that creates them, so the installer is created, run and destroyed
-            // there. Setting "BackgroundInstall" to false runs it in the UI thread, step by step from a timer.
+            // The installation runs in a worker thread so the window stays responsive. Ogre belongs to the thread
+            // that creates it, so the installer is created, run and destroyed there. Setting "BackgroundInstall" to
+            // false runs it in the UI thread, step by step from a timer.
             background_ = settings_->value("BackgroundInstall", true).toBool();
             if (background_){
                 stop_requested_ = false;
@@ -796,7 +618,6 @@ void MainWindow::on_btn_data_run_clicked(){
             InstallLog::Get().Add(std::string("[ERROR] Installation failed: ") + ex.what());
             InstallLog::Get().Close();
             installer_.reset();
-            installer_created = false;
             OnInstallStopped();
             QMessageBox::critical(this, tr("Installation error"), ex.what());
         }
@@ -808,8 +629,7 @@ void MainWindow::on_chk_advanced_options_stateChanged(){
 }
 
 void MainWindow::EnableUi(bool enable){
-    // The installer can't run twice, so once an installation has started the button never comes back.
-    main_window_->btn_data_run->setEnabled(enable && !install_started_);
+    main_window_->btn_data_run->setEnabled(enable);
     main_window_->btn_close->setEnabled(enable);
     main_window_->actionExit->setEnabled(enable);
     main_window_->label_tools->setEnabled(enable);
@@ -819,7 +639,6 @@ void MainWindow::EnableUi(bool enable){
     main_window_->btn_data_src->setEnabled(enable);
     main_window_->line_data_dst->setEnabled(enable);
     main_window_->btn_data_dst->setEnabled(enable);
-    main_window_->data_progress_bar->setValue(0);
     // In background mode the worker thread does the work, so there is nothing to poll.
     if (!enable && !background_) timer_->start(0);
     else timer_->stop();
@@ -830,23 +649,9 @@ void MainWindow::OnInstallStarted(){EnableUi(false);}
 void MainWindow::OnInstallStopped(){EnableUi(true);}
 
 void MainWindow::StartVideoExtraction(const QString& output){
+    main_window_->data_progress_bar->setValue(0);
     // Only the output directory is needed: no plugins, no configuration, no Ogre.
-    QStringList errors;
-    if (!QDir().mkpath(output)) errors << tr("The installation directory can't be created: %1").arg(output);
-    else{
-        QFile probe(output + ".v-gears-write-test");
-        if (!probe.open(QIODevice::WriteOnly)) errors << tr("The installation directory is not writable: %1").arg(output);
-        else{
-            probe.close();
-            probe.remove();
-        }
-        const QStorageInfo storage(output);
-        const qint64 needed = 1024LL * 1024 * 1024;
-        if (storage.isValid() && storage.bytesAvailable() < needed){
-            errors << tr("Not enough free space in %1: %2 MB available, about %3 MB needed.")
-              .arg(storage.rootPath()).arg(storage.bytesAvailable() / (1024 * 1024)).arg(needed / (1024 * 1024));
-        }
-    }
+    const QStringList errors = InstallSteps::CheckVideoOutput(output);
     if (!errors.isEmpty()){
         QMessageBox::critical(
           this, tr("The extraction can't start"), tr("Fix these problems and try again:\n\n- %1").arg(errors.join("\n- "))
@@ -873,16 +678,17 @@ void MainWindow::StartVideoExtraction(const QString& output){
               },
               [](const std::string& message){InstallLog::Get().Add(message);}, &extracted, &skipped
             );
-            if (ok) ConvertMovies(output.toStdString() + "data/video/");
+            if (ok) InstallSteps::ConvertMovies(output.toStdString() + "data/video/");
         }
         catch (const std::exception& ex){
             error = ex.what();
         }
         if (stop_requested_) return;
-        QMetaObject::invokeMethod(this, [this, ok, error, extracted, skipped](){
+        QMetaObject::invokeMethod(this, [this, ok, error, extracted, skipped, output](){
             if (worker_.joinable()) worker_.join();
             if (ok && error.empty()){
                 ShowProgress(100);
+                InstallSteps::MarkVideosInstalled(output);
                 InstallLog::Get().Add(
                   "Videos extracted: " + std::to_string(extracted) + " new, " + std::to_string(skipped)
                   + " already installed."
@@ -900,16 +706,10 @@ void MainWindow::StartVideoExtraction(const QString& output){
 void MainWindow::UpdateToolLocations(const QString& install_dir){
     // Where to look for FFmpeg and TiMidity: what the user chose, then a "tools" folder in the installation
     // directory or next to the installer, then the system PATH.
-    QString dir = QDir::fromNativeSeparators(install_dir);
-    if (!dir.isEmpty() && !dir.endsWith("/")) dir += "/";
-    ExternalTools::Locations& tools = ExternalTools::CurrentLocations();
-    tools.ffmpeg = settings_->value("FFmpegPath").toString().toStdString();
-    tools.timidity = settings_->value("TimidityPath").toString().toStdString();
-    const QString app_dir = QCoreApplication::applicationDirPath();
-    tools.directories.clear();
-    if (!dir.isEmpty()) tools.directories.push_back((dir + "tools").toStdString());
-    tools.directories.push_back((app_dir + "/tools").toStdString());
-    tools.directories.push_back(app_dir.toStdString());
+    InstallSteps::SetToolLocations(
+      install_dir, settings_->value("FFmpegPath").toString().toStdString(),
+      settings_->value("TimidityPath").toString().toStdString()
+    );
 }
 
 void MainWindow::RefreshToolStatus(){
@@ -1040,7 +840,8 @@ void MainWindow::RunInstallation(
             const auto now = std::chrono::steady_clock::now();
             if (progress >= 100 || now - last_shown > std::chrono::milliseconds(100)){
                 last_shown = now;
-                QMetaObject::invokeMethod(this, [this, progress](){ShowProgress(progress);}, Qt::QueuedConnection);
+                const float overall = InstallSteps::OverallProgress(InstallSteps::Phase::CONVERT, progress);
+                QMetaObject::invokeMethod(this, [this, overall](){ShowProgress(overall);}, Qt::QueuedConnection);
             }
         }
     }
@@ -1059,14 +860,13 @@ void MainWindow::RunInstallation(
         if (worker_.joinable()) worker_.join();
         if (finished){
             launch_available_ = true;
+            InstallSteps::MarkInstallFinished(install_dir_);
             OnInstallStopped();
             InstallLog::Get().Close();
         }
         else{
             InstallLog::Get().Add("[ERROR] Installation failed: " + error);
             InstallLog::Get().Close();
-            // If the installer could not even be created it can be tried again.
-            if (!created) installer_created = false;
             OnInstallStopped();
             QMessageBox::critical(this, created ? tr("Data conversion exception") : tr("Installation error"), QString::fromStdString(error));
         }
@@ -1076,9 +876,10 @@ void MainWindow::RunInstallation(
 void MainWindow::DoProgress(){
     try{
         const float progress = installer_->Progress();
-        ShowProgress(progress);
+        ShowProgress(InstallSteps::OverallProgress(InstallSteps::Phase::CONVERT, progress));
         if (progress >= 100){
             launch_available_ = true;
+            InstallSteps::MarkInstallFinished(install_dir_);
             OnInstallStopped();
             InstallLog::Get().Close();
         }

+ 5 - 5
src/installer/MainWindow.h

@@ -289,11 +289,6 @@ class MainWindow : public QMainWindow{
          */
         bool background_ = false;
 
-        /**
-         * True once an installation has started. The installer can only run once.
-         */
-        bool install_started_ = false;
-
         /**
          * True while the option rules are being applied, to avoid applying them recursively.
          */
@@ -315,4 +310,9 @@ class MainWindow : public QMainWindow{
          * The selected disk image.
          */
         DiskImage disk_image_;
+
+        /**
+         * The installation directory of the installation in progress, ending with '/'.
+         */
+        QString install_dir_;
 };

+ 3 - 3
src/installer/MainWindow.ui

@@ -570,7 +570,7 @@
             </size>
            </property>
            <property name="toolTip">
-            <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;span style=&quot; font-weight:700;&quot;&gt;Delete previously installed files.&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;br/&gt;&lt;/p&gt;&lt;p&gt;Performs a clean installation, unconditionally removing all previously installed data.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+            <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;b&gt;Delete the previous installation first.&lt;/b&gt;&lt;br&gt;&lt;br&gt;Before installing, the data of a previous installation in the installation directory is deleted: the converted game data, the temporary files and the extracted disk. The saves, the controls, the game configuration and the videos are kept.&lt;br&gt;&lt;br&gt;It needs 'Copy V-Gears data files', since the V-Gears data files are deleted too.&lt;/body&gt;&lt;/html&gt;</string>
            </property>
            <property name="text">
             <string>Clean install</string>
@@ -728,13 +728,13 @@
             </size>
            </property>
            <property name="toolTip">
-            <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;b&gt;Don't delete original data after installation.&lt;/b&gt;&lt;br&gt;&lt;br&gt;The installer extracts some original data from the installation disk, such as MIDI sounds, TEX images, and some LGP archives. If checked, this data will not be deleted when the installation is complete.&lt;br&gt;&lt;br&gt;This data is never used by V-Gears, and there is usually no need to check this.&lt;/body&gt;&lt;/html&gt;</string>
+            <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;b&gt;Keep the original data after the installation.&lt;/b&gt;&lt;br&gt;&lt;br&gt;The installer extracts the install disk and some original data (WAV sounds, MIDI music, TEX images and temporary model files) to convert it. Without this option, all of it is deleted when the installation is complete.&lt;br&gt;&lt;br&gt;V-Gears never uses this data, so there is usually no need to check this.&lt;/body&gt;&lt;/html&gt;</string>
            </property>
            <property name="text">
             <string>Preserve original data</string>
            </property>
            <property name="checked">
-            <bool>true</bool>
+            <bool>false</bool>
            </property>
           </widget>
           <widget class="QCheckBox" name="chk_fields">

+ 20 - 2
src/installer/MediaDataInstaller.cpp

@@ -33,6 +33,7 @@
 #include "data/VGearsLGPArchive.h"
 #include "data/VGearsTexFile.h"
 #include "TexFile.h"
+#include "WindowFonts.h"
 
 int MediaDataInstaller::TOTAL_SOUNDS = 750;
 
@@ -1315,6 +1316,25 @@ void MediaDataInstaller::InstallSprites(){
     }
 }
 
+bool MediaDataInstaller::InstallFonts(){
+    // WINDOW.BIN: the first file is the window graphics TIM, the second one the dialog font TIM.
+    WindowFonts::IndexImage window;
+    WindowFonts::IndexImage text;
+    for (u32 i = 0; i < 2; i ++){
+        const File tim = window_.ExtractGZip(i);
+        if (tim.GetFileSize() == 0) return false;
+        std::vector<u8> buffer(tim.GetFileSize());
+        tim.GetFileBuffer(buffer.data(), 0, buffer.size());
+        if (!WindowFonts::ReadTim4(buffer.data(), buffer.size(), i == 0 ? window : text)) return false;
+    }
+    const std::string font_dir = data_dir_ + "fonts/";
+    WindowFonts::SavePng(WindowFonts::BuildTextFont(text), font_dir + "ffvii_en.png");
+    WindowFonts::SavePng(WindowFonts::BuildMenuFont(window), font_dir + "ffvii_menu.png");
+    WindowFonts::SavePng(WindowFonts::BuildDigitsFont(window), font_dir + "ffvii_digits.png");
+    WindowFonts::SavePng(WindowFonts::BuildTimerFont(window), font_dir + "ffvii_timer.png");
+    return true;
+}
+
 int MediaDataInstaller::InstallSoundsInit(){
     std::unique_ptr<std::string> fmt_path = disk_image_.filePath("data/sound/audio.fmt");
     std::unique_ptr<std::string> data_path = disk_image_.filePath("data/sound/audio.dat");
@@ -1352,12 +1372,10 @@ bool MediaDataInstaller::InstallSounds(){
               [ffmpeg, wav, ogg](std::string* error){return ExternalTools::ConvertToOgg(ffmpeg, wav, ogg, error);},
               [wav, keep](){if (!keep) std::remove(wav.c_str());}
             );
-            std::cout << "    ADD SOUND " << processed_sounds_ << ".ogg" << std::endl;
             sounds_.push_back("audio/sounds/" + std::to_string(processed_sounds_) + ".ogg");
         }
         else{
             sounds_.push_back("audio/sounds/INVALID.ogg");
-            std::cout << "    -- ADD SOUND INVALID.ogg" << std::endl;
         }
     }
     processed_sounds_ ++;

+ 10 - 0
src/installer/MediaDataInstaller.h

@@ -59,6 +59,16 @@ class MediaDataInstaller{
          */
         void InstallSprites();
 
+        /**
+         * Builds the font images from the textures in WINDOW.BIN and saves them in the "fonts" directory.
+         *
+         * The font XML files that describe them are part of the V-Gears data files. The fonts are always
+         * needed, so this doesn't depend on the images option.
+         *
+         * @return True if all the fonts were saved, false if WINDOW.BIN couldn't be read.
+         */
+        bool InstallFonts();
+
         /**
          * Prepares the installer for the sounds extraction.
          *

+ 11 - 7
src/installer/TexFile.cpp

@@ -140,7 +140,9 @@ void TexFile::SavePng(
         return;
     }
     // TODO: Warn if wrong palette index.
-    Ogre::Image* image = new Ogre::Image(Ogre::PF_R8G8B8A8_UINT, w, h);
+    // What the texture doesn't cover is transparent, not whatever was in memory.
+    Ogre::Image image(Ogre::PF_R8G8B8A8_UINT, w, h);
+    image.setTo(Ogre::ColourValue::ZERO);
     int target_x = 0;
     int target_y = 0;
     for (int c_y = y; c_y < height_ && c_y < y + h; c_y ++){
@@ -171,7 +173,7 @@ void TexFile::SavePng(
                     a = palettes_.at(palette).at(pixel_ref_.at(i)).a;
                 }
             }
-            image->setColourAt(Ogre::ColourValue(r, g, b, a), target_x, target_y, 0);
+            image.setColourAt(Ogre::ColourValue(r, g, b, a), target_x, target_y, 0);
             target_x ++;
             if (target_x >= w){
                 target_y ++;
@@ -179,7 +181,7 @@ void TexFile::SavePng(
             }
         }
     }
-    image->save(file_name);
+    image.save(file_name);
 }
 
 void TexFile::SavePng(std::string file_name, unsigned int palette){
@@ -196,7 +198,9 @@ void TexFile::SavePng(
         return;
     }
     // TODO: Warn if wrong palette index.
-    Ogre::Image* image = new Ogre::Image(Ogre::PF_R8G8B8A8_UINT, w1 + w2, h);
+    // What the texture doesn't cover is transparent, not whatever was in memory.
+    Ogre::Image image(Ogre::PF_R8G8B8A8_UINT, w1 + w2, h);
+    image.setTo(Ogre::ColourValue::ZERO);
     int target_x = 0;
     int target_y = 0;
     // First image
@@ -219,7 +223,7 @@ void TexFile::SavePng(
                 b = palettes_.at(palette).at(pixel_ref_.at(i)).b;
                 a = palettes_.at(palette).at(pixel_ref_.at(i)).a;
             }
-            image->setColourAt(Ogre::ColourValue(r, g, b, a), target_x, target_y, 0);
+            image.setColourAt(Ogre::ColourValue(r, g, b, a), target_x, target_y, 0);
             target_x ++;
             if (target_x >= w1){
                 target_y ++;
@@ -248,7 +252,7 @@ void TexFile::SavePng(
                 b = palettes_.at(palette).at(pixel_ref_.at(i)).b;
                 a = palettes_.at(palette).at(pixel_ref_.at(i)).a;
             }
-            image->setColourAt(Ogre::ColourValue(r, g, b, a), target_x, target_y, 0);
+            image.setColourAt(Ogre::ColourValue(r, g, b, a), target_x, target_y, 0);
             target_x ++;
             if (target_x >= w1 + w2){
                 target_y ++;
@@ -256,5 +260,5 @@ void TexFile::SavePng(
             }
         }
     }
-    image->save(file_name);
+    image.save(file_name);
 }

+ 217 - 0
src/installer/WindowFonts.cpp

@@ -0,0 +1,217 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <array>
+#include <OgreImage.h>
+#include <OgreColourValue.h>
+#include "WindowFonts.h"
+
+namespace{
+
+    /**
+     * An RGBA colour.
+     */
+    struct Colour{
+        u8 r;
+        u8 g;
+        u8 b;
+        u8 a;
+    };
+
+    /**
+     * Fully transparent colour.
+     */
+    const Colour TRANSPARENT = {0, 0, 0, 0};
+
+    /**
+     * Colour of every palette index of a 4 bpp image.
+     */
+    typedef std::array<Colour, 16> Palette;
+
+    /**
+     * Palette of the dialog font: index 3 is the glyph, index 1 its shadow.
+     */
+    Palette TextPalette(){
+        Palette palette;
+        palette.fill(TRANSPARENT);
+        palette[1] = {32, 32, 32, 255};
+        palette[3] = {230, 230, 230, 255};
+        return palette;
+    }
+
+    /**
+     * Palette of the menu font and the small digits: index 1 is the glyph, index 15 its shadow.
+     */
+    Palette MenuPalette(){
+        Palette palette;
+        palette.fill(TRANSPARENT);
+        palette[1] = {230, 230, 230, 255};
+        palette[15] = {24, 24, 24, 255};
+        return palette;
+    }
+
+    /**
+     * Palette of the timer font. It's opaque: indices 2 to 4 are the glyph, the others the background.
+     */
+    Palette TimerPalette(){
+        Palette palette;
+        palette.fill({0, 0, 0, 255});
+        palette[2] = {255, 0, 255, 255};
+        palette[3] = {197, 0, 197, 255};
+        palette[4] = {139, 0, 139, 255};
+        palette[13] = {41, 41, 41, 255};
+        palette[14] = {24, 24, 24, 255};
+        palette[15] = {24, 24, 24, 255};
+        return palette;
+    }
+
+    /**
+     * Creates an image filled with a colour.
+     *
+     * @param[in] width Image width.
+     * @param[in] height Image height.
+     * @param[in] colour Colour of every pixel.
+     * @return The image.
+     */
+    WindowFonts::RgbaImage CreateImage(int width, int height, const Colour& colour){
+        WindowFonts::RgbaImage image;
+        image.width = width;
+        image.height = height;
+        image.pixels.resize(width * height * 4);
+        for (int i = 0; i < width * height; i ++){
+            image.pixels[i * 4] = colour.r;
+            image.pixels[i * 4 + 1] = colour.g;
+            image.pixels[i * 4 + 2] = colour.b;
+            image.pixels[i * 4 + 3] = colour.a;
+        }
+        return image;
+    }
+
+    /**
+     * Copies a rectangle of a TIM image into an RGBA image, converting it with a palette.
+     *
+     * Pixels outside of the destination are ignored.
+     *
+     * @param[in] src The TIM image.
+     * @param[in] src_x X coordinate of the rectangle in the TIM image.
+     * @param[in] src_y Y coordinate of the rectangle in the TIM image.
+     * @param[in] width Width of the rectangle.
+     * @param[in] height Height of the rectangle.
+     * @param[in] palette Colour of every palette index.
+     * @param[out] dst The destination image.
+     * @param[in] dst_x X coordinate of the rectangle in the destination image.
+     * @param[in] dst_y Y coordinate of the rectangle in the destination image.
+     */
+    void Blit(
+      const WindowFonts::IndexImage& src, int src_x, int src_y, int width, int height, const Palette& palette,
+      WindowFonts::RgbaImage& dst, int dst_x, int dst_y
+    ){
+        for (int y = 0; y < height; y ++){
+            for (int x = 0; x < width; x ++){
+                const int tx = dst_x + x;
+                const int ty = dst_y + y;
+                if (tx < 0 || ty < 0 || tx >= dst.width || ty >= dst.height) continue;
+                const Colour& c = palette[src.At(src_x + x, src_y + y) & 0x0F];
+                const int i = (ty * dst.width + tx) * 4;
+                dst.pixels[i] = c.r;
+                dst.pixels[i + 1] = c.g;
+                dst.pixels[i + 2] = c.b;
+                dst.pixels[i + 3] = c.a;
+            }
+        }
+    }
+
+    /**
+     * Reads a little endian 16 bit value.
+     */
+    u32 ReadU16(const u8* data){return data[0] | (data[1] << 8);}
+
+    /**
+     * Reads a little endian 32 bit value.
+     */
+    u32 ReadU32(const u8* data){return data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);}
+}
+
+u8 WindowFonts::IndexImage::At(int x, int y) const{
+    if (x < 0 || y < 0 || x >= width || y >= height) return 0;
+    return pixels[y * width + x];
+}
+
+bool WindowFonts::ReadTim4(const u8* data, size_t size, IndexImage& image){
+    // Header: magic (0x10) and flags. 4 bpp with a palette is 0x08.
+    if (size < 8 || ReadU32(data) != 0x10 || (ReadU32(data + 4) & 0x0F) != 0x08) return false;
+    size_t offset = 8;
+    // Palette block: its length comes first, the colours are not needed.
+    if (offset + 12 > size) return false;
+    offset += ReadU32(data + offset);
+    // Image block: length, x, y, width in 16 bit units, height.
+    if (offset + 12 > size) return false;
+    const int width = ReadU16(data + offset + 8) * 4;
+    const int height = ReadU16(data + offset + 10);
+    offset += 12;
+    if (offset + static_cast<size_t>(width / 2) * height > size) return false;
+    image.width = width;
+    image.height = height;
+    image.pixels.resize(width * height);
+    for (int i = 0; i < width * height / 2; i ++){
+        image.pixels[i * 2] = data[offset + i] & 0x0F;
+        image.pixels[i * 2 + 1] = data[offset + i] >> 4;
+    }
+    return true;
+}
+
+WindowFonts::RgbaImage WindowFonts::BuildTextFont(const IndexImage& font){
+    RgbaImage image = CreateImage(256, 256, TRANSPARENT);
+    Blit(font, 0, 0, 256, 256, TextPalette(), image, 0, 0);
+    return image;
+}
+
+WindowFonts::RgbaImage WindowFonts::BuildMenuFont(const IndexImage& window){
+    RgbaImage image = CreateImage(128, 256, TRANSPARENT);
+    // Twelve rows of 8 pixels at (128, 152).
+    for (int row = 0; row < 12; row ++) Blit(window, 128, 152 + row * 8, 128, 8, MenuPalette(), image, 0, row * 16 + 8);
+    return image;
+}
+
+WindowFonts::RgbaImage WindowFonts::BuildDigitsFont(const IndexImage& window){
+    RgbaImage image = CreateImage(128, 8, TRANSPARENT);
+    const Palette palette = MenuPalette();
+    // Digits 0 to 9, in cells of 8 pixels at (136, 0).
+    Blit(window, 136, 0, 80, 8, palette, image, 0, 0);
+    // Symbols, taken from the menu font: '-', '+', '%' and ':'. Cell 10 is the blank space.
+    Blit(window, 136, 240, 8, 8, palette, image, 88, 0);
+    Blit(window, 152, 216, 8, 8, palette, image, 96, 0);
+    Blit(window, 152, 232, 8, 8, palette, image, 104, 0);
+    Blit(window, 168, 232, 8, 8, palette, image, 112, 0);
+    return image;
+}
+
+WindowFonts::RgbaImage WindowFonts::BuildTimerFont(const IndexImage& window){
+    // Two rows of 24 pixels at (144, 80). The image is wider than what's left of the texture.
+    RgbaImage image = CreateImage(128, 48, {0, 0, 0, 255});
+    Blit(window, 144, 80, 112, 48, TimerPalette(), image, 0, 0);
+    return image;
+}
+
+void WindowFonts::SavePng(const RgbaImage& image, const std::string& file_name){
+    Ogre::Image png(Ogre::PF_R8G8B8A8_UINT, image.width, image.height);
+    for (int y = 0; y < image.height; y ++){
+        for (int x = 0; x < image.width; x ++){
+            const u8* p = &image.pixels[(y * image.width + x) * 4];
+            png.setColourAt(Ogre::ColourValue(p[0] / 255.0f, p[1] / 255.0f, p[2] / 255.0f, p[3] / 255.0f), x, y, 0);
+        }
+    }
+    png.save(file_name);
+}

+ 139 - 0
src/installer/WindowFonts.h

@@ -0,0 +1,139 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#pragma once
+
+#include <string>
+#include <vector>
+#include "common/TypeDefine.h"
+
+/**
+ * Builds the font images used by the game from the textures in WINDOW.BIN.
+ *
+ * WINDOW.BIN (data/kernel) holds three gzipped files. The first one is a 4 bpp TIM with the window
+ * graphics, including the menu font, the small digits and the timer digits. The second one is a 4 bpp
+ * TIM with the dialog font. The third one is the width table of the dialog font.
+ *
+ * The images built here have the layout described by the font XML files in data/fonts, so the XML
+ * files don't change. Only the palette indices of the TIM files are used, and they are mapped to fixed
+ * colours, because the game tints the text itself.
+ */
+namespace WindowFonts{
+
+    /**
+     * Palette indices of a 4 bpp TIM image, one byte per pixel.
+     */
+    struct IndexImage{
+
+        /**
+         * Image width, in pixels.
+         */
+        int width = 0;
+
+        /**
+         * Image height, in pixels.
+         */
+        int height = 0;
+
+        /**
+         * Palette index of every pixel, row by row.
+         */
+        std::vector<u8> pixels;
+
+        /**
+         * Gets the palette index of a pixel.
+         *
+         * @param[in] x X coordinate.
+         * @param[in] y Y coordinate.
+         * @return The palette index, or 0 if the coordinates are outside the image.
+         */
+        u8 At(int x, int y) const;
+    };
+
+    /**
+     * An RGBA image, four bytes per pixel.
+     */
+    struct RgbaImage{
+
+        /**
+         * Image width, in pixels.
+         */
+        int width = 0;
+
+        /**
+         * Image height, in pixels.
+         */
+        int height = 0;
+
+        /**
+         * Red, green, blue and alpha of every pixel, row by row.
+         */
+        std::vector<u8> pixels;
+    };
+
+    /**
+     * Reads the pixels of a 4 bpp TIM file.
+     *
+     * @param[in] data The TIM file.
+     * @param[in] size Size of the TIM file, in bytes.
+     * @param[out] image The palette indices of the image.
+     * @return True if the data is a valid 4 bpp TIM file, false otherwise.
+     */
+    bool ReadTim4(const u8* data, size_t size, IndexImage& image);
+
+    /**
+     * Builds the dialog font image (ffvii_en.png) from the second TIM of WINDOW.BIN.
+     *
+     * @param[in] font The dialog font TIM.
+     * @return The 256x256 font image.
+     */
+    RgbaImage BuildTextFont(const IndexImage& font);
+
+    /**
+     * Builds the menu font image (ffvii_menu.png) from the first TIM of WINDOW.BIN.
+     *
+     * The menu font is made of rows of 8 pixels. Each row is placed in a slot of 16 pixels, with the
+     * glyphs in the lower half. The four last rows of the image are empty, the PC version doesn't have
+     * the voiced kana that the XML expects there.
+     *
+     * @param[in] window The window graphics TIM.
+     * @return The 128x256 font image.
+     */
+    RgbaImage BuildMenuFont(const IndexImage& window);
+
+    /**
+     * Builds the small digits font image (ffvii_digits.png) from the first TIM of WINDOW.BIN.
+     *
+     * @param[in] window The window graphics TIM.
+     * @return The 128x8 font image.
+     */
+    RgbaImage BuildDigitsFont(const IndexImage& window);
+
+    /**
+     * Builds the timer font image (ffvii_timer.png) from the first TIM of WINDOW.BIN.
+     *
+     * @param[in] window The window graphics TIM.
+     * @return The 128x48 font image.
+     */
+    RgbaImage BuildTimerFont(const IndexImage& window);
+
+    /**
+     * Saves an image as a PNG file.
+     *
+     * @param[in] image The image to save.
+     * @param[in] file_name Path of the PNG file.
+     */
+    void SavePng(const RgbaImage& image, const std::string& file_name);
+}

+ 2 - 2
src/installer/WorldInstaller.cpp

@@ -44,8 +44,8 @@ std::string WorldInstaller::TERRAIN_MODELS_DIR("models/world/terrain");
 
 WorldInstaller::WorldInstaller(
   const DiskImage& disk_image, const std::string output_dir,
-  const bool keep_originals, Ogre::ResourceGroupManager* res_mgr
-): disk_image_(disk_image), output_dir_(output_dir), data_dir_(output_dir + "data/"), keep_originals_(keep_originals), res_mgr_(res_mgr) {}
+  Ogre::ResourceGroupManager* res_mgr
+): disk_image_(disk_image), output_dir_(output_dir), data_dir_(output_dir + "data/"), res_mgr_(res_mgr) {}
 
 WorldInstaller::~WorldInstaller(){}
 

+ 1 - 9
src/installer/WorldInstaller.h

@@ -35,13 +35,10 @@ class WorldInstaller{
          *
          * @param[in] disk_image Disk image to extract the data from.
          * @param[in] output_dir Path to the directory of the installation data.
-         * @param[in] keep_originals True to keep original data after
-         * conversion, false to remove.
          * @param[in] res_mgr The application resource manager.
          */
         WorldInstaller(
-          const DiskImage& disk_image, const std::string output_dir,
-          const bool keep_originals, Ogre::ResourceGroupManager* res_mgr
+          const DiskImage& disk_image, const std::string output_dir, Ogre::ResourceGroupManager* res_mgr
         );
 
         /**
@@ -347,11 +344,6 @@ class WorldInstaller{
          */
         std::string data_dir_;
 
-        /**
-         * If true, original files will not be deleted after conversion.
-         */
-        bool keep_originals_;
-
         /**
          * Number of maps already processed.
          */

+ 55 - 70
src/installer/common/BinGZipFile.cpp

@@ -39,89 +39,74 @@ BinGZipFile::BinGZipFile(u8* buffer, u32 offset, u32 length):
 
 BinGZipFile::~BinGZipFile(){}
 
-File* BinGZipFile::ExtractGZip(u32 file_index){
-    if (file_index >= file_count_) return NULL;
-    u32 extract_size = 256 * 1024;
-    u8* extract_buffer = static_cast<u8*>(malloc(extract_size));
-    int ret;
-    z_stream strm;
-    u32 offset = InnerGetFileOffset(file_index);
-
-    strm.zalloc = Z_NULL; // Used to allocate the internal state.
-    strm.zfree = Z_NULL; // Used to free the internal state.
-    strm.opaque = Z_NULL; // Private data object passed to zalloc and zfree.
-    strm.next_in = buffer_ + offset; //Next input byte.
-    strm.avail_in = buffer_size_; // Number of bytes available at next_in.
-    strm.next_out = extract_buffer; // Next output byte should be put there.
-    strm.avail_out = extract_size; // Remaining free space at next_out.
-    ret = inflateInit2(&strm, 15 + 32);
+bool BinGZipFile::Inflate(const u8* data, size_t size, std::vector<u8>& out, std::string& error){
+    out.assign(256 * 1024, 0);
+    z_stream strm{};
+    strm.zalloc = Z_NULL;
+    strm.zfree = Z_NULL;
+    strm.opaque = Z_NULL;
+    strm.next_in = const_cast<u8*>(data);
+    strm.avail_in = static_cast<uInt>(size);
+    strm.next_out = out.data();
+    strm.avail_out = static_cast<uInt>(out.size());
+    int ret = inflateInit2(&strm, 15 + 32);
     if (ret != Z_OK){
-        switch (ret){
-            case Z_MEM_ERROR:
-                inflateEnd(&strm);
-                LOGGER->Log("Warning: inflateInit2 - Z_MEM_ERROR in file " + file_name_);
-                break;
-            case Z_STREAM_ERROR:
-                inflateEnd(&strm);
-                LOGGER->Log("Warning: inflateInit2 - Z_STREAM_ERROR in file " + file_name_);
-                break;
-            default:
-                inflateEnd(&strm);
-                LOGGER->Log("Warning: inflateInit2 - unknown error in file " + file_name_);
-        }
-        return NULL;
+        error = ret == Z_MEM_ERROR ? "inflateInit2: Z_MEM_ERROR"
+          : (ret == Z_STREAM_ERROR ? "inflateInit2: Z_STREAM_ERROR" : "inflateInit2: unknown error");
+        out.clear();
+        return false;
     }
     do{
-        if (strm.next_out == NULL){
+        ret = inflate(&strm, Z_NO_FLUSH);
+        if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR || ret == Z_MEM_ERROR || ret == Z_STREAM_ERROR){
+            error = ret == Z_NEED_DICT ? "inflate: Z_NEED_DICT"
+              : (ret == Z_DATA_ERROR ? "inflate: Z_DATA_ERROR"
+              : (ret == Z_MEM_ERROR ? "inflate: Z_MEM_ERROR" : "inflate: Z_STREAM_ERROR"));
             inflateEnd(&strm);
-            LOGGER->Log("Warning: strm.next_out == NULL in file " + file_name_);
-            return NULL;
+            out.clear();
+            return false;
         }
-        ret = inflate(&strm, Z_NO_FLUSH);
-        assert(ret != Z_STREAM_ERROR);
-        switch (ret){
-            case Z_NEED_DICT:
-                inflateEnd(&strm);
-                LOGGER->Log("Warning: inflate - Z_NEED_DICT in file " + file_name_);
-                return NULL;
-            case Z_DATA_ERROR:
-                inflateEnd(&strm);
-                LOGGER->Log("Warning: inflate - Z_DATA_ERROR in file " + file_name_);
-                return NULL;
-            case Z_MEM_ERROR:
-                inflateEnd(&strm);
-                LOGGER->Log("Warning: inflate - Z_MEM_ERROR in file " + file_name_);
-                return NULL;
+        if (ret == Z_STREAM_END) break;
+        if (strm.avail_out == 0){
+            // The output is full: make it twice as big.
+            const size_t used = strm.total_out;
+            out.resize(out.size() * 2);
+            strm.next_out = out.data() + used;
+            strm.avail_out = static_cast<uInt>(out.size() - used);
         }
-
-        if (ret != Z_STREAM_END){
-            extract_buffer = static_cast<u8*>(realloc(extract_buffer, extract_size * 2));
-            if (extract_buffer == NULL){
-                inflateEnd(&strm);
-                LOGGER->Log("Warning: extract_buffer == NULL in file " + file_name_);
-                return NULL;
-            }
-            strm.next_out = static_cast<u8*>(extract_buffer + extract_size);
-            strm.avail_out = extract_size;
-            extract_size *= 2;
+        else if (strm.avail_in == 0){
+            // Room to write but nothing left to read: the data is cut.
+            error = "the compressed data is incomplete";
+            inflateEnd(&strm);
+            out.clear();
+            return false;
         }
-    } while (ret != Z_STREAM_END);
-    extract_size = extract_size - strm.avail_out;
-    (void)inflateEnd(&strm);
-    if (ret != Z_STREAM_END){
-        LOGGER->Log("Warning: ret != Z_STREAM_END in file " + file_name_);
-        return NULL;
+    } while (true);
+    out.resize(strm.total_out);
+    inflateEnd(&strm);
+    return true;
+}
+
+File BinGZipFile::ExtractGZip(u32 file_index){
+    if (file_index >= file_count_) return File();
+    const u32 offset = InnerGetFileOffset(file_index);
+    if (offset >= GetFileSize()) return File();
+    std::vector<u8> out;
+    std::string error;
+    if (!Inflate(buffer_.data() + offset, GetFileSize() - offset, out, error)){
+        LOGGER->Log("Warning: " + error + " in file " + file_name_);
+        return File();
     }
-    File* file = new File(extract_buffer, 0, extract_size);
-    free(extract_buffer);
-    return file;
+    if (out.empty()) return File();
+    return File(out.data(), 0, static_cast<u32>(out.size()));
 }
 
 u32 BinGZipFile::GetNumberOfFiles(){return file_count_;}
 
 void BinGZipFile::InnerGetNumberOfFiles(){
     file_count_ = 0;
-    for (u32 pointer = 0; pointer < buffer_size_;){
+    // Each file has a 6 byte header, then the GZip data, whose header is checked: stop when they don't fit.
+    for (u32 pointer = 0; pointer + 6 + 8 <= GetFileSize();){
         u16 temp = GetU16LE(pointer);
         if (temp == 0xFFFF) temp = 0; // Hack to deal with scene.bin
         pointer += 6;
@@ -141,7 +126,7 @@ void BinGZipFile::InnerGetNumberOfFiles(){
 u32 BinGZipFile::InnerGetFileOffset(u32 file_index){
     if (file_index >= file_count_) return 0;
     u32 current_file = 0;
-    for (u32 pointer = 0; pointer < buffer_size_;){
+    for (u32 pointer = 0; pointer + 6 + 8 <= GetFileSize();){
         u16 temp = GetU16LE(pointer);
         pointer += 6;
         // Condition for GZip header

+ 17 - 3
src/installer/common/BinGZipFile.h

@@ -15,6 +15,9 @@
 
 #pragma once
 
+#include <string>
+#include <vector>
+
 #include "common/File.h"
 
 /**
@@ -65,10 +68,21 @@ class BinGZipFile : public File{
          * Extracts a file from the compressed BIN file.
          *
          * @param[in] file_index The index of the file to extract.
-         * @return The extracted file, or NULL if there is no file at the
-         * specified index.
+         * @return The extracted file. It is empty if there is no file at the specified index, or it can't be
+         * extracted.
+         */
+        File ExtractGZip(u32 file_index);
+
+        /**
+         * Decompresses GZip data.
+         *
+         * @param[in] data The compressed data.
+         * @param[in] size Size of the compressed data.
+         * @param[out] out The decompressed data.
+         * @param[out] error What went wrong, if it fails.
+         * @return True if the data was decompressed.
          */
-        File* ExtractGZip(u32 file_index);
+        static bool Inflate(const u8* data, size_t size, std::vector<u8>& out, std::string& error);
 
         /**
          * Counts the number of files packed in the compressed BIN file.

+ 0 - 8
src/installer/data/BattleSceneFile.cpp

@@ -259,14 +259,6 @@ void BattleSceneFile::Read(File file){
                 enemy.immunities.push_back(immunity);
             }
         }
-        for (int a = 0; a < 16; a ++){
-            if (scene_.enemy_data[e].attacks[a] == 0xFFFF) continue;
-            Enemy::Attack attack;
-            attack.id = scene_.enemy_data[e].attacks[a];
-            if (scene_.enemy_data[e].attack_camera[a] == 0xFFFF) attack.camera = -1;
-            else attack.camera = scene_.enemy_data[e].attack_camera[a];
-            enemy.attacks.push_back(attack);
-        }
         for (int m = 0; m < 3; m ++){
             if (scene_.enemy_data[e].maniputale_attacks[m] == 0xFFFF) continue;
             enemy.manipulate_attacks.push_back(scene_.enemy_data[e].maniputale_attacks[m]);

+ 6 - 3
src/installer/data/DaFile.cpp

@@ -26,8 +26,8 @@ DaFile::DaFile(File file): da_file_(file){
     animations_.clear();
     // Save file contents as a byte array.
     file.SetOffset(0);
-    da_bytes_ = new u8[file.GetFileSize()];
-    file.GetFileBuffer(da_bytes_, 0, file.GetFileSize());
+    da_bytes_.assign(file.GetFileSize(), 0);
+    if (!da_bytes_.empty()) file.GetFileBuffer(da_bytes_.data(), 0, da_bytes_.size());
     bit_offset_ = 0;
     file.SetOffset(0);
     Read();
@@ -211,7 +211,10 @@ int DaFile::GetBitsU(int bits){
     // Bits are read most significant first.
     int value = 0;
     for (int i = 0; i < bits; i ++){
-        const int byte = da_bytes_[bit_offset_ / 8];
+        // Some animations are cut short in the original files, and their last frame goes past the end of the
+        // file. Those bits are read as 0, instead of whatever is in memory after the file.
+        const size_t byte_index = bit_offset_ / 8;
+        const int byte = byte_index < da_bytes_.size() ? da_bytes_[byte_index] : 0;
         const int bit = (byte >> (7 - (bit_offset_ % 8))) & 1;
         value = (value << 1) | bit;
         bit_offset_ ++;

+ 1 - 1
src/installer/data/DaFile.h

@@ -294,7 +294,7 @@ class DaFile{
         /**
          * Contents of the da file as a byte array.
          */
-        u8* da_bytes_;
+        std::vector<u8> da_bytes_;
 
         /**
          * List of animations.

+ 3 - 3
src/installer/data/Enemy.h

@@ -51,20 +51,20 @@ struct Enemy{
         /**
          * Attack ID.
          */
-        u16 id;
+        u16 id = 0;
 
         /**
          * Camera ID to use during the attack.
          *
          * -1 to not move the camera.
          */
-        int camera;
+        int camera = -1;
 
         /**
          * Animation script of the model to play for the attack, as in the model animation scripts
          * ("scriptN"). -1 if there is none.
          */
-        int animation;
+        int animation = -1;
     };
 
     /**

BIN=BIN
src/installer/decompiler/test/branches.dmp


+ 0 - 5
src/installer/decompiler/test/branches.txt

@@ -1,5 +0,0 @@
-pushWord 0
-jumpFalse postBranch
-stopObjectCodeA
-postBranch:
-stopObjectCodeA

BIN=BIN
src/installer/decompiler/test/break-do-while.dmp


+ 0 - 14
src/installer/decompiler/test/break-do-while.txt

@@ -1,14 +0,0 @@
-do:
-pushWord 18
-pushWordVar 321
-eq
-jumpTrue postBreak
-jump postDo
-postBreak:
-wordVarInc 123
-pushWord 42
-pushWordVar 123
-eq
-jumpTrue do
-postDo:
-stopObjectCodeA

BIN=BIN
src/installer/decompiler/test/break-do-while2.dmp


+ 0 - 15
src/installer/decompiler/test/break-do-while2.txt

@@ -1,15 +0,0 @@
-do:
-wordVarInc 321
-pushWord 18
-pushWordVar 321
-eq
-jumpTrue postBreak
-jump postDo
-postBreak:
-wordVarInc 123
-pushWord 42
-pushWordVar 123
-eq
-jumpTrue do
-postDo:
-stopObjectCodeA

BIN=BIN
src/installer/decompiler/test/break-while.dmp


+ 0 - 15
src/installer/decompiler/test/break-while.txt

@@ -1,15 +0,0 @@
-while:
-pushWord 42
-pushWordVar 123
-eq
-jumpTrue postWhile
-pushWord 18
-pushWordVar 321
-eq
-jumpTrue postBreak
-jump postWhile
-postBreak:
-wordVarInc 123
-jump while
-postWhile:
-stopObjectCodeA

BIN=BIN
src/installer/decompiler/test/bug_fixes.dat


+ 0 - 554
src/installer/decompiler/test/cfg_test.cpp

@@ -1,554 +0,0 @@
-/* ScummVM Tools
- *
- * ScummVM Tools is the legal property of its developers, whose
- * names are too numerous to list here. Please refer to the
- * COPYRIGHT file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include "decompiler/scummv6/engine.h"
-#include <gmock/gmock.h>
-#include <vector>
-#include "../ControlFlow.h"
-#include "../Disassembler.h"
-#include "../Graph.h"
-
-#define GET(vertex) (boost::get(boost::vertex_name, g, vertex))
-
-
-TEST(CFG, testUnreachable) {
-    InstVec insts;
-    Scumm::v6::Scummv6Engine *engine = new Scumm::v6::Scummv6Engine();
-    auto d = engine->GetDisassembler(insts);
-    d->open("decompiler/test/unreachable.dmp");
-    d->disassemble();
-    ControlFlow *c = new ControlFlow(insts, *engine);
-    Graph g = c->getGraph();
-    ASSERT_TRUE(boost::num_vertices(g) == 4);
-    VertexRange range = boost::vertices(g);
-    for (VertexIterator it = range.first; it != range.second; ++it) {
-        GroupPtr gr = GET(*it);
-        switch ((*gr->_start)->_address) {
-        case 0:
-            ASSERT_TRUE(boost::in_degree(*it, g) == 0 && boost::out_degree(*it, g) == 1);
-            break;
-        case 2:
-            ASSERT_TRUE(boost::in_degree(*it, g) == 1 && boost::out_degree(*it, g) == 1);
-            break;
-        case 5:
-            ASSERT_TRUE(boost::in_degree(*it, g) == 0 && boost::out_degree(*it, g) == 1);
-            break;
-        case 6:
-            ASSERT_TRUE(boost::in_degree(*it, g) == 2 && boost::out_degree(*it, g) == 0);
-            break;
-        default:
-            ASSERT_TRUE(false);
-        }
-    }
-    delete c;
-    delete engine;
-};
-
-TEST(CFG, testBranching) {
-    InstVec insts;
-    Scumm::v6::Scummv6Engine *engine = new Scumm::v6::Scummv6Engine();
-    auto d = engine->GetDisassembler(insts);
-    d->open("decompiler/test/branches.dmp");
-    d->disassemble();
-
-    ControlFlow *c = new ControlFlow(insts, *engine);
-    Graph g = c->getGraph();
-    ASSERT_TRUE(boost::num_vertices(g) == 4);
-    VertexRange range = boost::vertices(g);
-    for (VertexIterator it = range.first; it != range.second; ++it) {
-        GroupPtr gr = GET(*it);
-        switch ((*gr->_start)->_address) {
-        case 0:
-            ASSERT_TRUE(boost::in_degree(*it, g) == 0 && boost::out_degree(*it, g) == 1);
-            break;
-        case 2:
-            ASSERT_TRUE(boost::in_degree(*it, g) == 1 && boost::out_degree(*it, g) == 2);
-            break;
-        case 5:
-            ASSERT_TRUE(boost::in_degree(*it, g) == 1 && boost::out_degree(*it, g) == 1);
-            break;
-        case 6:
-            ASSERT_TRUE(boost::in_degree(*it, g) == 2 && boost::out_degree(*it, g) == 0);
-            break;
-        default:
-            ASSERT_TRUE(false);
-        }
-    }
-    delete c;
-    delete engine;
-}
-
-TEST(CFG, testGrouping) {
-    InstVec insts;
-    auto engine = std::make_unique<Scumm::v6::Scummv6Engine>();
-    auto d = engine->GetDisassembler(insts);
-    d->open("decompiler/test/branches.dmp");
-    d->disassemble();
-
-    auto c = std::make_unique<ControlFlow>(insts, *engine);
-    c->createGroups();
-    Graph g = c->getGraph();
-    ASSERT_TRUE(boost::num_vertices(g) == 3);
-    VertexRange range = boost::vertices(g);
-    for (VertexIterator it = range.first; it != range.second; ++it) {
-        GroupPtr gr = GET(*it);
-        switch ((*gr->_start)->_address) {
-        case 0:
-            ASSERT_TRUE((*gr->_end)->_address == 2);
-            ASSERT_TRUE(boost::in_degree(*it, g) == 0 && boost::out_degree(*it, g) == 2);
-            break;
-        case 5:
-            ASSERT_TRUE(boost::in_degree(*it, g) == 1 && boost::out_degree(*it, g) == 1);
-            break;
-        case 6:
-            ASSERT_TRUE(boost::in_degree(*it, g) == 2 && boost::out_degree(*it, g) == 0);
-            break;
-        default:
-            ASSERT_TRUE(false);
-            break;
-        }
-    }
-}
-
-// TODO: Fix me, this fails but looks like it shouldn't
-TEST(CFG, DISABLED_testShortCircuitDetection) {
-    InstVec insts;
-    auto engine = std::make_unique<Scumm::v6::Scummv6Engine>();
-    auto d = engine->GetDisassembler(insts);
-    d->open("decompiler/test/short-circuit.dmp");
-    d->disassemble();
-    auto c = std::make_unique<ControlFlow>(insts, *engine);
-    c->createGroups();
-    Graph g = c->getGraph();
-    ASSERT_TRUE(boost::num_vertices(g) == 3);
-}
-
-TEST(CFG, testWhileDetection) {
-    InstVec insts;
-    auto engine = std::make_unique<Scumm::v6::Scummv6Engine>();
-    auto d = engine->GetDisassembler(insts);
-    d->open("decompiler/test/while.dmp");
-    d->disassemble();
-    auto c = std::make_unique<ControlFlow>(insts, *engine);
-    c->createGroups();
-    Graph g = c->analyze();
-    VertexRange range = boost::vertices(g);
-    for (VertexIterator it = range.first; it != range.second; ++it) {
-        GroupPtr gr = GET(*it);
-        if ((*gr->_start)->_address == 0)
-            ASSERT_TRUE(gr->_type == kWhileCondGroupType);
-    }
-
-}
-
-TEST(CFG, testDoWhileDetection) {
-    InstVec insts;
-    auto engine = std::make_unique<Scumm::v6::Scummv6Engine>();
-    auto d = engine->GetDisassembler(insts);
-    d->open("decompiler/test/while.dmp");
-    d->disassemble();
-    auto c = std::make_unique<ControlFlow>(insts, *engine);
-    c->createGroups();
-    Graph g = c->analyze();
-    VertexRange range = boost::vertices(g);
-    for (VertexIterator it = range.first; it != range.second; ++it) {
-        GroupPtr gr = GET(*it);
-        if ((*gr->_start)->_address == 3)
-            ASSERT_TRUE(gr->_type == kDoWhileCondGroupType);
-    }
-}
-
-TEST(CFG, testBreakDetection) {
-    InstVec insts;
-    auto engine = std::make_unique<Scumm::v6::Scummv6Engine>();
-    auto d = engine->GetDisassembler(insts);
-    d->open("decompiler/test/break-while.dmp");
-    d->disassemble();
-    auto c = std::make_unique<ControlFlow>(insts, *engine);
-    c->createGroups();
-    Graph g = c->analyze();
-    VertexRange range = boost::vertices(g);
-    for (VertexIterator it = range.first; it != range.second; ++it) {
-        GroupPtr gr = GET(*it);
-        if ((*gr->_start)->_address == 0x14)
-            ASSERT_TRUE(gr->_type == kBreakGroupType);
-    }
-
-
-    insts.clear();
-    engine = std::make_unique<Scumm::v6::Scummv6Engine>();
-    d = engine->GetDisassembler(insts);
-    d->open("decompiler/test/break-do-while.dmp");
-    d->disassemble();
-
-    c = std::make_unique<ControlFlow>(insts, *engine);
-    c->createGroups();
-    g = c->analyze();
-    range = boost::vertices(g);
-    for (VertexIterator it = range.first; it != range.second; ++it) {
-        GroupPtr gr = GET(*it);
-        if ((*gr->_start)->_address == 0xA)
-            ASSERT_TRUE(gr->_type == kBreakGroupType);
-    }
-
-    insts.clear();
-    engine = std::make_unique<Scumm::v6::Scummv6Engine>();
-    d = engine->GetDisassembler(insts);
-    d->open("decompiler/test/break-do-while2.dmp");
-    d->disassemble();
-    c = std::make_unique<ControlFlow>(insts, *engine);
-    c->createGroups();
-    g = c->analyze();
-    range = boost::vertices(g);
-    for (VertexIterator it = range.first; it != range.second; ++it) {
-        GroupPtr gr = GET(*it);
-        if ((*gr->_start)->_address == 0xD)
-            ASSERT_TRUE(gr->_type == kBreakGroupType);
-    }
-
-}
-
-TEST(CFG, testContinueDetection) {
-    InstVec insts;
-    auto engine = std::make_unique<Scumm::v6::Scummv6Engine>();
-    auto d = engine->GetDisassembler(insts);
-    d->open("decompiler/test/continue-while.dmp");
-    d->disassemble();
-    auto c = std::make_unique<ControlFlow>(insts, *engine);
-    c->createGroups();
-    Graph g = c->analyze();
-    VertexRange range = boost::vertices(g);
-    for (VertexIterator it = range.first; it != range.second; ++it) {
-        GroupPtr gr = GET(*it);
-        if ((*gr->_start)->_address == 0x14)
-            ASSERT_TRUE(gr->_type == kContinueGroupType);
-        if ((*gr->_start)->_address == 0x1a)
-            ASSERT_TRUE(gr->_type == kNormalGroupType);
-    }
-;
-
-    insts.clear();
-    engine = std::make_unique<Scumm::v6::Scummv6Engine>();
-    d = engine->GetDisassembler(insts);
-    d->open("decompiler/test/continue-do-while.dmp");
-    d->disassemble();
-    c = std::make_unique<ControlFlow>(insts, *engine);
-    c->createGroups();
-    g = c->analyze();
-    range = boost::vertices(g);
-    for (VertexIterator it = range.first; it != range.second; ++it) {
-        GroupPtr gr = GET(*it);
-        if ((*gr->_start)->_address == 0xA)
-            ASSERT_TRUE(gr->_type == kContinueGroupType);
-    }
-
-    insts.clear();
-    engine = std::make_unique<Scumm::v6::Scummv6Engine>();
-    d = engine->GetDisassembler(insts);
-    d->open("decompiler/test/continue-do-while2.dmp");
-    d->disassemble();
-    c = std::make_unique<ControlFlow>(insts, *engine);
-    c->createGroups();
-    g = c->analyze();
-    range = boost::vertices(g);
-    for (VertexIterator it = range.first; it != range.second; ++it) {
-        GroupPtr gr = GET(*it);
-        if ((*gr->_start)->_address == 0xD)
-            ASSERT_TRUE(gr->_type == kContinueGroupType);
-    }
-}
-
-TEST(CFG, testIfDetection) {
-    InstVec insts;
-    auto engine = std::make_unique<Scumm::v6::Scummv6Engine>();
-    auto d = engine->GetDisassembler(insts);
-    d->open("decompiler/test/if.dmp");
-    d->disassemble();
-    auto c = std::make_unique<ControlFlow>(insts, *engine);
-    c->createGroups();
-    Graph g = c->analyze();
-    VertexRange range = boost::vertices(g);
-    for (VertexIterator it = range.first; it != range.second; ++it) {
-        GroupPtr gr = GET(*it);
-        if ((*gr->_start)->_address == 0x0)
-            ASSERT_TRUE(gr->_type == kIfCondGroupType);
-    }
-
-    insts.clear();
-    engine = std::make_unique<Scumm::v6::Scummv6Engine>();
-    d = engine->GetDisassembler(insts);
-    d->open("decompiler/test/break-do-while.dmp");
-    d->disassemble();
-
-    c = std::make_unique<ControlFlow>(insts, *engine);
-    c->createGroups();
-    g = c->analyze();
-    range = boost::vertices(g);
-    for (VertexIterator it = range.first; it != range.second; ++it) {
-        GroupPtr gr = GET(*it);
-        if ((*gr->_start)->_address == 0x0)
-            ASSERT_TRUE(gr->_type == kIfCondGroupType);
-    }
-
-    insts.clear();
-    engine = std::make_unique<Scumm::v6::Scummv6Engine>();
-    d = engine->GetDisassembler(insts);
-    d->open("decompiler/test/break-do-while2.dmp");
-    d->disassemble();
-    c = std::make_unique<ControlFlow>(insts, *engine);
-    c->createGroups();
-    g = c->analyze();
-    range = boost::vertices(g);
-    for (VertexIterator it = range.first; it != range.second; ++it) {
-        GroupPtr gr = GET(*it);
-        if ((*gr->_start)->_address == 0x3)
-            ASSERT_TRUE(gr->_type == kIfCondGroupType);
-    }
-
-
-    insts.clear();
-    engine = std::make_unique<Scumm::v6::Scummv6Engine>();
-    d = engine->GetDisassembler(insts);
-    d->open("decompiler/test/continue-do-while.dmp");
-    d->disassemble();
-    c = std::make_unique<ControlFlow>(insts, *engine);
-    c->createGroups();
-    g = c->analyze();
-    range = boost::vertices(g);
-    for (VertexIterator it = range.first; it != range.second; ++it) {
-        GroupPtr gr = GET(*it);
-        if ((*gr->_start)->_address == 0x0)
-            ASSERT_TRUE(gr->_type == kIfCondGroupType);
-    }
-
-    insts.clear();
-    engine = std::make_unique<Scumm::v6::Scummv6Engine>();
-    d = engine->GetDisassembler(insts);
-    d->open("decompiler/test/continue-do-while2.dmp");
-    d->disassemble();
-    c = std::make_unique<ControlFlow>(insts, *engine);
-    c->createGroups();
-    g = c->analyze();
-    range = boost::vertices(g);
-    for (VertexIterator it = range.first; it != range.second; ++it) {
-        GroupPtr gr = GET(*it);
-        if ((*gr->_start)->_address == 0x3)
-            ASSERT_TRUE(gr->_type == kIfCondGroupType);
-    }
-}
-
-TEST(CFG, testElseDetection) {
-    InstVec insts;
-    auto engine = std::make_unique<Scumm::v6::Scummv6Engine>();
-    auto d = engine->GetDisassembler(insts);
-    d->open("decompiler/test/if-else.dmp");
-    d->disassemble();
-    auto c = std::make_unique<ControlFlow>(insts, *engine);
-    c->createGroups();
-    Graph g = c->analyze();
-    VertexRange range = boost::vertices(g);
-    for (VertexIterator it = range.first; it != range.second; ++it) {
-        GroupPtr gr = GET(*it);
-        if ((*gr->_start)->_address == 0x10) {
-            ASSERT_TRUE(gr->_startElse);
-            ASSERT_TRUE(gr->_endElse.size() == 1 && gr->_endElse[0] == gr);
-        }
-    }
-
-    insts.clear();
-    engine = std::make_unique<Scumm::v6::Scummv6Engine>();
-    d = engine->GetDisassembler(insts);
-    d->open("decompiler/test/if-no-else.dmp");
-    d->disassemble();
-
-    c = std::make_unique<ControlFlow>(insts, *engine);
-    c->createGroups();
-    g = c->analyze();
-    range = boost::vertices(g);
-    for (VertexIterator it = range.first; it != range.second; ++it) {
-        GroupPtr gr = GET(*it);
-        if ((*gr->_start)->_address == 0x0)
-            ASSERT_TRUE(gr->_type == kIfCondGroupType);
-        ASSERT_TRUE(!gr->_startElse);
-    }
-}
-
-TEST(CFG, testNestedLoops) {
-    InstVec insts;
-    auto engine = std::make_unique<Scumm::v6::Scummv6Engine>();
-    auto d = engine->GetDisassembler(insts);
-    d->open("decompiler/test/do-while-in-while.dmp");
-    d->disassemble();
-    auto c = std::make_unique<ControlFlow>(insts, *engine);
-    c->createGroups();
-    Graph g = c->analyze();
-    VertexRange range = boost::vertices(g);
-    for (VertexIterator it = range.first; it != range.second; ++it) {
-        GroupPtr gr = GET(*it);
-        if ((*gr->_start)->_address == 0x0)
-            ASSERT_TRUE(gr->_type == kWhileCondGroupType);
-        if ((*gr->_start)->_address == 0xd)
-            ASSERT_TRUE(gr->_type == kDoWhileCondGroupType);
-    }
-
-    insts.clear();
-    engine = std::make_unique<Scumm::v6::Scummv6Engine>();
-    d = engine->GetDisassembler(insts);
-    d->open("decompiler/test/nested-do-while.dmp");
-    d->disassemble();
-
-    c = std::make_unique<ControlFlow>(insts, *engine);
-    c->createGroups();
-    g = c->analyze();
-    range = boost::vertices(g);
-    for (VertexIterator it = range.first; it != range.second; ++it) {
-        GroupPtr gr = GET(*it);
-        if ((*gr->_start)->_address == 0x6)
-            ASSERT_TRUE(gr->_type == kDoWhileCondGroupType);
-        if ((*gr->_start)->_address == 0x10)
-            ASSERT_TRUE(gr->_type == kDoWhileCondGroupType);
-    }
-
-    insts.clear();
-    engine = std::make_unique<Scumm::v6::Scummv6Engine>();
-    d = engine->GetDisassembler(insts);
-    d->open("decompiler/test/nested-while.dmp");
-    d->disassemble();
-    c = std::make_unique<ControlFlow>(insts, *engine);
-    c->createGroups();
-    g = c->analyze();
-    range = boost::vertices(g);
-    for (VertexIterator it = range.first; it != range.second; ++it) {
-        GroupPtr gr = GET(*it);
-        if ((*gr->_start)->_address == 0x0)
-            ASSERT_TRUE(gr->_type == kWhileCondGroupType);
-        if ((*gr->_start)->_address == 0xa)
-            ASSERT_TRUE(gr->_type == kWhileCondGroupType);
-    }
-
-    insts.clear();
-    engine = std::make_unique<Scumm::v6::Scummv6Engine>();
-    d = engine->GetDisassembler(insts);
-    d->open("decompiler/test/nested-while2.dmp");
-    d->disassemble();
-    c = std::make_unique<ControlFlow>(insts, *engine);
-    c->createGroups();
-    g = c->analyze();
-    range = boost::vertices(g);
-    for (VertexIterator it = range.first; it != range.second; ++it) {
-        GroupPtr gr = GET(*it);
-        if ((*gr->_start)->_address == 0x0)
-            ASSERT_TRUE(gr->_type == kWhileCondGroupType);
-        if ((*gr->_start)->_address == 0xd)
-            ASSERT_TRUE(gr->_type == kWhileCondGroupType);
-    }
-
-    insts.clear();
-    engine = std::make_unique<Scumm::v6::Scummv6Engine>();
-    d = engine->GetDisassembler(insts);
-    d->open("decompiler/test/while-in-do-while.dmp");
-    d->disassemble();
-    c = std::make_unique<ControlFlow>(insts, *engine);
-    c->createGroups();
-    g = c->analyze();
-    range = boost::vertices(g);
-    for (VertexIterator it = range.first; it != range.second; ++it) {
-        GroupPtr gr = GET(*it);
-        if ((*gr->_start)->_address == 0x0)
-            ASSERT_TRUE(gr->_type == kWhileCondGroupType);
-        if ((*gr->_start)->_address == 0x10)
-            ASSERT_TRUE(gr->_type == kDoWhileCondGroupType);
-    }
-
-    insts.clear();
-    engine = std::make_unique<Scumm::v6::Scummv6Engine>();
-    d = engine->GetDisassembler(insts);
-    d->open("decompiler/test/while-in-do-while2.dmp");
-    d->disassemble();
-
-    c = std::make_unique<ControlFlow>(insts, *engine);
-    c->createGroups();
-    g = c->analyze();
-    range = boost::vertices(g);
-    for (VertexIterator it = range.first; it != range.second; ++it) {
-        GroupPtr gr = GET(*it);
-        if ((*gr->_start)->_address == 0x3)
-            ASSERT_TRUE(gr->_type == kWhileCondGroupType);
-        if ((*gr->_start)->_address == 0x13)
-            ASSERT_TRUE(gr->_type == kDoWhileCondGroupType);
-    }
-}
-
-// This test requires script-30.dmp from Sam & Max: Hit The Road.
-// 6e48faca13e1f6df9341567608962744 *script-30.dmp
-// Disabled as mentioned file is copyrighted
-TEST(CFG, DISABLED_testSamAndMaxScript30) {
-    InstVec insts;
-    auto engine = std::make_unique<Scumm::v6::Scummv6Engine>();
-    auto d = engine->GetDisassembler(insts);
-    d->open("decompiler/test/script-30.dmp");
-    d->disassemble();
-    auto c = std::make_unique<ControlFlow>(insts, *engine);
-    c->createGroups();
-    Graph g = c->analyze();
-    VertexRange range = boost::vertices(g);
-    for (VertexIterator it = range.first; it != range.second; ++it) {
-        GroupPtr gr = GET(*it);
-        switch ((*gr->_start)->_address) {
-        case 0x6:
-            ASSERT_TRUE(gr->_type == kWhileCondGroupType);
-            ASSERT_TRUE(!gr->_startElse);
-            ASSERT_TRUE(gr->_endElse.empty());
-            break;
-        case 0x19:
-        case 0x3A:
-        case 0x4F:
-        case 0x68:
-        case 0x74: // Allow inclusion of the pop instruction immediately before
-        case 0x75:
-        case 0x92:
-            ASSERT_TRUE(gr->_type == kIfCondGroupType);
-            ASSERT_TRUE(!gr->_startElse);
-            ASSERT_TRUE(gr->_endElse.empty());
-            break;
-        case 0x8B:
-            ASSERT_TRUE(gr->_type == kNormalGroupType);
-            ASSERT_TRUE(gr->_startElse);
-            ASSERT_TRUE(gr->_endElse.size() == 1 && (*gr->_endElse[0]->_start)->_address == 0x8B);
-            break;
-        case 0x91:
-            ASSERT_TRUE(gr->_type == kNormalGroupType || gr->_type == kIfCondGroupType); // Allow inclusion of the pop instruction immediately before
-            ASSERT_TRUE(gr->_startElse);
-            ASSERT_TRUE(gr->_endElse.empty());
-            break;
-        case 0xA6:
-            ASSERT_TRUE(gr->_type == kNormalGroupType);
-            ASSERT_TRUE(!gr->_startElse);
-            ASSERT_TRUE(gr->_endElse.size() == 1 && (*gr->_endElse[0]->_start)->_address == 0x91);
-            break;
-        default:
-            ASSERT_TRUE(gr->_type == kNormalGroupType);
-            ASSERT_TRUE(!gr->_startElse);
-            ASSERT_TRUE(gr->_endElse.empty());
-            break;
-        }
-    }
-}

+ 0 - 217
src/installer/decompiler/test/codegen.cpp

@@ -1,217 +0,0 @@
-/* ScummVM Tools
- *
- * ScummVM Tools is the legal property of its developers, whose
- * names are too numerous to list here. Please refer to the
- * COPYRIGHT file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-
-#include "decompiler/scummv6/engine.h"
-
-#include <vector>
-
-#include "../CodeGenerator.h"
-#include "../ControlFlow.h"
-#include "../Disassembler.h"
-#include "../Graph.h"
-#define GET(vertex) (boost::get(boost::vertex_name, g, vertex))
-
-#include <streambuf>
-#include <ostream>
-#include <gmock/gmock.h>
-#include "util.h"
-
-std::string removeSpaces(std::string s) {
-    size_t found;
-    while ((found = s.find(' ')) != std::string::npos)
-        s = s.erase(found, 1);
-    return s;
-}
-
-typedef std::vector<std::string>::iterator CodeIterator;
-
-
-TEST(CodeGen, testContinue) {
-    InstVec insts;
-    auto engine = std::make_unique<Scumm::v6::Scummv6Engine>();
-    auto d = engine->GetDisassembler(insts);
-    d->open("decompiler/test/continue-do-while.dmp");
-    d->disassemble();
-    auto c = std::make_unique<ControlFlow>(insts, *engine);
-    c->createGroups();
-    Graph g = c->analyze();
-    onullstream ns;
-    auto cg = engine->GetCodeGenerator(insts, ns);
-    cg->generate(insts, g);
-
-    VertexIterator v = boost::vertices(g).first;
-    std::vector<std::string> output, expected;
-    expected.push_back("do{");
-    expected.push_back("if(18 != var321) {");
-    expected.push_back("continue;");
-    expected.push_back("}");
-    expected.push_back("VAR_CHARSET_MASK--;");
-    expected.push_back("} while (42 == VAR_CHARSET_MASK)");
-    expected.push_back("stopObjectCodeA();");
-    GroupPtr gr = GET(*v);
-    // Find first node
-    while (gr->_prev != NULL)
-        gr = gr->_prev;
-    // Copy out all lines of code
-    while (gr != NULL) {
-        for (std::vector<CodeLine>::iterator it = gr->_code.begin(); it != gr->_code.end(); ++it)
-            output.push_back(it->_line);
-        gr = gr->_next;
-    }
-    ASSERT_TRUE(output.size() == expected.size());
-    CodeIterator it, it2;
-    for (it = output.begin(), it2 = expected.begin(); it != output.end() && it2 != expected.end(); ++it, ++it2) {
-        ASSERT_TRUE(removeSpaces(*it).compare(removeSpaces(*it2)) == 0);
-    }
-}
-
-TEST(CodeGen, testBreak) {
-    InstVec insts;
-    auto engine = std::make_unique<Scumm::v6::Scummv6Engine>();
-    auto d = engine->GetDisassembler(insts);
-    d->open("decompiler/test/break-while.dmp");
-    d->disassemble();
-    auto c = std::make_unique<ControlFlow>(insts, *engine);
-    c->createGroups();
-    Graph g = c->analyze();
-    onullstream ns;
-    auto cg = engine->GetCodeGenerator(insts, ns);
-    cg->generate(insts, g);
-
-    VertexIterator v = boost::vertices(g).first;
-    std::vector<std::string> output, expected;
-    expected.push_back("while (42 != VAR_CHARSET_MASK) {");
-    expected.push_back("if (18 != var321) {");
-    expected.push_back("break;");
-    expected.push_back("}");
-    expected.push_back("VAR_CHARSET_MASK--;");
-    expected.push_back("}");
-    expected.push_back("stopObjectCodeA();");
-    GroupPtr gr = GET(*v);
-    // Find first node
-    while (gr->_prev != NULL)
-        gr = gr->_prev;
-    // Copy out all lines of code
-    while (gr != NULL) {
-        for (std::vector<CodeLine>::iterator it = gr->_code.begin(); it != gr->_code.end(); ++it)
-            output.push_back(it->_line);
-        gr = gr->_next;
-    }
-    ASSERT_TRUE(output.size() == expected.size());
-    CodeIterator it, it2;
-    for (it = output.begin(), it2 = expected.begin(); it != output.end() && it2 != expected.end(); ++it, ++it2) {
-        ASSERT_TRUE(removeSpaces(*it).compare(removeSpaces(*it2)) == 0);
-    }
-}
-
-TEST(CodeGen, testElse) {
-    InstVec insts;
-    auto engine = std::make_unique<Scumm::v6::Scummv6Engine>();
-    auto d = engine->GetDisassembler(insts);
-    d->open("decompiler/test/if-else.dmp");
-    d->disassemble();
-    auto c = std::make_unique<ControlFlow>(insts, *engine);
-    c->createGroups();
-    Graph g = c->analyze();
-    onullstream ns;
-    auto cg = engine->GetCodeGenerator(insts, ns);
-    cg->generate(insts, g);
-
-    VertexIterator v = boost::vertices(g).first;
-    std::vector<std::string> output, expected;
-    expected.push_back("if (42 != VAR_CHARSET_MASK) {");
-    expected.push_back("VAR_CHARSET_MASK--;");
-    expected.push_back("} else {");
-    expected.push_back("VAR_CHARSET_MASK++;");
-    expected.push_back("}");
-    expected.push_back("stopObjectCodeA();");
-    GroupPtr gr = GET(*v);
-    // Find first node
-    while (gr->_prev != NULL)
-        gr = gr->_prev;
-    // Copy out all lines of code
-    while (gr != NULL) {
-        for (std::vector<CodeLine>::iterator it = gr->_code.begin(); it != gr->_code.end(); ++it)
-            output.push_back(it->_line);
-        gr = gr->_next;
-    }
-    ASSERT_TRUE(output.size() == expected.size());
-    CodeIterator it, it2;
-    for (it = output.begin(), it2 = expected.begin(); it != output.end() && it2 != expected.end(); ++it, ++it2) {
-        ASSERT_TRUE(removeSpaces(*it).compare(removeSpaces(*it2)) == 0);
-    }
-}
-
-// This test requires script-30 and script-48.dmp from Sam & Max: Hit The Road.
-// 6e48faca13e1f6df9341567608962744 *script-30.dmp
-// afd7dc5d377894b3b9d0504927adf1b1 *script-48.dmp
-// Disabled as mentioned file is copyrighted
-TEST(CodeGen, DISABLED_testCoalescing) {
-    InstVec insts;
-    auto engine = std::make_unique<Scumm::v6::Scummv6Engine>();
-    auto d = engine->GetDisassembler(insts);
-    d->open("decompiler/test/script-30.dmp");
-    d->disassemble();
-    auto c = std::make_unique<ControlFlow>(insts, *engine);
-    c->createGroups();
-    Graph g = c->analyze();
-    onullstream ns;
-    auto cg = engine->GetCodeGenerator(insts, ns);
-    cg->generate(insts, g);
-
-    VertexIterator v = boost::vertices(g).first;
-    GroupPtr gr = GET(*v);
-    // Find first node
-    while (gr->_prev != NULL)
-        gr = gr->_prev;
-    // Find vertex to test
-    while ((*gr->_start)->_address != 0x91)
-        gr = gr->_next;
-
-    ASSERT_TRUE(gr->_code.size() == 2);
-    ASSERT_TRUE(removeSpaces(gr->_code[0]._line).compare("}else{") == 0);
-    ASSERT_TRUE(removeSpaces(gr->_code[1]._line).substr(0, 2).compare("if") == 0);
-
-    insts.clear();
-    engine = std::make_unique<Scumm::v6::Scummv6Engine>();
-    d = engine->GetDisassembler(insts);
-    d->open("decompiler/test/script-48.dmp");
-    d->disassemble();
-
-    c = std::make_unique<ControlFlow>(insts, *engine);
-    c->createGroups();
-    g = c->analyze();
-    cg = engine->GetCodeGenerator(insts, ns);
-    cg->generate(insts, g);
-
-    v = boost::vertices(g).first;
-    gr = GET(*v);
-    // Find first node
-    while (gr->_prev != NULL)
-        gr = gr->_prev;
-    // Find vertex to test
-    while ((*gr->_start)->_address != 0x191)
-        gr = gr->_next;
-
-    ASSERT_TRUE(gr->_code.size() == 1);
-    ASSERT_TRUE(removeSpaces(gr->_code[0]._line).substr(0, 7).compare("}elseif") == 0);
-}

BIN=BIN
src/installer/decompiler/test/continue-do-while.dmp


+ 0 - 14
src/installer/decompiler/test/continue-do-while.txt

@@ -1,14 +0,0 @@
-do:
-pushWord 18
-pushWordVar 321
-eq
-jumpTrue postContinue
-jump while
-postContinue:
-wordVarInc 123
-while:
-pushWord 42
-pushWordVar 123
-eq
-jumpTrue do
-stopObjectCodeA

BIN=BIN
src/installer/decompiler/test/continue-do-while2.dmp


+ 0 - 15
src/installer/decompiler/test/continue-do-while2.txt

@@ -1,15 +0,0 @@
-do:
-wordVarInc 321
-pushWord 18
-pushWordVar 321
-eq
-jumpTrue postContinue
-jump while
-postContinue:
-wordVarInc 123
-while:
-pushWord 42
-pushWordVar 123
-eq
-jumpTrue do
-stopObjectCodeA

BIN=BIN
src/installer/decompiler/test/continue-while.dmp


+ 0 - 15
src/installer/decompiler/test/continue-while.txt

@@ -1,15 +0,0 @@
-while:
-pushWord 42
-pushWordVar 123
-eq
-jumpTrue postWhile
-pushWord 18
-pushWordVar 321
-eq
-jumpTrue postContinue
-jump while
-postContinue:
-wordVarInc 123
-jump while
-postWhile:
-stopObjectCodeA

+ 0 - 147
src/installer/decompiler/test/disassembler/pasc.cpp

@@ -1,147 +0,0 @@
-/* ScummVM Tools
- *
- * ScummVM Tools is the legal property of its developers, whose
- * names are too numerous to list here. Please refer to the
- * COPYRIGHT file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include "pasc.h"
-
-PasCDisassembler::PasCDisassembler(InstVec &insts) : ::SimpleDisassembler(insts) {
-}
-
-void PasCDisassembler::doDisassemble(){
-	START_OPCODES;
-		//Basic machine operations
-		OPCODE(0x00, "PUSH", PasCFakeInstruction, 0, "i");
-		OPCODE(0x01, "POP",	PasCFakeInstruction, 0, "i");
-		OPCODE(0x02, "CALL", PasCFakeInstruction, 0, "d");
-		OPCODE(0x03, "RETURN", PasCFakeInstruction, 0, "");
-		OPCODE(0x04, "HALT", PasCFakeInstruction, 0, "");
-
-		//Jumps
-		OPCODE(0x10, "JUMP", PasCFakeInstruction, 0, "a");
-		OPCODE(0x11, "JEQ", PasCFakeInstruction, 0, "a");
-		OPCODE(0x12, "JAEQ", PasCFakeInstruction, 0, "a");
-		OPCODE(0x13, "JGT", PasCFakeInstruction, 0, "a");
-		OPCODE(0x14, "JLT", PasCFakeInstruction, 0, "a");
-		OPCODE(0x15, "JALT", PasCFakeInstruction, 0, "a");
-		OPCODE(0x16, "JAGT", PasCFakeInstruction, 0, "a");
-
-		//Boolean operations
-		OPCODE(0x20, "OR", PasCFakeInstruction, -1, "");
-		OPCODE(0x21, "AND", PasCFakeInstruction, -1, "");
-		OPCODE(0x22, "XOR", PasCFakeInstruction, -1, "");
-		OPCODE(0x23, "NOT", PasCFakeInstruction, -1, "");
-
-		//Padding instructions (smaller integer -> larger integer)
-		OPCODE(0x30, "SPAD", PasCFakeInstruction, 0, "B");
-		OPCODE(0x31, "UPAD", PasCFakeInstruction, 0, "B");
-
-		//32-bit operations
-		OPCODE(0x80, "IADD", PasCFakeInstruction, -4, "");
-		OPCODE(0x81, "ISUB", PasCFakeInstruction, -4, "");
-		OPCODE(0x82, "IMULT", PasCFakeInstruction, -4, "");
-		OPCODE(0x83, "IDIV", PasCFakeInstruction, -4, "");
-		OPCODE(0x84, "IMOD", PasCFakeInstruction, -4, "");
-		OPCODE(0x85, "ISHL", PasCFakeInstruction, -4, "");
-		OPCODE(0x86, "ISHR", PasCFakeInstruction, -4, "");
-		OPCODE(0x87, "ISTOREA [SB]", PasCFakeInstruction, -4, "i");
-		OPCODE(0x88, "ISTOREL [SB]", PasCFakeInstruction, 0, "ii");
-		OPCODE(0x89, "ILOADA [SB]", PasCFakeInstruction, 4, "i");
-		OPCODE(0x8A, "ISTOREA", PasCFakeInstruction, -4, "d");
-		OPCODE(0x8B, "ISTOREL", PasCFakeInstruction, 0, "di");
-		OPCODE(0x8C, "ILOADA", PasCFakeInstruction, 4, "d");
-		OPCODE(0x8D, "ILOADL", PasCFakeInstruction, 0, "i");
-		OPCODE(0x8E, "ICMP", PasCFakeInstruction, -8, "");
-		OPCODE(0x8F, "UICMP", PasCFakeInstruction, -8, "");
-		OPCODE(0x90, "IDUP", PasCFakeInstruction, 4, "");
-		OPCODE(0x91, "IPRINT", PasCFakeInstruction, -4, "");
-		OPCODE(0x92, "UIPRINT", PasCFakeInstruction, -4, "");
-		OPCODE(0x96, "ISTORE [SB]", PasCFakeInstruction, -8, "");
-		OPCODE(0x97, "ISTORE", PasCFakeInstruction, -8, "");
-		OPCODE(0x98, "ILOAD [SB]", PasCFakeInstruction, -8, "");
-		OPCODE(0x99, "ILOAD", PasCFakeInstruction, -8, "");
-
-		//16-bit operations
-		OPCODE(0xA0, "SADD", PasCFakeInstruction, -2, "");
-		OPCODE(0xA1, "SSUB", PasCFakeInstruction, -2, "");
-		OPCODE(0xA2, "SMULT", PasCFakeInstruction, -2, "");
-		OPCODE(0xA3, "SDIV", PasCFakeInstruction, -2, "");
-		OPCODE(0xA4, "SMOD", PasCFakeInstruction, -2, "");
-		OPCODE(0xA5, "SSHL", PasCFakeInstruction, -2, "");
-		OPCODE(0xA6, "SSHR", PasCFakeInstruction, -2, "");
-		OPCODE(0xA7, "SSTOREA [SB]", PasCFakeInstruction, -2, "i");
-		OPCODE(0xA8, "SSTOREL [SB]", PasCFakeInstruction, 0, "is");
-		OPCODE(0xA9, "SLOADA [SB]", PasCFakeInstruction, 2, "i");
-		OPCODE(0xAA, "SSTOREA", PasCFakeInstruction, -2, "d");
-		OPCODE(0xAB, "SSTOREL", PasCFakeInstruction, 0, "ds");
-		OPCODE(0xAC, "SLOADA", PasCFakeInstruction, 2, "d");
-		OPCODE(0xAD, "SLOADL", PasCFakeInstruction, 0, "s");
-		OPCODE(0xAE, "SCMP", PasCFakeInstruction, -4, "");
-		OPCODE(0xAF, "USCMP", PasCFakeInstruction, -4, "");
-		OPCODE(0xB0, "SDUP", PasCFakeInstruction, 2, "");
-		OPCODE(0xB1, "SPRINT", PasCFakeInstruction, -2, "");
-		OPCODE(0xB2, "USPRINT", PasCFakeInstruction, -2, "");
-		OPCODE(0xB6, "SSTORE [SB]", PasCFakeInstruction, -6, "");
-		OPCODE(0xB7, "SSTORE", PasCFakeInstruction, -6, "");
-		OPCODE(0xB8, "SLOAD [SB]", PasCFakeInstruction, -6, "");
-		OPCODE(0xB9, "SLOAD", PasCFakeInstruction, -6, "");
-
-		//8-bit operations
-		OPCODE(0xC0, "BADD", PasCFakeInstruction, -1, "");
-		OPCODE(0xC1, "BSUB", PasCFakeInstruction, -1, "");
-		OPCODE(0xC2, "BMULT", PasCFakeInstruction, -1, "");
-		OPCODE(0xC3, "BDIV", PasCFakeInstruction, -1, "");
-		OPCODE(0xC4, "BMOD", PasCFakeInstruction, -1, "");
-		OPCODE(0xC5, "BSHL", PasCFakeInstruction, -1, "");
-		OPCODE(0xC6, "BSHR", PasCFakeInstruction, -1, "");
-		OPCODE(0xC7, "BSTOREA [SB]", PasCFakeInstruction, -1, "i");
-		OPCODE(0xC8, "BSTOREL [SB]", PasCFakeInstruction, 0, "iB");
-		OPCODE(0xC9, "BLOADA [SB]", PasCFakeInstruction, 1, "i");
-		OPCODE(0xCA, "BSTOREA", PasCFakeInstruction, -1, "d");
-		OPCODE(0xCB, "BSTOREL", PasCFakeInstruction, 0, "dB");
-		OPCODE(0xCC, "BLOADA", PasCFakeInstruction, 1, "d");
-		OPCODE(0xCD, "BLOADL", PasCFakeInstruction, 0, "B");
-		OPCODE(0xCE, "SBCMP", PasCFakeInstruction, -2, "");
-		OPCODE(0xCF, "BCMP", PasCFakeInstruction, -2, "");
-		OPCODE(0xD0, "BDUP", PasCFakeInstruction, 1, "");
-		OPCODE(0xD1, "SBPRINT", PasCFakeInstruction, -1, "");
-		OPCODE(0xD2, "BPRINT", PasCFakeInstruction, -1, "");
-		OPCODE(0xD3, "CPRINT", PasCFakeInstruction, -1, "");
-		OPCODE(0xD6, "BSTORE [SB]", PasCFakeInstruction, -5, "");
-		OPCODE(0xD7, "BSTORE", PasCFakeInstruction, -5, "");
-		OPCODE(0xD8, "BLOAD [SB]", PasCFakeInstruction, -5, "");
-		OPCODE(0xD9, "BLOAD", PasCFakeInstruction, -5, "");
-	END_OPCODES;
-}
-
-ValuePtr PasCDisassembler::readParameter(InstPtr inst, std::string type)
-{
-    ValuePtr retval = NULL;
-    if (type == "a")
-    {
-        retval = new AddressValue(stream_->ReadU32());
-        address_ += 4;
-    }
-    else
-    {
-        // Defer handling to parent implementation
-        retval = SimpleDisassembler::readParameter(inst, type);
-    }
-    return retval;
-}

+ 0 - 39
src/installer/decompiler/test/disassembler/pasc.h

@@ -1,39 +0,0 @@
-/* ScummVM Tools
- *
- * ScummVM Tools is the legal property of its developers, whose
- * names are too numerous to list here. Please refer to the
- * COPYRIGHT file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#ifndef DEC_TEST_DISASM_PASC_H
-#define DEC_TEST_DISASM_PASC_H
-
-#include "decompiler/simple_disassembler.h"
-
-class PasCDisassembler : public SimpleDisassembler {
-public:
-	PasCDisassembler(InstVec &insts);
-	virtual void doDisassemble() override;
-    virtual ValuePtr readParameter(InstPtr inst, std::string type) override;
-};
-
-class PasCFakeInstruction : public Instruction {
-public:
-    virtual void ProcessInst(Function&, ValueStack&, Engine*, CodeGenerator*) override {}
-};
-
-#endif

+ 0 - 33
src/installer/decompiler/test/disassembler/subopcode.cpp

@@ -1,33 +0,0 @@
-/* ScummVM Tools
- *
- * ScummVM Tools is the legal property of its developers, whose
- * names are too numerous to list here. Please refer to the
- * COPYRIGHT file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#include "subopcode.h"
-
-SubOpcodeDisassembler::SubOpcodeDisassembler(InstVec &insts) : ::SimpleDisassembler(insts) {
-}
-
-void SubOpcodeDisassembler::doDisassemble() {
-	START_OPCODES;
-		START_SUBOPCODE(0xFF)
-			OPCODE(0xFF, "FOO", SubOpcodeFakeInstruction, 0, "");
-		END_SUBOPCODE
-	END_OPCODES;
-}

+ 0 - 38
src/installer/decompiler/test/disassembler/subopcode.h

@@ -1,38 +0,0 @@
-/* ScummVM Tools
- *
- * ScummVM Tools is the legal property of its developers, whose
- * names are too numerous to list here. Please refer to the
- * COPYRIGHT file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-#ifndef DEC_TEST_DISASM_SUBOPCODE_H
-#define DEC_TEST_DISASM_SUBOPCODE_H
-
-#include "decompiler/simple_disassembler.h"
-
-class SubOpcodeDisassembler : public SimpleDisassembler {
-public:
-	SubOpcodeDisassembler(InstVec &insts);
-	void doDisassemble() override;
-};
-
-class SubOpcodeFakeInstruction : public Instruction {
-public:
-    virtual void ProcessInst(Function&, ValueStack&, Engine*, CodeGenerator*) override {}
-};
-
-#endif

+ 0 - 227
src/installer/decompiler/test/disassembler_test.cpp

@@ -1,227 +0,0 @@
-/* ScummVM Tools
- *
- * ScummVM Tools is the legal property of its developers, whose
- * names are too numerous to list here. Please refer to the
- * COPYRIGHT file distributed with this source distribution.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-
-#include "disassembler/pasc.h"
-#include "disassembler/subopcode.h"
-#include "decompiler/scummv6/disassembler.h"
-#include <gmock/gmock.h>
-
-
-TEST(Disassembler, testDisassembly) {
-    try {
-        InstVec insts;
-        PasCDisassembler p(insts);
-        p.open("decompiler/test/hanoi20.pasb");
-        p.disassemble();
-        ASSERT_EQ(insts[0]->_address, 0);
-        ASSERT_EQ(insts[0]->_opcode, 0x00);
-        ASSERT_EQ(insts[0]->_name, "PUSH");
-        ASSERT_EQ(insts[0]->_stackChange, 0);
-        ASSERT_TRUE(insts[0]->_params[0]->isInteger());
-        ASSERT_EQ(insts[0]->_params[0]->getSigned(), 0x60);
-    }
-    catch (UnknownOpcodeException &uoe) {
-        printf("Exception message: %s\n", uoe.what());
-        ASSERT_TRUE(false);
-    }
-    catch (std::exception &ex) {
-        printf("Exception message: %s\n", ex.what());
-        ASSERT_TRUE(false);
-    }
-}
-
-TEST(Disassembler, testSubOpcodeDisassembly) {
-    InstVec insts;
-    SubOpcodeDisassembler s(insts);
-    s.open("decompiler/test/subopcode_test.bin");
-    s.disassemble();
-    ASSERT_TRUE(insts[0]->_name == "FOO");
-    ASSERT_TRUE(insts[0]->_opcode == 0xFFFF);
-}
-
-TEST(Disassembler, testUnknownOpcodeException) {
-    try {
-        InstVec insts;
-        SubOpcodeDisassembler s(insts);
-        s.open("decompiler/test/unknownopcode_test.bin");
-        s.disassemble();
-        ASSERT_TRUE(false);
-    }
-    catch (UnknownOpcodeException) {
-        ASSERT_TRUE(true);
-    }
-}
-
-// This test requires script-15.dmp from Sam & Max: Hit The Road.
-// 1ab08298c9c8fb4c77953756989c7449 *script-15.dmp
-// Disabled as mentioned file is copyrighted
-TEST(Disassembler, DISABLED_testScummv6DisassemblerScript15) {
-    InstVec insts;
-    Scumm::v6::Scummv6Disassembler s(insts);
-    s.open("decompiler/test/script-15.dmp");
-    s.disassemble();
-    ASSERT_TRUE(insts.size() == 11);
-    ASSERT_TRUE(insts[0]->_address == 0);
-    ASSERT_TRUE(insts[0]->_opcode == 0x03);
-    ASSERT_TRUE(insts[0]->_name == "pushWordVar");
-    ASSERT_TRUE(insts[0]->_params[0]->getUnsigned() == 16384);
-    ASSERT_TRUE(insts[1]->_address == 3);
-    ASSERT_TRUE(insts[1]->_opcode == 0x43);
-    ASSERT_TRUE(insts[1]->_name == "writeWordVar");
-    ASSERT_TRUE(insts[1]->_params[0]->getUnsigned() == 197);
-    ASSERT_TRUE(insts[2]->_address == 6);
-    ASSERT_TRUE(insts[2]->_opcode == 0x01);
-    ASSERT_TRUE(insts[2]->_name == "pushWord");
-    ASSERT_TRUE(insts[2]->_params[0]->getSigned() == 0);
-    ASSERT_TRUE(insts[3]->_address == 9);
-    ASSERT_TRUE(insts[3]->_opcode == 0x01);
-    ASSERT_TRUE(insts[3]->_name == "pushWord");
-    ASSERT_TRUE(insts[3]->_params[0]->getSigned() == 11);
-    ASSERT_TRUE(insts[4]->_address == 12);
-    ASSERT_TRUE(insts[4]->_opcode == 0x01);
-    ASSERT_TRUE(insts[4]->_name == "pushWord");
-    ASSERT_TRUE(insts[4]->_params[0]->getSigned() == 0);
-    ASSERT_TRUE(insts[5]->_address == 15);
-    ASSERT_TRUE(insts[5]->_opcode == 0x5E);
-    ASSERT_TRUE(insts[5]->_name == "startScript");
-    ASSERT_TRUE(insts[6]->_address == 16);
-    ASSERT_TRUE(insts[6]->_opcode == 0x01);
-    ASSERT_TRUE(insts[6]->_name == "pushWord");
-    ASSERT_TRUE(insts[6]->_params[0]->getSigned() == 0);
-    ASSERT_TRUE(insts[7]->_address == 19);
-    ASSERT_TRUE(insts[7]->_opcode == 0x01);
-    ASSERT_TRUE(insts[7]->_name == "pushWord");
-    ASSERT_TRUE(insts[7]->_params[0]->getSigned() == 14);
-    ASSERT_TRUE(insts[8]->_address == 22);
-    ASSERT_TRUE(insts[8]->_opcode == 0x01);
-    ASSERT_TRUE(insts[8]->_name == "pushWord");
-    ASSERT_TRUE(insts[8]->_params[0]->getSigned() == 0);
-    ASSERT_TRUE(insts[9]->_address == 25);
-    ASSERT_TRUE(insts[9]->_opcode == 0x5E);
-    ASSERT_TRUE(insts[9]->_name == "startScript");
-    ASSERT_TRUE(insts[10]->_address == 26);
-    ASSERT_TRUE(insts[10]->_opcode == 0x66);
-    ASSERT_TRUE(insts[10]->_name == "stopObjectCodeB");
-}
-
-// This test requires script-31.dmp from Sam & Max: Hit The Road.
-// f75f7ce110f378735d449f8eeb4a68e5 *script-31.dmp
-// Disabled as mentioned file is copyrighted
-TEST(Disassembler, DISABLED_testScummv6DisassemblerScript31) {
-    InstVec insts;
-    Scumm::v6::Scummv6Disassembler s(insts);
-    s.open("decompiler/test/script-31.dmp");
-    s.disassemble();
-    ASSERT_TRUE(insts.size() == 5);
-    ASSERT_TRUE(insts[0]->_address == 0);
-    ASSERT_TRUE(insts[0]->_opcode == 0x01);
-    ASSERT_TRUE(insts[0]->_name == "pushWord");
-    ASSERT_TRUE(insts[0]->_params[0]->getSigned() == 0);
-    ASSERT_TRUE(insts[1]->_address == 3);
-    ASSERT_TRUE(insts[1]->_opcode == 0x43);
-    ASSERT_TRUE(insts[1]->_name == "writeWordVar");
-    ASSERT_TRUE(insts[1]->_params[0]->getUnsigned() == 180);
-    ASSERT_TRUE(insts[2]->_address == 6);
-    ASSERT_TRUE(insts[2]->_opcode == 0x01);
-    ASSERT_TRUE(insts[2]->_name == "pushWord");
-    ASSERT_TRUE(insts[2]->_params[0]->getSigned() == 0);
-    ASSERT_TRUE(insts[3]->_address == 9);
-    ASSERT_TRUE(insts[3]->_opcode == 0x43);
-    ASSERT_TRUE(insts[3]->_name == "writeWordVar");
-    ASSERT_TRUE(insts[3]->_params[0]->getUnsigned() == 181);
-    ASSERT_TRUE(insts[4]->_address == 12);
-    ASSERT_TRUE(insts[4]->_opcode == 0x66);
-    ASSERT_TRUE(insts[4]->_name == "stopObjectCodeB");
-}
-
-// This test requires script-33.dmp from Sam & Max: Hit The Road.
-// 9f09418bf34abbdec0ec54f388d8dca4 *script-33.dmp
-// Disabled as mentioned file is copyrighted
-TEST(Disassembler, DISABLED_testScummv6DisassemblerScript33) {
-    InstVec insts;
-    Scumm::v6::Scummv6Disassembler s(insts);
-    s.open("decompiler/test/script-33.dmp");
-    s.disassemble();
-    ASSERT_TRUE(insts.size() == 10);
-    ASSERT_TRUE(insts[0]->_address == 0);
-    ASSERT_TRUE(insts[0]->_opcode == 0x01);
-    ASSERT_TRUE(insts[0]->_name == "pushWord");
-    ASSERT_TRUE(insts[0]->_params[0]->getSigned() == 0);
-    ASSERT_TRUE(insts[1]->_address == 3);
-    ASSERT_TRUE(insts[1]->_opcode == 0x43);
-    ASSERT_TRUE(insts[1]->_name == "writeWordVar");
-    ASSERT_TRUE(insts[1]->_params[0]->getUnsigned() == 71);
-    ASSERT_TRUE(insts[2]->_address == 6);
-    ASSERT_TRUE(insts[2]->_opcode == 0x03);
-    ASSERT_TRUE(insts[2]->_name == "pushWordVar");
-    ASSERT_TRUE(insts[2]->_params[0]->getUnsigned() == 177);
-    ASSERT_TRUE(insts[3]->_address == 9);
-    ASSERT_TRUE(insts[3]->_opcode == 0x43);
-    ASSERT_TRUE(insts[3]->_name == "writeWordVar");
-    ASSERT_TRUE(insts[3]->_params[0]->getUnsigned() == 173);
-    ASSERT_TRUE(insts[4]->_address == 12);
-    ASSERT_TRUE(insts[4]->_opcode == 0x01);
-    ASSERT_TRUE(insts[4]->_name == "pushWord");
-    ASSERT_TRUE(insts[4]->_params[0]->getSigned() == 874);
-    ASSERT_TRUE(insts[5]->_address == 15);
-    ASSERT_TRUE(insts[5]->_opcode == 0x43);
-    ASSERT_TRUE(insts[5]->_name == "writeWordVar");
-    ASSERT_TRUE(insts[5]->_params[0]->getUnsigned() == 177);
-    ASSERT_TRUE(insts[6]->_address == 18);
-    ASSERT_TRUE(insts[6]->_opcode == 0x03);
-    ASSERT_TRUE(insts[6]->_name == "pushWordVar");
-    ASSERT_TRUE(insts[6]->_params[0]->getUnsigned() == 177);
-    ASSERT_TRUE(insts[7]->_address == 21);
-    ASSERT_TRUE(insts[7]->_opcode == 0x01);
-    ASSERT_TRUE(insts[7]->_name == "pushWord");
-    ASSERT_TRUE(insts[7]->_params[0]->getSigned() == 93);
-    ASSERT_TRUE(insts[8]->_address == 24);
-    ASSERT_TRUE(insts[8]->_opcode == 0x6B99);
-    ASSERT_TRUE(insts[8]->_name == "cursorCommand.setCursorImg");
-    ASSERT_TRUE(insts[9]->_address == 26);
-    ASSERT_TRUE(insts[9]->_opcode == 0x66);
-    ASSERT_TRUE(insts[9]->_name == "stopObjectCodeB");
-}
-
-// This test requires room-9-202.dmp from Sam & Max: Hit The Road.
-// f010dc659264674a2b6da298acd0b88b *room-9-202.dmp
-TEST(Disassembler, DISABLED_testScummv6StackChangeFixRoom9202) {
-    InstVec insts;
-    Scumm::v6::Scummv6Disassembler s(insts);
-    s.open("decompiler/test/room-9-202.dmp");
-    s.disassemble();
-    InstIterator it = insts.end();
-    it -= 8;
-    ASSERT_TRUE((*it)->_stackChange == -3);
-}
-
-// This test requires script-30.dmp from Sam & Max: Hit The Road.
-// 6e48faca13e1f6df9341567608962744 *script-30.dmp
-TEST(Disassembler, DISABLED_testScummv6StackChangeFixScript30) {
-    InstVec insts;
-    Scumm::v6::Scummv6Disassembler s(insts);
-    s.open("decompiler/test/script-30.dmp");
-    s.disassemble();
-    InstIterator it = insts.end();
-    it -= 3;
-    ASSERT_TRUE((*it)->_stackChange == -6);
-}

BIN=BIN
src/installer/decompiler/test/do-while-in-while.dmp


+ 0 - 20
src/installer/decompiler/test/do-while-in-while.txt

@@ -1,20 +0,0 @@
-while (var123 != 18) {
-	do {
-		var123++
-	} while (var321 != 42)
-}
-
-while:
-pushWord 18
-pushWordVar 123
-eq
-jumpTrue postWhile
-do:
-wordVarInc 123
-pushWord 42
-pushWordVar 321
-eq
-jumpTrue do
-jump while
-postWhile:
-stopObjectCodeA

BIN=BIN
src/installer/decompiler/test/do-while.dmp


+ 0 - 7
src/installer/decompiler/test/do-while.txt

@@ -1,7 +0,0 @@
-do:
-wordVarInc 123
-pushWord 42
-pushWordVar 123
-eq
-jumpTrue do
-stopObjectCodeA

BIN=BIN
src/installer/decompiler/test/ff7.dat


BIN=BIN
src/installer/decompiler/test/ff7_all_opcodes.dat


BIN=BIN
src/installer/decompiler/test/ff7_all_opcodes_OLD.dat


Algúns arquivos non se mostraron porque demasiados arquivos cambiaron neste cambio