FieldCodeGenerator.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. /*
  2. * Copyright (C) 2022 The V-Gears Team
  3. *
  4. * This file is part of V-Gears
  5. *
  6. * V-Gears is free software: you can redistribute it and/or modify it under
  7. * terms of the GNU General Public License as published by the Free Software
  8. * Foundation, version 3.0 (GPLv3) of the License.
  9. *
  10. * V-Gears is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. */
  15. #include <cctype>
  16. #include <boost/algorithm/string/predicate.hpp>
  17. #include <algorithm>
  18. #include <stdexcept>
  19. #include <unordered_set>
  20. #include "FieldCodeGenerator.h"
  21. #include "FieldDisassembler.h"
  22. #include "FieldEngine.h"
  23. const std::string FieldCodeGenerator::ON_UPDATE_FINISHED_CONDITION("self.on_update_finished");
  24. const std::string FieldCodeGenerator::ON_UPDATE_FINISHED_STATEMENT("self.on_update_finished = true");
  25. const std::string FunctionMetaData::DELIMITER("_");
  26. const std::string FunctionMetaData::START("start");
  27. const std::string FunctionMetaData::END("end");
  28. FunctionMetaData::FunctionMetaData(std::string meta_data){Parse(meta_data);}
  29. bool FunctionMetaData::IsStart() const{return start_;}
  30. bool FunctionMetaData::IsEnd() const{return end_;}
  31. std::string FunctionMetaData::GetEntityName(){return entity_name_;}
  32. int FunctionMetaData::GetCharacterId(){return character_id_;}
  33. void FunctionMetaData::Parse(std::string meta_data){
  34. std::deque<std::string> strs;
  35. boost::split(strs, meta_data, boost::is_any_of(DELIMITER), boost::token_compress_on);
  36. if (!strs.empty()){
  37. auto tmp = strs.front();
  38. strs.pop_front();
  39. ParseStart(tmp, strs);
  40. }
  41. }
  42. void FunctionMetaData::ParseStart(const std::string& item, std::deque<std::string>& strs){
  43. if (item == START){
  44. start_ = true;
  45. if (!strs.empty()){
  46. auto tmp = strs.front();
  47. strs.pop_front();
  48. ParseEnd(tmp, strs);
  49. }
  50. }
  51. else ParseEnd(item, strs);
  52. }
  53. void FunctionMetaData::ParseEnd(const std::string& item, std::deque<std::string>& strs){
  54. if (item == END){
  55. end_ = true;
  56. if (!strs.empty()){
  57. auto tmp = strs.front();
  58. strs.pop_front();
  59. ParseCharId(tmp, strs);
  60. }
  61. }
  62. else ParseCharId(item, strs);
  63. }
  64. void FunctionMetaData::ParseCharId(const std::string& item, std::deque<std::string>& strs){
  65. size_t parsed_length = 0;
  66. try{
  67. const int parsed_character_id = std::stoi(item, &parsed_length);
  68. if (parsed_length == item.size()){
  69. character_id_ = parsed_character_id;
  70. if (!strs.empty()){
  71. auto tmp = strs.front();
  72. strs.pop_front();
  73. ParseEntity(tmp, strs);
  74. }
  75. return;
  76. }
  77. }
  78. catch (const std::invalid_argument&){
  79. }
  80. catch (const std::out_of_range&){
  81. }
  82. ParseEntity(item, strs);
  83. }
  84. void FunctionMetaData::ParseEntity(const std::string& item, std::deque<std::string>& strs){
  85. entity_name_ = item;
  86. for (auto& part : strs) if (!part.empty()) entity_name_ += "_" + part;
  87. }
  88. void FieldCodeGenerator::Generate(InstVec& insts, const Graph& graph){
  89. // TODO: Break into parts
  90. auto instruction = insts.begin();
  91. std::vector<std::pair<Function&, InstVec>> functions_with_bodies;
  92. for (auto function = engine_->functions.begin(); function != engine_->functions.end(); ++ function){
  93. InstVec body;
  94. for (size_t i = 0; i < function->second.num_instructions; ++ i, ++ instruction)
  95. body.push_back(*instruction);
  96. functions_with_bodies.push_back(std::pair<Function&, InstVec> {function->second, body});
  97. }
  98. for (auto function = functions_with_bodies.begin(); function != functions_with_bodies.end(); ++ function){
  99. const size_t first_line_of_function = lines_.size();
  100. OnBeforeStartFunction(function->first);
  101. auto signature = ConstructFuncSignature(function->first);
  102. AddOutputLine(signature, false, true);
  103. OnStartFunction(function->first);
  104. // Generate labels for jump instruction targets.
  105. std::unordered_map<uint32, InstVec> labels;
  106. for (auto instruction = function->second.begin(); instruction != function->second.end(); ++ instruction){
  107. if ((*instruction)->IsCondJump() || (*instruction)->IsUncondJump()){
  108. auto targetAddr = (*instruction)->GetDestAddress();
  109. auto label = labels.find(targetAddr);
  110. if (label == labels.end()) labels.insert({targetAddr, InstVec()});
  111. labels[targetAddr].push_back(*instruction);
  112. }
  113. }
  114. // Lua can't jump into a block. If a jump from outside of the body of a conditional lands
  115. // in the middle of it, the conditional is written as a jump over its body instead of a
  116. // block, so the label ends up where every jump can see it.
  117. std::unordered_set<const Instruction*> flattened;
  118. for (auto cond = function->second.begin(); cond != function->second.end(); ++ cond){
  119. if (!(*cond)->IsCondJump()) continue;
  120. const uint32 start = (*cond)->GetAddress();
  121. const uint32 end = (*cond)->GetDestAddress();
  122. // The target has to be in the function to have a label.
  123. const bool target_in_function = std::any_of(
  124. function->second.begin(), function->second.end(),
  125. [end](const InstPtr& i){return i->GetAddress() == end;}
  126. );
  127. if (!target_in_function) continue;
  128. for (auto jump = function->second.begin(); jump != function->second.end(); ++ jump){
  129. if (!(*jump)->IsUncondJump()) continue;
  130. const uint32 destination = (*jump)->GetDestAddress();
  131. const uint32 origin = (*jump)->GetAddress();
  132. if (destination > start && destination < end && (origin < start || origin >= end)){
  133. flattened.insert(cond->get());
  134. break;
  135. }
  136. }
  137. }
  138. // Implemented instructions.
  139. // Some conditional jumps point to an address outside the function (i.e the starting
  140. // address of the next function) and the 'end' are not written to the Lua script. Keep
  141. // track of how many are needed and add them at the end of the function.
  142. int ends_needed = 0;
  143. for (auto instruction = function->second.begin(); instruction != function->second.end(); ++ instruction){
  144. auto label = labels.find((*instruction)->GetAddress());
  145. if (label != labels.end()){
  146. bool needs_label = false;
  147. bool needs_new_line = false;
  148. for (auto origin = label->second.begin(); origin != label->second.end(); ++ origin){
  149. if ((*origin)->IsCondJump() && flattened.count(origin->get()) == 0){
  150. ends_needed --;
  151. AddOutputLine("end", true, false);
  152. needs_new_line = true;
  153. }
  154. else needs_label = true;
  155. }
  156. if (needs_new_line) AddOutputLine("");
  157. if (needs_label) AddOutputLine((boost::format("::label_0x%1$X::") % label->first).str());
  158. }
  159. ValueStack stack;
  160. (*instruction)->ProcessInst(function->first, stack, engine_, this);
  161. //if (end_needed){
  162. // AddOutputLine("end -- end if", true, false);
  163. // end_needed = false;
  164. //}
  165. if ((*instruction)->IsCondJump() && flattened.count(instruction->get()) != 0){
  166. AddOutputLine((
  167. boost::format("if not (%s) then goto label_0x%X end")
  168. % stack.Pop()->GetString() % (*instruction)->GetDestAddress()
  169. ).str());
  170. }
  171. else if ((*instruction)->IsCondJump()){
  172. ends_needed ++;
  173. AddOutputLine((boost::format("if (%s) then") % stack.Pop()->GetString()).str(), false, true);
  174. // If the next instruction is the last in the function, mark the next pass to
  175. // add an 'end' after the instruction to close the if.
  176. //if ((*(instruction + 1))->GetAddress() == (*(function->second.back())).GetAddress())
  177. // end_needed = true;
  178. }
  179. else if ((*instruction)->IsUncondJump()){
  180. // If destination address is outside the functions, turn goto into a return.
  181. if ((*instruction)->GetDestAddress() > function->first.end_addr){
  182. AddOutputLine(
  183. "-- Overflowed jump to " + (boost::format("0x%1$X") % (*instruction)->GetDestAddress()).str()
  184. + " (last address in function is " + (boost::format("0x%1$X)") % function->first.end_addr).str()
  185. );
  186. if ("on_update" == function->first.name) AddOutputLine(ON_UPDATE_FINISHED_STATEMENT);
  187. AddOutputLine("do return 0 end");
  188. }
  189. // Prevent backward jumps in the on_start script.
  190. else if (
  191. "on_start" == function->first.name && (*instruction)->GetDestAddress() <= (*instruction)->GetAddress()
  192. ){
  193. AddOutputLine("-- No infinite loops in the on_start script.");
  194. AddOutputLine((boost::format("-- goto label_0x%1$X") % (*instruction)->GetDestAddress()).str());
  195. }
  196. else AddOutputLine((boost::format("goto label_0x%1$X") % (*instruction)->GetDestAddress()).str());
  197. }
  198. // Else, already output'd.
  199. }
  200. for(; ends_needed > 0; ends_needed --) AddOutputLine("end -- clean-up", true, false);
  201. // Add missing return:
  202. if ("return 0" != lines_.at(lines_.size() - 1).line && "do return 0 end" != lines_.at(lines_.size() - 1).line){
  203. if ("on_update" == function->first.name) AddOutputLine(ON_UPDATE_FINISHED_STATEMENT);
  204. // A function with no return goes on in the code of the next script.
  205. FunctionMetaData fall_meta(function->first.metadata);
  206. const std::string next = static_cast<FieldEngine*>(engine_)->GetFunctionFallThrough(
  207. fall_meta.GetEntityName(), function->first.name
  208. );
  209. if (!next.empty())
  210. AddOutputLine(
  211. "return EntityContainer[\"" + fall_meta.GetEntityName() + "\"]."
  212. + formatter_.GetFriendlyFunctionName(fall_meta.GetEntityName(), next) + "(self)"
  213. );
  214. else AddOutputLine("do return 0 end", false, false);
  215. }
  216. // A goto to a label that isn't in the function can't be compiled, and the whole script
  217. // would fail to load. It can't continue where it was told to, so it ends the script.
  218. {
  219. std::unordered_set<std::string> emitted_labels;
  220. for (size_t i = first_line_of_function; i < lines_.size(); ++ i)
  221. if (lines_[i].line.rfind("::label_0x", 0) == 0) emitted_labels.insert(lines_[i].line);
  222. for (size_t i = first_line_of_function; i < lines_.size(); ++ i){
  223. const std::string prefix = "goto label_0x";
  224. if (lines_[i].line.rfind(prefix, 0) != 0) continue;
  225. const std::string label = "::" + lines_[i].line.substr(5) + "::";
  226. if (emitted_labels.count(label) == 0)
  227. lines_[i].line = "do return 0 end -- was: " + lines_[i].line + " (not in this function)";
  228. }
  229. }
  230. OnEndFunction(function->first);
  231. }
  232. for (auto i = lines_.begin(); i != lines_.end(); ++i){
  233. if (i->unindent_before && indent_level_ > 0) indent_level_ --;
  234. output_ << IndentString(i->line) << std::endl;
  235. if (i->indent_after) indent_level_++;
  236. }
  237. }
  238. void FieldCodeGenerator::AddOutputLine(std::string line, bool unindent_before, bool indent_after){
  239. lines_.push_back(CodeLine(line, unindent_before, indent_after));
  240. }
  241. float FieldCodeGenerator::GetScaleFactor() const{return static_cast<FieldEngine*>(engine_)->GetScaleFactor();}
  242. // A name can be a field of a table written as "name = value" only if it is an identifier of Lua. The
  243. // entities of some fields have names such as "60f_1".
  244. static bool IsLuaIdentifier(const std::string& name){
  245. if (name.empty() || std::isdigit(static_cast<unsigned char>(name[0]))) return false;
  246. for (const char c : name)
  247. if (!std::isalnum(static_cast<unsigned char>(c)) && c != '_') return false;
  248. return true;
  249. }
  250. void FieldCodeGenerator::OnBeforeStartFunction(const Function& function){
  251. FunctionMetaData meta_data(function.metadata);
  252. if (meta_data.IsStart()){
  253. AddOutputLine("EntityContainer[\"" + meta_data.GetEntityName() + "\"] = {", false, true);
  254. if (meta_data.GetCharacterId() != -1) AddOutputLine(meta_data.GetEntityName() + " = nil,\n");
  255. // Entities without a model (the Director and other helper scripts) still run the opcodes
  256. // that move or hide a model, and they do nothing. Give them an object that ignores them.
  257. else if (IsLuaIdentifier(meta_data.GetEntityName()))
  258. AddOutputLine(meta_data.GetEntityName() + " = NullEntity,\n");
  259. }
  260. const auto comment = formatter_.GetFunctionComment(meta_data.GetEntityName(), function.name);
  261. if (!comment.empty()) AddOutputLine("-- " + comment);
  262. }
  263. void FieldCodeGenerator::OnStartFunction(const Function& func){
  264. // Add some hacks for Director entity before the comments
  265. FunctionMetaData meta_data(func.metadata);
  266. if (meta_data.GetEntityName() == "Director" && func.name == "on_start"){
  267. // TODO: Don't hardcode Cloud, Use the one from the previous level,
  268. // The entity of Cloud is called "Cloud" in most fields, but not in all of them (md0 and
  269. // sinbil_1 call it "CLOUD", for example).
  270. std::string player_name = "Cloud";
  271. for (auto& other : static_cast<FieldEngine*>(engine_)->functions){
  272. FunctionMetaData other_meta(other.second.metadata);
  273. std::string lower = other_meta.GetEntityName();
  274. std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
  275. if (lower == "cloud"){
  276. player_name = other_meta.GetEntityName();
  277. break;
  278. }
  279. }
  280. AddOutputLine("-- HACK: Set default playable entity an ensure the camera follows it.");
  281. AddOutputLine("place_player_at_map_entry(\"" + player_name + "\")");
  282. AddOutputLine(
  283. "background2d:autoscroll_to_entity(entity_manager:get_entity(\"" + player_name + "\"))\n"
  284. );
  285. }
  286. // Don't run on_update again once it has reached its end.
  287. if (func.name == "on_update"){
  288. AddOutputLine("if " + ON_UPDATE_FINISHED_CONDITION + " then", false, true);
  289. AddOutputLine("return 0");
  290. AddOutputLine("end", true, false);
  291. }
  292. // For lines, exit if they are off.
  293. if (
  294. func.name == "on_approach" || func.name == "on_cross" || func.name == "on_near"
  295. || func.name == "on_near_once" || func.name == "on_leave"
  296. ){
  297. AddOutputLine("if self.on ~= nil and self.on == false then", false, true);
  298. AddOutputLine("return 0");
  299. AddOutputLine("end", true, false);
  300. }
  301. AddOutputLine("--[[");
  302. for (const auto& inst : insts_){
  303. if (inst->GetAddress() >= func.start_addr && inst->GetAddress() <= func.end_addr){
  304. std::stringstream output;
  305. output << inst;
  306. AddOutputLine(output.str());
  307. }
  308. }
  309. AddOutputLine("]]\n");
  310. }
  311. void FieldCodeGenerator::OnEndFunction(const Function& function){
  312. // End function.
  313. AddOutputLine("end,", true, false);
  314. // End class?
  315. FunctionMetaData meta_data(function.metadata);
  316. if (meta_data.IsEnd()){
  317. AddOutputLine("}\n", true, false);
  318. // The scripts of the entity that have the same code as other of its scripts.
  319. for (const auto& alias : static_cast<FieldEngine*>(engine_)->GetFunctionAliases()){
  320. if (alias.entity_name != meta_data.GetEntityName()) continue;
  321. const std::string container = "EntityContainer[\"" + alias.entity_name + "\"]";
  322. const std::string alias_name
  323. = formatter_.GetFriendlyFunctionName(alias.entity_name, alias.alias);
  324. const std::string target_name
  325. = formatter_.GetFriendlyFunctionName(alias.entity_name, alias.target);
  326. // The events of a line don't run while it is off, as in the functions of their own.
  327. if (
  328. alias.alias == "on_approach" || alias.alias == "on_cross" || alias.alias == "on_near"
  329. || alias.alias == "on_near_once" || alias.alias == "on_leave"
  330. ){
  331. AddOutputLine(
  332. container + "." + alias_name + " = function(self, ...)", false, true
  333. );
  334. AddOutputLine("if self.on ~= nil and self.on == false then", false, true);
  335. AddOutputLine("return 0");
  336. AddOutputLine("end", true, false);
  337. AddOutputLine("return " + container + "." + target_name + "(self, ...)");
  338. AddOutputLine("end", true, false);
  339. }
  340. else AddOutputLine(container + "." + alias_name + " = " + container + "." + target_name);
  341. }
  342. AddOutputLine("\n\n");
  343. }
  344. else AddOutputLine("\n");
  345. }
  346. std::string FieldCodeGenerator::ConstructFuncSignature(const Function &function){
  347. // Generate name
  348. FunctionMetaData meta_data(function.metadata);
  349. return formatter_.GetFriendlyFunctionName(meta_data.GetEntityName(), function.name) + " = function(self)";
  350. }
  351. bool FieldCodeGenerator::OutputOnlyRequiredLabels() const{return true;}
  352. FieldScriptFormatter& FieldCodeGenerator::GetFormatter(){return formatter_;}
  353. const int FieldCodeGenerator::DEFAULT_WINDOW_X = 16;
  354. const int FieldCodeGenerator::DEFAULT_WINDOW_Y = 176;
  355. const int FieldCodeGenerator::DEFAULT_WINDOW_WIDTH = 288;
  356. const int FieldCodeGenerator::DEFAULT_WINDOW_HEIGHT = 56;
  357. bool FieldCodeGenerator::IsWindowDefined(uint32 window_id) const{
  358. if (!defined_windows_collected_){
  359. for (const auto& inst : insts_){
  360. const uint32 opcode = inst->GetOpcode();
  361. if (opcode == OPCODES::WINDOW || opcode == OPCODES::WSIZW)
  362. defined_windows_.insert(inst->GetParam(0)->GetUnsigned());
  363. }
  364. defined_windows_collected_ = true;
  365. }
  366. return defined_windows_.find(window_id) != defined_windows_.end();
  367. }
  368. const std::string FieldCodeGenerator::FormatInstructionNotImplemented(
  369. const std::string& entity, uint32 address, uint32 opcode
  370. ){
  371. return (
  372. boost::format(
  373. "-- log:log(\"In entity \\\"%1%\\\", address 0x%2$08x: instruction 0x%3$04x not implemented\")"
  374. ) % entity % address % opcode
  375. ).str();
  376. }
  377. const std::string FieldCodeGenerator::FormatInstructionNotImplemented(
  378. const std::string& entity, uint32 address, const Instruction& instruction
  379. ){
  380. std::stringstream parameterList;
  381. //for (auto i = instruction._params.begin(); i != instruction._params.end(); ++ i){
  382. for (auto i = instruction.GetParams().begin(); i != instruction.GetParams().end(); ++ i){
  383. //if (i != instruction._params.begin()) parameterList << ", ";
  384. if (i != instruction.GetParams().begin()) parameterList << ", ";
  385. parameterList << *i;
  386. }
  387. return(
  388. boost::format(
  389. "-- log:log(\"In entity \\\"%1%\\\", address 0x%2$08x: instruction %3%(%4%) not implemented\")"
  390. ) % entity % address % instruction.GetName() % parameterList.str()
  391. ).str();
  392. }
  393. const std::string FieldCodeGenerator::FormatBool(uint32 value){return value == 0 ? "false" : "true";}
  394. const std::string FieldCodeGenerator::FormatInvertedBool(uint32 value){return value == 0 ? "true" : "false";}