Ei kuvausta

project.cpp 61KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613
  1. #include "asm.h"
  2. #include "project.h"
  3. #include "tile.h"
  4. #include "tileset.h"
  5. #include "metatile.h"
  6. #include "event.h"
  7. #include <QDebug>
  8. #include <QDir>
  9. #include <QFile>
  10. #include <QTextStream>
  11. #include <QStandardItem>
  12. #include <QMessageBox>
  13. #include <QRegularExpression>
  14. Project::Project()
  15. {
  16. groupNames = new QStringList;
  17. map_groups = new QMap<QString, int>;
  18. groupedMapNames = new QList<QStringList*>;
  19. mapNames = new QStringList;
  20. map_cache = new QMap<QString, Map*>;
  21. mapConstantsToMapNames = new QMap<QString, QString>;
  22. mapNamesToMapConstants = new QMap<QString, QString>;
  23. mapAttributesTable = new QMap<int, QString>;
  24. mapAttributes = new QMap<QString, QMap<QString, QString>*>;
  25. tileset_cache = new QMap<QString, Tileset*>;
  26. }
  27. QString Project::getProjectTitle() {
  28. if (!root.isNull()) {
  29. return root.section('/', -1);
  30. } else {
  31. return QString();
  32. }
  33. }
  34. Map* Project::loadMap(QString map_name) {
  35. // New maps are saved to actual files yet, so we need to fetch their data from the map_cache.
  36. Map *map;
  37. if (map_cache->contains(map_name) && !map_cache->value(map_name)->isPersistedToFile) {
  38. map = map_cache->value(map_name);
  39. } else {
  40. map = new Map;
  41. map->setName(map_name);
  42. }
  43. readMapHeader(map);
  44. readMapAttributes(map);
  45. getTilesets(map);
  46. loadBlockdata(map);
  47. loadMapBorder(map);
  48. readMapEvents(map);
  49. loadMapConnections(map);
  50. map->commit();
  51. map->history.save();
  52. map_cache->insert(map_name, map);
  53. return map;
  54. }
  55. void Project::loadMapConnections(Map *map) {
  56. if (!map->isPersistedToFile) {
  57. return;
  58. }
  59. map->connections.clear();
  60. if (!map->connections_label.isNull()) {
  61. QString path = root + QString("/data/maps/%1/connections.inc").arg(map->name);
  62. QString text = readTextFile(path);
  63. if (!text.isNull()) {
  64. QList<QStringList> *commands = parse(text);
  65. QStringList *list = getLabelValues(commands, map->connections_label);
  66. //// Avoid using this value. It ought to be generated instead.
  67. //int num_connections = list->value(0).toInt(nullptr, 0);
  68. QString connections_list_label = list->value(1);
  69. QList<QStringList> *connections = getLabelMacros(commands, connections_list_label);
  70. for (QStringList command : *connections) {
  71. QString macro = command.value(0);
  72. if (macro == "connection") {
  73. Connection *connection = new Connection;
  74. connection->direction = command.value(1);
  75. connection->offset = command.value(2);
  76. QString mapConstant = command.value(3);
  77. if (mapConstantsToMapNames->contains(mapConstant)) {
  78. connection->map_name = mapConstantsToMapNames->value(mapConstant);
  79. map->connections.append(connection);
  80. } else {
  81. qDebug() << QString("Failed to find connected map for map constant '%1'").arg(mapConstant);
  82. }
  83. }
  84. }
  85. }
  86. }
  87. }
  88. void Project::setNewMapConnections(Map *map) {
  89. map->connections.clear();
  90. }
  91. QList<QStringList>* Project::getLabelMacros(QList<QStringList> *list, QString label) {
  92. bool in_label = false;
  93. QList<QStringList> *new_list = new QList<QStringList>;
  94. for (int i = 0; i < list->length(); i++) {
  95. QStringList params = list->value(i);
  96. QString macro = params.value(0);
  97. if (macro == ".label") {
  98. if (params.value(1) == label) {
  99. in_label = true;
  100. } else if (in_label) {
  101. // If nothing has been read yet, assume the label
  102. // we're looking for is in a stack of labels.
  103. if (new_list->length() > 0) {
  104. break;
  105. }
  106. }
  107. } else if (in_label) {
  108. new_list->append(params);
  109. }
  110. }
  111. return new_list;
  112. }
  113. // For if you don't care about filtering by macro,
  114. // and just want all values associated with some label.
  115. QStringList* Project::getLabelValues(QList<QStringList> *list, QString label) {
  116. list = getLabelMacros(list, label);
  117. QStringList *values = new QStringList;
  118. for (int i = 0; i < list->length(); i++) {
  119. QStringList params = list->value(i);
  120. QString macro = params.value(0);
  121. // Ignore .align
  122. if (macro == ".align") {
  123. continue;
  124. }
  125. for (int j = 1; j < params.length(); j++) {
  126. values->append(params.value(j));
  127. }
  128. }
  129. return values;
  130. }
  131. void Project::readMapHeader(Map* map) {
  132. if (!map->isPersistedToFile) {
  133. return;
  134. }
  135. QString label = map->name;
  136. Asm *parser = new Asm;
  137. QString header_text = readTextFile(root + "/data/maps/" + label + "/header.inc");
  138. if (header_text.isNull()) {
  139. return;
  140. }
  141. QStringList *header = getLabelValues(parser->parse(header_text), label);
  142. map->attributes_label = header->value(0);
  143. map->events_label = header->value(1);
  144. map->scripts_label = header->value(2);
  145. map->connections_label = header->value(3);
  146. map->song = header->value(4);
  147. map->index = header->value(5);
  148. map->location = header->value(6);
  149. map->visibility = header->value(7);
  150. map->weather = header->value(8);
  151. map->type = header->value(9);
  152. map->unknown = header->value(10);
  153. map->show_location = header->value(11);
  154. map->battle_scene = header->value(12);
  155. }
  156. void Project::setNewMapHeader(Map* map, int mapIndex) {
  157. map->attributes_label = QString("%1_MapAttributes").arg(map->name);
  158. map->events_label = QString("%1_MapEvents").arg(map->name);;
  159. map->scripts_label = QString("%1_MapScripts").arg(map->name);;
  160. map->connections_label = "0x0";
  161. map->song = "BGM_DAN02";
  162. map->index = QString("%1").arg(mapIndex);
  163. map->location = "0";
  164. map->visibility = "0";
  165. map->weather = "2";
  166. map->type = "1";
  167. map->unknown = "0";
  168. map->show_location = "1";
  169. map->battle_scene = "0";
  170. }
  171. void Project::saveMapHeader(Map *map) {
  172. QString label = map->name;
  173. QString header_path = root + "/data/maps/" + label + "/header.inc";
  174. QString text = "";
  175. text += QString("%1::\n").arg(label);
  176. text += QString("\t.4byte %1\n").arg(map->attributes_label);
  177. text += QString("\t.4byte %1\n").arg(map->events_label);
  178. text += QString("\t.4byte %1\n").arg(map->scripts_label);
  179. text += QString("\t.4byte %1\n").arg(map->connections_label);
  180. text += QString("\t.2byte %1\n").arg(map->song);
  181. text += QString("\t.2byte %1\n").arg(map->index);
  182. text += QString("\t.byte %1\n").arg(map->location);
  183. text += QString("\t.byte %1\n").arg(map->visibility);
  184. text += QString("\t.byte %1\n").arg(map->weather);
  185. text += QString("\t.byte %1\n").arg(map->type);
  186. text += QString("\t.2byte %1\n").arg(map->unknown);
  187. text += QString("\t.byte %1\n").arg(map->show_location);
  188. text += QString("\t.byte %1\n").arg(map->battle_scene);
  189. saveTextFile(header_path, text);
  190. }
  191. void Project::readMapAttributesTable() {
  192. int curMapIndex = 1;
  193. QString attributesText = readTextFile(getMapAttributesTableFilepath());
  194. QList<QStringList>* values = parse(attributesText);
  195. bool inAttributePointers = false;
  196. for (int i = 0; i < values->length(); i++) {
  197. QStringList params = values->value(i);
  198. QString macro = params.value(0);
  199. if (macro == ".label") {
  200. if (inAttributePointers) {
  201. break;
  202. }
  203. if (params.value(1) == "gMapAttributes") {
  204. inAttributePointers = true;
  205. }
  206. } else if (macro == ".4byte" && inAttributePointers) {
  207. QString mapName = params.value(1);
  208. if (!mapName.contains("UnknownMapAttributes")) {
  209. // Strip off "_MapAttributes" from the label if it's a real map label.
  210. mapName = mapName.remove(mapName.length() - 14, 14);
  211. }
  212. mapAttributesTable->insert(curMapIndex, mapName);
  213. curMapIndex++;
  214. }
  215. }
  216. }
  217. void Project::saveMapAttributesTable() {
  218. QString text = "";
  219. text += QString("\t.align 2\n");
  220. text += QString("gMapAttributes::\n");
  221. for (int i = 0; i < mapAttributesTable->count(); i++) {
  222. int mapIndex = i + 1;
  223. QString mapName = mapAttributesTable->value(mapIndex);
  224. if (!mapName.contains("UnknownMapAttributes")) {
  225. text += QString("\t.4byte %1_MapAttributes\n").arg(mapName);
  226. } else {
  227. text += QString("\t.4byte %1\n").arg(mapName);
  228. }
  229. }
  230. saveTextFile(getMapAttributesTableFilepath(), text);
  231. }
  232. QString Project::getMapAttributesTableFilepath() {
  233. return QString("%1/data/maps/attributes_table.inc").arg(root);
  234. }
  235. void Project::readMapAttributes(Map* map) {
  236. if (!map->isPersistedToFile) {
  237. return;
  238. }
  239. Asm *parser = new Asm;
  240. QString assets_text = readTextFile(getMapAssetsFilepath());
  241. if (assets_text.isNull()) {
  242. return;
  243. }
  244. QStringList *attributes = getLabelValues(parser->parse(assets_text), map->attributes_label);
  245. map->width = attributes->value(0);
  246. map->height = attributes->value(1);
  247. map->border_label = attributes->value(2);
  248. map->blockdata_label = attributes->value(3);
  249. map->tileset_primary_label = attributes->value(4);
  250. map->tileset_secondary_label = attributes->value(5);
  251. }
  252. void Project::readAllMapAttributes() {
  253. mapAttributes->clear();
  254. Asm *parser = new Asm;
  255. QString assets_text = readTextFile(getMapAssetsFilepath());
  256. if (assets_text.isNull()) {
  257. return;
  258. }
  259. QList<QStringList> *commands = parser->parse(assets_text);
  260. // Assume the _assets.inc file is grouped consistently in the order of:
  261. // 1. <map_name>_MapBorder
  262. // 2. <map_name>_MapBlockdata
  263. // 3. <map_name>_MapAttributes
  264. int i = 0;
  265. while (i < commands->length()) {
  266. // Read MapBorder assets.
  267. QStringList borderParams = commands->value(i++);
  268. bool isUnknownMapBorder = borderParams.value(1).startsWith("UnknownMapBorder_");
  269. if (borderParams.value(0) != ".label" || (!borderParams.value(1).endsWith("_MapBorder") && !isUnknownMapBorder)) {
  270. qDebug() << QString("Expected MapBorder label, but found %1").arg(borderParams.value(1));
  271. continue;
  272. }
  273. QString borderLabel = borderParams.value(1);
  274. QString mapName;
  275. if (!isUnknownMapBorder) {
  276. mapName = borderLabel.remove(borderLabel.length() - 10, 10);
  277. } else {
  278. // Unknown map name has to match the MapAttributes label.
  279. mapName = borderLabel.replace("Border", "Attributes");
  280. }
  281. QMap<QString, QString>* attrs = new QMap<QString, QString>;
  282. mapAttributes->insert(mapName, attrs);
  283. attrs->insert("border_label", borderParams.value(1));
  284. borderParams = commands->value(i++);
  285. attrs->insert("border_filepath", borderParams.value(1).replace("\"", ""));
  286. // Read MapBlockData assets.
  287. QStringList blockDataParams = commands->value(i++);
  288. bool isUnknownMapBlockdata = blockDataParams.value(1).startsWith("UnknownMapBlockdata_");
  289. if (blockDataParams.value(0) != ".label" || (!blockDataParams.value(1).endsWith("_MapBlockdata") && !isUnknownMapBlockdata)) {
  290. qDebug() << QString("Expected MapBlockdata label, but found %1").arg(blockDataParams.value(1));
  291. continue;
  292. }
  293. QString blockDataLabel = blockDataParams.value(1);
  294. attrs->insert("blockdata_label", blockDataLabel);
  295. blockDataParams = commands->value(i++);
  296. attrs->insert("blockdata_filepath", blockDataParams.value(1).replace("\"", ""));
  297. // Read MapAttributes assets.
  298. i++; // skip .align
  299. // Maps can share MapAttributes, so gather a list of them.
  300. QStringList attributeMapLabels;
  301. QStringList attributesParams;
  302. QStringList* sharedAttrMaps = new QStringList;
  303. while (i < commands->length()) {
  304. attributesParams = commands->value(i);
  305. if (attributesParams.value(0) != ".label") {
  306. break;
  307. }
  308. QString attrLabel = attributesParams.value(1);
  309. attributeMapLabels.append(attrLabel);
  310. sharedAttrMaps->append(attrLabel);
  311. i++;
  312. }
  313. // Apply the map attributes to each of the shared maps.
  314. QString attrWidth = commands->value(i++).value(1);
  315. QString attrHeight = commands->value(i++).value(1);
  316. QString attrBorderLabel = commands->value(i++).value(1);
  317. QString attrBlockdataLabel = commands->value(i++).value(1);
  318. QString attrTilesetPrimary = commands->value(i++).value(1);
  319. QString attrTilesetSecondary = commands->value(i++).value(1);
  320. for (QString attributeMapLabel: attributeMapLabels) {
  321. QString altMapName = attributeMapLabel;
  322. if (!altMapName.startsWith("UnknownMapAttributes_")) {
  323. altMapName.remove(altMapName.length() - 14, 14);
  324. }
  325. if (!mapAttributes->contains(altMapName)) {
  326. mapAttributes->insert(altMapName, new QMap<QString, QString>);
  327. }
  328. mapAttributes->value(altMapName)->insert("attributes_label", attributeMapLabel);
  329. mapAttributes->value(altMapName)->insert("width", attrWidth);
  330. mapAttributes->value(altMapName)->insert("height", attrHeight);
  331. mapAttributes->value(altMapName)->insert("border_label", attrBorderLabel);
  332. mapAttributes->value(altMapName)->insert("blockdata_label", attrBlockdataLabel);
  333. mapAttributes->value(altMapName)->insert("tileset_primary", attrTilesetPrimary);
  334. mapAttributes->value(altMapName)->insert("tileset_secondary", attrTilesetSecondary);
  335. if (sharedAttrMaps->length() > 1) {
  336. mapAttributes->value(altMapName)->insert("shared_attr_maps", sharedAttrMaps->join(":"));
  337. }
  338. }
  339. }
  340. }
  341. void Project::saveAllMapAttributes() {
  342. QString text = "";
  343. for (int i = 0; i < mapAttributesTable->count(); i++) {
  344. int mapIndex = i + 1;
  345. QString mapName = mapAttributesTable->value(mapIndex);
  346. QMap<QString, QString>* attrs = mapAttributes->value(mapName);
  347. // Find the map attributes object that contains the border data.
  348. QMap<QString, QString>* attrsWithBorder;
  349. if (attrs->contains("border_filepath")) {
  350. attrsWithBorder = attrs;
  351. } else {
  352. QStringList labels = attrs->value("shared_attr_maps").split(":");
  353. for (QString label : labels) {
  354. label.remove(label.length() - 14, 14);
  355. if (mapAttributes->contains(label) && mapAttributes->value(label)->contains("border_filepath")) {
  356. attrsWithBorder = mapAttributes->value(label);
  357. break;
  358. }
  359. }
  360. }
  361. if (attrsWithBorder != nullptr) {
  362. text += QString("%1::\n").arg(attrsWithBorder->value("border_label"));
  363. text += QString("\t.incbin \"%1\"\n").arg(attrsWithBorder->value("border_filepath"));
  364. text += QString("\n");
  365. }
  366. // Find the map attributes object that contains the blockdata.
  367. QMap<QString, QString>* attrsWithBlockdata;
  368. if (attrs->contains("blockdata_filepath")) {
  369. attrsWithBlockdata = attrs;
  370. } else {
  371. QStringList labels = attrs->value("shared_attr_maps").split(":");
  372. for (QString label : labels) {
  373. label.remove(label.length() - 14, 14);
  374. if (mapAttributes->contains(label) && mapAttributes->value(label)->contains("blockdata_filepath")) {
  375. attrsWithBlockdata = mapAttributes->value(label);
  376. break;
  377. }
  378. }
  379. }
  380. if (attrsWithBlockdata != nullptr) {
  381. text += QString("%1::\n").arg(attrsWithBlockdata->value("blockdata_label"));
  382. text += QString("\t.incbin \"%1\"\n").arg(attrsWithBorder->value("blockdata_filepath"));
  383. text += QString("\n");
  384. }
  385. text += QString("\t.align 2\n");
  386. if (attrs->contains("shared_attr_maps")) {
  387. QStringList labels = attrs->value("shared_attr_maps").split(":");
  388. for (QString label : labels) {
  389. text += QString("%1::\n").arg(label);
  390. }
  391. } else {
  392. text += QString("%1::\n").arg(attrs->value("attributes_label"));
  393. }
  394. text += QString("\t.4byte %1\n").arg(attrs->value("width"));
  395. text += QString("\t.4byte %1\n").arg(attrs->value("height"));
  396. text += QString("\t.4byte %1\n").arg(attrs->value("border_label"));
  397. text += QString("\t.4byte %1\n").arg(attrs->value("blockdata_label"));
  398. text += QString("\t.4byte %1\n").arg(attrs->value("tileset_primary"));
  399. text += QString("\t.4byte %1\n").arg(attrs->value("tileset_secondary"));
  400. text += QString("\n");
  401. }
  402. saveTextFile(getMapAssetsFilepath(), text);
  403. }
  404. QString Project::getMapAssetsFilepath() {
  405. return root + "/data/maps/_assets.inc";
  406. }
  407. void Project::setNewMapAttributes(Map* map) {
  408. map->width = "20";
  409. map->height = "20";
  410. map->border_label = QString("%1_MapBorder").arg(map->name);
  411. map->blockdata_label = QString("%1_MapBlockdata").arg(map->name);
  412. map->tileset_primary_label = "gTileset_General";
  413. map->tileset_secondary_label = "gTileset_Petalburg";
  414. // Insert new entry into the global map attributes.
  415. QMap<QString, QString>* attrs = new QMap<QString, QString>;
  416. attrs->insert("border_label", QString("%1_MapBorder").arg(map->name));
  417. attrs->insert("border_filepath", QString("data/maps/%1/border.bin").arg(map->name));
  418. attrs->insert("blockdata_label", QString("%1_MapBlockdata").arg(map->name));
  419. attrs->insert("blockdata_filepath", QString("data/maps/%1/map.bin").arg(map->name));
  420. attrs->insert("attributes_label", QString("%1_MapAttributes").arg(map->name));
  421. attrs->insert("width", map->width);
  422. attrs->insert("height", map->height);
  423. attrs->insert("tileset_primary", map->tileset_primary_label);
  424. attrs->insert("tileset_secondary", map->tileset_secondary_label);
  425. mapAttributes->insert(map->name, attrs);
  426. }
  427. void Project::saveMapGroupsTable() {
  428. QString text = "";
  429. int groupNum = 0;
  430. for (QStringList* mapNames : *groupedMapNames) {
  431. text += QString("\t.align 2\n");
  432. text += QString("gMapGroup%1::\n").arg(groupNum);
  433. for (QString mapName : *mapNames) {
  434. text += QString("\t.4byte %1\n").arg(mapName);
  435. }
  436. text += QString("\n");
  437. groupNum++;
  438. }
  439. text += QString("\t.align 2\n");
  440. text += QString("gMapGroups::\n");
  441. for (int i = 0; i < groupNum; i++) {
  442. text += QString("\t.4byte gMapGroup%1\n").arg(i);
  443. }
  444. saveTextFile(root + "/data/maps/_groups.inc", text);
  445. }
  446. void Project::getTilesets(Map* map) {
  447. map->tileset_primary = getTileset(map->tileset_primary_label);
  448. map->tileset_secondary = getTileset(map->tileset_secondary_label);
  449. }
  450. Tileset* Project::loadTileset(QString label) {
  451. Asm *parser = new Asm;
  452. QString headers_text = readTextFile(root + "/data/tilesets/headers.inc");
  453. QStringList *values = getLabelValues(parser->parse(headers_text), label);
  454. Tileset *tileset = new Tileset;
  455. tileset->name = label;
  456. tileset->is_compressed = values->value(0);
  457. tileset->is_secondary = values->value(1);
  458. tileset->padding = values->value(2);
  459. tileset->tiles_label = values->value(3);
  460. tileset->palettes_label = values->value(4);
  461. tileset->metatiles_label = values->value(5);
  462. tileset->metatile_attrs_label = values->value(6);
  463. tileset->callback_label = values->value(7);
  464. loadTilesetAssets(tileset);
  465. tileset_cache->insert(label, tileset);
  466. return tileset;
  467. }
  468. QString Project::getBlockdataPath(Map* map) {
  469. QString text = readTextFile(getMapAssetsFilepath());
  470. QStringList *values = getLabelValues(parse(text), map->blockdata_label);
  471. QString path;
  472. if (!values->isEmpty()) {
  473. path = root + "/" + values->value(0).section('"', 1, 1);
  474. } else {
  475. path = root + "/data/maps/" + map->name + "/map.bin";
  476. }
  477. return path;
  478. }
  479. QString Project::getMapBorderPath(Map *map) {
  480. QString text = readTextFile(getMapAssetsFilepath());
  481. QStringList *values = getLabelValues(parse(text), map->border_label);
  482. QString path;
  483. if (!values->isEmpty()) {
  484. path = root + "/" + values->value(0).section('"', 1, 1);
  485. } else {
  486. path = root + "/data/maps/" + map->name + "/border.bin";
  487. }
  488. return path;
  489. }
  490. void Project::loadBlockdata(Map* map) {
  491. if (!map->isPersistedToFile) {
  492. return;
  493. }
  494. QString path = getBlockdataPath(map);
  495. map->blockdata = readBlockdata(path);
  496. }
  497. void Project::setNewMapBlockdata(Map* map) {
  498. Blockdata *blockdata = new Blockdata;
  499. for (int i = 0; i < map->getWidth() * map->getHeight(); i++) {
  500. blockdata->addBlock(qint16(0x3001));
  501. }
  502. map->blockdata = blockdata;
  503. }
  504. void Project::loadMapBorder(Map *map) {
  505. if (!map->isPersistedToFile) {
  506. return;
  507. }
  508. QString path = getMapBorderPath(map);
  509. map->border = readBlockdata(path);
  510. }
  511. void Project::setNewMapBorder(Map *map) {
  512. Blockdata *blockdata = new Blockdata;
  513. blockdata->addBlock(qint16(0x01D4));
  514. blockdata->addBlock(qint16(0x01D5));
  515. blockdata->addBlock(qint16(0x01DC));
  516. blockdata->addBlock(qint16(0x01DD));
  517. map->border = blockdata;
  518. }
  519. void Project::saveMapBorder(Map *map) {
  520. QString path = getMapBorderPath(map);
  521. writeBlockdata(path, map->border);
  522. }
  523. void Project::saveBlockdata(Map* map) {
  524. QString path = getBlockdataPath(map);
  525. writeBlockdata(path, map->blockdata);
  526. map->history.save();
  527. }
  528. void Project::writeBlockdata(QString path, Blockdata *blockdata) {
  529. QFile file(path);
  530. if (file.open(QIODevice::WriteOnly)) {
  531. QByteArray data = blockdata->serialize();
  532. file.write(data);
  533. }
  534. }
  535. void Project::saveAllMaps() {
  536. QList<QString> keys = map_cache->keys();
  537. for (int i = 0; i < keys.length(); i++) {
  538. QString key = keys.value(i);
  539. Map* map = map_cache->value(key);
  540. saveMap(map);
  541. }
  542. }
  543. void Project::saveMap(Map *map) {
  544. // Create/Modify a few collateral files for brand new maps.
  545. if (!map->isPersistedToFile) {
  546. QString newMapDataDir = QString(root + "/data/maps/%1").arg(map->name);
  547. if (!QDir::root().mkdir(newMapDataDir)) {
  548. qDebug() << "Error: failed to create directory for new map. " << newMapDataDir;
  549. }
  550. // Create file data/scripts/maps/<map_name>.inc
  551. QString text = QString("%1_MapScripts::\n\t.byte 0\n").arg(map->name);
  552. saveTextFile(root + "/data/scripts/maps/" + map->name + ".inc", text);
  553. // Create file data/text/maps/<map_name>.inc
  554. saveTextFile(root + "/data/text/maps/" + map->name + ".inc", "\n");
  555. // Simply append to data/event_scripts.s.
  556. // TODO: In the future, this file needs more structure to allow for proper parsing.
  557. text = QString("\n\t.include \"data/scripts/maps/%1.inc\"\n").arg(map->name);
  558. text += QString("\t.include \"data/text/maps/%1.inc\"\n").arg(map->name);
  559. appendTextFile(root + "/data/event_scripts.s", text);
  560. // Simply append to data/map_events.s.
  561. text = QString("\n\t.include \"data/maps/events/%1.inc\"\n").arg(map->name);
  562. appendTextFile(root + "/data/map_events.s", text);
  563. // Simply append to data/maps/headers.inc.
  564. text = QString("\t.include \"data/maps/%1/header.inc\"\n").arg(map->name);
  565. appendTextFile(root + "/data/maps/headers.inc", text);
  566. }
  567. saveMapBorder(map);
  568. saveMapHeader(map);
  569. saveBlockdata(map);
  570. saveMapEvents(map);
  571. map->isPersistedToFile = true;
  572. }
  573. void Project::saveAllDataStructures() {
  574. saveMapAttributesTable();
  575. saveAllMapAttributes();
  576. saveMapGroupsTable();
  577. }
  578. void Project::loadTilesetAssets(Tileset* tileset) {
  579. Asm* parser = new Asm;
  580. QString category = (tileset->is_secondary == "TRUE") ? "secondary" : "primary";
  581. if (tileset->name.isNull()) {
  582. return;
  583. }
  584. QString dir_path = root + "/data/tilesets/" + category + "/" + tileset->name.replace("gTileset_", "").toLower();
  585. QString graphics_text = readTextFile(root + "/data/tilesets/graphics.inc");
  586. QList<QStringList> *graphics = parser->parse(graphics_text);
  587. QStringList *tiles_values = getLabelValues(graphics, tileset->tiles_label);
  588. QStringList *palettes_values = getLabelValues(graphics, tileset->palettes_label);
  589. QString tiles_path;
  590. if (!tiles_values->isEmpty()) {
  591. tiles_path = root + "/" + tiles_values->value(0).section('"', 1, 1);
  592. } else {
  593. tiles_path = dir_path + "/tiles.4bpp";
  594. if (tileset->is_compressed == "TRUE") {
  595. tiles_path += ".lz";
  596. }
  597. }
  598. QStringList *palette_paths = new QStringList;
  599. if (!palettes_values->isEmpty()) {
  600. for (int i = 0; i < palettes_values->length(); i++) {
  601. QString value = palettes_values->value(i);
  602. palette_paths->append(root + "/" + value.section('"', 1, 1));
  603. }
  604. } else {
  605. QString palettes_dir_path = dir_path + "/palettes";
  606. for (int i = 0; i < 16; i++) {
  607. palette_paths->append(palettes_dir_path + "/" + QString("%1").arg(i, 2, 10, QLatin1Char('0')) + ".gbapal");
  608. }
  609. }
  610. QString metatiles_path;
  611. QString metatile_attrs_path;
  612. QString metatiles_text = readTextFile(root + "/data/tilesets/metatiles.inc");
  613. QList<QStringList> *metatiles_macros = parser->parse(metatiles_text);
  614. QStringList *metatiles_values = getLabelValues(metatiles_macros, tileset->metatiles_label);
  615. if (!metatiles_values->isEmpty()) {
  616. metatiles_path = root + "/" + metatiles_values->value(0).section('"', 1, 1);
  617. } else {
  618. metatiles_path = dir_path + "/metatiles.bin";
  619. }
  620. QStringList *metatile_attrs_values = getLabelValues(metatiles_macros, tileset->metatile_attrs_label);
  621. if (!metatile_attrs_values->isEmpty()) {
  622. metatile_attrs_path = root + "/" + metatile_attrs_values->value(0).section('"', 1, 1);
  623. } else {
  624. metatile_attrs_path = dir_path + "/metatile_attributes.bin";
  625. }
  626. // tiles
  627. tiles_path = fixGraphicPath(tiles_path);
  628. QImage *image = new QImage(tiles_path);
  629. //image->setColor(0, qRgb(0xff, 0, 0)); // debug
  630. QList<QImage> *tiles = new QList<QImage>;
  631. int w = 8;
  632. int h = 8;
  633. for (int y = 0; y < image->height(); y += h)
  634. for (int x = 0; x < image->width(); x += w) {
  635. QImage tile = image->copy(x, y, w, h);
  636. tiles->append(tile);
  637. }
  638. tileset->tiles = tiles;
  639. // metatiles
  640. //qDebug() << metatiles_path;
  641. QFile metatiles_file(metatiles_path);
  642. if (metatiles_file.open(QIODevice::ReadOnly)) {
  643. QByteArray data = metatiles_file.readAll();
  644. int num_metatiles = data.length() / 16;
  645. int num_layers = 2;
  646. QList<Metatile*> *metatiles = new QList<Metatile*>;
  647. for (int i = 0; i < num_metatiles; i++) {
  648. Metatile *metatile = new Metatile;
  649. int index = i * (2 * 4 * num_layers);
  650. for (int j = 0; j < 4 * num_layers; j++) {
  651. uint16_t word = data[index++] & 0xff;
  652. word += (data[index++] & 0xff) << 8;
  653. Tile tile;
  654. tile.tile = word & 0x3ff;
  655. tile.xflip = (word >> 10) & 1;
  656. tile.yflip = (word >> 11) & 1;
  657. tile.palette = (word >> 12) & 0xf;
  658. metatile->tiles->append(tile);
  659. }
  660. metatiles->append(metatile);
  661. }
  662. tileset->metatiles = metatiles;
  663. } else {
  664. tileset->metatiles = new QList<Metatile*>;
  665. qDebug() << QString("Could not open '%1'").arg(metatiles_path);
  666. }
  667. QFile attrs_file(metatile_attrs_path);
  668. //qDebug() << metatile_attrs_path;
  669. if (attrs_file.open(QIODevice::ReadOnly)) {
  670. QByteArray data = attrs_file.readAll();
  671. int num_metatiles = data.length() / 2;
  672. for (int i = 0; i < num_metatiles; i++) {
  673. uint16_t word = data[i*2] & 0xff;
  674. word += (data[i*2 + 1] & 0xff) << 8;
  675. tileset->metatiles->value(i)->attr = word;
  676. }
  677. } else {
  678. qDebug() << QString("Could not open '%1'").arg(metatile_attrs_path);
  679. }
  680. // palettes
  681. QList<QList<QRgb>> *palettes = new QList<QList<QRgb>>;
  682. for (int i = 0; i < palette_paths->length(); i++) {
  683. QString path = palette_paths->value(i);
  684. // the palettes are not compressed. this should never happen. it's only a precaution.
  685. path = path.replace(QRegExp("\\.lz$"), "");
  686. // TODO default to .pal (JASC-PAL)
  687. // just use .gbapal for now
  688. QFile file(path);
  689. QList<QRgb> palette;
  690. if (file.open(QIODevice::ReadOnly)) {
  691. QByteArray data = file.readAll();
  692. for (int j = 0; j < 16; j++) {
  693. uint16_t word = data[j*2] & 0xff;
  694. word += (data[j*2 + 1] & 0xff) << 8;
  695. int red = word & 0x1f;
  696. int green = (word >> 5) & 0x1f;
  697. int blue = (word >> 10) & 0x1f;
  698. QRgb color = qRgb(red * 8, green * 8, blue * 8);
  699. palette.prepend(color);
  700. }
  701. } else {
  702. for (int j = 0; j < 16; j++) {
  703. palette.append(qRgb(j * 16, j * 16, j * 16));
  704. }
  705. qDebug() << QString("Could not open '%1'").arg(path);
  706. }
  707. //qDebug() << path;
  708. palettes->append(palette);
  709. }
  710. tileset->palettes = palettes;
  711. }
  712. Blockdata* Project::readBlockdata(QString path) {
  713. Blockdata *blockdata = new Blockdata;
  714. //qDebug() << path;
  715. QFile file(path);
  716. if (file.open(QIODevice::ReadOnly)) {
  717. QByteArray data = file.readAll();
  718. for (int i = 0; (i + 1) < data.length(); i += 2) {
  719. uint16_t word = (data[i] & 0xff) + ((data[i + 1] & 0xff) << 8);
  720. blockdata->addBlock(word);
  721. }
  722. }
  723. return blockdata;
  724. }
  725. Map* Project::getMap(QString map_name) {
  726. if (map_cache->contains(map_name)) {
  727. return map_cache->value(map_name);
  728. } else {
  729. Map *map = loadMap(map_name);
  730. return map;
  731. }
  732. }
  733. Tileset* Project::getTileset(QString label) {
  734. if (tileset_cache->contains(label)) {
  735. return tileset_cache->value(label);
  736. } else {
  737. Tileset *tileset = loadTileset(label);
  738. return tileset;
  739. }
  740. }
  741. QString Project::readTextFile(QString path) {
  742. QFile file(path);
  743. if (!file.open(QIODevice::ReadOnly)) {
  744. //QMessageBox::information(0, "Error", QString("Could not open '%1': ").arg(path) + file.errorString());
  745. qDebug() << QString("Could not open '%1': ").arg(path) + file.errorString();
  746. return QString();
  747. }
  748. QTextStream in(&file);
  749. QString text = "";
  750. while (!in.atEnd()) {
  751. text += in.readLine() + "\n";
  752. }
  753. return text;
  754. }
  755. void Project::saveTextFile(QString path, QString text) {
  756. QFile file(path);
  757. if (file.open(QIODevice::WriteOnly)) {
  758. file.write(text.toUtf8());
  759. } else {
  760. qDebug() << QString("Could not open '%1' for writing: ").arg(path) + file.errorString();
  761. }
  762. }
  763. void Project::appendTextFile(QString path, QString text) {
  764. QFile file(path);
  765. if (file.open(QIODevice::Append)) {
  766. file.write(text.toUtf8());
  767. } else {
  768. qDebug() << QString("Could not open '%1' for appending: ").arg(path) + file.errorString();
  769. }
  770. }
  771. void Project::readMapGroups() {
  772. QString text = readTextFile(root + "/data/maps/_groups.inc");
  773. if (text.isNull()) {
  774. return;
  775. }
  776. Asm *parser = new Asm;
  777. QList<QStringList> *commands = parser->parse(text);
  778. bool in_group_pointers = false;
  779. QStringList *groups = new QStringList;
  780. for (int i = 0; i < commands->length(); i++) {
  781. QStringList params = commands->value(i);
  782. QString macro = params.value(0);
  783. if (macro == ".label") {
  784. if (in_group_pointers) {
  785. break;
  786. }
  787. if (params.value(1) == "gMapGroups") {
  788. in_group_pointers = true;
  789. }
  790. } else if (macro == ".4byte") {
  791. if (in_group_pointers) {
  792. for (int j = 1; j < params.length(); j++) {
  793. groups->append(params.value(j));
  794. }
  795. }
  796. }
  797. }
  798. QList<QStringList*> *groupedMaps = new QList<QStringList*>;
  799. for (int i = 0; i < groups->length(); i++) {
  800. QStringList *list = new QStringList;
  801. groupedMaps->append(list);
  802. }
  803. QStringList *maps = new QStringList;
  804. int group = -1;
  805. for (int i = 0; i < commands->length(); i++) {
  806. QStringList params = commands->value(i);
  807. QString macro = params.value(0);
  808. if (macro == ".label") {
  809. group = groups->indexOf(params.value(1));
  810. } else if (macro == ".4byte") {
  811. if (group != -1) {
  812. for (int j = 1; j < params.length(); j++) {
  813. QString mapName = params.value(j);
  814. QStringList *list = groupedMaps->value(group);
  815. list->append(mapName);
  816. maps->append(mapName);
  817. map_groups->insert(mapName, group);
  818. // Build the mapping and reverse mapping between map constants and map names.
  819. QString mapConstant = Map::mapConstantFromName(mapName);
  820. mapConstantsToMapNames->insert(mapConstant, mapName);
  821. mapNamesToMapConstants->insert(mapName, mapConstant);
  822. }
  823. }
  824. }
  825. }
  826. groupNames = groups;
  827. groupedMapNames = groupedMaps;
  828. mapNames = maps;
  829. }
  830. void Project::addNewMapToGroup(QString mapName, int groupNum) {
  831. int mapIndex = mapAttributesTable->count() + 1;
  832. mapAttributesTable->insert(mapIndex, mapName);
  833. // Setup new map in memory, but don't write to file until map is actually saved later.
  834. mapNames->append(mapName);
  835. map_groups->insert(mapName, groupNum);
  836. groupedMapNames->value(groupNum)->append(mapName);
  837. Map *map = new Map;
  838. map->isPersistedToFile = false;
  839. map->setName(mapName);
  840. setNewMapHeader(map, mapIndex);
  841. setNewMapAttributes(map);
  842. getTilesets(map);
  843. setNewMapBlockdata(map);
  844. setNewMapBorder(map);
  845. setNewMapEvents(map);
  846. setNewMapConnections(map);
  847. map->commit();
  848. map->history.save();
  849. map_cache->insert(mapName, map);
  850. // QString dataDir = QString("%1/data/").arg(root);
  851. // QString dataMapsDir = QString("%1maps/").arg(dataDir);
  852. // QString newMapDataDir = QString("%1%2/").arg(dataMapsDir).arg(mapName);
  853. // // 1. Create directory data/maps/<map_name>/
  854. // if (!QDir::root().mkdir(newMapDataDir)) {
  855. // qDebug() << "Error: failed to create directory for new map. " << newMapDataDir;
  856. // return;
  857. // }
  858. // // 2. Create file data/maps/<map_name>/border.bin
  859. // QFile borderFile(newMapDataDir + "border.bin");
  860. // borderFile.open(QIODevice::WriteOnly);
  861. // QDataStream borderStream(&borderFile);
  862. // borderStream.setByteOrder(QDataStream::LittleEndian);
  863. // borderStream << qint16(0x01D4) << qint16(0x01D5) << qint16(0x01DC) << qint16(0x01DD);
  864. // borderFile.close();
  865. // // 3. Create file data/maps/<map_name>/header.inc
  866. // QFile headerFile(newMapDataDir + "header.inc");
  867. // headerFile.open(QIODevice::WriteOnly);
  868. // QTextStream headerStream(&headerFile);
  869. // headerStream << mapName << "::" << endl
  870. // << "\t.4byte " << mapName << "_MapAttributes" << endl
  871. // << "\t.4byte " << mapName << "_MapEvents" << endl
  872. // << "\t.4byte " << mapName << "_MapScripts" << endl
  873. // << "\t.4byte 0x0" << endl
  874. // << "\t.2byte BGM_DAN02" << endl
  875. // << "\t.2byte " << mapIndex << endl
  876. // << "\t.byte 0" << endl
  877. // << "\t.byte 0" << endl
  878. // << "\t.byte 11" << endl
  879. // << "\t.byte 4" << endl
  880. // << "\t.2byte 0" << endl
  881. // << "\t.byte 1" << endl
  882. // << "\t.byte 0" << endl;
  883. // headerFile.close();
  884. // // 4. Create file data/maps/<map_name>/map.bin
  885. // QFile mapFile(newMapDataDir + "map.bin");
  886. // mapFile.open(QIODevice::WriteOnly);
  887. // QDataStream mapStream(&mapFile);
  888. // mapStream.setByteOrder(QDataStream::LittleEndian);
  889. // for (int i = 0; i < 20 * 20; i++) {
  890. // mapStream << qint16(0x3001);
  891. // }
  892. // mapFile.close();
  893. // // 5. Create file data/maps/events/<map_name>.inc
  894. // QFile eventsFile(dataMapsDir + "events/" + mapName + ".inc");
  895. // eventsFile.open(QIODevice::WriteOnly);
  896. // QTextStream eventsStream(&eventsFile);
  897. // eventsStream << mapName << "_MapEvents::" << endl
  898. // << "\tmap_events 0x0, 0x0, 0x0, 0x0" << endl;
  899. // eventsFile.close();
  900. // // 6. Create file data/scripts/maps/<map_name>.inc
  901. // QFile scriptsFile(dataDir + "scripts/maps/" + mapName + ".inc");
  902. // scriptsFile.open(QIODevice::WriteOnly);
  903. // QTextStream scriptsStream(&scriptsFile);
  904. // scriptsStream << mapName << "_MapScripts::" << endl
  905. // << "\t.byte 0" << endl;
  906. // scriptsFile.close();
  907. // // 7. Create file data/text/maps/<map_name>.inc
  908. // QFile textFile(dataDir + "text/maps/" + mapName + ".inc");
  909. // textFile.open(QIODevice::WriteOnly);
  910. // QTextStream textStream(&textFile);
  911. // textStream << endl;
  912. // textFile.close();
  913. // // 8. Modify data/event_scripts.s:
  914. // QFile eventScriptsFile(dataDir + "event_scripts.s");
  915. // eventScriptsFile.open(QIODevice::Append);
  916. // QTextStream eventScriptsStream(&eventScriptsFile);
  917. // eventScriptsStream << endl
  918. // << "\t.include \"data/scripts/maps/" << mapName << ".inc\"" << endl
  919. // << "\t.include \"data/text/maps/" << mapName << ".inc\"" << endl;
  920. // eventScriptsFile.close();
  921. // // 9. Modify data/map_events.s:
  922. // QFile mapEventsFile(dataDir + "map_events.s");
  923. // mapEventsFile.open(QIODevice::Append);
  924. // QTextStream mapEventsStream(&mapEventsFile);
  925. // mapEventsStream << endl
  926. // << "\t.include \"data/maps/events/" << mapName << ".inc\"" << endl;
  927. // mapEventsFile.close();
  928. // // 10. Modify data/maps/_assets.inc
  929. // QFile assetsFile(dataMapsDir + "_assets.inc");
  930. // assetsFile.open(QIODevice::Append);
  931. // QTextStream assetsStream(&assetsFile);
  932. // assetsStream << endl
  933. // << mapName << "_MapBorder::" << endl
  934. // << "\t.incbin \"data/maps/" << mapName << "/border.bin\"" << endl
  935. // << endl
  936. // << mapName << "_MapBlockdata::" << endl
  937. // << "\t.incbin \"data/maps/" << mapName << "/map.bin\"" << endl
  938. // << endl
  939. // << "\t.align 2" << endl
  940. // << mapName << "_MapAttributes::" << endl
  941. // << "\t.4byte 0x14" << endl
  942. // << "\t.4byte 0x14" << endl
  943. // << "\t.4byte " << mapName << "_MapBorder" << endl
  944. // << "\t.4byte " << mapName << "_MapBlockdata" << endl
  945. // << "\t.4byte gTileset_General" << endl
  946. // << "\t.4byte gTileset_Pacifidlog" << endl
  947. // << endl;
  948. // assetsFile.close();
  949. // // 11. Modify data/maps/_groups.inc
  950. // // TODO:
  951. // // 12. Modify data/maps/attributes_table.inc
  952. // QFile attributesFile(dataMapsDir + "attributes_table.inc");
  953. // attributesFile.open(QIODevice::Append);
  954. // QTextStream attributesStream(&attributesFile);
  955. // attributesStream << endl
  956. // << "\t.4byte " << mapName << "_MapAttributes" << endl;
  957. // attributesFile.close();
  958. // // 13. Modify data/maps/headers.inc
  959. // QFile headersFile(dataMapsDir + "headers.inc");
  960. // headersFile.open(QIODevice::Append);
  961. // QTextStream headersStream(&headersFile);
  962. // headersStream << endl
  963. // << "\t.include \"data/maps/" << mapName << "/header.inc\"" << endl;
  964. // headersFile.close();
  965. }
  966. QString Project::getNewMapName() {
  967. // Ensure default name doesn't already exist.
  968. int i = 0;
  969. QString newMapName;
  970. do {
  971. newMapName = QString("NewMap%1").arg(++i);
  972. } while (mapNames->contains(newMapName));
  973. return newMapName;
  974. }
  975. QList<QStringList>* Project::parse(QString text) {
  976. Asm *parser = new Asm;
  977. return parser->parse(text);
  978. }
  979. QStringList Project::getLocations() {
  980. // TODO
  981. QStringList names;
  982. for (int i = 0; i < 88; i++) {
  983. names.append(QString("%1").arg(i));
  984. }
  985. return names;
  986. }
  987. QStringList Project::getVisibilities() {
  988. // TODO
  989. QStringList names;
  990. for (int i = 0; i < 16; i++) {
  991. names.append(QString("%1").arg(i));
  992. }
  993. return names;
  994. }
  995. QStringList Project::getWeathers() {
  996. // TODO
  997. QStringList names;
  998. for (int i = 0; i < 16; i++) {
  999. names.append(QString("%1").arg(i));
  1000. }
  1001. return names;
  1002. }
  1003. QStringList Project::getMapTypes() {
  1004. // TODO
  1005. QStringList names;
  1006. for (int i = 0; i < 16; i++) {
  1007. names.append(QString("%1").arg(i));
  1008. }
  1009. return names;
  1010. }
  1011. QStringList Project::getBattleScenes() {
  1012. // TODO
  1013. QStringList names;
  1014. for (int i = 0; i < 16; i++) {
  1015. names.append(QString("%1").arg(i));
  1016. }
  1017. return names;
  1018. }
  1019. QStringList Project::getSongNames() {
  1020. QStringList names;
  1021. QString text = readTextFile(root + "/include/constants/songs.h");
  1022. if (!text.isNull()) {
  1023. QStringList songDefinePrefixes;
  1024. songDefinePrefixes << "SE_" << "BGM_";
  1025. QMap<QString, int> songDefines = readCDefines(text, songDefinePrefixes);
  1026. names = songDefines.keys();
  1027. }
  1028. return names;
  1029. }
  1030. QString Project::getSongName(int songNumber) {
  1031. QStringList names;
  1032. QString text = readTextFile(root + "/include/constants/songs.h");
  1033. if (!text.isNull()) {
  1034. QStringList songDefinePrefixes;
  1035. songDefinePrefixes << "SE_" << "BGM_";
  1036. QMap<QString, int> songDefines = readCDefines(text, songDefinePrefixes);
  1037. // Loop through song defines, and fine the one with the matching song number.
  1038. QMap<QString, int>::iterator iter = songDefines.begin();
  1039. while (iter != songDefines.end()) {
  1040. if (iter.value() == songNumber) {
  1041. return iter.key();
  1042. }
  1043. iter++;
  1044. }
  1045. }
  1046. return "";
  1047. }
  1048. QMap<QString, int> Project::getMapObjGfxConstants() {
  1049. QMap<QString, int> constants;
  1050. QString text = readTextFile(root + "/include/constants/map_objects.h");
  1051. if (!text.isNull()) {
  1052. QStringList mapObjGfxPrefixes;
  1053. mapObjGfxPrefixes << "MAP_OBJ_GFX_";
  1054. constants = readCDefines(text, mapObjGfxPrefixes);
  1055. }
  1056. return constants;
  1057. }
  1058. QString Project::fixGraphicPath(QString path) {
  1059. path = path.replace(QRegExp("\\.lz$"), "");
  1060. path = path.replace(QRegExp("\\.[1248]bpp$"), ".png");
  1061. return path;
  1062. }
  1063. void Project::loadObjectPixmaps(QList<Event*> objects) {
  1064. bool needs_update = false;
  1065. for (Event *object : objects) {
  1066. if (object->pixmap.isNull()) {
  1067. needs_update = true;
  1068. break;
  1069. }
  1070. }
  1071. if (!needs_update) {
  1072. return;
  1073. }
  1074. QMap<QString, int> constants = getMapObjGfxConstants();
  1075. QString pointers_text = readTextFile(root + "/src/data/field_map_obj/map_object_graphics_info_pointers.h");
  1076. QString info_text = readTextFile(root + "/src/data/field_map_obj/map_object_graphics_info.h");
  1077. QString pic_text = readTextFile(root + "/src/data/field_map_obj/map_object_pic_tables.h");
  1078. QString assets_text = readTextFile(root + "/src/field/field_map_obj.c");
  1079. QStringList pointers = readCArray(pointers_text, "gMapObjectGraphicsInfoPointers");
  1080. for (Event *object : objects) {
  1081. if (!object->pixmap.isNull()) {
  1082. continue;
  1083. }
  1084. QString event_type = object->get("event_type");
  1085. if (event_type == "object") {
  1086. object->pixmap = QPixmap(":/images/Entities_16x16.png").copy(0, 0, 16, 16);
  1087. } else if (event_type == "warp") {
  1088. object->pixmap = QPixmap(":/images/Entities_16x16.png").copy(16, 0, 16, 16);
  1089. } else if (event_type == "trap" || event_type == "trap_weather") {
  1090. object->pixmap = QPixmap(":/images/Entities_16x16.png").copy(32, 0, 16, 16);
  1091. } else if (event_type == "sign" || event_type == "event_hidden_item" || event_type == "event_secret_base") {
  1092. object->pixmap = QPixmap(":/images/Entities_16x16.png").copy(48, 0, 16, 16);
  1093. }
  1094. if (event_type == "object") {
  1095. int sprite_id = constants.value(object->get("sprite"));
  1096. QString info_label = pointers.value(sprite_id).replace("&", "");
  1097. QString pic_label = readCArray(info_text, info_label).value(14);
  1098. QString gfx_label = readCArray(pic_text, pic_label).value(0);
  1099. gfx_label = gfx_label.section(QRegExp("[\\(\\)]"), 1, 1);
  1100. QString path = readCIncbin(assets_text, gfx_label);
  1101. if (!path.isNull()) {
  1102. path = fixGraphicPath(path);
  1103. QPixmap pixmap(root + "/" + path);
  1104. if (!pixmap.isNull()) {
  1105. object->pixmap = pixmap;
  1106. }
  1107. }
  1108. }
  1109. }
  1110. }
  1111. void Project::saveMapEvents(Map *map) {
  1112. QString path = root + QString("/data/maps/events/%1.inc").arg(map->name);
  1113. QString text = "";
  1114. if (map->events["object"].length() > 0) {
  1115. text += QString("%1::\n").arg(map->object_events_label);
  1116. for (int i = 0; i < map->events["object"].length(); i++) {
  1117. Event *object_event = map->events["object"].value(i);
  1118. int radius_x = object_event->getInt("radius_x");
  1119. int radius_y = object_event->getInt("radius_y");
  1120. QString radius = QString("%1").arg((radius_x & 0xf) + ((radius_y & 0xf) << 4));
  1121. uint16_t x = object_event->getInt("x");
  1122. uint16_t y = object_event->getInt("y");
  1123. text += QString("\tobject_event %1").arg(i + 1);
  1124. text += QString(", %1").arg(object_event->get("sprite"));
  1125. text += QString(", %1").arg(object_event->get("replacement"));
  1126. text += QString(", %1").arg(x & 0xff);
  1127. text += QString(", %1").arg((x >> 8) & 0xff);
  1128. text += QString(", %1").arg(y & 0xff);
  1129. text += QString(", %1").arg((y >> 8) & 0xff);
  1130. text += QString(", %1").arg(object_event->get("elevation"));
  1131. text += QString(", %1").arg(object_event->get("behavior"));
  1132. text += QString(", %1").arg(radius);
  1133. text += QString(", 0");
  1134. text += QString(", %1").arg(object_event->get("property"));
  1135. text += QString(", 0");
  1136. text += QString(", %1").arg(object_event->get("sight_radius"));
  1137. text += QString(", 0");
  1138. text += QString(", %1").arg(object_event->get("script_label"));
  1139. text += QString(", %1").arg(object_event->get("event_flag"));
  1140. text += QString(", 0");
  1141. text += QString(", 0");
  1142. text += "\n";
  1143. }
  1144. text += "\n";
  1145. }
  1146. if (map->events["warp"].length() > 0) {
  1147. text += QString("%1::\n").arg(map->warps_label);
  1148. for (Event *warp : map->events["warp"]) {
  1149. text += QString("\twarp_def %1").arg(warp->get("x"));
  1150. text += QString(", %1").arg(warp->get("y"));
  1151. text += QString(", %1").arg(warp->get("elevation"));
  1152. text += QString(", %1").arg(warp->get("destination_warp"));
  1153. text += QString(", %1").arg(mapNamesToMapConstants->value(warp->get("destination_map_name")));
  1154. text += "\n";
  1155. }
  1156. text += "\n";
  1157. }
  1158. if (map->events["trap"].length() + map->events["trap_weather"].length() > 0) {
  1159. text += QString("%1::\n").arg(map->coord_events_label);
  1160. for (Event *coords : map->events["trap"]) {
  1161. text += QString("\tcoord_event %1").arg(coords->get("x"));
  1162. text += QString(", %1").arg(coords->get("y"));
  1163. text += QString(", %1").arg(coords->get("elevation"));
  1164. text += QString(", 0");
  1165. text += QString(", %1").arg(coords->get("coord_unknown1"));
  1166. text += QString(", %1").arg(coords->get("coord_unknown2"));
  1167. text += QString(", 0");
  1168. text += QString(", %1").arg(coords->get("script_label"));
  1169. text += "\n";
  1170. }
  1171. for (Event *coords : map->events["trap_weather"]) {
  1172. text += QString("\tcoord_weather_event %1").arg(coords->get("x"));
  1173. text += QString(", %1").arg(coords->get("y"));
  1174. text += QString(", %1").arg(coords->get("elevation"));
  1175. text += QString(", %1").arg(coords->get("weather"));
  1176. text += "\n";
  1177. }
  1178. text += "\n";
  1179. }
  1180. if (map->events["sign"].length() +
  1181. map->events["event_hidden_item"].length() +
  1182. map->events["event_secret_base"].length() > 0)
  1183. {
  1184. text += QString("%1::\n").arg(map->bg_events_label);
  1185. for (Event *sign : map->events["sign"]) {
  1186. text += QString("\tbg_event %1").arg(sign->get("x"));
  1187. text += QString(", %1").arg(sign->get("y"));
  1188. text += QString(", %1").arg(sign->get("elevation"));
  1189. text += QString(", %1").arg(sign->get("type"));
  1190. text += QString(", 0");
  1191. text += QString(", %1").arg(sign->get("script_label"));
  1192. text += "\n";
  1193. }
  1194. for (Event *item : map->events["event_hidden_item"]) {
  1195. text += QString("\tbg_hidden_item_event %1").arg(item->get("x"));
  1196. text += QString(", %1").arg(item->get("y"));
  1197. text += QString(", %1").arg(item->get("elevation"));
  1198. text += QString(", %1").arg(item->get("item"));
  1199. text += QString(", %1").arg(item->get("flag"));
  1200. text += "\n";
  1201. }
  1202. for (Event *item : map->events["event_secret_base"]) {
  1203. text += QString("\tbg_secret_base_event %1").arg(item->get("x"));
  1204. text += QString(", %1").arg(item->get("y"));
  1205. text += QString(", %1").arg(item->get("elevation"));
  1206. text += QString(", %1").arg(item->get("secret_base_map"));
  1207. text += "\n";
  1208. }
  1209. text += "\n";
  1210. }
  1211. text += QString("%1::\n").arg(map->events_label);
  1212. text += QString("\tmap_events %1, %2, %3, %4\n")
  1213. .arg(map->object_events_label)
  1214. .arg(map->warps_label)
  1215. .arg(map->coord_events_label)
  1216. .arg(map->bg_events_label);
  1217. saveTextFile(path, text);
  1218. }
  1219. void Project::readMapEvents(Map *map) {
  1220. if (!map->isPersistedToFile) {
  1221. return;
  1222. }
  1223. // lazy
  1224. QString path = root + QString("/data/maps/events/%1.inc").arg(map->name);
  1225. QString text = readTextFile(path);
  1226. if (text.isNull()) {
  1227. return;
  1228. }
  1229. QStringList *labels = getLabelValues(parse(text), map->events_label);
  1230. map->object_events_label = labels->value(0);
  1231. map->warps_label = labels->value(1);
  1232. map->coord_events_label = labels->value(2);
  1233. map->bg_events_label = labels->value(3);
  1234. QList<QStringList> *object_events = getLabelMacros(parse(text), map->object_events_label);
  1235. map->events["object"].clear();
  1236. for (QStringList command : *object_events) {
  1237. if (command.value(0) == "object_event") {
  1238. Event *object = new Event;
  1239. object->put("map_name", map->name);
  1240. // This macro is not fixed as of writing, but it should take fewer args.
  1241. bool old_macro = false;
  1242. if (command.length() >= 20) {
  1243. command.removeAt(19);
  1244. command.removeAt(18);
  1245. command.removeAt(15);
  1246. command.removeAt(13);
  1247. command.removeAt(11);
  1248. command.removeAt(1); // id. not 0, but is just the index in the list of objects
  1249. old_macro = true;
  1250. }
  1251. int i = 1;
  1252. object->put("sprite", command.value(i++));
  1253. object->put("replacement", command.value(i++));
  1254. int16_t x = command.value(i++).toInt(nullptr, 0) | (command.value(i++).toInt(nullptr, 0) << 8);
  1255. int16_t y = command.value(i++).toInt(nullptr, 0) | (command.value(i++).toInt(nullptr, 0) << 8);
  1256. object->put("x", x);
  1257. object->put("y", y);
  1258. object->put("elevation", command.value(i++));
  1259. object->put("behavior", command.value(i++));
  1260. if (old_macro) {
  1261. int radius = command.value(i++).toInt(nullptr, 0);
  1262. object->put("radius_x", radius & 0xf);
  1263. object->put("radius_y", (radius >> 4) & 0xf);
  1264. } else {
  1265. object->put("radius_x", command.value(i++));
  1266. object->put("radius_y", command.value(i++));
  1267. }
  1268. object->put("property", command.value(i++));
  1269. object->put("sight_radius", command.value(i++));
  1270. object->put("script_label", command.value(i++));
  1271. object->put("event_flag", command.value(i++));
  1272. object->put("event_type", "object");
  1273. map->events["object"].append(object);
  1274. }
  1275. }
  1276. QList<QStringList> *warps = getLabelMacros(parse(text), map->warps_label);
  1277. map->events["warp"].clear();
  1278. for (QStringList command : *warps) {
  1279. if (command.value(0) == "warp_def") {
  1280. Event *warp = new Event;
  1281. warp->put("map_name", map->name);
  1282. int i = 1;
  1283. warp->put("x", command.value(i++));
  1284. warp->put("y", command.value(i++));
  1285. warp->put("elevation", command.value(i++));
  1286. warp->put("destination_warp", command.value(i++));
  1287. // Ensure the warp destination map constant is valid before adding it to the warps.
  1288. QString mapConstant = command.value(i++);
  1289. if (mapConstantsToMapNames->contains(mapConstant)) {
  1290. warp->put("destination_map_name", mapConstantsToMapNames->value(mapConstant));
  1291. warp->put("event_type", "warp");
  1292. map->events["warp"].append(warp);
  1293. } else {
  1294. qDebug() << QString("Destination map constant '%1' is invalid for warp").arg(mapConstant);
  1295. }
  1296. }
  1297. }
  1298. QList<QStringList> *coords = getLabelMacros(parse(text), map->coord_events_label);
  1299. map->events["trap"].clear();
  1300. map->events["trap_weather"].clear();
  1301. for (QStringList command : *coords) {
  1302. if (command.value(0) == "coord_event") {
  1303. Event *coord = new Event;
  1304. coord->put("map_name", map->name);
  1305. bool old_macro = false;
  1306. if (command.length() >= 9) {
  1307. command.removeAt(7);
  1308. command.removeAt(4);
  1309. old_macro = true;
  1310. }
  1311. int i = 1;
  1312. coord->put("x", command.value(i++));
  1313. coord->put("y", command.value(i++));
  1314. coord->put("elevation", command.value(i++));
  1315. coord->put("coord_unknown1", command.value(i++));
  1316. coord->put("coord_unknown2", command.value(i++));
  1317. coord->put("script_label", command.value(i++));
  1318. //coord_unknown3
  1319. //coord_unknown4
  1320. coord->put("event_type", "trap");
  1321. map->events["trap"].append(coord);
  1322. } else if (command.value(0) == "coord_weather_event") {
  1323. Event *coord = new Event;
  1324. coord->put("map_name", map->name);
  1325. int i = 1;
  1326. coord->put("x", command.value(i++));
  1327. coord->put("y", command.value(i++));
  1328. coord->put("elevation", command.value(i++));
  1329. coord->put("weather", command.value(i++));
  1330. coord->put("event_type", "trap_weather");
  1331. map->events["trap_weather"].append(coord);
  1332. }
  1333. }
  1334. QList<QStringList> *bgs = getLabelMacros(parse(text), map->bg_events_label);
  1335. map->events["sign"].clear();
  1336. map->events["event_hidden_item"].clear();
  1337. map->events["event_secret_base"].clear();
  1338. for (QStringList command : *bgs) {
  1339. if (command.value(0) == "bg_event") {
  1340. Event *bg = new Event;
  1341. bg->put("map_name", map->name);
  1342. int i = 1;
  1343. bg->put("x", command.value(i++));
  1344. bg->put("y", command.value(i++));
  1345. bg->put("elevation", command.value(i++));
  1346. bg->put("type", command.value(i++));
  1347. i++;
  1348. bg->put("script_label", command.value(i++));
  1349. //sign_unknown7
  1350. bg->put("event_type", "sign");
  1351. map->events["sign"].append(bg);
  1352. } else if (command.value(0) == "bg_hidden_item_event") {
  1353. Event *bg = new Event;
  1354. bg->put("map_name", map->name);
  1355. int i = 1;
  1356. bg->put("x", command.value(i++));
  1357. bg->put("y", command.value(i++));
  1358. bg->put("elevation", command.value(i++));
  1359. bg->put("item", command.value(i++));
  1360. bg->put("flag", command.value(i++));
  1361. bg->put("event_type", "event_hidden_item");
  1362. map->events["event_hidden_item"].append(bg);
  1363. } else if (command.value(0) == "bg_secret_base_event") {
  1364. Event *bg = new Event;
  1365. bg->put("map_name", map->name);
  1366. int i = 1;
  1367. bg->put("x", command.value(i++));
  1368. bg->put("y", command.value(i++));
  1369. bg->put("elevation", command.value(i++));
  1370. bg->put("secret_base_map", command.value(i++));
  1371. bg->put("event_type", "event_secret_base");
  1372. map->events["event_secret_base"].append(bg);
  1373. }
  1374. }
  1375. }
  1376. void Project::setNewMapEvents(Map *map) {
  1377. map->object_events_label = "0x0";
  1378. map->warps_label = "0x0";
  1379. map->coord_events_label = "0x0";
  1380. map->bg_events_label = "0x0";
  1381. map->events["object"].clear();
  1382. map->events["warp"].clear();
  1383. map->events["trap"].clear();
  1384. map->events["trap_weather"].clear();
  1385. map->events["sign"].clear();
  1386. map->events["event_hidden_item"].clear();
  1387. map->events["event_secret_base"].clear();
  1388. }
  1389. QStringList Project::readCArray(QString text, QString label) {
  1390. QStringList list;
  1391. if (label.isNull()) {
  1392. return list;
  1393. }
  1394. QRegExp *re = new QRegExp(QString("\\b%1\\b\\s*\\[?\\s*\\]?\\s*=\\s*\\{([^\\}]*)\\}").arg(label));
  1395. int pos = re->indexIn(text);
  1396. if (pos != -1) {
  1397. QString body = re->cap(1);
  1398. body = body.replace(QRegExp("\\s*"), "");
  1399. list = body.split(',');
  1400. /*
  1401. QRegExp *inner = new QRegExp("&?\\b([A-Za-z0-9_\\(\\)]*)\\b,");
  1402. int pos = 0;
  1403. while ((pos = inner->indexIn(body, pos)) != -1) {
  1404. list << inner->cap(1);
  1405. pos += inner->matchedLength();
  1406. }
  1407. */
  1408. }
  1409. return list;
  1410. }
  1411. QString Project::readCIncbin(QString text, QString label) {
  1412. QString path;
  1413. if (label.isNull()) {
  1414. return path;
  1415. }
  1416. QRegExp *re = new QRegExp(QString(
  1417. "\\b%1\\b"
  1418. "\\s*\\[?\\s*\\]?\\s*=\\s*"
  1419. "INCBIN_[US][0-9][0-9]?"
  1420. "\\(\"([^\"]*)\"\\)").arg(label));
  1421. int pos = re->indexIn(text);
  1422. if (pos != -1) {
  1423. path = re->cap(1);
  1424. }
  1425. return path;
  1426. }
  1427. QMap<QString, int> Project::readCDefines(QString text, QStringList prefixes) {
  1428. QMap<QString, int> defines;
  1429. QString combinedPrefixes = "[" + prefixes.join('|') + "]";
  1430. QRegularExpression re(QString("#define\\s+(?<defineName>%1\\w+)\\s(?<defineValue>\\w+)").arg(combinedPrefixes));
  1431. QRegularExpressionMatchIterator iter = re.globalMatch(text);
  1432. while (iter.hasNext()) {
  1433. QRegularExpressionMatch match = iter.next();
  1434. QString name = match.captured("defineName");
  1435. QString value = match.captured("defineValue");
  1436. bool valid;
  1437. int parsedValue = value.startsWith("0x") ? value.toInt(&valid, 16) : value.toInt(&valid, 10);
  1438. if (valid) {
  1439. if (!defines.contains(name)) {
  1440. defines.insert(name, parsedValue);
  1441. } else {
  1442. qDebug() << QString("Define '%1' is defined multiple times'").arg(name);
  1443. }
  1444. } else {
  1445. qDebug() << QString("Failed to parse define '%1' value '%2' as base 10 or hexadecimal value").arg(name, value);
  1446. }
  1447. }
  1448. return defines;
  1449. }