ff7DataInstaller.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  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. QGears::String baseMeshName;
  66. QGears::StringUtil::splitFull(mesh->getName(), baseMeshName);
  67. Ogre::MeshSerializer mesh_ser;
  68. Ogre::SkeletonPtr skeleton(mesh->getSkeleton());
  69. Ogre::SkeletonSerializer sk_ser;
  70. sk_ser.exportSkeleton(skeleton.getPointer(), outdir + baseMeshName + ".skeleton");
  71. mesh->setSkeletonName(FieldModelDir() + "/" + baseMeshName + ".skeleton");
  72. mesh_ser.exportMesh(mesh.getPointer(), outdir + mesh->getName());
  73. Ogre::Mesh::SubMeshIterator it(mesh->getSubMeshIterator());
  74. Ogre::MaterialSerializer mat_ser;
  75. size_t i(0);
  76. std::set<std::string> textures;
  77. while (it.hasMoreElements())
  78. {
  79. Ogre::SubMesh *sub_mesh(it.getNext());
  80. Ogre::MaterialPtr mat(Ogre::MaterialManager::getSingleton().getByName(sub_mesh->getMaterialName()));
  81. if (!mat.isNull())
  82. {
  83. for (size_t techNum = 0; techNum < mat->getNumTechniques(); techNum++)
  84. {
  85. Ogre::Technique* tech = mat->getTechnique(techNum);
  86. if (tech)
  87. {
  88. for (size_t passNum = 0; passNum < tech->getNumPasses(); passNum++)
  89. {
  90. Ogre::Pass* pass = tech->getPass(passNum);
  91. if (pass)
  92. {
  93. for (size_t textureUnitNum = 0; textureUnitNum < pass->getNumTextureUnitStates(); textureUnitNum++)
  94. {
  95. Ogre::TextureUnitState* unit = pass->getTextureUnitState(textureUnitNum);
  96. if (unit)
  97. {
  98. if (unit->getTextureName().empty() == false)
  99. {
  100. // Ensure the output material script references png files rather than tex files
  101. textures.insert(unit->getTextureName());
  102. Ogre::String baseName;
  103. QGears::StringUtil::splitBase(unit->getTextureName(), baseName);
  104. unit->setTextureName(FieldModelDir() + "/" + baseMeshName + "_" + baseName + ".png");
  105. }
  106. }
  107. }
  108. }
  109. }
  110. }
  111. }
  112. mat_ser.queueForExport(mat);
  113. }
  114. ++i;
  115. }
  116. mat_ser.exportQueued(outdir + baseMeshName + 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 + baseMeshName + "_" + 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 mFieldName + "_" + 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", fieldIdToNameLookup.at(spawnPointRecords[i].mFieldId) + "_" + spawnPointRecords[i].mEntityName + "_" + spawnPointRecords[i].mScriptFunctionName + "_addr_" + std::to_string(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. unsigned int triIndex = static_cast<unsigned int>(gateway.destination.z);
  469. if (triIndex >= field->getWalkmesh()->getTriangles().size())
  470. {
  471. std::cout << "WARNING MAP JUMP TRIANGLE OUT OF BOUNDS" << std::endl;
  472. triIndex = 0;
  473. }
  474. const float zOfTriangleWithId = field->getWalkmesh()->getTriangles().at(triIndex).a.z;
  475. const Ogre::Vector3 posVec(gateway.destination.x / downscaler_next, gateway.destination.y / downscaler_next, zOfTriangleWithId);
  476. xmlEntityPoint->SetAttribute("position", Ogre::StringConverter::toString(posVec));
  477. const float rotation = (360.0f * static_cast<float>(gateway.dir)) / 255.0f;
  478. xmlEntityPoint->SetAttribute("rotation", std::to_string(rotation));
  479. element->LinkEndChild(xmlEntityPoint.release());
  480. }
  481. }
  482. doc.LinkEndChild(element.release());
  483. doc.SaveFile(outDir + "/" + FieldMapDir() + "/" + field->getName() + "/map.xml");
  484. const QGears::PaletteFilePtr& pal = field->getPalette();
  485. const QGears::BackgroundFilePtr& bg = field->getBackground();
  486. std::unique_ptr<Ogre::Image> bgImage(bg->createImage(pal));
  487. bgImage->save(outDir + "/" + FieldMapDir() + "/" + field->getName() + "/tiles.png");
  488. {
  489. TiXmlDocument doc;
  490. std::unique_ptr<TiXmlElement> element(new TiXmlElement("background2d"));
  491. // Magic constants
  492. const int kScaleUpFactor = 3;
  493. const int kPsxScreenWidth = 320;
  494. const int kPsxScreenHeight = 240;
  495. // Get texture atlas size
  496. const int width = bgImage->getWidth();
  497. const int height = bgImage->getHeight();
  498. const QGears::CameraMatrixFilePtr& camMatrix = field->getCameraMatrix();
  499. const Ogre::Vector3 position = camMatrix->getPosition() / FieldScaleFactor(scaleFactorMap, thisFieldId);
  500. const Ogre::Quaternion orientation = camMatrix->getOrientation();
  501. const Ogre::Degree fov = camMatrix->getFov(static_cast<float>(kPsxScreenHeight));
  502. const int min_x = triggers->getCameraRange().left * kScaleUpFactor;
  503. const int min_y = triggers->getCameraRange().top * kScaleUpFactor;
  504. const int max_x = triggers->getCameraRange().right * kScaleUpFactor;
  505. const int max_y = triggers->getCameraRange().bottom * kScaleUpFactor;
  506. element->SetAttribute("image", FieldMapDir() + "/" + field->getName() + "/tiles.png");
  507. element->SetAttribute("position", Ogre::StringConverter::toString(position));
  508. element->SetAttribute("orientation", Ogre::StringConverter::toString(orientation));
  509. element->SetAttribute("fov", Ogre::StringConverter::toString(fov));
  510. element->SetAttribute("range", std::to_string(min_x) + " " + std::to_string(min_y) + " " + std::to_string(max_x) + " " + std::to_string(max_y));
  511. element->SetAttribute("clip", std::to_string(kPsxScreenWidth * kScaleUpFactor) + " " + std::to_string(kPsxScreenHeight * kScaleUpFactor));
  512. // Write out the *_BG.XML data
  513. auto& layers = bg->getLayers();
  514. for (const auto& layer : layers)
  515. {
  516. // TODO: Should we only output tiles to construct enabled layers?
  517. // if (layer.enabled)
  518. {
  519. for (const QGears::BackgroundFile::SpriteData& sprite : layer.sprites)
  520. {
  521. std::unique_ptr<TiXmlElement> xmlElement(new TiXmlElement("tile"));
  522. xmlElement->SetAttribute("destination",
  523. Ogre::StringConverter::toString(sprite.dst.x * kScaleUpFactor) + " " +
  524. Ogre::StringConverter::toString(sprite.dst.y * kScaleUpFactor));
  525. xmlElement->SetAttribute("width", Ogre::StringConverter::toString(sprite.width * kScaleUpFactor));
  526. xmlElement->SetAttribute("height", Ogre::StringConverter::toString(sprite.height * kScaleUpFactor));
  527. // 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
  528. const float u0 = static_cast<float>(sprite.src.x) / bgImage->getWidth();
  529. const float v0 = static_cast<float>(sprite.src.y) / bgImage->getHeight();
  530. const float u1 = static_cast<float>(sprite.src.x + sprite.width) / bgImage->getWidth();
  531. const float v1 = static_cast<float>(sprite.src.y + sprite.height) / bgImage->getHeight();
  532. xmlElement->SetAttribute("uv",
  533. Ogre::StringConverter::toString(u0) + " " + Ogre::StringConverter::toString(v0) + " " +
  534. Ogre::StringConverter::toString(u1) + " " + Ogre::StringConverter::toString(v1)
  535. );
  536. // TODO: Figure out how to scale this value correctly
  537. xmlElement->SetAttribute("depth", "999" /* Ogre::StringConverter::toString(static_cast<float>(sprite.depth) / (4096.0f/10.0f))*/);
  538. // TODO: Copied from DatFile::AddTile - add to common method
  539. Ogre::String blending_str = "";
  540. if (sprite.blending == 0)
  541. {
  542. blending_str = "alpha";
  543. }
  544. else if (sprite.blending == 1 || sprite.blending == 3) // 3 is source + 0.25 * destination
  545. {
  546. blending_str = "add";
  547. }
  548. else if (sprite.blending == 2)
  549. {
  550. blending_str = "subtract";
  551. }
  552. else
  553. {
  554. // TODO: Should probably throw to fail conversion
  555. blending_str = "unknown";
  556. }
  557. xmlElement->SetAttribute("blending", blending_str);
  558. element->LinkEndChild(xmlElement.release());
  559. }
  560. }
  561. }
  562. doc.LinkEndChild(element.release());
  563. doc.SaveFile(outDir + "/" + FieldMapDir() + "/" + field->getName() + "/bg.xml");
  564. }
  565. }
  566. {
  567. // Save out the walk mesh as XML
  568. const QGears::WalkmeshFilePtr& walkmesh = field->getWalkmesh();
  569. TiXmlDocument doc;
  570. std::unique_ptr<TiXmlElement> element(new TiXmlElement("walkmesh"));
  571. for (QGears::WalkmeshFile::Triangle& tri : walkmesh->getTriangles())
  572. {
  573. std::unique_ptr<TiXmlElement> xmlElement(new TiXmlElement("triangle"));
  574. xmlElement->SetAttribute("a", Ogre::StringConverter::toString(tri.a));
  575. xmlElement->SetAttribute("b", Ogre::StringConverter::toString(tri.b));
  576. xmlElement->SetAttribute("c", Ogre::StringConverter::toString(tri.c));
  577. xmlElement->SetAttribute("a_b", std::to_string(tri.access_side[0]));
  578. xmlElement->SetAttribute("b_c", std::to_string(tri.access_side[1]));
  579. xmlElement->SetAttribute("c_a", std::to_string(tri.access_side[2]));
  580. element->LinkEndChild(xmlElement.release());
  581. }
  582. doc.LinkEndChild(element.release());
  583. doc.SaveFile(outDir + "/" + FieldMapDir() + "/" + field->getName() + "/wm.xml");
  584. }
  585. maps.insert(field->getName());
  586. }
  587. class FF7FieldScriptGatewayCollector : public BaseFF7FieldScriptFormatter
  588. {
  589. public:
  590. FF7FieldScriptGatewayCollector(const std::string& fieldName, const std::vector<std::string>& fieldIdToNameLookup, FieldSpawnPointsMap& spawnPoints, size_t thisFieldId)
  591. : BaseFF7FieldScriptFormatter(fieldName, fieldIdToNameLookup, spawnPoints), mThisFieldId(thisFieldId)
  592. {
  593. }
  594. 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
  595. {
  596. auto it = mSpawnPoints.find(targetMapId);
  597. QGears::TriggersFile::Gateway gw = {};
  598. gw.destinationFieldId = targetMapId;
  599. gw.destination.x = x;
  600. gw.destination.y = y;
  601. gw.destination.z = z;
  602. gw.dir = angle;
  603. if (it != std::end(mSpawnPoints))
  604. {
  605. // Add to the list of gateways that link to destinationFieldId
  606. SpawnPointDb::Record rec;
  607. rec.mFromScript = true;
  608. rec.mFieldId = mThisFieldId;
  609. rec.mGateway = gw;
  610. rec.mEntityName = entity;
  611. rec.mScriptFunctionName = funcName;
  612. rec.GatewayIndexOrMapJumpAddress = address;
  613. it->second.mGatewaysToThisField.push_back(rec);
  614. }
  615. else
  616. {
  617. // Create a new record for destinationFieldId
  618. SpawnPointDb db;
  619. db.mTargetFieldId = targetMapId;
  620. SpawnPointDb::Record rec;
  621. rec.mFromScript = true;
  622. rec.mFieldId = mThisFieldId;
  623. rec.mGateway = gw;
  624. rec.mEntityName = entity;
  625. rec.mScriptFunctionName = funcName;
  626. rec.GatewayIndexOrMapJumpAddress = address;
  627. db.mGatewaysToThisField.push_back(rec);
  628. mSpawnPoints.insert(std::make_pair(db.mTargetFieldId, db));
  629. }
  630. }
  631. private:
  632. size_t mThisFieldId;
  633. };
  634. static void CollectSpawnPoints(QGears::FLevelFilePtr& field, const std::vector<std::string>& fieldIdToNameLookup, FieldSpawnPointsMap& spawnPoints)
  635. {
  636. const size_t thisFieldId = FieldId(field->getName(), fieldIdToNameLookup);
  637. // Decompile the script just so we can collect up the MAPJUMP's we need this to construct the full list of entries
  638. // to each field
  639. try
  640. {
  641. // Get the raw script bytes
  642. SUDM::FF7::Field::DecompiledScript decompiled;
  643. const std::vector<u8> rawFieldData = field->getRawScript();
  644. // Decompile to LUA
  645. FF7FieldScriptGatewayCollector formatter(field->getName(), fieldIdToNameLookup, spawnPoints, thisFieldId);
  646. decompiled = SUDM::FF7::Field::Decompile(field->getName(), rawFieldData, formatter, "", "EntityContainer = {}\n\n");
  647. }
  648. catch (const ::InternalDecompilerError& ex)
  649. {
  650. std::cerr << "InternalDecompilerError: " << ex.what() << std::endl;
  651. }
  652. const QGears::TriggersFilePtr& triggers = field->getTriggers();
  653. const auto& gateways = triggers->GetGateways();
  654. for (size_t i = 0; i < gateways.size(); i++)
  655. {
  656. const QGears::TriggersFile::Gateway& gateway = gateways[i];
  657. if (gateway.destinationFieldId != kInactiveGateWayId)
  658. {
  659. auto it = spawnPoints.find(gateway.destinationFieldId);
  660. if (it != std::end(spawnPoints))
  661. {
  662. // Add to the list of gateways that link to destinationFieldId
  663. SpawnPointDb::Record rec;
  664. rec.mFieldId = thisFieldId;
  665. rec.mGateway = gateway;
  666. rec.GatewayIndexOrMapJumpAddress = i;
  667. it->second.mGatewaysToThisField.push_back(rec);
  668. }
  669. else
  670. {
  671. // Create a new record for destinationFieldId
  672. SpawnPointDb db;
  673. db.mTargetFieldId = gateway.destinationFieldId;
  674. SpawnPointDb::Record rec;
  675. rec.mFieldId = thisFieldId;
  676. rec.mGateway = gateway;
  677. rec.GatewayIndexOrMapJumpAddress = i;
  678. db.mGatewaysToThisField.push_back(rec);
  679. spawnPoints.insert(std::make_pair(db.mTargetFieldId, db));
  680. }
  681. }
  682. }
  683. }
  684. static bool IsAFieldFile(Ogre::String& resourceName)
  685. {
  686. return (!QGears::StringUtil::endsWith(resourceName, ".tex")
  687. && !QGears::StringUtil::endsWith(resourceName, ".tut")
  688. && !QGears::StringUtil::endsWith(resourceName, ".siz")
  689. && resourceName != "maplist");
  690. }
  691. // Exclude fields which cause fatal crash bugs :)
  692. // this can be removed when whatever is causing the crash(s) is fixed
  693. static bool WillCrash(Ogre::String& resourceName)
  694. {
  695. if (
  696. // crashes in back ground image generation
  697. resourceName == "bugin1a" ||
  698. // Hangs in decompliation
  699. resourceName == "frcyo" ||
  700. // bg image crash
  701. resourceName == "fr_e" ||
  702. resourceName == "las4_2" ||
  703. resourceName == "las4_3" ||
  704. resourceName == "lastmap" ||
  705. resourceName == "md_e1" ||
  706. resourceName == "trnad_3"
  707. )
  708. {
  709. // NOTE: Even so, conversion of all models will fail with a bone index out of bounds
  710. return true;
  711. }
  712. return false;
  713. }
  714. static bool IsTestField(Ogre::String& resourceName)
  715. {
  716. if (
  717. resourceName == "startmap" ||
  718. resourceName == "md1stin" ||
  719. resourceName == "md1_1" ||
  720. resourceName == "md1_2" ||
  721. resourceName == "md8_1" ||
  722. resourceName == "nmkin_1" ||
  723. resourceName == "nmkin_2" ||
  724. resourceName == "nmkin_3" ||
  725. resourceName == "nrthmk" ||
  726. resourceName == "elevtr1" ||
  727. resourceName == "tin_1" ||
  728. resourceName == "tin_2" ||
  729. resourceName == "rootmap" ||
  730. resourceName == "md8_4"
  731. )
  732. {
  733. return true;
  734. }
  735. return false;
  736. }
  737. static void CollectFieldScaleFactors(QGears::FLevelFilePtr& field, FieldScaleFactorMap& scaleFactors, const std::vector<std::string>& fieldIdToNameLookup)
  738. {
  739. scaleFactors[FieldId(field->getName(), fieldIdToNameLookup)] = ::SUDM::FF7::Field::ScaleFactor(field->getRawScript());
  740. }
  741. void FF7DataInstaller::ConvertFields(std::string archive, std::string inputDir, std::string outDir)
  742. {
  743. mOutputDir = outDir;
  744. CreateDir(FieldMapDir());
  745. CreateDir(FieldModelDir());
  746. // List whats in the LGP archive
  747. Ogre::StringVectorPtr resources = mApp.ResMgr()->listResourceNames("FFVIIFields", "*");
  748. // Load the map list field
  749. QGears::MapListFilePtr mapList = QGears::MapListFileManager::getSingleton().load("maplist", "FFVIIFields").staticCast<QGears::MapListFile>();
  750. // On the first pass collate required field information
  751. FieldSpawnPointsMap spawnPoints;
  752. FieldScaleFactorMap scaleFactors;
  753. for (auto& resourceName : *resources)
  754. {
  755. // Exclude things that are not fields
  756. if (IsAFieldFile(resourceName) && /*IsTestField(resourceName) &&*/ !WillCrash(resourceName))
  757. {
  758. QGears::FLevelFilePtr field = QGears::LZSFLevelFileManager::getSingleton().load(resourceName, "FFVIIFields").staticCast<QGears::FLevelFile>();
  759. CollectSpawnPoints(field, mapList->GetMapList(), spawnPoints);
  760. CollectFieldScaleFactors(field, scaleFactors, mapList->GetMapList());
  761. }
  762. }
  763. ModelsAndAnimationsDb modelAnimationDb;
  764. MapCollection maps;
  765. // Now we can do the full conversion with the collated data
  766. for (auto& resourceName : *resources)
  767. {
  768. // Exclude things that are not fields
  769. if (IsAFieldFile(resourceName))
  770. {
  771. if (IsTestField(resourceName) &&
  772. !WillCrash(resourceName))
  773. {
  774. std::cout << "Converting: " << resourceName << std::endl;
  775. CreateDir(FieldMapDir() + "/" + resourceName);
  776. QGears::FLevelFilePtr field = QGears::LZSFLevelFileManager::getSingleton().load(resourceName, "FFVIIFields").staticCast<QGears::FLevelFile>();
  777. FF7PcFieldToQGearsField(field, outDir, mapList->GetMapList(), spawnPoints, scaleFactors, modelAnimationDb, maps);
  778. }
  779. else
  780. {
  781. std::cout << "Skip: " << resourceName << " as it has a crash or hang issue" << std::endl;
  782. }
  783. }
  784. }
  785. {
  786. // Write out maps.xml
  787. TiXmlDocument doc;
  788. std::unique_ptr<TiXmlElement> element(new TiXmlElement("maps"));
  789. // TODO: Probably need to inject "empty" and "test" fields
  790. for (const auto& map : maps)
  791. {
  792. std::unique_ptr<TiXmlElement> xmlElement(new TiXmlElement("map"));
  793. xmlElement->SetAttribute("name", FieldName(map));
  794. xmlElement->SetAttribute("file_name", FieldMapDir() + "/" + map + "/map.xml");
  795. element->LinkEndChild(xmlElement.release());
  796. }
  797. doc.LinkEndChild(element.release());
  798. doc.SaveFile(outDir + "/maps.xml");
  799. }
  800. // TODO: Convert models and animations in modelAnimationDb
  801. auto fullPath = inputDir + "field/char.lgp";
  802. mApp.getRoot()->addResourceLocation(fullPath, "LGP", "FFVII");
  803. Ogre::StringVectorPtr resources2 = mApp.ResMgr()->listResourceNames("FFVII", "*");
  804. for (auto& name : modelAnimationDb.mMap)
  805. {
  806. Ogre::ResourcePtr hrc = QGears::HRCFileManager::getSingleton().load(name.first, "FFVII");
  807. Ogre::String baseName;
  808. QGears::StringUtil::splitBase(name.first, baseName);
  809. auto meshName = QGears::FF7::NameLookup::model(baseName) + ".mesh";
  810. Ogre::MeshPtr mesh(Ogre::MeshManager::getSingleton().load(meshName, "FFVII"));
  811. Ogre::SkeletonPtr skeleton(mesh->getSkeleton());
  812. for (auto& anim : name.second)
  813. {
  814. QGears::AFileManager &afl_mgr(QGears::AFileManager::getSingleton());
  815. QGears::AFilePtr a = afl_mgr.load(anim, "FFVII").staticCast<QGears::AFile>();
  816. // Convert the FF7 name to a more readable name set in the meta data
  817. Ogre::String baseName;
  818. QGears::StringUtil::splitBase(anim, baseName);
  819. a->addTo(skeleton, QGears::FF7::NameLookup::animation(baseName));
  820. }
  821. exportMesh(outDir + "/" + FieldModelDir() + "/", mesh);
  822. }
  823. mApp.getRoot()->removeResourceLocation(fullPath, "FFVII");
  824. }