No Description

project.cpp 59KB

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