No Description

project.cpp 55KB

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