No Description

project.cpp 61KB

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