FieldDataInstaller.cpp 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  1. /*
  2. * Copyright (C) 2022 The V-Gears Team
  3. *
  4. * This file is part of V-Gears
  5. *
  6. * V-Gears is free software: you can redistribute it and/or modify it under
  7. * terms of the GNU General Public License as published by the Free Software
  8. * Foundation, version 3.0 (GPLv3) of the License.
  9. *
  10. * V-Gears is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. */
  15. #include <cmath>
  16. #include <set>
  17. #include <string>
  18. #include <fstream>
  19. #include <algorithm>
  20. #include <boost/filesystem.hpp>
  21. #include <QtCore/QDir>
  22. #include "DiskImage.h"
  23. #include "FieldDataInstaller.h"
  24. #include "ModelMaterials.h"
  25. #include "TexFile.h"
  26. #include "common/File.h"
  27. #include "data/VGearsMapListFile.h"
  28. #include "data/VGearsLZSFLevelFileManager.h"
  29. #include "data/VGearsHRCFileManager.h"
  30. #include "data/VGearsLGPArchive.h"
  31. #include "data/VGearsAFileManager.h"
  32. float FieldDataInstaller::LINE_SCALE_FACTOR(0.0078124970964f);
  33. std::string FieldDataInstaller::FIELD_MODELS_DIR("models/fields");
  34. std::string FieldDataInstaller::FIELD_MAPS_DIR("fields");
  35. int FieldDataInstaller::INACTIVE_GATEWAY_ID(32767);
  36. const std::vector<int> FieldDataInstaller::TEMPORARY_BANKS{5};
  37. std::string FieldDataInstaller::FieldScriptHeader(const int field_id){
  38. std::string header = "EntityContainer = {}\n\n";
  39. if (field_id >= 0){
  40. // LSTMP reads the ID of the field the player comes from. The field being left is the
  41. // previous one, unless the field was just reloaded (after a battle, for example).
  42. header += "-- The IDs of this field and of the previous one, for LSTMP.\n"
  43. "if Data.FieldId ~= " + std::to_string(field_id) + " then\n"
  44. " Data.PreviousFieldId = Data.FieldId or 0\n"
  45. " Data.FieldId = " + std::to_string(field_id) + "\n"
  46. "end\n\n";
  47. }
  48. for (const int bank : TEMPORARY_BANKS){
  49. header += "-- Temporary variables start at zero in every field.\n"
  50. "for address = 0, Banks.SIZE do\n"
  51. " Banks[" + std::to_string(bank) + "][address] = 0\n"
  52. "end\n\n";
  53. }
  54. return header;
  55. }
  56. std::string FieldDataInstaller::CreateGateWayScript(
  57. const std::string& gateway_entity_name, const std::string& target_map_name,
  58. const std::string& source_spawn_point_name
  59. ){
  60. return
  61. "\nEntityContainer[ \"" + gateway_entity_name + "\" ] = {\n\n"
  62. " on_start = function(self)\n"
  63. " return 0\n"
  64. " end,\n\n"
  65. " on_approach = function(self, entity)\n"
  66. " return 0\n"
  67. " end,\n\n"
  68. " on_cross = function(self, entity)\n"
  69. " return 0\n"
  70. " end,\n\n"
  71. " on_near = function(self, entity)\n"
  72. " if entity ~= nil then\n"
  73. " if not Data.DisableGateways then\n"
  74. " load_field_map_request(\"" + target_map_name + "\", \"" + source_spawn_point_name + "\")\n"
  75. " end\n"
  76. " end\n"
  77. " return 0\n"
  78. " end,\n\n"
  79. " on_leave = function(self, entity)\n"
  80. " return 0\n"
  81. " end,\n"
  82. "}\n\n";
  83. }
  84. namespace{
  85. /**
  86. * Checks if a background trigger is in use. Unused ones are all zeroes.
  87. */
  88. bool IsBackgroundTriggerUsed(const VGears::TriggersFile::Trigger& t){
  89. for (const auto& v : t.trigger_line){
  90. if (v.x != 0 || v.y != 0 || v.z != 0) return true;
  91. }
  92. return false;
  93. }
  94. /**
  95. * Creates the script of the entity of a background trigger.
  96. *
  97. * Behaviors: 0 on, 1 off, 2 on and off when away, 3 off and on when away, 4 and 5 the same as
  98. * 2 and 3 (the original only reverts when the player leaves by the plus side of the line; here
  99. * it is when the player leaves the line on any side).
  100. */
  101. std::string CreateBackgroundTriggerScript(
  102. const std::string& name, const VGears::TriggersFile::Trigger& t
  103. ){
  104. const std::string area = std::to_string(t.background_parameter);
  105. const std::string state = std::to_string(t.background_state);
  106. const std::string on = "background2d:area_on(" + area + ", " + state + ")";
  107. const std::string off = "background2d:area_off(" + area + ", " + state + ")";
  108. std::string enter, leave;
  109. switch (t.behavior){
  110. case 0: enter = on; break;
  111. case 1: enter = off; break;
  112. case 2: case 4: enter = on; leave = off; break;
  113. case 3: case 5: enter = off; leave = on; break;
  114. default: break;
  115. }
  116. return
  117. "\nEntityContainer[ \"" + name + "\" ] = {\n\n"
  118. " on_start = function(self)\n"
  119. " return 0\n"
  120. " end,\n\n"
  121. " on_approach = function(self, entity)\n"
  122. " if entity ~= nil then " + enter + " end\n"
  123. " return 0\n"
  124. " end,\n\n"
  125. " on_cross = function(self, entity)\n"
  126. " return 0\n"
  127. " end,\n\n"
  128. " on_near = function(self, entity)\n"
  129. " return 0\n"
  130. " end,\n\n"
  131. " on_leave = function(self, entity)\n"
  132. " if entity ~= nil then " + leave + " end\n"
  133. " return 0\n"
  134. " end,\n"
  135. "}\n\n";
  136. }
  137. }
  138. namespace{
  139. /**
  140. * Writes the data the engine needs to animate the palettes of a background.
  141. *
  142. * Format (little endian): "VGPL", u16 number of pages, u16 colors per page, the colors of the
  143. * pages as the u16 values of the original game (5 bits per channel and the 0x8000 flag), u32
  144. * number of tiles, and for each tile: u16 x, y, width, height in the image, u16 page, u8 first
  145. * color hidden, and one byte per pixel with the palette index.
  146. *
  147. * @return True if the file was written. It is not when no tile uses an animated palette.
  148. */
  149. bool WritePaletteFile(
  150. const std::string& path, const VGears::PaletteFilePtr& palette,
  151. const std::vector<VGears::BackgroundFile::PaletteTile>& tiles,
  152. const std::set<int>& pages, bool all_pages
  153. ){
  154. std::vector<const VGears::BackgroundFile::PaletteTile*> used;
  155. for (const auto& tile : tiles){
  156. if (all_pages || pages.count(tile.palette_page) > 0) used.push_back(&tile);
  157. }
  158. if (used.empty() || palette.isNull() || palette->GetPages().empty()) return false;
  159. std::ofstream file(path, std::ios::binary);
  160. if (!file.is_open()) return false;
  161. auto write16 = [&file](uint16_t v){
  162. const char bytes[2] = {static_cast<char>(v & 0xFF), static_cast<char>(v >> 8)};
  163. file.write(bytes, 2);
  164. };
  165. const auto& palette_pages = palette->GetPages();
  166. file.write("VGPL", 4);
  167. write16(static_cast<uint16_t>(palette_pages.size()));
  168. write16(static_cast<uint16_t>(palette_pages[0].size()));
  169. for (const auto& page : palette_pages){
  170. for (const auto& color : page){
  171. const int r = static_cast<int>(std::lround(color.r * 31.0f));
  172. const int g = static_cast<int>(std::lround(color.g * 31.0f));
  173. const int b = static_cast<int>(std::lround(color.b * 31.0f));
  174. write16(static_cast<uint16_t>(r | (g << 5) | (b << 10) | (color.a > 0.0f ? 0x8000 : 0)));
  175. }
  176. }
  177. const uint32_t count = static_cast<uint32_t>(used.size());
  178. write16(static_cast<uint16_t>(count & 0xFFFF));
  179. write16(static_cast<uint16_t>(count >> 16));
  180. for (const auto* tile : used){
  181. write16(tile->x);
  182. write16(tile->y);
  183. write16(tile->width);
  184. write16(tile->height);
  185. write16(tile->palette_page);
  186. file.put(tile->first_color_hidden ? 1 : 0);
  187. file.write(
  188. reinterpret_cast<const char*>(tile->indexes.data()),
  189. static_cast<std::streamsize>(tile->indexes.size())
  190. );
  191. }
  192. return true;
  193. }
  194. }
  195. size_t FieldDataInstaller::GetFieldId(
  196. const std::string& name, const std::vector<std::string>& field_id_to_name_lookup
  197. ){
  198. for (size_t i = 0; i < field_id_to_name_lookup.size(); i ++){
  199. if (field_id_to_name_lookup[i] == name) return i;
  200. }
  201. throw std::runtime_error("No Id found for field name");
  202. }
  203. bool FieldDataInstaller::IsAFieldFile(const Ogre::String& resource_name){
  204. return (
  205. !VGears::StringUtil::endsWith(resource_name, ".tex")
  206. && !VGears::StringUtil::endsWith(resource_name, ".tut")
  207. && !VGears::StringUtil::endsWith(resource_name, ".siz")
  208. && resource_name != "maplist"
  209. );
  210. }
  211. bool FieldDataInstaller::WillCrash(const Ogre::String& resource_name){
  212. if (
  213. resource_name == "bugin1a" // crashes in back ground image generation
  214. || resource_name == "fr_e" // Background image crash
  215. || resource_name == "las4_2" // Background image crash
  216. || resource_name == "las4_3" // Background image crash
  217. || resource_name == "lastmap" // Background image crash
  218. || resource_name == "md_e1" // Background image crash
  219. || resource_name == "trnad_3" // Background image crash
  220. || resource_name == "bonevil2" // stof
  221. || resource_name == "coloin1" // boost::bad_format_string: format-string is ill-formed
  222. || resource_name == "elmin4_2" // boost::bad_format_string: format-string is ill-formed
  223. ) return true;
  224. return false;
  225. }
  226. bool FieldDataInstaller::IsTestField(const Ogre::String& resource_name){
  227. if (
  228. resource_name == "startmap"
  229. || resource_name == "md1stin"
  230. || resource_name == "md1_1"
  231. || resource_name == "md1_2"
  232. || resource_name == "nrthmk"
  233. || resource_name == "nmkin_1"
  234. || resource_name == "elevtr1"
  235. || resource_name == "nmkin_2"
  236. || resource_name == "nmkin_3"
  237. || resource_name == "nmkin_4"
  238. || resource_name == "nmkin_5"
  239. || resource_name == "southmk1"
  240. || resource_name == "southmk2"
  241. || resource_name == "smkin_1"
  242. || resource_name == "smkin_2"
  243. || resource_name == "smkin_3"
  244. || resource_name == "smkin_4"
  245. || resource_name == "smkin_5"
  246. || resource_name == "md8_1"
  247. || resource_name == "md8_2"
  248. || resource_name == "md8_3"
  249. || resource_name == "md8_4"
  250. || resource_name == "md8brdg"
  251. || resource_name == "cargoin"
  252. || resource_name == "tin_1"
  253. || resource_name == "tin_2"
  254. || resource_name == "tin_3"
  255. || resource_name == "tin_4"
  256. || resource_name == "rootmap"
  257. || resource_name == "mds7st1"
  258. || resource_name == "mds7st2"
  259. || resource_name == "mds7st3"
  260. || resource_name == "mds7st32"
  261. || resource_name == "mds7_w1"
  262. || resource_name == "mds7_w2"
  263. || resource_name == "mds7_w3"
  264. || resource_name == "mds7"
  265. )return true;
  266. return false;
  267. }
  268. void FieldDataInstaller::CreateDir(const std::string& path){
  269. QString target = QString::fromStdString(data_dir_ + path);
  270. QDir dir(target);
  271. if (!dir.mkpath(".")) throw std::runtime_error("Failed to mkpath");
  272. }
  273. void FieldDataInstaller::CollectFieldScaleFactors(
  274. VGears::FLevelFilePtr& field, FieldScaleFactorMap& scale_factors,
  275. const std::vector<std::string>& field_id_to_name_lookup
  276. ){
  277. scale_factors[GetFieldId(field->getName(), field_id_to_name_lookup)]
  278. = FieldDecompiler::ScaleFactor(field->GetRawScript());
  279. }
  280. bool FieldDataInstaller::CollectSpawnPoints(
  281. VGears::FLevelFilePtr& field, const std::vector<std::string>& field_id_to_name_lookup,
  282. FieldSpawnPointsMap& spawn_points
  283. ){
  284. const size_t this_field_id = GetFieldId(field->getName(), field_id_to_name_lookup);
  285. // Decompile the script just so the MAPJUMPs can be collected. This is needed to construct the
  286. // full list of entries to each field.
  287. try{
  288. // Get the raw script bytes.
  289. FieldDecompiler::DecompiledScript decompiled;
  290. const std::vector<u8> raw_field_data = field->GetRawScript();
  291. // Decompile to LUA.
  292. FF7FieldScriptGatewayCollector formatter(
  293. field->getName(), field_id_to_name_lookup, spawn_points, this_field_id
  294. );
  295. decompiled = FieldDecompiler::Decompile(
  296. field->getName(), raw_field_data, formatter, "", "EntityContainer = {}\n\n"
  297. );
  298. }
  299. catch (const ::DecompilerException& ex){
  300. std::cerr << "[WARNING] CollectSpawnPoints: decompiler failed for " << field->getName()
  301. << ": " << ex.what() << std::endl;
  302. return false;
  303. }
  304. const VGears::TriggersFilePtr& triggers = field->GetTriggers();
  305. if (triggers.isNull()){
  306. std::cerr << "CollectSpawnPoints: missing trigger data for " << field->getName() << std::endl;
  307. return false;
  308. }
  309. const auto& gateways = triggers->GetGateways();
  310. for (size_t i = 0; i < gateways.size(); i ++){
  311. const VGears::TriggersFile::Gateway& gateway = gateways[i];
  312. if (gateway.destination_field_id != INACTIVE_GATEWAY_ID){
  313. auto it = spawn_points.find(gateway.destination_field_id);
  314. if (it != std::end(spawn_points)){
  315. // Add to the list of gateways that link to
  316. // destination_field_id.
  317. SpawnPointDb::Record rec;
  318. rec.field_id = this_field_id;
  319. rec.gateway = gateway;
  320. rec.gateway_index_or_map_jump_address = i;
  321. it->second.gateways_to_this_field.push_back(rec);
  322. }
  323. else{
  324. // Create a new record for destination_field_id.
  325. SpawnPointDb db;
  326. db.target_field_id = gateway.destination_field_id;
  327. SpawnPointDb::Record rec;
  328. rec.field_id = this_field_id;
  329. rec.gateway = gateway;
  330. rec.gateway_index_or_map_jump_address = i;
  331. db.gateways_to_this_field.push_back(rec);
  332. spawn_points.insert(std::make_pair(db.target_field_id, db));
  333. }
  334. }
  335. }
  336. return true;
  337. }
  338. FieldDataInstaller::FieldDataInstaller(
  339. const DiskImage& disk_image, const std::string output_dir,
  340. std::function<void(std::string)> log_output_line
  341. ):
  342. disk_image_(disk_image), output_dir_(output_dir), data_dir_(output_dir + "data/"),
  343. write_output_line_(log_output_line)
  344. {}
  345. FieldDataInstaller::~FieldDataInstaller(){}
  346. int FieldDataInstaller::CollectSpawnAndScaleFactorsInit(Ogre::ResourceGroupManager* res_mgr){
  347. // List what's in the LGP archive.
  348. //flevel_file_list_ = application_.ResMgr()->listResourceNames("FFVIIFields", "*");
  349. flevel_file_list_ = res_mgr->listResourceNames("FFVIIFields", "*");
  350. // Load the map list field.
  351. VGears::MapListFilePtr map_list = VGears::MapListFileManager::GetSingleton().load(
  352. "maplist", "FFVIIFields"
  353. ).staticCast<VGears::MapListFile>();
  354. map_list_ = map_list->GetMapList();
  355. return flevel_file_list_->size();
  356. }
  357. void FieldDataInstaller::CollectSpawnAndScaleFactors(int field_index){
  358. // On the first pass collate required field information.
  359. progress_step_num_elements_ = flevel_file_list_->size();
  360. if (field_index >= flevel_file_list_->size()){
  361. // TODO: Show invalid index.
  362. return;
  363. }
  364. auto resource_name = (*flevel_file_list_)[field_index];
  365. // Exclude things that are not fields.
  366. if (IsAFieldFile(resource_name) && !WillCrash(resource_name)){
  367. try{
  368. VGears::FLevelFilePtr field = VGears::LZSFLevelFileManager::GetSingleton()
  369. .load(resource_name, "FFVIIFields").staticCast<VGears::FLevelFile>();
  370. if (!CollectSpawnPoints(field, map_list_, spawn_points_)){
  371. failed_fields_.push_back(resource_name);
  372. return;
  373. }
  374. CollectFieldScaleFactors(field, scale_factors_, map_list_);
  375. }
  376. catch (const std::exception& exception){
  377. failed_fields_.push_back(resource_name);
  378. std::cerr << "[WARNING] CollectSpawnAndScaleFactors: skipped " << resource_name
  379. << " after error: " << exception.what() << std::endl;
  380. }
  381. }
  382. }
  383. void FieldDataInstaller::LoadInstalledFields(){
  384. converted_map_list_.clear();
  385. for (const std::string& name : map_list_){
  386. if (boost::filesystem::exists(data_dir_ + FIELD_MAPS_DIR + "/" + name + "/map.xml")){
  387. converted_map_list_.push_back(name);
  388. }
  389. }
  390. }
  391. void FieldDataInstaller::WriteWorldArrivals(){
  392. // The exits to the world map ("wm<N>") have no field to write the spawn points into, so the coordinates
  393. // that each exit gives (world units) are written for the world map scripts, by spawn point name.
  394. std::string output = "-- Generated by the installer: where each field exit puts the player in the world map.\n"
  395. "WorldArrivals = {\n";
  396. for (const auto& entry : spawn_points_){
  397. if (entry.first >= map_list_.size()) continue;
  398. const std::string& target = map_list_[entry.first];
  399. if (target.size() < 3 || target.compare(0, 2, "wm") != 0
  400. || target.find_first_not_of("0123456789", 2) != std::string::npos) continue;
  401. for (const SpawnPointDb::Record& record : entry.second.gateways_to_this_field){
  402. std::string name;
  403. if (record.from_script){
  404. name = map_list_.at(record.field_id) + "_" + record.entity_name + "_" + record.script_function_name
  405. + "_addr_" + std::to_string(record.gateway_index_or_map_jump_address);
  406. }
  407. else{
  408. name = "Spawn_" + map_list_.at(record.field_id) + "_"
  409. + std::to_string(record.gateway_index_or_map_jump_address);
  410. }
  411. output += " [\"" + name + "\"] = {x = " + std::to_string(record.gateway.destination.x)
  412. + ", y = " + std::to_string(record.gateway.destination.y)
  413. + ", dir = " + std::to_string(record.gateway.dir) + "},\n";
  414. }
  415. }
  416. output += "}\n";
  417. boost::filesystem::create_directories(data_dir_ + "scripts/worldmap");
  418. std::ofstream file(data_dir_ + "scripts/worldmap/world_arrivals.lua");
  419. file << output;
  420. }
  421. void FieldDataInstaller::Convert(int field_index){
  422. if (field_index == 0) WriteWorldArrivals();
  423. // Do the full conversion with the collated data.
  424. if (field_index >= flevel_file_list_->size()){
  425. // TODO: Show invalid index.
  426. return;
  427. }
  428. auto resource_name = (*flevel_file_list_)[field_index];
  429. // Exclude things that are not fields.
  430. if (IsAFieldFile(resource_name)){
  431. if (std::find(failed_fields_.begin(), failed_fields_.end(), resource_name)
  432. != failed_fields_.end()){
  433. std::cerr << "[ERROR] Skip field: " << resource_name
  434. << " because its scripts or scale factor could not be collected." << std::endl;
  435. }
  436. else if (!WillCrash(resource_name)){
  437. //write_output_line_("Converting field " + resource_name);
  438. CreateDir(FIELD_MAPS_DIR + "/" + resource_name);
  439. VGears::FLevelFilePtr field = VGears::LZSFLevelFileManager::GetSingleton()
  440. .load(resource_name, "FFVIIFields").staticCast<VGears::FLevelFile>();
  441. PcFieldToVGearsField(field);
  442. }
  443. else{
  444. std::cerr << "[ERROR] Skip field: " << resource_name
  445. << " due to a known crash or hang issue." << std::endl;
  446. }
  447. }
  448. }
  449. int FieldDataInstaller::WriteInit(){
  450. doc_ = std::make_unique<TiXmlDocument>();
  451. element_ = std::make_unique<TiXmlElement>("maps");
  452. return converted_map_list_.size();
  453. }
  454. void FieldDataInstaller::Write(int field_index){
  455. // TODO: Probably need to inject "empty" and "test" fields.
  456. if (field_index >= flevel_file_list_->size()){
  457. // TODO: Show invalid index.
  458. return;
  459. }
  460. auto map = converted_map_list_[field_index];
  461. //write_output_line_("Writing field " + FieldName(map));
  462. std::unique_ptr<TiXmlElement> xml_element(new TiXmlElement("map"));
  463. xml_element->SetAttribute("name", map);
  464. xml_element->SetAttribute("file_name", map + "/map.xml");
  465. element_->LinkEndChild(xml_element.release());
  466. }
  467. void FieldDataInstaller::WriteEnd(){
  468. doc_->LinkEndChild(element_.release());
  469. doc_->SaveFile(data_dir_ + "/fields/_fields.xml");
  470. }
  471. std::vector<std::string> FieldDataInstaller::ConvertModelsInit(){
  472. std::vector<std::string> models;
  473. // Open char_lgp as a lgp archive
  474. VGears::LGPArchive char_lgp(*disk_image_.filePath("data/field/char.lgp"), "LGP");
  475. char_lgp.open(*disk_image_.filePath("data/field/char.lgp"), true);
  476. char_lgp.load();
  477. // Also, open it as a file for reading
  478. File char_file(*disk_image_.filePath("data/field/char.lgp"));
  479. //Ogre::StringVectorPtr file_list = char_lgp.list(true, true);
  480. field_model_file_list_ = char_lgp.list(true, true);
  481. VGears::LGPArchive::FileList files = char_lgp.GetFiles();
  482. for (int i = 0; i < field_model_file_list_->size(); i ++){
  483. VGears::LGPArchive::FileEntry f = files.at(i);
  484. // Save the TEX File
  485. std::fstream out;
  486. out.open(output_dir_ + "temp/char/" + f.file_name, std::ios::out);
  487. char_file.SetOffset(f.data_offset);
  488. for (int j = 0; j < f.data_size; j ++) out << char_file.readU8();
  489. out.close();
  490. //field_model_file_list_->push_back(f.file_name);
  491. }
  492. // Ogre indexes a resource location when it is added, so files written afterwards are not found until the
  493. // location is registered again. On a clean install the folder was empty when it was first added.
  494. Ogre::ResourceGroupManager& res_mgr = Ogre::ResourceGroupManager::getSingleton();
  495. res_mgr.removeResourceLocation(output_dir_ + "temp/char/", "FFVII");
  496. res_mgr.addResourceLocation(output_dir_ + "temp/char/", "FileSystem", "FFVII", true, true);
  497. for (auto it = used_models_and_anims_.map.begin(); it != used_models_and_anims_.map.end(); it ++){
  498. models.push_back(it->first);
  499. }
  500. return models;
  501. }
  502. void FieldDataInstaller::ConvertModels(std::string model_name){
  503. auto model = used_models_and_anims_.map.find(model_name);
  504. try{
  505. Ogre::ResourcePtr hrc = VGears::HRCFileManager::GetSingleton().load(model->first, "FFVII");
  506. //Ogre::ResourcePtr hrc = VGears::HRCFile();
  507. Ogre::String base_name;
  508. VGears::StringUtil::splitBase(model->first, base_name);
  509. auto mesh_name = VGears::NameLookup::model(base_name) + ".mesh";
  510. Ogre::MeshPtr mesh(Ogre::MeshManager::getSingleton().load(mesh_name, "FFVII"));
  511. Ogre::SkeletonPtr skeleton(mesh->getSkeleton());
  512. const Ogre::AxisAlignedBox bind_bounds = mesh->getBounds();
  513. Ogre::AxisAlignedBox translation_bounds(Ogre::Vector3::ZERO, Ogre::Vector3::ZERO);
  514. for (auto& anim : model->second){
  515. VGears::AFileManager &afl_mgr(VGears::AFileManager::GetSingleton());
  516. VGears::AFilePtr a = afl_mgr.load(anim, "FFVII").staticCast<VGears::AFile>();
  517. // Convert the FF7 name to a more readable name set in the meta data.
  518. VGears::StringUtil::splitBase(anim, base_name);
  519. a->AddTo(skeleton, VGears::NameLookup::Animation(base_name), true);
  520. translation_bounds.merge(a->GetRootTranslationBounds(true));
  521. }
  522. if (bind_bounds.isFinite()){
  523. const Ogre::AxisAlignedBox animated_bounds(
  524. bind_bounds.getMinimum() + translation_bounds.getMinimum(),
  525. bind_bounds.getMaximum() + translation_bounds.getMaximum()
  526. );
  527. mesh->_setBounds(animated_bounds, false);
  528. mesh->_setBoundingSphereRadius(std::max(
  529. mesh->getBoundingSphereRadius(),
  530. animated_bounds.getCenter().length() + animated_bounds.getHalfSize().length()
  531. ));
  532. }
  533. ExportMesh(data_dir_ + FIELD_MODELS_DIR + "/", mesh);
  534. // Models can share a skeleton name with different bones. Drop the model (and its skeleton and mesh) so the
  535. // next one doesn't reuse them.
  536. VGears::HRCFileManager::GetSingleton().remove(model->first, "FFVII");
  537. }
  538. catch (const Ogre::Exception& ex){
  539. if (VGears::HRCFileManager::GetSingleton().resourceExists(model->first, "FFVII"))
  540. VGears::HRCFileManager::GetSingleton().remove(model->first, "FFVII");
  541. write_output_line_("[ERROR] Ogre exception converting model " + model->first + ": " + ex.what());
  542. std::cerr << "[ERROR] Ogre exception converting model " << model->first <<": " << ex.what() << std::endl;
  543. }
  544. catch (const std::exception& ex){
  545. if (VGears::HRCFileManager::GetSingleton().resourceExists(model->first, "FFVII"))
  546. VGears::HRCFileManager::GetSingleton().remove(model->first, "FFVII");
  547. write_output_line_("[ERROR] Exception converting model " + model->first + ": " + ex.what());
  548. std::cerr << "[ERROR] Exception converting model " << model->first << ": " << ex.what() << std::endl;
  549. }
  550. }
  551. void FieldDataInstaller::ExportMesh(const std::string outdir, const Ogre::MeshPtr &mesh){
  552. // TODO: Share function with pc model exporter
  553. VGears::String base_mesh_name;
  554. VGears::StringUtil::splitFull(mesh->getName(), base_mesh_name);
  555. MakeMaterialsUnique(mesh, base_mesh_name);
  556. Ogre::MeshSerializer mesh_serializer;
  557. Ogre::SkeletonPtr skeleton(mesh->getSkeleton());
  558. Ogre::SkeletonSerializer skeleton_serializer;
  559. skeleton_serializer.exportSkeleton(skeleton.getPointer(), outdir + base_mesh_name + ".skeleton");
  560. mesh->setSkeletonName(base_mesh_name + ".skeleton");
  561. mesh_serializer.exportMesh(mesh.getPointer(), outdir + mesh->getName());
  562. Ogre::Mesh::SubMeshIterator it(mesh->getSubMeshIterator());
  563. Ogre::MaterialSerializer mat_ser;
  564. size_t i(0);
  565. while (it.hasMoreElements()){
  566. Ogre::SubMesh *sub_mesh(it.getNext());
  567. Ogre::MaterialPtr mat(Ogre::MaterialManager::getSingleton().getByName(sub_mesh->getMaterialName()));
  568. if (mat != nullptr){
  569. for (size_t techs = 0; techs < mat->getNumTechniques(); techs ++){
  570. Ogre::Technique* tech = mat->getTechnique(techs);
  571. if (tech){
  572. for (size_t pass_num = 0; pass_num < tech->getNumPasses(); pass_num ++){
  573. Ogre::Pass* pass = tech->getPass(pass_num);
  574. if (pass){
  575. for (
  576. size_t texture_unit_num = 0;
  577. texture_unit_num < pass->getNumTextureUnitStates();
  578. texture_unit_num ++
  579. ){
  580. Ogre::TextureUnitState* unit = pass->getTextureUnitState(texture_unit_num);
  581. if (unit && unit->getTextureName().empty() == false){
  582. // Materials are shared by name across all model types, so this one may have
  583. // already been converted for a battle model (its texture is then a png in
  584. // another folder). There is nothing to convert in that case.
  585. if (!boost::filesystem::exists(output_dir_ + "temp/char/" + unit->getTextureName())){
  586. write_output_line_(
  587. "[WARNING] Texture " + unit->getTextureName() + " of model " + base_mesh_name
  588. + " not found; skipping it."
  589. );
  590. continue;
  591. }
  592. // Convert the texture from .tex to .png.
  593. TexFile tex(output_dir_ + "temp/char/" + unit->getTextureName());
  594. // Ensure the output material script references png files
  595. // rather than tex files.
  596. Ogre::String base_name;
  597. VGears::StringUtil::splitBase(unit->getTextureName(), base_name);
  598. unit->setTextureName(base_mesh_name + "_" + base_name + ".png");
  599. tex.SavePng(data_dir_ + FIELD_MODELS_DIR + "/" + base_name + ".png", 0);
  600. // Copy subtexture (xxxx.png) to model_xxxx.png
  601. // TODO: obtain the "data" folder
  602. // programatically.
  603. boost::filesystem::copy_file(
  604. data_dir_ + FIELD_MODELS_DIR + "/" + base_name + ".png",
  605. data_dir_ + FIELD_MODELS_DIR + "/"
  606. + base_mesh_name + "_" + base_name + ".png",
  607. boost::filesystem::copy_options::overwrite_existing
  608. );
  609. }
  610. }
  611. }
  612. }
  613. }
  614. }
  615. if (std::count(materials_.begin(), materials_.end(), sub_mesh->getMaterialName()) == 0){
  616. mat_ser.queueForExport(mat);
  617. materials_.push_back(sub_mesh->getMaterialName());
  618. }
  619. }
  620. ++ i;
  621. }
  622. mat_ser.exportQueued(outdir + base_mesh_name + VGears::EXT_MATERIAL);
  623. }
  624. float FieldDataInstaller::GetFieldScaleFactor(size_t field_id){
  625. auto it = scale_factors_.find(field_id);
  626. if (it == std::end(scale_factors_)) throw std::runtime_error("Scale factor not found for field id");
  627. return it->second;
  628. }
  629. std::vector<int> FieldDataInstaller::ExtractMusicTrackIds(VGears::FLevelFilePtr& field){
  630. // Search for the "AKAO" string in the raw field data.
  631. // The next byte is a track id.
  632. const std::vector<u8> raw = field->GetRawScript();
  633. std::vector<int> tracks;
  634. for (int i = 0; i < raw.size() - 5; i ++){
  635. if (raw[i] == 0x41){ // A
  636. if (raw[i + 1] == 0x4B){ // K
  637. if (raw[i + 2] == 0x41){ // A
  638. if (raw[i + 3] == 0x4f){ // O
  639. tracks.push_back(static_cast<int>(raw[i + 4]) - 2);
  640. }
  641. }
  642. }
  643. }
  644. }
  645. return tracks;
  646. }
  647. void FieldDataInstaller::PcFieldToVGearsField(VGears::FLevelFilePtr& field){
  648. // Generate triggers script to insert into main
  649. // decompiled FF7 field -> LUA script.
  650. std::string gateway_script_data;
  651. const VGears::TriggersFilePtr& triggers = field->GetTriggers();
  652. const auto& gateways = triggers->GetGateways();
  653. for (size_t i = 0; i < gateways.size(); i ++){
  654. const VGears::TriggersFile::Gateway& gateway = gateways[i];
  655. if (gateway.destination_field_id != INACTIVE_GATEWAY_ID){
  656. const std::string gateway_entity_name = "Gateway" + std::to_string(i);
  657. gateway_script_data += CreateGateWayScript(
  658. gateway_entity_name, map_list_.at(gateway.destination_field_id),
  659. "Spawn_" + field->getName() + "_" + std::to_string(i)
  660. );
  661. }
  662. }
  663. const auto& bg_triggers = triggers->GetBackgroundTriggers();
  664. for (size_t i = 0; i < bg_triggers.size(); i ++){
  665. if (IsBackgroundTriggerUsed(bg_triggers[i])){
  666. gateway_script_data += CreateBackgroundTriggerScript(
  667. "BgTrigger" + std::to_string(i), bg_triggers[i]
  668. );
  669. }
  670. }
  671. const VGears::ModelListFilePtr& models = field->GetModelList();
  672. FieldDecompiler::DecompiledScript decompiled;
  673. FF7FieldScriptFormatter formatter(field->getName(), models, map_list_, spawn_points_);
  674. try{
  675. // Get the raw script bytes.
  676. const std::vector<u8> raw_field_data = field->GetRawScript();
  677. // Decompile to LUA.
  678. decompiled = FieldDecompiler::Decompile(
  679. field->getName(), raw_field_data, formatter, gateway_script_data,
  680. FieldScriptHeader(static_cast<int>(GetFieldId(field->getName(), map_list_)))
  681. );
  682. std::ofstream script_file(data_dir_ + "/" + FIELD_MAPS_DIR + "/" + field->getName() + "/script.lua");
  683. if (script_file.is_open()){
  684. script_file << decompiled.luaScript;
  685. field_text_writer_.Begin(data_dir_ + "/" + FIELD_MAPS_DIR + "/" + field->getName() + "/text.xml");
  686. try{field_text_writer_.Write(raw_field_data, field->getName());}
  687. catch (const std::out_of_range& ex){
  688. write_output_line_("[ERROR] Failed to read texts from field " + field->getName() + ": " + ex.what());
  689. std::cerr << "[ERROR] Failed to read texts from field "
  690. << field->getName() << ": " << ex.what() << std::endl;
  691. }
  692. field_text_writer_.End();
  693. }
  694. else{
  695. write_output_line_("[ERROR] Failed to open script file from field " + field->getName() + " for writing.");
  696. std::cerr << "[ERROR] Failed to open script file from field "
  697. << field->getName() << "for writing." << std::endl;
  698. }
  699. }
  700. catch (const ::DecompilerException& ex){
  701. write_output_line_("[ERROR] Internal decompiler error in field " + field->getName() + ": " + ex.what());
  702. std::cerr << "[ERROR] Internal decompiler error in field "
  703. << field->getName() << ": " << ex.what() << std::endl;
  704. }
  705. // Write out the map file which links all the other files together for a given field.
  706. {
  707. TiXmlDocument doc;
  708. std::unique_ptr<TiXmlElement> element(new TiXmlElement("map"));
  709. // Script.
  710. std::unique_ptr<TiXmlElement> xml_script_element(new TiXmlElement("script"));
  711. xml_script_element->SetAttribute("file_name", field->getName() + "/script.lua");
  712. element->LinkEndChild(xml_script_element.release());
  713. // Background.
  714. std::unique_ptr<TiXmlElement> xml_background_2d(new TiXmlElement("background2d"));
  715. xml_background_2d->SetAttribute("file_name", field->getName() + "/bg.xml");
  716. element->LinkEndChild(xml_background_2d.release());
  717. // Texts.
  718. std::unique_ptr<TiXmlElement> xml_texts(new TiXmlElement("texts"));
  719. xml_texts->SetAttribute("file_name", field->getName() + "/text.xml");
  720. element->LinkEndChild(xml_texts.release());
  721. // Walkmesh.
  722. std::unique_ptr<TiXmlElement> xml_walkmesh(new TiXmlElement("walkmesh"));
  723. xml_walkmesh->SetAttribute("file_name", field->getName() + "/wm.xml");
  724. element->LinkEndChild(xml_walkmesh.release());
  725. // Forward direction (angle player moves when "up" is pressed)
  726. std::unique_ptr<TiXmlElement> xml_forward_direction(new TiXmlElement("movement_rotation"));
  727. xml_forward_direction->SetAttribute("degree", std::to_string(triggers->MovementRotation()));
  728. element->LinkEndChild(xml_forward_direction.release());
  729. // Random encounters. The section has two tables of 24 bytes: enabled (1 byte), rate
  730. // (1 byte), six standard and four special encounters (16 bits each, battle ID in the lower
  731. // 10 bits and probability, out of 64, in the upper 6), and 2 bytes of padding.
  732. {
  733. const std::vector<u8>& raw_encounter = field->GetRawEncounter();
  734. std::unique_ptr<TiXmlElement> xml_encounters(new TiXmlElement("encounters"));
  735. bool any_table = false;
  736. for (int table = 0; table < 2 && raw_encounter.size() >= static_cast<size_t>(24 * (table + 1)); table ++){
  737. const u8* data = raw_encounter.data() + 24 * table;
  738. if (data[0] == 0) continue;
  739. std::unique_ptr<TiXmlElement> xml_table(new TiXmlElement("table"));
  740. xml_table->SetAttribute("id", table + 1);
  741. xml_table->SetAttribute("rate", static_cast<int>(data[1]));
  742. for (int e = 0; e < 10; e ++){
  743. const unsigned int value = data[2 + 2 * e] | (data[3 + 2 * e] << 8);
  744. const int battle = value & 0x3FF;
  745. const int probability = value >> 10;
  746. if (probability == 0) continue;
  747. std::unique_ptr<TiXmlElement> xml_encounter(new TiXmlElement(e < 6 ? "battle" : "special"));
  748. xml_encounter->SetAttribute("id", battle);
  749. xml_encounter->SetAttribute("probability", probability);
  750. xml_table->LinkEndChild(xml_encounter.release());
  751. }
  752. xml_encounters->LinkEndChild(xml_table.release());
  753. any_table = true;
  754. }
  755. if (any_table) element->LinkEndChild(xml_encounters.release());
  756. }
  757. // Get this fields Id.
  758. const size_t this_field_id = GetFieldId(field->getName(), map_list_);
  759. // Use the ID to find the pre-computed list of gateways in all other fields that link to
  760. // this field.
  761. auto spawn_iterator = spawn_points_.find(this_field_id);
  762. Ogre::Vector3 first_entity_point = Ogre::Vector3::ZERO;
  763. // If none found it probably just means no other fields have doors to this one.
  764. if (spawn_iterator != std::end(spawn_points_)){
  765. const std::vector<SpawnPointDb::Record>& spawn_point_records
  766. = spawn_iterator->second.gateways_to_this_field;
  767. for (size_t i = 0; i < spawn_point_records.size(); i ++){
  768. const VGears::TriggersFile::Gateway& gateway = spawn_point_records[i].gateway;
  769. // Entity_point:
  770. std::unique_ptr<TiXmlElement> xml_entity_point(new TiXmlElement("entity_point"));
  771. if (spawn_point_records[i].from_script){
  772. // Spawn points from map jumps have a another algorithm.
  773. xml_entity_point->SetAttribute(
  774. "name",
  775. map_list_.at(
  776. spawn_point_records[i].field_id) + "_" + spawn_point_records[i].entity_name
  777. + "_" + spawn_point_records[i].script_function_name + "_addr_"
  778. + std::to_string(spawn_point_records[i].gateway_index_or_map_jump_address)
  779. );
  780. }
  781. else{
  782. // Must also include the gateway index for the case where 2
  783. // fields have more than one door linking to each other.
  784. xml_entity_point->SetAttribute(
  785. "name",
  786. "Spawn_" + map_list_.at(spawn_point_records[i].field_id) + "_"
  787. + std::to_string(spawn_point_records[i].gateway_index_or_map_jump_address)
  788. );
  789. }
  790. const float downscaler_next = 128.0f * GetFieldScaleFactor(gateway.destination_field_id);
  791. // Position Z is actually the target walkmesh triangle ID, so this is tiny bit more
  792. // complex. Now "get the Z value of the triangle with that ID". Note that ID
  793. // actually just means index.
  794. unsigned int triangle_index = static_cast<unsigned int>(gateway.destination.z);
  795. if (triangle_index >= field->GetWalkmesh()->GetTriangles().size()){
  796. write_output_line_(
  797. "[WARNING] In field " + field->getName() + ": Map jump triangle ("
  798. + std::to_string(triangle_index) + ") out of bounds ("
  799. + std::to_string(field->GetWalkmesh()->GetTriangles().size()) + ")"
  800. );
  801. std::cerr << "[WARNING] In field " << field->getName()
  802. << ": Map jump triangle (" << triangle_index << ") out of bounds ("
  803. << field->GetWalkmesh()->GetTriangles().size() << ")" << std::endl;
  804. triangle_index = 0;
  805. }
  806. const float z_of_triangle_with_id
  807. = field->GetWalkmesh()->GetTriangles().at(triangle_index).a.z / GetFieldScaleFactor(this_field_id);
  808. const Ogre::Vector3 position(
  809. gateway.destination.x / downscaler_next, gateway.destination.y / downscaler_next,
  810. z_of_triangle_with_id
  811. );
  812. if (position != Ogre::Vector3::ZERO && first_entity_point == Ogre::Vector3::ZERO){
  813. first_entity_point = position;
  814. }
  815. xml_entity_point->SetAttribute("position", Ogre::StringConverter::toString(position));
  816. const float rotation = (360.0f * static_cast<float>(gateway.dir)) / 256.0f;
  817. xml_entity_point->SetAttribute("rotation", std::to_string(rotation));
  818. element->LinkEndChild(xml_entity_point.release());
  819. }
  820. }
  821. // The entities (lines, scripts and models) must be in the order of the original field:
  822. // the engine starts their scripts in that order, and some scripts depend on it (a script
  823. // that clears the background areas has to start before the doors that set them).
  824. std::vector<std::pair<uint, std::unique_ptr<TiXmlElement>>> ordered_entities;
  825. // Get lines. Add them to a list, so they aren't processed later as regular entities.
  826. std::vector<std::string> line_entities;
  827. const float line_scale = LINE_SCALE_FACTOR / GetFieldScaleFactor(this_field_id);
  828. for (FieldDecompiler::Line line : decompiled.lines){
  829. std::unique_ptr<TiXmlElement> xml_entity_trigger(new TiXmlElement("entity_trigger"));
  830. line_entities.push_back(line.name);
  831. xml_entity_trigger->SetAttribute("name", line.name);
  832. xml_entity_trigger->SetAttribute(
  833. "point1",
  834. std::to_string(line.point_a[0] * line_scale)
  835. + " " + std::to_string(line.point_a[1] * line_scale)
  836. + " " + std::to_string(line.point_a[2] * line_scale)
  837. );
  838. xml_entity_trigger->SetAttribute(
  839. "point2",
  840. std::to_string(line.point_b[0] * line_scale)
  841. + " " + std::to_string(line.point_b[1] * line_scale)
  842. + " " + std::to_string(line.point_b[2] * line_scale)
  843. );
  844. xml_entity_trigger->SetAttribute("enabled", "true");
  845. ordered_entities.emplace_back(line.index, std::move(xml_entity_trigger));
  846. }
  847. // Get entities.
  848. for (FieldDecompiler::FieldEntity entity : decompiled.entities){
  849. // If the entity has been added as a line, skip.
  850. if (line_entities.size() > 0){
  851. if (std::find(line_entities.begin(), line_entities.end(), entity.name)
  852. != line_entities.end()) continue;
  853. }
  854. const int char_id = entity.char_id;
  855. if (char_id != -1){
  856. const VGears::ModelListFile::ModelDescription& desc = models->GetModels().at(char_id);
  857. auto& animations = used_models_and_anims_.ModelAnimations(desc.hrc_name);
  858. for (const auto& anim : desc.animations){
  859. animations.insert(used_models_and_anims_.NormalizeAnimationName(anim.name));
  860. }
  861. std::unique_ptr<TiXmlElement> xml_entity_script(new TiXmlElement("entity_model"));
  862. xml_entity_script->SetAttribute("name", entity.name);
  863. // TODO: Add to list of HRC's to convert, obtain name of converted .mesh file.
  864. auto lower_case_hrc_name = desc.hrc_name;
  865. VGears::StringUtil::toLowerCase(lower_case_hrc_name);
  866. xml_entity_script->SetAttribute(
  867. "file_name", used_models_and_anims_.ModelMetaDataName(lower_case_hrc_name)
  868. );
  869. xml_entity_script->SetAttribute("index", entity.index);
  870. if (desc.type == VGears::ModelListFile::PLAYER){
  871. // For player models the position is set manually in the xml because if a map
  872. // is loaded manually this is where the player will end up. Hence we set the
  873. // position to the first entity_point that we have.
  874. xml_entity_script->SetAttribute("position", Ogre::StringConverter::toString(first_entity_point));
  875. }
  876. else{
  877. xml_entity_script->SetAttribute("position", Ogre::StringConverter::toString(Ogre::Vector3::ZERO));
  878. }
  879. xml_entity_script->SetAttribute("direction", "0");
  880. // TODO: This isn't quite right, the models animation
  881. // translation seems to be inverted?
  882. xml_entity_script->SetAttribute("scale", "0.03125 0.03125 0.03125");
  883. xml_entity_script->SetAttribute("root_orientation", "0.7071067811865476 0.7071067811865476 0 0");
  884. ordered_entities.emplace_back(entity.index, std::move(xml_entity_script));
  885. }
  886. else{
  887. std::unique_ptr<TiXmlElement> xml_entity_script(new TiXmlElement("entity_script"));
  888. xml_entity_script->SetAttribute("name", entity.name);//it.first);
  889. ordered_entities.emplace_back(entity.index, std::move(xml_entity_script));
  890. }
  891. }
  892. std::stable_sort(
  893. ordered_entities.begin(), ordered_entities.end(),
  894. [](const auto& a, const auto& b){return a.first < b.first;}
  895. );
  896. for (auto& ordered : ordered_entities) element->LinkEndChild(ordered.second.release());
  897. const float downscaler_this = 128.0f * GetFieldScaleFactor(this_field_id);
  898. for (size_t i = 0; i < gateways.size(); i ++){
  899. const VGears::TriggersFile::Gateway& gateway = gateways[i];
  900. // If non-inactive gateway:
  901. if (gateway.destination_field_id != INACTIVE_GATEWAY_ID){
  902. std::unique_ptr<TiXmlElement> xml_entity_trigger(new TiXmlElement("entity_trigger"));
  903. xml_entity_trigger->SetAttribute("name", "Gateway" + std::to_string(i));
  904. xml_entity_trigger->SetAttribute(
  905. "point1",
  906. Ogre::StringConverter::toString(
  907. Ogre::Vector3(
  908. gateway.exit_line[0].x, gateway.exit_line[0].y, gateway.exit_line[0].z) / downscaler_this
  909. )
  910. );
  911. xml_entity_trigger->SetAttribute(
  912. "point2",
  913. Ogre::StringConverter::toString(
  914. Ogre::Vector3(
  915. gateway.exit_line[1].x, gateway.exit_line[1].y, gateway.exit_line[1].z) / downscaler_this
  916. )
  917. );
  918. // Enabled is hard coded to true.
  919. xml_entity_trigger->SetAttribute("enabled", "true");
  920. element->LinkEndChild(xml_entity_trigger.release());
  921. }
  922. }
  923. // Background triggers (doors and similar that change tiles).
  924. const auto& bg_triggers_xml = triggers->GetBackgroundTriggers();
  925. for (size_t i = 0; i < bg_triggers_xml.size(); i ++){
  926. const VGears::TriggersFile::Trigger& bg_trigger = bg_triggers_xml[i];
  927. if (!IsBackgroundTriggerUsed(bg_trigger)) continue;
  928. std::unique_ptr<TiXmlElement> xml_entity_trigger(new TiXmlElement("entity_trigger"));
  929. xml_entity_trigger->SetAttribute("name", "BgTrigger" + std::to_string(i));
  930. xml_entity_trigger->SetAttribute(
  931. "point1",
  932. Ogre::StringConverter::toString(Ogre::Vector3(
  933. bg_trigger.trigger_line[0].x, bg_trigger.trigger_line[0].y,
  934. bg_trigger.trigger_line[0].z
  935. ) / downscaler_this)
  936. );
  937. xml_entity_trigger->SetAttribute(
  938. "point2",
  939. Ogre::StringConverter::toString(Ogre::Vector3(
  940. bg_trigger.trigger_line[1].x, bg_trigger.trigger_line[1].y,
  941. bg_trigger.trigger_line[1].z
  942. ) / downscaler_this)
  943. );
  944. xml_entity_trigger->SetAttribute("enabled", "true");
  945. element->LinkEndChild(xml_entity_trigger.release());
  946. }
  947. // Get music tracks
  948. std::vector<int> tracks = ExtractMusicTrackIds(field);
  949. std::unique_ptr<TiXmlElement> xml_tracks(new TiXmlElement("tracks"));
  950. for (int t = 0; t < tracks.size(); t ++){
  951. std::unique_ptr<TiXmlElement> xml_track(new TiXmlElement("track"));
  952. xml_track->SetAttribute("id", t);
  953. xml_track->SetAttribute("track_id", tracks[t]);
  954. xml_tracks->LinkEndChild(xml_track.release());
  955. }
  956. element->LinkEndChild(xml_tracks.release());
  957. doc.LinkEndChild(element.release());
  958. doc.SaveFile(data_dir_ + "/" + FIELD_MAPS_DIR + "/" + field->getName() + "/map.xml");
  959. const VGears::PaletteFilePtr& pal = field->GetPalette();
  960. const VGears::BackgroundFilePtr& bg = field->GetBackground();
  961. std::unique_ptr<Ogre::Image> bg_image(bg->CreateImage(pal));
  962. bg_image->encode("png");
  963. bg_image->save(data_dir_ + "/" + FIELD_MAPS_DIR + "/" + field->getName() + "/tiles.png");
  964. {
  965. TiXmlDocument bg_doc;
  966. std::unique_ptr<TiXmlElement> bg_element(new TiXmlElement("background2d"));
  967. // Magic constants.
  968. const int BG_SCALE_UP_FACTOR = 3;
  969. const int BG_PSX_SCREEN_WIDTH = 320;
  970. const int BG_PSX_SCREEN_HEIGHT = 240;
  971. // Get texture atlas size.
  972. const int width = bg_image->getWidth();
  973. const int height = bg_image->getHeight();
  974. const VGears::CameraMatrixFilePtr& camera_matrix = field->GetCameraMatrix();
  975. const Ogre::Vector3 position = camera_matrix->GetPosition() / GetFieldScaleFactor(this_field_id);
  976. const Ogre::Quaternion orientation = camera_matrix->GetOrientation();
  977. const Ogre::Degree fov = camera_matrix->GetFov(static_cast<float>(BG_PSX_SCREEN_HEIGHT));
  978. const int min_x = triggers->GetCameraRange().left * BG_SCALE_UP_FACTOR;
  979. const int min_y = triggers->GetCameraRange().top * BG_SCALE_UP_FACTOR;
  980. const int max_x = triggers->GetCameraRange().right * BG_SCALE_UP_FACTOR;
  981. const int max_y = triggers->GetCameraRange().bottom * BG_SCALE_UP_FACTOR;
  982. bg_element->SetAttribute("image", field->getName() + "/tiles.png");
  983. bg_element->SetAttribute("position", Ogre::StringConverter::toString(position));
  984. bg_element->SetAttribute("orientation", Ogre::StringConverter::toString(orientation));
  985. bg_element->SetAttribute("fov", Ogre::StringConverter::toString(fov));
  986. bg_element->SetAttribute(
  987. "range",
  988. std::to_string(min_x) + " " + std::to_string(min_y) + " "
  989. + std::to_string(max_x) + " " + std::to_string(max_y)
  990. );
  991. bg_element->SetAttribute(
  992. "clip",
  993. std::to_string(BG_PSX_SCREEN_WIDTH * BG_SCALE_UP_FACTOR) + " "
  994. + std::to_string(BG_PSX_SCREEN_HEIGHT * BG_SCALE_UP_FACTOR)
  995. );
  996. // The palette animations: the tiles of the palettes a script changes are painted again
  997. // by the engine.
  998. if (
  999. !decompiled.palette_pages.empty() || decompiled.palette_pages_dynamic
  1000. ){
  1001. const std::string palette_name = field->getName() + "/palette.bin";
  1002. if (WritePaletteFile(
  1003. data_dir_ + "/" + FIELD_MAPS_DIR + "/" + palette_name, pal, bg->GetPaletteTiles(),
  1004. decompiled.palette_pages, decompiled.palette_pages_dynamic
  1005. )){
  1006. bg_element->SetAttribute("palette", palette_name);
  1007. }
  1008. }
  1009. // Write out the *_BG.XML data.
  1010. auto& layers = bg->GetLayers();
  1011. int layer_index = -1;
  1012. for (const auto& layer : layers){
  1013. ++ layer_index;
  1014. // TODO: Should only the tiles to construct enabled layers be outputted?
  1015. // if (layer.enabled){
  1016. for (const VGears::BackgroundFile::SpriteData& sprite : layer.sprites){
  1017. std::unique_ptr<TiXmlElement> xml_element(new TiXmlElement("tile"));
  1018. xml_element->SetAttribute(
  1019. "destination",
  1020. Ogre::StringConverter::toString(sprite.dst.x * BG_SCALE_UP_FACTOR) + " "
  1021. + Ogre::StringConverter::toString(sprite.dst.y * BG_SCALE_UP_FACTOR)
  1022. );
  1023. xml_element->SetAttribute(
  1024. "width", Ogre::StringConverter::toString(sprite.width * BG_SCALE_UP_FACTOR)
  1025. );
  1026. xml_element->SetAttribute(
  1027. "height", Ogre::StringConverter::toString(sprite.height * BG_SCALE_UP_FACTOR)
  1028. );
  1029. // Each tile is added to a big texture atlas with hard coded size of 1024x1024,
  1030. // convert UV's to the 0.0f to 1.0f range.
  1031. const float u0 = static_cast<float>(sprite.src.x) / width;
  1032. const float v0 = static_cast<float>(sprite.src.y) / height;
  1033. const float u1 = static_cast<float>(sprite.src.x + sprite.width) / width;
  1034. const float v1 = static_cast<float>(sprite.src.y + sprite.height) / height;
  1035. xml_element->SetAttribute(
  1036. "uv",
  1037. Ogre::StringConverter::toString(u0) + " " + Ogre::StringConverter::toString(v0) + " "
  1038. + Ogre::StringConverter::toString(u1) + " " + Ogre::StringConverter::toString(v1)
  1039. );
  1040. // TODO: It works (on FFVII PC), but why this number?
  1041. // The depth is a distance from the camera, so it has the scale of the field
  1042. // like the position of the camera does. The far depths (the backgrounds, from
  1043. // 127 on) are only an order and are kept.
  1044. float tile_depth = static_cast<float>(sprite.depth) * (0.03125f);
  1045. if (tile_depth < 127.0f) tile_depth /= GetFieldScaleFactor(this_field_id);
  1046. xml_element->SetAttribute("depth", Ogre::StringConverter::toString(tile_depth));
  1047. // TODO: Copied from DatFile::AddTile.
  1048. // Add to common method.
  1049. Ogre::String blending_str = "";
  1050. if (sprite.blending == 0) blending_str = "alpha";
  1051. // 3 is source + 0.25 * destination:
  1052. else if (sprite.blending == 1 || sprite.blending == 3) blending_str = "add";
  1053. else if (sprite.blending == 2) blending_str = "subtract";
  1054. // TODO: Should probably throw to fail conversion:
  1055. else blending_str = "unknown";
  1056. xml_element->SetAttribute("blending", blending_str);
  1057. // Type 3 adds only a quarter of the colour of the tile: with all of it the
  1058. // glows turn white (ujunon4).
  1059. if (sprite.blending == 3) xml_element->SetAttribute("intensity", "0.25");
  1060. // The layer is needed by the scripts that scroll them at their own speed.
  1061. xml_element->SetAttribute("layer", layer_index);
  1062. // The sprites that belong to a group (animation_id) are drawn only while a
  1063. // script (BGON) or a background trigger turns on one of their states. The
  1064. // original game clears the state of every group when it loads a field, so a
  1065. // group that nothing turns on is never drawn (the debris behind the doors of
  1066. // mds6_2, for example).
  1067. if (sprite.animation_id != 0){
  1068. xml_element->SetAttribute("area", static_cast<int>(sprite.animation_id));
  1069. xml_element->SetAttribute("state", static_cast<int>(sprite.animation_frame));
  1070. }
  1071. bg_element->LinkEndChild(xml_element.release());
  1072. }
  1073. //}
  1074. }
  1075. bg_doc.LinkEndChild(bg_element.release());
  1076. bg_doc.SaveFile(data_dir_ + "/" + FIELD_MAPS_DIR + "/" + field->getName() + "/bg.xml");
  1077. }
  1078. }
  1079. {
  1080. // Save out the walk mesh as XML.
  1081. const VGears::WalkmeshFilePtr& walkmesh = field->GetWalkmesh();
  1082. // Scripts, gateways and the camera use the field's scale, so the walkmesh must too.
  1083. const float field_scale = GetFieldScaleFactor(GetFieldId(field->getName(), map_list_));
  1084. TiXmlDocument doc;
  1085. std::unique_ptr<TiXmlElement> wmesh_element(new TiXmlElement("walkmesh"));
  1086. for (VGears::WalkmeshFile::Triangle& tri : walkmesh->GetTriangles()){
  1087. std::unique_ptr<TiXmlElement> xml_element(new TiXmlElement("triangle"));
  1088. xml_element->SetAttribute("a", Ogre::StringConverter::toString(tri.a / field_scale));
  1089. xml_element->SetAttribute("b", Ogre::StringConverter::toString(tri.b / field_scale));
  1090. xml_element->SetAttribute("c", Ogre::StringConverter::toString(tri.c / field_scale));
  1091. xml_element->SetAttribute("a_b", std::to_string(tri.access_side[0]));
  1092. xml_element->SetAttribute("b_c", std::to_string(tri.access_side[1]));
  1093. xml_element->SetAttribute("c_a", std::to_string(tri.access_side[2]));
  1094. wmesh_element->LinkEndChild(xml_element.release());
  1095. }
  1096. doc.LinkEndChild(wmesh_element.release());
  1097. doc.SaveFile(data_dir_ + "/" + FIELD_MAPS_DIR + "/" + field->getName() + "/wm.xml");
  1098. }
  1099. converted_map_list_.push_back(field->getName());
  1100. }