ff7DataInstaller.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  1. #include "ff7DataInstaller.h"
  2. #include <boost/filesystem.hpp>
  3. #include <boost/program_options.hpp>
  4. #include <OgreConfigFile.h>
  5. #include <OgreArchiveManager.h>
  6. #include <OgreMeshSerializer.h>
  7. #include <OgreSkeletonSerializer.h>
  8. #include <OgreMeshManager.h>
  9. #include <OgreRenderWindow.h>
  10. #include <OgreHardwarePixelBuffer.h>
  11. #include "QGearsGameState.h"
  12. #include "data/QGearsAFileManager.h"
  13. #include "data/QGearsBackgroundFileManager.h"
  14. #include "data/QGearsCameraMatrixFileManager.h"
  15. #include "data/QGearsHRCFileManager.h"
  16. #include "data/QGearsLZSFLevelFileManager.h"
  17. #include "data/QGearsPaletteFileManager.h"
  18. #include "data/QGearsPFileManager.h"
  19. #include "data/QGearsRSDFileManager.h"
  20. #include "data/QGearsTexCodec.h"
  21. #include "map/QGearsBackground2DFileManager.h"
  22. #include "map/QGearsWalkmeshFileManager.h"
  23. #include "data/FF7ModelListFileManager.h"
  24. #include "data/QGearsLGPArchiveFactory.h"
  25. #include "common/QGearsStringUtil.h"
  26. #include "common/FF7NameLookup.h"
  27. #include "data/QGearsTexCodec.h"
  28. #include "data/QGearsMapListFile.h"
  29. #include "decompiler/sudm.h"
  30. #include <memory>
  31. #include <QDir>
  32. FF7DataInstaller::FF7DataInstaller()
  33. #ifdef _DEBUG
  34. : mApp("plugins_d.cfg", "resources_d.cfg", "install_d.log")
  35. #else
  36. : mApp("plugins.cfg", "resources.cfg", "install.log")
  37. #endif
  38. {
  39. mApp.initOgre(true);
  40. }
  41. FF7DataInstaller::~FF7DataInstaller()
  42. {
  43. }
  44. void FF7DataInstaller::Convert(std::string inputDir, std::string outputDir, const std::vector<std::string>& files)
  45. {
  46. // TODO: Just validate required files are present
  47. for (const auto& file : files)
  48. {
  49. if (file == "field/flevel.lgp")
  50. {
  51. auto fullPath = inputDir + file;
  52. mApp.getRoot()->addResourceLocation(fullPath, "LGP", "FFVIIFields");
  53. ConvertFields(fullPath, inputDir, outputDir);
  54. mApp.getRoot()->removeResourceLocation(fullPath, "FFVIIFields");
  55. }
  56. }
  57. }
  58. static std::string FieldModelDir()
  59. {
  60. return "models/ffvii/field/units";
  61. }
  62. // TOOD: Share with pc model exporter
  63. static void exportMesh(std::string outdir, const Ogre::MeshPtr &mesh)
  64. {
  65. Ogre::MeshSerializer mesh_ser;
  66. Ogre::SkeletonPtr skeleton(mesh->getSkeleton());
  67. Ogre::SkeletonSerializer sk_ser;
  68. sk_ser.exportSkeleton(skeleton.getPointer(), outdir + skeleton->getName());
  69. mesh->setSkeletonName(FieldModelDir() + "/" + mesh->getSkeletonName());
  70. mesh_ser.exportMesh(mesh.getPointer(), outdir + mesh->getName());
  71. Ogre::Mesh::SubMeshIterator it(mesh->getSubMeshIterator());
  72. Ogre::MaterialSerializer mat_ser;
  73. size_t i(0);
  74. std::set<std::string> textures;
  75. while (it.hasMoreElements())
  76. {
  77. Ogre::SubMesh *sub_mesh(it.getNext());
  78. Ogre::MaterialPtr mat(Ogre::MaterialManager::getSingleton().getByName(sub_mesh->getMaterialName()));
  79. if (!mat.isNull())
  80. {
  81. for (size_t techNum = 0; techNum < mat->getNumTechniques(); techNum++)
  82. {
  83. Ogre::Technique* tech = mat->getTechnique(techNum);
  84. if (tech)
  85. {
  86. for (size_t passNum = 0; passNum < tech->getNumPasses(); passNum++)
  87. {
  88. Ogre::Pass* pass = tech->getPass(passNum);
  89. if (pass)
  90. {
  91. for (size_t textureUnitNum = 0; textureUnitNum < pass->getNumTextureUnitStates(); textureUnitNum++)
  92. {
  93. Ogre::TextureUnitState* unit = pass->getTextureUnitState(textureUnitNum);
  94. if (unit)
  95. {
  96. if (unit->getTextureName().empty() == false)
  97. {
  98. // Ensure the output material script references png files rather than tex files
  99. textures.insert(unit->getTextureName());
  100. Ogre::String baseName;
  101. QGears::StringUtil::splitBase(unit->getTextureName(), baseName);
  102. unit->setTextureName(FieldModelDir() + "/" + baseName + ".png");
  103. }
  104. }
  105. }
  106. }
  107. }
  108. }
  109. }
  110. mat_ser.queueForExport(mat);
  111. }
  112. ++i;
  113. }
  114. QGears::String base_name;
  115. QGears::StringUtil::splitFull(mesh->getName(), base_name);
  116. mat_ser.exportQueued(outdir + base_name + QGears::EXT_MATERIAL);
  117. for (auto& textureName : textures)
  118. {
  119. Ogre::TexturePtr texturePtr = Ogre::TextureManager::getSingleton().load(textureName.c_str(), "FFVII");
  120. Ogre::Image image;
  121. texturePtr->convertToImage(image);
  122. Ogre::String baseName;
  123. QGears::StringUtil::splitBase(textureName, baseName);
  124. image.save(outdir + baseName + ".png");
  125. }
  126. }
  127. static std::string FieldName(const std::string& name)
  128. {
  129. return "ffvii_" + name;
  130. }
  131. void FF7DataInstaller::CreateDir(const std::string& path)
  132. {
  133. QString target = QString::fromStdString(mOutputDir + path);
  134. QDir dir(target);
  135. if (!dir.mkpath("."))
  136. {
  137. throw std::runtime_error("Failed to mkpath");
  138. }
  139. }
  140. static std::string FieldMapDir()
  141. {
  142. return "maps/ffvii/field";
  143. }
  144. typedef std::set<std::string> MapCollection;
  145. class SpawnPointDb
  146. {
  147. public:
  148. // Id of the field the gateways records from N other number of fields are linking to
  149. u16 mTargetFieldId = 0;
  150. class Record
  151. {
  152. public:
  153. // Field that wants to link to mTargetFieldId
  154. u16 mFieldId = 0;
  155. // Index of the gateway in mFieldId
  156. u32 GatewayIndexOrMapJumpAddress = 0;
  157. // Gateway data
  158. QGears::TriggersFile::Gateway mGateway;
  159. bool mFromScript = false;
  160. // Only used from script calls
  161. std::string mEntityName;
  162. std::string mScriptFunctionName;
  163. };
  164. std::vector<Record> mGatewaysToThisField;
  165. };
  166. typedef std::map<u16, SpawnPointDb> FieldSpawnPointsMap;
  167. class BaseFF7FieldScriptFormatter : public SUDM::IScriptFormatter
  168. {
  169. public:
  170. BaseFF7FieldScriptFormatter(const std::string& fieldName, const std::vector<std::string>& fieldIdToNameLookup, FieldSpawnPointsMap& spawnPoints)
  171. : mFieldName(fieldName), mFieldIdToNameLookup(fieldIdToNameLookup), mSpawnPoints(spawnPoints)
  172. {
  173. }
  174. virtual std::string SpawnPointName(unsigned int targetMapId, const std::string& entity, const std::string& funcName, unsigned int address) override
  175. {
  176. return mFieldIdToNameLookup[targetMapId] + "_" + entity + "_" + funcName + "_addr_" + std::to_string(address);
  177. }
  178. virtual std::string MapName(unsigned int mapId) override
  179. {
  180. return FieldName(mFieldIdToNameLookup[mapId]);
  181. }
  182. // Renames a variable, return empty string for generated name
  183. virtual std::string VarName(unsigned int bank, unsigned int addr) override
  184. {
  185. return QGears::FF7::NameLookup::FieldScriptVarName(bank, addr);
  186. }
  187. // Renames an entity
  188. virtual std::string EntityName(const std::string& entity) override
  189. {
  190. return QGears::FF7::NameLookup::FieldScriptEntityName(entity);
  191. }
  192. // Get name of char from its id, can't return empty
  193. virtual std::string CharName(int charId) override
  194. {
  195. return QGears::FF7::NameLookup::CharName(charId);
  196. }
  197. // Renames a function in an entity
  198. virtual std::string FunctionName(const std::string& entity, const std::string& funcName) override
  199. {
  200. return QGears::FF7::NameLookup::FieldScriptFunctionName(mFieldName, entity, funcName);
  201. }
  202. // Sets the header comment for a function in an entity
  203. virtual std::string FunctionComment(const std::string& entity, const std::string& funcName) override
  204. {
  205. return QGears::FF7::NameLookup::FieldScriptFunctionComment(mFieldName, entity, funcName);
  206. }
  207. protected:
  208. std::string mFieldName;
  209. FieldSpawnPointsMap& mSpawnPoints;
  210. const std::vector<std::string>& mFieldIdToNameLookup;
  211. };
  212. class FF7FieldScriptFormatter : public BaseFF7FieldScriptFormatter
  213. {
  214. public:
  215. FF7FieldScriptFormatter(const std::string& fieldName, const QGears::ModelListFilePtr& models, const std::vector<std::string>& fieldIdToNameLookup, FieldSpawnPointsMap& spawnPoints)
  216. : BaseFF7FieldScriptFormatter(fieldName, fieldIdToNameLookup, spawnPoints), mModelLoader(models)
  217. {
  218. }
  219. // Names an animation, can't return empty
  220. virtual std::string AnimationName(int charId, int id) override
  221. {
  222. // Get the animation file name, then look up the friendly name of the "raw" animation
  223. if (static_cast<unsigned int>(charId) >= mModelLoader->getModels().size())
  224. {
  225. std::cout << "ERROR CHAR ID IS OUT OF BOUNDS" << std::endl;
  226. return std::to_string(id);
  227. }
  228. const auto& modelInfo = mModelLoader->getModels().at(charId);
  229. if (static_cast<unsigned int>(id) >= modelInfo.animations.size())
  230. {
  231. std::cout << "ERROR ANIMATION ID IS OUT OF BOUNDS" << std::endl;
  232. return std::to_string(id);
  233. }
  234. const auto rawName = modelInfo.animations.at(id).name;
  235. // Trim off ".yos" or whatever other crazy extension the model loader adds in
  236. Ogre::String baseName;
  237. QGears::StringUtil::splitBase(rawName, baseName);
  238. QGears::StringUtil::toLowerCase(baseName);
  239. return QGears::FF7::NameLookup::animation(baseName);
  240. }
  241. private:
  242. const QGears::ModelListFilePtr& mModelLoader;
  243. };
  244. static std::string CreateGateWayScript(const std::string& gatewayEntityName, const std::string& targetMapName, const std::string& sourceSpawnPointName)
  245. {
  246. return "\nEntityContainer[ \"" + gatewayEntityName + "\" ] = {\n"
  247. "on_start = function(self)\n"
  248. " return 0\n"
  249. "end,\n"
  250. "on_enter_line = function(self, entity)\n"
  251. " return 0\n"
  252. "end,\n\n"
  253. "on_move_to_line = function(self, entity)\n"
  254. " return 0\n"
  255. "end,\n\n"
  256. "on_cross_line = function(self, entity)\n"
  257. " if entity == \"Cloud\" then\n"
  258. " if not FFVII.Data.DisableGateways then\n"
  259. " load_field_map_request(\"" + targetMapName + "\", \"" + sourceSpawnPointName + "\")\n"
  260. " end\n"
  261. " end\n\n"
  262. " return 0\n"
  263. "end,\n\n"
  264. "on_leave_line = function(self, entity)\n"
  265. " return 0\n"
  266. "end,\n"
  267. "}\n\n";
  268. }
  269. const int kInactiveGateWayId = 32767;
  270. typedef std::map<u16, float> FieldScaleFactorMap;
  271. typedef std::map<std::string, std::set<std::string>> ModelAnimationMap;
  272. class ModelsAndAnimationsDb
  273. {
  274. public:
  275. std::string NormalizeAnimationName(const std::string& name)
  276. {
  277. Ogre::String baseName;
  278. QGears::StringUtil::splitBase(name, baseName);
  279. std::transform(baseName.begin(), baseName.end(), baseName.begin(), ::tolower);
  280. return baseName + ".a";
  281. }
  282. std::set<std::string>& ModelAnimations(const std::string model)
  283. {
  284. // HACK FIX LGP READING
  285. std::string modelLower = model;
  286. std::transform(modelLower.begin(), modelLower.end(), modelLower.begin(), ::tolower);
  287. return mMap[modelLower];
  288. }
  289. std::string ModelMetaDataName(const std::string& modelName)
  290. {
  291. // If not in meta data then just replace .hrc with .mesh
  292. Ogre::String baseName;
  293. QGears::StringUtil::splitBase(modelName, baseName);
  294. return QGears::FF7::NameLookup::model(baseName) + ".mesh";
  295. }
  296. //private:
  297. ModelAnimationMap mMap;
  298. };
  299. static size_t FieldId(const std::string& name, const std::vector<std::string>& fieldIdToNameLookup)
  300. {
  301. for (size_t i = 0; i < fieldIdToNameLookup.size(); i++)
  302. {
  303. if (fieldIdToNameLookup[i] == name)
  304. {
  305. return i;
  306. }
  307. }
  308. throw std::runtime_error("No Id found for field name");
  309. }
  310. static float FieldScaleFactor(const FieldScaleFactorMap& scaleFactorMap, size_t fieldId)
  311. {
  312. auto it = scaleFactorMap.find(fieldId);
  313. if (it == std::end(scaleFactorMap))
  314. {
  315. throw std::runtime_error("Scale factor not found for field id");
  316. }
  317. return it->second;
  318. }
  319. static void FF7PcFieldToQGearsField(
  320. QGears::FLevelFilePtr& field,
  321. const std::string& outDir,
  322. const std::vector<std::string>& fieldIdToNameLookup,
  323. FieldSpawnPointsMap& spawnMap,
  324. const FieldScaleFactorMap& scaleFactorMap,
  325. ModelsAndAnimationsDb& modelAnimationDb,
  326. MapCollection& maps)
  327. {
  328. // Generate triggers script to insert into main decompiled FF7 field -> LUA script
  329. std::string gatewayScriptData;
  330. const QGears::TriggersFilePtr& triggers = field->getTriggers();
  331. const auto& gateways = triggers->GetGateways();
  332. for (size_t i = 0; i < gateways.size(); i++)
  333. {
  334. const QGears::TriggersFile::Gateway& gateway = gateways[i];
  335. if (gateway.destinationFieldId != kInactiveGateWayId)
  336. {
  337. const std::string gatewayEntityName = "Gateway" + std::to_string(i);
  338. gatewayScriptData += CreateGateWayScript(gatewayEntityName, FieldName(fieldIdToNameLookup.at(gateway.destinationFieldId)), "Spawn_" + field->getName() + "_" + std::to_string(i));
  339. }
  340. }
  341. const QGears::ModelListFilePtr& models = field->getModelList();
  342. SUDM::FF7::Field::DecompiledScript decompiled;
  343. FF7FieldScriptFormatter formatter(field->getName(), models, fieldIdToNameLookup, spawnMap);
  344. try
  345. {
  346. // Get the raw script bytes
  347. const std::vector<u8> rawFieldData = field->getRawScript();
  348. // Decompile to LUA
  349. decompiled = SUDM::FF7::Field::Decompile(field->getName(), rawFieldData, formatter, gatewayScriptData, "EntityContainer = {}\n\n");
  350. std::ofstream scriptFile(outDir + "/" + FieldMapDir() + "/" + field->getName() + "/script.lua");
  351. if (scriptFile.is_open())
  352. {
  353. scriptFile << decompiled.luaScript;
  354. }
  355. else
  356. {
  357. std::cerr << "Failed to open script file for writing" << std::endl;
  358. }
  359. }
  360. catch (const ::InternalDecompilerError& ex)
  361. {
  362. std::cerr << "InternalDecompilerError: " << ex.what() << std::endl;
  363. }
  364. // Write out the map file which links all the other files together for a given field
  365. {
  366. TiXmlDocument doc;
  367. std::unique_ptr<TiXmlElement> element(new TiXmlElement("map"));
  368. // Script
  369. std::unique_ptr<TiXmlElement> xmlScriptElement(new TiXmlElement("script"));
  370. xmlScriptElement->SetAttribute("file_name", FieldMapDir() + "/" + field->getName() + "/script.lua");
  371. element->LinkEndChild(xmlScriptElement.release());
  372. // Background
  373. std::unique_ptr<TiXmlElement> xmlBackground2d(new TiXmlElement("background2d"));
  374. xmlBackground2d->SetAttribute("file_name", FieldMapDir() + "/" + field->getName() + "/bg.xml");
  375. element->LinkEndChild(xmlBackground2d.release());
  376. // walkmesh
  377. std::unique_ptr<TiXmlElement> xmlWalkmesh(new TiXmlElement("walkmesh"));
  378. xmlWalkmesh->SetAttribute("file_name", FieldMapDir() + "/" + field->getName() + "/wm.xml");
  379. element->LinkEndChild(xmlWalkmesh.release());
  380. // Angle player moves when "up" is pressed
  381. std::unique_ptr<TiXmlElement> xmlMovementRotation(new TiXmlElement("movement_rotation"));
  382. xmlMovementRotation->SetAttribute("degree", std::to_string(triggers->MovementRotation()));
  383. element->LinkEndChild(xmlMovementRotation.release());
  384. for (const auto& it : decompiled.entities)
  385. {
  386. const int charId = it.second;
  387. if (charId != -1)
  388. {
  389. const QGears::ModelListFile::ModelDescription& desc = models->getModels().at(charId);
  390. auto& animVec = modelAnimationDb.ModelAnimations(desc.hrc_name);
  391. for (auto& anim : desc.animations)
  392. {
  393. animVec.insert(modelAnimationDb.NormalizeAnimationName(anim.name));
  394. }
  395. std::unique_ptr<TiXmlElement> xmlEntityScript(new TiXmlElement("entity_model"));
  396. xmlEntityScript->SetAttribute("name", it.first);
  397. // TODO: Add to list of HRC's to convert, obtain name of target converted .mesh file
  398. auto lowerCaseHrcName = desc.hrc_name;
  399. QGears::StringUtil::toLowerCase(lowerCaseHrcName);
  400. xmlEntityScript->SetAttribute("file_name", FieldModelDir() + "/" + modelAnimationDb.ModelMetaDataName(lowerCaseHrcName));
  401. // TODO: entity_model - name, file_name, position, direction
  402. // We set char 1 position to be position of first entity_point so player is spawned in sane
  403. // position if map is manually loaded via console.
  404. // None player chars set their first position in the init scripts. We know its a entity_model
  405. // because it uses PC opcode in init script.
  406. // entity_manager:get_entity("cl") is done via CHAR opcode
  407. xmlEntityScript->SetAttribute("position", "0 0 0");
  408. xmlEntityScript->SetAttribute("direction", "0");
  409. // TODO: This isn't quite right, the models animation translation seems to be inverted?
  410. xmlEntityScript->SetAttribute("scale", "0.03125 0.03125 0.03125");
  411. xmlEntityScript->SetAttribute("root_orientation", "0.7071067811865476 0.7071067811865476 0 0");
  412. element->LinkEndChild(xmlEntityScript.release());
  413. }
  414. else
  415. {
  416. std::unique_ptr<TiXmlElement> xmlEntityScript(new TiXmlElement("entity_script"));
  417. xmlEntityScript->SetAttribute("name", it.first);
  418. element->LinkEndChild(xmlEntityScript.release());
  419. }
  420. }
  421. // Get this fields Id
  422. const size_t thisFieldId = FieldId(field->getName(), fieldIdToNameLookup);
  423. const float downscaler_this = 128.0f * FieldScaleFactor(scaleFactorMap, thisFieldId);
  424. const auto& gateways = triggers->GetGateways();
  425. for (size_t i = 0; i < gateways.size(); i++)
  426. {
  427. const QGears::TriggersFile::Gateway& gateway = gateways[i];
  428. // if not inactive gateway
  429. if (gateway.destinationFieldId != kInactiveGateWayId)
  430. {
  431. std::unique_ptr<TiXmlElement> xmlEntityTrigger(new TiXmlElement("entity_trigger"));
  432. xmlEntityTrigger->SetAttribute("name", "Gateway" + std::to_string(i));
  433. xmlEntityTrigger->SetAttribute("point1",
  434. Ogre::StringConverter::toString(
  435. Ogre::Vector3(gateway.exit_line[0].x, gateway.exit_line[0].y, gateway.exit_line[0].z) / downscaler_this));
  436. xmlEntityTrigger->SetAttribute("point2",
  437. Ogre::StringConverter::toString(
  438. Ogre::Vector3(gateway.exit_line[1].x, gateway.exit_line[1].y, gateway.exit_line[1].z) / downscaler_this));
  439. // enabled hard coded to true
  440. xmlEntityTrigger->SetAttribute("enabled", "true");
  441. element->LinkEndChild(xmlEntityTrigger.release());
  442. }
  443. }
  444. // Use that to find the pre-computed list of gateways in all other fields that link to this field
  445. auto spawnIterator = spawnMap.find(thisFieldId);
  446. // If not found that it probably just means no other fields have doors to this one
  447. if (spawnIterator != std::end(spawnMap))
  448. {
  449. const std::vector<SpawnPointDb::Record>& spawnPointRecords = spawnIterator->second.mGatewaysToThisField;
  450. for (size_t i = 0; i < spawnPointRecords.size(); i++)
  451. {
  452. const QGears::TriggersFile::Gateway& gateway = spawnPointRecords[i].mGateway;
  453. // entity_point
  454. std::unique_ptr<TiXmlElement> xmlEntityPoint(new TiXmlElement("entity_point"));
  455. if (spawnPointRecords[i].mFromScript)
  456. {
  457. // Spawn points from map jumps have a another algorithm
  458. xmlEntityPoint->SetAttribute("name", formatter.SpawnPointName(spawnPointRecords[i].mFieldId, spawnPointRecords[i].mEntityName, spawnPointRecords[i].mScriptFunctionName, spawnPointRecords[i].GatewayIndexOrMapJumpAddress));
  459. }
  460. else
  461. {
  462. // Must also include the gateway index for the case where 2 fields have more than one door linking to each other
  463. xmlEntityPoint->SetAttribute("name", "Spawn_" + fieldIdToNameLookup.at(spawnPointRecords[i].mFieldId) + "_" + std::to_string(spawnPointRecords[i].GatewayIndexOrMapJumpAddress));
  464. }
  465. const float downscaler_next = 128.0f * FieldScaleFactor(scaleFactorMap, gateway.destinationFieldId);
  466. // Position Z is actually the target walkmesh triangle ID, so this is tiny bit more
  467. // complex as we have to say "get the Z value of the triangle with that ID". Note that ID actually just means index.
  468. const float zOfTriangleWithId = field->getWalkmesh()->getTriangles().at(static_cast<unsigned int>(gateway.destination.z)).a.z;
  469. const Ogre::Vector3 posVec(gateway.destination.x / downscaler_next, gateway.destination.y / downscaler_next, zOfTriangleWithId);
  470. xmlEntityPoint->SetAttribute("position", Ogre::StringConverter::toString(posVec));
  471. const float rotation = (360.0f * static_cast<float>(gateway.dir)) / 255.0f;
  472. xmlEntityPoint->SetAttribute("rotation", std::to_string(rotation));
  473. element->LinkEndChild(xmlEntityPoint.release());
  474. }
  475. }
  476. doc.LinkEndChild(element.release());
  477. doc.SaveFile(outDir + "/" + FieldMapDir() + "/" + field->getName() + "/map.xml");
  478. const QGears::PaletteFilePtr& pal = field->getPalette();
  479. const QGears::BackgroundFilePtr& bg = field->getBackground();
  480. std::unique_ptr<Ogre::Image> bgImage(bg->createImage(pal));
  481. bgImage->save(outDir + "/" + FieldMapDir() + "/" + field->getName() + "/tiles.png");
  482. {
  483. TiXmlDocument doc;
  484. std::unique_ptr<TiXmlElement> element(new TiXmlElement("background2d"));
  485. // Magic constants
  486. const int kScaleUpFactor = 3;
  487. const int kPsxScreenWidth = 320;
  488. const int kPsxScreenHeight = 240;
  489. // Get texture atlas size
  490. const int width = bgImage->getWidth();
  491. const int height = bgImage->getHeight();
  492. const QGears::CameraMatrixFilePtr& camMatrix = field->getCameraMatrix();
  493. const Ogre::Vector3 position = camMatrix->getPosition() / FieldScaleFactor(scaleFactorMap, thisFieldId);
  494. const Ogre::Quaternion orientation = camMatrix->getOrientation();
  495. const Ogre::Degree fov = camMatrix->getFov(static_cast<float>(kPsxScreenHeight));
  496. const int min_x = triggers->getCameraRange().left * kScaleUpFactor;
  497. const int min_y = triggers->getCameraRange().top * kScaleUpFactor;
  498. const int max_x = triggers->getCameraRange().right * kScaleUpFactor;
  499. const int max_y = triggers->getCameraRange().bottom * kScaleUpFactor;
  500. element->SetAttribute("image", FieldMapDir() + "/" + field->getName() + "/tiles.png");
  501. element->SetAttribute("position", Ogre::StringConverter::toString(position));
  502. element->SetAttribute("orientation", Ogre::StringConverter::toString(orientation));
  503. element->SetAttribute("fov", Ogre::StringConverter::toString(fov));
  504. element->SetAttribute("range", std::to_string(min_x) + " " + std::to_string(min_y) + " " + std::to_string(max_x) + " " + std::to_string(max_y));
  505. element->SetAttribute("clip", std::to_string(kPsxScreenWidth * kScaleUpFactor) + " " + std::to_string(kPsxScreenHeight * kScaleUpFactor));
  506. // Write out the *_BG.XML data
  507. auto& layers = bg->getLayers();
  508. for (const auto& layer : layers)
  509. {
  510. // TODO: Should we only output tiles to construct enabled layers?
  511. // if (layer.enabled)
  512. {
  513. for (const QGears::BackgroundFile::SpriteData& sprite : layer.sprites)
  514. {
  515. std::unique_ptr<TiXmlElement> xmlElement(new TiXmlElement("tile"));
  516. xmlElement->SetAttribute("destination",
  517. Ogre::StringConverter::toString(sprite.dst.x * kScaleUpFactor) + " " +
  518. Ogre::StringConverter::toString(sprite.dst.y * kScaleUpFactor));
  519. xmlElement->SetAttribute("width", Ogre::StringConverter::toString(sprite.width * kScaleUpFactor));
  520. xmlElement->SetAttribute("height", Ogre::StringConverter::toString(sprite.height * kScaleUpFactor));
  521. // Each tile is added to a big texture atlas with hard coded size of 1024x1024, convert UV's to the 0.0f to 1.0f range
  522. const float u0 = static_cast<float>(sprite.src.x) / bgImage->getWidth();
  523. const float v0 = static_cast<float>(sprite.src.y) / bgImage->getHeight();
  524. const float u1 = static_cast<float>(sprite.src.x + sprite.width) / bgImage->getWidth();
  525. const float v1 = static_cast<float>(sprite.src.y + sprite.height) / bgImage->getHeight();
  526. xmlElement->SetAttribute("uv",
  527. Ogre::StringConverter::toString(u0) + " " + Ogre::StringConverter::toString(v0) + " " +
  528. Ogre::StringConverter::toString(u1) + " " + Ogre::StringConverter::toString(v1)
  529. );
  530. // TODO: Figure out how to scale this value correctly
  531. xmlElement->SetAttribute("depth", "999" /* Ogre::StringConverter::toString(static_cast<float>(sprite.depth) / (4096.0f/10.0f))*/);
  532. // TODO: Copied from DatFile::AddTile - add to common method
  533. Ogre::String blending_str = "";
  534. if (sprite.blending == 0)
  535. {
  536. blending_str = "alpha";
  537. }
  538. else if (sprite.blending == 1 || sprite.blending == 3) // 3 is source + 0.25 * destination
  539. {
  540. blending_str = "add";
  541. }
  542. else if (sprite.blending == 2)
  543. {
  544. blending_str = "subtract";
  545. }
  546. else
  547. {
  548. // TODO: Should probably throw to fail conversion
  549. blending_str = "unknown";
  550. }
  551. xmlElement->SetAttribute("blending", blending_str);
  552. element->LinkEndChild(xmlElement.release());
  553. }
  554. }
  555. }
  556. doc.LinkEndChild(element.release());
  557. doc.SaveFile(outDir + "/" + FieldMapDir() + "/" + field->getName() + "/bg.xml");
  558. }
  559. }
  560. {
  561. // Save out the walk mesh as XML
  562. const QGears::WalkmeshFilePtr& walkmesh = field->getWalkmesh();
  563. TiXmlDocument doc;
  564. std::unique_ptr<TiXmlElement> element(new TiXmlElement("walkmesh"));
  565. for (QGears::WalkmeshFile::Triangle& tri : walkmesh->getTriangles())
  566. {
  567. std::unique_ptr<TiXmlElement> xmlElement(new TiXmlElement("triangle"));
  568. xmlElement->SetAttribute("a", Ogre::StringConverter::toString(tri.a));
  569. xmlElement->SetAttribute("b", Ogre::StringConverter::toString(tri.b));
  570. xmlElement->SetAttribute("c", Ogre::StringConverter::toString(tri.c));
  571. xmlElement->SetAttribute("a_b", std::to_string(tri.access_side[0]));
  572. xmlElement->SetAttribute("b_c", std::to_string(tri.access_side[1]));
  573. xmlElement->SetAttribute("c_a", std::to_string(tri.access_side[2]));
  574. element->LinkEndChild(xmlElement.release());
  575. }
  576. doc.LinkEndChild(element.release());
  577. doc.SaveFile(outDir + "/" + FieldMapDir() + "/" + field->getName() + "/wm.xml");
  578. }
  579. maps.insert(field->getName());
  580. }
  581. class FF7FieldScriptGatewayCollector : public BaseFF7FieldScriptFormatter
  582. {
  583. public:
  584. FF7FieldScriptGatewayCollector(const std::string& fieldName, const std::vector<std::string>& fieldIdToNameLookup, FieldSpawnPointsMap& spawnPoints, size_t thisFieldId)
  585. : BaseFF7FieldScriptFormatter(fieldName, fieldIdToNameLookup, spawnPoints), mThisFieldId(thisFieldId)
  586. {
  587. }
  588. virtual void AddSpawnPoint(unsigned int targetMapId, const std::string& entity, const std::string& funcName, unsigned int address, int x, int y, int z, int angle) override
  589. {
  590. auto it = mSpawnPoints.find(targetMapId);
  591. QGears::TriggersFile::Gateway gw = {};
  592. gw.destinationFieldId = targetMapId;
  593. gw.destination.x = x;
  594. gw.destination.y = y;
  595. gw.destination.z = z;
  596. gw.dir = angle;
  597. if (it != std::end(mSpawnPoints))
  598. {
  599. // Add to the list of gateways that link to destinationFieldId
  600. SpawnPointDb::Record rec;
  601. rec.mFromScript = true;
  602. rec.mFieldId = mThisFieldId;
  603. rec.mGateway = gw;
  604. rec.mEntityName = entity;
  605. rec.mScriptFunctionName = funcName;
  606. rec.GatewayIndexOrMapJumpAddress = address;
  607. it->second.mGatewaysToThisField.push_back(rec);
  608. }
  609. else
  610. {
  611. // Create a new record for destinationFieldId
  612. SpawnPointDb db;
  613. db.mTargetFieldId = targetMapId;
  614. SpawnPointDb::Record rec;
  615. rec.mFromScript = true;
  616. rec.mFieldId = mThisFieldId;
  617. rec.mGateway = gw;
  618. rec.mEntityName = entity;
  619. rec.mScriptFunctionName = funcName;
  620. rec.GatewayIndexOrMapJumpAddress = address;
  621. db.mGatewaysToThisField.push_back(rec);
  622. mSpawnPoints.insert(std::make_pair(db.mTargetFieldId, db));
  623. }
  624. }
  625. private:
  626. size_t mThisFieldId;
  627. };
  628. static void CollectSpawnPoints(QGears::FLevelFilePtr& field, const std::vector<std::string>& fieldIdToNameLookup, FieldSpawnPointsMap& spawnPoints)
  629. {
  630. const size_t thisFieldId = FieldId(field->getName(), fieldIdToNameLookup);
  631. // Decompile the script just so we can collect up the MAPJUMP's we need this to construct the full list of entries
  632. // to each field
  633. try
  634. {
  635. // Get the raw script bytes
  636. SUDM::FF7::Field::DecompiledScript decompiled;
  637. const std::vector<u8> rawFieldData = field->getRawScript();
  638. // Decompile to LUA
  639. FF7FieldScriptGatewayCollector formatter(field->getName(), fieldIdToNameLookup, spawnPoints, thisFieldId);
  640. decompiled = SUDM::FF7::Field::Decompile(field->getName(), rawFieldData, formatter, "", "EntityContainer = {}\n\n");
  641. }
  642. catch (const ::InternalDecompilerError& ex)
  643. {
  644. std::cerr << "InternalDecompilerError: " << ex.what() << std::endl;
  645. }
  646. const QGears::TriggersFilePtr& triggers = field->getTriggers();
  647. const auto& gateways = triggers->GetGateways();
  648. for (size_t i = 0; i < gateways.size(); i++)
  649. {
  650. const QGears::TriggersFile::Gateway& gateway = gateways[i];
  651. if (gateway.destinationFieldId != kInactiveGateWayId)
  652. {
  653. auto it = spawnPoints.find(gateway.destinationFieldId);
  654. if (it != std::end(spawnPoints))
  655. {
  656. // Add to the list of gateways that link to destinationFieldId
  657. SpawnPointDb::Record rec;
  658. rec.mFieldId = thisFieldId;
  659. rec.mGateway = gateway;
  660. rec.GatewayIndexOrMapJumpAddress = i;
  661. it->second.mGatewaysToThisField.push_back(rec);
  662. }
  663. else
  664. {
  665. // Create a new record for destinationFieldId
  666. SpawnPointDb db;
  667. db.mTargetFieldId = gateway.destinationFieldId;
  668. SpawnPointDb::Record rec;
  669. rec.mFieldId = thisFieldId;
  670. rec.mGateway = gateway;
  671. rec.GatewayIndexOrMapJumpAddress = i;
  672. db.mGatewaysToThisField.push_back(rec);
  673. spawnPoints.insert(std::make_pair(db.mTargetFieldId, db));
  674. }
  675. }
  676. }
  677. }
  678. static bool IsAFieldFile(Ogre::String& resourceName)
  679. {
  680. return (!QGears::StringUtil::endsWith(resourceName, ".tex")
  681. && !QGears::StringUtil::endsWith(resourceName, ".tut")
  682. && !QGears::StringUtil::endsWith(resourceName, ".siz")
  683. && resourceName != "maplist");
  684. }
  685. // Exclude fields which cause fatal crash bugs :)
  686. // this can be removed when whatever is causing the crash(s) is fixed
  687. static bool WillCrash(Ogre::String& resourceName)
  688. {
  689. if (
  690. // crashes in back ground image generation
  691. resourceName == "bugin1a" ||
  692. // Hangs in decompliation
  693. resourceName == "frcyo" ||
  694. // bg image crash
  695. resourceName == "fr_e" ||
  696. resourceName == "las4_2" ||
  697. resourceName == "las4_3" ||
  698. resourceName == "lastmap" ||
  699. resourceName == "md_e1" ||
  700. resourceName == "trnad_3"
  701. )
  702. {
  703. // NOTE: Even so, conversion of all models will fail with a bone index out of bounds
  704. return true;
  705. }
  706. return false;
  707. }
  708. static bool IsTestField(Ogre::String& resourceName)
  709. {
  710. if (
  711. resourceName == "startmap" ||
  712. resourceName == "md1stin" ||
  713. resourceName == "md1_1" ||
  714. resourceName == "md1_2" ||
  715. resourceName == "nmkin_1" ||
  716. resourceName == "nmkin_2" ||
  717. resourceName == "nmkin_3" ||
  718. resourceName == "nrthmk" ||
  719. resourceName == "elevtr1" ||
  720. resourceName == "tin_2" ||
  721. resourceName == "md8_4"
  722. )
  723. {
  724. return true;
  725. }
  726. return false;
  727. }
  728. static void CollectFieldScaleFactors(QGears::FLevelFilePtr& field, FieldScaleFactorMap& scaleFactors, const std::vector<std::string>& fieldIdToNameLookup)
  729. {
  730. scaleFactors[FieldId(field->getName(), fieldIdToNameLookup)] = ::SUDM::FF7::Field::ScaleFactor(field->getRawScript());
  731. }
  732. void FF7DataInstaller::ConvertFields(std::string archive, std::string inputDir, std::string outDir)
  733. {
  734. mOutputDir = outDir;
  735. CreateDir(FieldMapDir());
  736. CreateDir(FieldModelDir());
  737. // List whats in the LGP archive
  738. Ogre::StringVectorPtr resources = mApp.ResMgr()->listResourceNames("FFVIIFields", "*");
  739. // Load the map list field
  740. QGears::MapListFilePtr mapList = QGears::MapListFileManager::getSingleton().load("maplist", "FFVIIFields").staticCast<QGears::MapListFile>();
  741. // On the first pass collate required field information
  742. FieldSpawnPointsMap spawnPoints;
  743. FieldScaleFactorMap scaleFactors;
  744. for (auto& resourceName : *resources)
  745. {
  746. // Exclude things that are not fields
  747. if (IsAFieldFile(resourceName) && /*IsTestField(resourceName) &&*/ !WillCrash(resourceName))
  748. {
  749. QGears::FLevelFilePtr field = QGears::LZSFLevelFileManager::getSingleton().load(resourceName, "FFVIIFields").staticCast<QGears::FLevelFile>();
  750. CollectSpawnPoints(field, mapList->GetMapList(), spawnPoints);
  751. CollectFieldScaleFactors(field, scaleFactors, mapList->GetMapList());
  752. }
  753. }
  754. ModelsAndAnimationsDb modelAnimationDb;
  755. MapCollection maps;
  756. // Now we can do the full conversion with the collated data
  757. for (auto& resourceName : *resources)
  758. {
  759. // Exclude things that are not fields
  760. if (IsAFieldFile(resourceName))
  761. {
  762. if (IsTestField(resourceName) &&
  763. !WillCrash(resourceName))
  764. {
  765. std::cout << "Converting: " << resourceName << std::endl;
  766. CreateDir(FieldMapDir() + "/" + resourceName);
  767. QGears::FLevelFilePtr field = QGears::LZSFLevelFileManager::getSingleton().load(resourceName, "FFVIIFields").staticCast<QGears::FLevelFile>();
  768. FF7PcFieldToQGearsField(field, outDir, mapList->GetMapList(), spawnPoints, scaleFactors, modelAnimationDb, maps);
  769. }
  770. else
  771. {
  772. std::cout << "Skip: " << resourceName << " as it has a crash or hang issue" << std::endl;
  773. }
  774. }
  775. }
  776. {
  777. // Write out maps.xml
  778. TiXmlDocument doc;
  779. std::unique_ptr<TiXmlElement> element(new TiXmlElement("maps"));
  780. // TODO: Probably need to inject "empty" and "test" fields
  781. for (const auto& map : maps)
  782. {
  783. std::unique_ptr<TiXmlElement> xmlElement(new TiXmlElement("map"));
  784. xmlElement->SetAttribute("name", FieldName(map));
  785. xmlElement->SetAttribute("file_name", FieldMapDir() + "/" + map + "/map.xml");
  786. element->LinkEndChild(xmlElement.release());
  787. }
  788. doc.LinkEndChild(element.release());
  789. doc.SaveFile(outDir + "/maps.xml");
  790. }
  791. // TODO: Convert models and animations in modelAnimationDb
  792. auto fullPath = inputDir + "field/char.lgp";
  793. mApp.getRoot()->addResourceLocation(fullPath, "LGP", "FFVII");
  794. Ogre::StringVectorPtr resources2 = mApp.ResMgr()->listResourceNames("FFVII", "*");
  795. for (auto& name : modelAnimationDb.mMap)
  796. {
  797. Ogre::ResourcePtr hrc = QGears::HRCFileManager::getSingleton().load(name.first, "FFVII");
  798. Ogre::String baseName;
  799. QGears::StringUtil::splitBase(name.first, baseName);
  800. auto meshName = QGears::FF7::NameLookup::model(baseName) + ".mesh";
  801. Ogre::MeshPtr mesh(Ogre::MeshManager::getSingleton().load(meshName, "FFVII"));
  802. Ogre::SkeletonPtr skeleton(mesh->getSkeleton());
  803. for (auto& anim : name.second)
  804. {
  805. QGears::AFileManager &afl_mgr(QGears::AFileManager::getSingleton());
  806. QGears::AFilePtr a = afl_mgr.load(anim, "FFVII").staticCast<QGears::AFile>();
  807. // Convert the FF7 name to a more readble name set in the meta data
  808. Ogre::String baseName;
  809. QGears::StringUtil::splitBase(anim, baseName);
  810. a->addTo(skeleton, QGears::FF7::NameLookup::animation(baseName));
  811. }
  812. exportMesh(outDir + "/" + FieldModelDir() + "/", mesh);
  813. }
  814. mApp.getRoot()->removeResourceLocation(fullPath, "FFVII");
  815. }