FieldDataInstaller.cpp 58 KB

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