gameres.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. #include "gameres.h"
  2. #include "aconfig.h"
  3. #include "filesystem.h"
  4. #include <QString>
  5. #include <QDir>
  6. #include <QFile>
  7. #include <QTime>
  8. #include <string>
  9. GameRes::GameRes() {}
  10. GameRes::GameRes(const GameRes&) {}
  11. GameRes& GameRes::operator=(GameRes&) {}
  12. // Public functions
  13. void GameRes::openDatFile(int id) {
  14. QStringList dat_files;
  15. dat_files << AConfig::getInstance()->getValue("Local", "file")
  16. << "client_general.dat"
  17. << "client_sound.dat"
  18. << "client_surface.dat"
  19. << "client_highres.dat";
  20. if (dat_files[id] == nullptr) {
  21. emit openDatFileFinished(-100); // -100 = incorrect id
  22. return;
  23. }
  24. std::string filename = (app->config->getValue("Local", "folder") + "/" + dat_files[id]).toStdString();
  25. qDebug("%s:%i: %s%s", __FILE__, __LINE__, "Инициализация dat-файла. Открываем файл ", filename);
  26. int dat_state = app->datfiles[id].InitDatFile(file, 0);
  27. qDebug("%s:%i: %s%d", __FILE__, __LINE__, "Состояние dat-файла: ", dat_state);
  28. emit openDatFileFinished(dat_state);
  29. }
  30. void GameRes::closeDatFile(int id) {
  31. int result = datfiles[id].CloseDatFile();
  32. emit closeDatFileFinished(result);
  33. return;
  34. }
  35. void GameRes::applyPatch(QString name) {
  36. emit startedPatching(name);
  37. qDebug("%s:%i: %s%s", __FILE__, __LINE__, "Начинаем применение патча ", app->helper->stringToChar(name));
  38. QLabel* label = app->window->findChild<QLabel*>(name + "Status");
  39. QDir dir(QApplication::applicationDirPath() + "/data");
  40. if (!dir.exists()) {
  41. emit applyAllFinished(-100); // -100 - not found data folder
  42. return;
  43. }
  44. QStringList paths = dir.entryList(QStringList(name + "*"));
  45. qDebug() << ("data/" + paths.first()).toStdString();
  46. if(!paths.empty()) {
  47. db_.InitDatabase(("data/" + paths.first()).toStdString());
  48. int indb = db_.CountRows();
  49. qInfo("%s:%i: %s%d", __FILE__, __LINE__, "Файлов в обновлении: ", indb);
  50. int percent = -1;
  51. for (int i = 0; i <= indb; i++) {
  52. if (i * 100 / indb > percent) {
  53. percent = i * 100 / indb;
  54. qInfo("%s:%i: %s%d%s", __FILE__, __LINE__, "Применение обновления: ", percent, "%");
  55. emit updatedPatchPercent(percent);
  56. }
  57. processFile();
  58. }
  59. AConfig::getInstance()->setValue("Applied", name, paths.first());
  60. db_.CloseDatabase();
  61. }
  62. emit applyPatchFinished(0);
  63. }
  64. void GameRes::setGameLocale(QString locale) {
  65. openDatFile(0);
  66. locale_ = app->datfiles[0].current_locale();
  67. if(locale_ == PATCHED) qDebug() << "Starting " + locale + " version. Current locale is PATCHED";
  68. if(locale_ == ORIGINAL) qDebug() << "Starting " + locale + " version. Current locale is ORIGINAL";
  69. if(locale_ != ORIGINAL && loc != PATCHED) qDebug() << "Starting " + locale + " version. Current locale is UNKNOWN";
  70. if(locale == "RU" && loc != PATCHED) {qDebug()<< "Current locale Original"; app->datfiles[0].SetLocale(PATCHED); dat_locale = PATCHED;}
  71. if(locale == "Original" && loc != ORIGINAL) {qDebug()<< "Current locale RU"; app->datfiles[0].SetLocale(ORIGINAL); dat_locale = ORIGINAL;}
  72. closeDatFile(0);
  73. emit setGameLocaleFinished(0);
  74. }
  75. void GameRes::startGame() {
  76. AConfig::getInstance()->saveAllDatFiles();
  77. QStringList args;
  78. args << "-skiprawdownload" << "-nosplash";
  79. if (locale_ == PATCHED)
  80. args << "-disablePatch";
  81. QFile f(app->config->getValue("Local", "folder") + "/TurbineLauncher.exe");
  82. QProcess process;
  83. if(fileExists(f.fileName())){
  84. if (f.fileName().contains(" "))
  85. f.setFileName("\"" + f.fileName() + "\"");
  86. process.startDetached(f.fileName(), args);
  87. process.waitForFinished(-1);
  88. process.deleteLater();
  89. QApplication::quit();
  90. emit startGameFinished(0);
  91. } else {
  92. //QString text = "Запуск не удался";
  93. //QString info = "Не удалось запустить игру. Во время запуска произшла непредвиденная ошибка (возможно, не найден файл TurbineLauncher.exe в папке с игрой. Проверьте в 'Настройках', что у вас указан верный путь к игре, и повторите попытку запуска).";
  94. //app->helper->myDialogBox(text, info, "OK", "Отмена", "gandalf.png", "", "", 400, 160, true, false);
  95. emit startGameFinished(-100);
  96. }
  97. }
  98. void GameRes::installMicroPatch() {
  99. prepareMicroPatch();
  100. applyMicroPatch();
  101. QDir dir("/data/micro");
  102. FileSystem::clearFolder(dir);
  103. emit installMicroPatchFinished(0);
  104. }
  105. void GameRes::applyAll() {
  106. // Применяем патч с заставочными экранами
  107. if(AConfig::getInstance()->getValue("Editor", "screens") == "true") {
  108. applyLoadscreens();
  109. }
  110. // Применяем остальные патчи
  111. QStringList names;
  112. names << "fonts" << "sounds" << "texts" << "images" << "videos" << "textures";
  113. QDir dir(QApplication::applicationDirPath() + "/data");
  114. QStringList need;
  115. foreach(QString name, names){
  116. QStringList list = dir.entryList(QStringList(name + "*"));
  117. if(list.size() > 0 && list.first() != ""){
  118. QString isset = app->config->getValue("Applied", name);
  119. if(list.first() != isset && app->config->getValue("Editor", name) == "true") {
  120. need.append(name);
  121. }
  122. }
  123. }
  124. if(need.size() > 0){
  125. openDatFile(0);
  126. foreach(QString name, need) {
  127. applyPatch(name);
  128. }
  129. }
  130. if(app->config->getValue("Updates", "micro") == "true")
  131. installMicroPatch();
  132. emit applyAllFinished(0);
  133. }
  134. void GameRes::checkDatFile() {
  135. openDatFile(0);
  136. if(datfiles_[0].CheckIfUpdatedByGame()){
  137. emit checkDatFileFinished(1);
  138. return;
  139. }
  140. if(datfiles_[0].CheckIfNotPatched() && AConfig::getInstance()->getValue("Local", "runfirst") == "1"){
  141. emit checkDatFileFinished(2);
  142. return;
  143. }
  144. if(datfiles_[0].CheckIfPatchedByOldLauncher()){
  145. emit checkDatFileFinished(3);
  146. return;
  147. }
  148. }
  149. QStringList GameRes::getLotroPath(){
  150. App *app = &App::getInstance();
  151. QStringList paths;
  152. //#if defined(Q_WS_WIN)
  153. // Windows 7
  154. QSettings m("HKEY_CLASSES_ROOT\\Local Settings\\Software\\Microsoft\\Windows\\Shell\\MuiCache", QSettings::NativeFormat);
  155. foreach (QString key, m.allKeys()) {
  156. if(key.contains("TurbineLauncher.exe") && app->helper->fileExists(key)){
  157. paths.append(key.replace("/TurbineLauncher.exe", ""));
  158. }
  159. }
  160. // Windows 8, 10
  161. QSettings n("HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\12bbe590-c890-11d9-9669-0800200c9a66_is1", QSettings::NativeFormat);
  162. foreach (QString key, n.allKeys()) {
  163. qDebug() << key;
  164. if(key.contains("InstallLocation") || key.contains("installlocation")){
  165. QString folder = n.value(key).toString().replace("\\", "/").replace("/TurbineLauncher.exe", "").replace("\"", "");
  166. if(app->helper->fileExists(folder + "/TurbineLauncher.exe")) paths.append(folder);
  167. }
  168. }
  169. //#else
  170. // Реализация под Linux
  171. //#endif
  172. return paths;
  173. }
  174. // Private functions
  175. void GameRes::processFile() {
  176. SubfileData subfile;
  177. subfile = app->db->GetNextFile();
  178. if (subfile.Empty()){
  179. qInfo("%s:%i: %s", __FILE__, __LINE__, "Достигнут конец файла.");
  180. } else {
  181. int dat_id = subfile.options["did"].as<int>();
  182. int dat_state = datfiles_[dat_id].InitDatFile(getDatPath(dat_id), dat_id);
  183. if(dat_state > 0)
  184. datfiles_[dat_id].PatchFile(subfile);
  185. }
  186. }
  187. void GameRes::prepareMicroPatch() {
  188. QString date = AConfig::getInstance()->getValue("Updates", "update");
  189. if(date == "false")
  190. date = QDate::currentDate().toString("yyyy-MM-dd");
  191. QTime time = QTime::currentTime();
  192. int seconds = QTime(0, 0, 0).secsTo(time);
  193. int timestamp = app->helper->dateToTimestamp(date + " " + time.toString("hh:mm:ss"), "yyyy-MM-dd hh:mm:ss") - 2592000;
  194. qInfo("%s:%i: %s", __FILE__, __LINE__, "Опция активна. Начинаем загрузку обновлений");
  195. app->network->micropatch = QApplication::applicationDirPath() + "/data/micro/" + QString::number(timestamp + seconds) + ".db";
  196. if(!app->helper->fileExists(app->network->micropatch)){
  197. qInfo("%s:%i: %s%s", __FILE__, __LINE__, "Файл патча: ", app->helper->stringToChar(app->network->micropatch));
  198. app->network->micropatch = app->network->getMicroPath(timestamp);
  199. }
  200. qInfo("%s:%i: %s", __FILE__, __LINE__, "Выполнено.");
  201. }
  202. void GameRes::applyMicroPatch() {
  203. emit startedPatching(" новые переводы");
  204. db_.InitDatabase(app->helper->stringToChar(app->network->micropatch));
  205. qInfo("%s:%i: %s%d", __FILE__, __LINE__, "Файлов в обновлении: ", indb);
  206. int indb = app->db->CountRows();
  207. int percent = -1;
  208. for(int i = 0; i <= indb; i++) {
  209. if (i * 100 / indb > percent) {
  210. percent = i * 100 / indb;
  211. qInfo("%s:%i: %s%d%s", __FILE__, __LINE__, "Применение обновления: ", percent, "%");
  212. emit updatedPatchPercent(percent);
  213. }
  214. processFile();
  215. }
  216. db_.CloseDatabase();
  217. qInfo("%s:%i: %s", __FILE__, __LINE__, "Выполнено.");
  218. }
  219. void GameRes::applyLoadscreens() {
  220. QString datafolder = QApplication::applicationDirPath() + "/data";
  221. QDir dir(datafolder);
  222. if (!dir.exists())
  223. return;
  224. QStringList paths = dir.entryList(QStringList("loadscreens*"));
  225. if(!paths.empty()){
  226. if(paths.first() == AConfig::getInstance()->getValue("Applied", "screens")){
  227. return;
  228. }
  229. QString lang = AConfig::getInstance()->getValue("Local", "lang");
  230. QString folder = AConfig::getInstance()->getValue("Local", "folder") + "/raw/" + lang + "/logo/";
  231. SubfileData subfile;
  232. QStringList filenames;
  233. QString mainscreen = (lang == "en" ? "lotro_ad_pregame.jpg" : "lotro_ad_pregame_" + lang + ".jpg");
  234. filenames << mainscreen << "lotro_generic_teleport_screen_01.jpg" << "lotro_generic_teleport_screen_02.jpg"
  235. << "lotro_generic_teleport_screen_03.jpg" << "lotro_generic_teleport_screen_04.jpg" << "lotro_generic_teleport_screen_05.jpg"
  236. << "lotro_generic_teleport_screen_06.jpg" << "lotro_generic_teleport_screen_07.jpg" << "lotro_generic_teleport_screen_08.jpg"
  237. << "lotro_generic_teleport_screen_09.jpg" << "lotro_generic_teleport_screen_10.jpg";
  238. QString basename = datafolder + "/" + paths.first();
  239. db_.InitDatabase(basename.toStdString());
  240. int indb = db_.CountRows();
  241. qInfo("%s:%i: %s%d", __FILE__, __LINE__, "Файлы загрузочных экранов: ", indb);
  242. for (int i = 0; i < indb; i++) {
  243. subfile = db_.GetNextFile();
  244. qDebug() << i;
  245. if (!subfile.Empty()){
  246. qInfo("%s:%i: %s", __FILE__, __LINE__, (folder + filenames[i]).toStdString().c_str());
  247. QFile::remove(folder + filenames[i]);
  248. subfile.binary_data.WriteToFile((folder + filenames[i]).toStdString());
  249. }
  250. }
  251. db_.CloseDatabase();
  252. }
  253. qInfo("%s:%i: %s", __FILE__, __LINE__, "Выполнено.");
  254. }
  255. bool GameRes::isDatReady() { // Checks if file is ready to write data
  256. bool free = false;
  257. QString dir = AConfig::getInstance()->getValue("Local", "folder");
  258. QString file = AConfig::getInstance()->getValue("Local", "file");
  259. QFile fl(dir+"/" + file);
  260. qDebug() << fl.fileName();
  261. if(FileSystem::fileExists(fl.fileName())){
  262. QDir game_dir(dir);
  263. free = game_dir.rename(fl.fileName(), fl.fileName() + "99");
  264. game_dir.rename(fl.fileName() + "99", fl.fileName());
  265. } else {
  266. free = false;
  267. }
  268. if (free == true)
  269. qDebug() << "Dat is FREE"; else qDebug() << "Dat is BUSY";
  270. return free;
  271. }
  272. std::string GameRes::getDatPath(int id){
  273. App *app = &App::getInstance();
  274. QStringList dats;
  275. dats << app->config->getValue("Local", "file") << "client_general.dat" << "client_sound.dat" << "client_surface.dat" << "client_highres.dat";
  276. //std::string file = (app->config->getValue("Local", "folder") + "/" + dats.at(id)).toStdString();
  277. return app->helper->stringToChar(app->config->getValue("Local", "folder") + "/" + dats.at(id));
  278. }