ScriptManager.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  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 <algorithm>
  16. #include "engine/config/ConfigVar.h"
  17. #include "engine/graphics/DebugDraw.h"
  18. #include "common/Logger.h"
  19. #include "core/ScriptManager.h"
  20. #include "core/ScriptManagerBinds.h"
  21. #include "core/ScriptManagerCommands.h"
  22. #include "core/Timer.h"
  23. #include "common/Utilites.h"
  24. #include "core/XmlScriptsFile.h"
  25. #include "LuaIncludes.h"
  26. ConfigVar cv_debug_script(
  27. "debug_script", "Debug script flags. 0x01 - System, 0x02 - Entity, 0x04 - Ui.", "0"
  28. );
  29. /**
  30. * Script manager singleton.
  31. */
  32. template<>ScriptManager *Ogre::Singleton<ScriptManager>::msSingleton = nullptr;
  33. Ogre::String script_entity_type[] = {"SYSTEM", "ENTITY", "UI", "BATTLE"};
  34. /**
  35. * Compares the priority of two scripts.
  36. *
  37. * @param[in] a The first script to compare.
  38. * @param[in] b The second script to compare.
  39. * @return True if the script a has a lower priority number than b, false if a has a higher or
  40. * equal priority than b.
  41. */
  42. bool priority_queue_compare(QueueScript a, QueueScript b){return a.priority < b.priority;}
  43. ScriptManager::ScriptManager():
  44. system_table_name_("System"), entity_table_name_("EntityContainer"), ui_table_name_("UiContainer")
  45. {
  46. lua_state_ = lua_open();
  47. sol::register_main_thread(lua_state_);
  48. luaopen_base(lua_state_);
  49. luaopen_string(lua_state_);
  50. luaopen_table(lua_state_);
  51. luaopen_math(lua_state_);
  52. luaopen_io(lua_state_);
  53. InitBinds();
  54. InitCmd();
  55. // TODO: Use the one in data/ ?
  56. RunFile("system/system.lua");
  57. XmlScriptsFile scripts("./data/scripts/_scripts.xml");
  58. scripts.LoadScripts();
  59. }
  60. ScriptManager::~ScriptManager(){lua_close(lua_state_);}
  61. void ScriptManager::Input(const VGears::Event& event){
  62. if (
  63. event.event != ""
  64. && (event.type == VGears::ET_KEY_PRESS || event.type == VGears::ET_KEY_REPEAT_WAIT)
  65. ){
  66. Ogre::String argument2 = "";
  67. if (event.type == VGears::ET_KEY_PRESS) argument2 = "Press";
  68. else if (event.type == VGears::ET_KEY_REPEAT_WAIT) argument2 = "Repeat";
  69. const Ogre::String source_key = KeyToString(
  70. static_cast<OIS::KeyCode>(event.param1)
  71. );
  72. for (unsigned int i = 0; i < script_entity_.size(); ++ i){
  73. ScriptRequest(
  74. &script_entity_[i], "on_button", 100,
  75. event.event, argument2, false, false, source_key, true
  76. );
  77. }
  78. return;
  79. }
  80. if (
  81. (event.type == VGears::ET_KEY_PRESS || event.type == VGears::ET_KEY_REPEAT_WAIT)
  82. && (
  83. // Only the keys that scripts read by themselves reach them as raw keys: the letters and the
  84. // space bar, to type in the name menu and for the debug keys of the battle. Everything else
  85. // goes through the game events of config.cfg, so it can be remapped.
  86. // TODO: Do this the other way: block keys NOT TO pass to scripts.
  87. event.param1 == OIS::KC_SPACE
  88. || event.param1 == OIS::KC_A || event.param1 == OIS::KC_B || event.param1 == OIS::KC_C
  89. || event.param1 == OIS::KC_D || event.param1 == OIS::KC_E || event.param1 == OIS::KC_F
  90. || event.param1 == OIS::KC_G || event.param1 == OIS::KC_H || event.param1 == OIS::KC_I
  91. || event.param1 == OIS::KC_J || event.param1 == OIS::KC_K || event.param1 == OIS::KC_L
  92. || event.param1 == OIS::KC_M || event.param1 == OIS::KC_N || event.param1 == OIS::KC_O
  93. || event.param1 == OIS::KC_P || event.param1 == OIS::KC_Q || event.param1 == OIS::KC_R
  94. || event.param1 == OIS::KC_S || event.param1 == OIS::KC_T || event.param1 == OIS::KC_U
  95. || event.param1 == OIS::KC_V || event.param1 == OIS::KC_W || event.param1 == OIS::KC_X
  96. || event.param1 == OIS::KC_Y || event.param1 == OIS::KC_Z || event.param1 == OIS::KC_X
  97. )
  98. ){
  99. for (unsigned int i = 0; i < script_entity_.size(); ++ i){
  100. Ogre::String argument2 = "";
  101. if (event.type == VGears::ET_KEY_PRESS) argument2 = "Press";
  102. else if (event.type == VGears::ET_KEY_REPEAT_WAIT) argument2 = "Repeat";
  103. ScriptRequest(
  104. &script_entity_[i], "on_button", 100,
  105. KeyToString((OIS::KeyCode) ((int) event.param1)), argument2, false, false
  106. );
  107. }
  108. }
  109. }
  110. void ScriptManager::Update(const ScriptManager::Type type){
  111. // Remove the scripts that a request has replaced.
  112. for (unsigned int i = 0; i < script_entity_.size(); ++ i){
  113. if (script_entity_[i].type != type) continue;
  114. for (size_t k = script_entity_[i].queue.size(); k --;){
  115. if (script_entity_[i].queue[k].replaced) RemoveEntityScript(script_entity_[i], k);
  116. }
  117. }
  118. // Resort all queue. This will give correct info for debug draw.
  119. for (unsigned int i = 0; i < script_entity_.size(); ++ i){
  120. if (script_entity_[i].type == type){
  121. if (script_entity_[i].queue.size() > 0){
  122. if (script_entity_[i].resort == true){
  123. std::stable_sort(
  124. script_entity_[i].queue.begin(),
  125. script_entity_[i].queue.end(), priority_queue_compare
  126. );
  127. script_entity_[i].resort = false;
  128. }
  129. }
  130. }
  131. }
  132. // Draw debug before update. This way it will be possible to see
  133. // scripts that run once
  134. int debug = cv_debug_script.GetI();
  135. if (debug != 0){
  136. DEBUG_DRAW.SetTextAlignment(DEBUG_DRAW.LEFT);
  137. DEBUG_DRAW.SetScreenSpace(true);
  138. int y = 34;
  139. for (unsigned int i = 0; i < 3; ++ i){
  140. if ((debug & (1 << i)) != 0){
  141. DEBUG_DRAW.SetColour(Ogre::ColourValue(0.8f, 0.8f, 0.0f, 1.0f));
  142. DEBUG_DRAW.Text(
  143. 10.0f, static_cast<float>(y), "Script \"" + script_entity_type[i] + "\" entity:"
  144. );
  145. y += 16;
  146. for (unsigned int j = 0; j < script_entity_.size(); ++ j){
  147. if (script_entity_[j].type == i){
  148. Ogre::String text = script_entity_[j].name;
  149. unsigned int queue_size = script_entity_[j].queue.size();
  150. if (queue_size > 0){
  151. text += ": ";
  152. DEBUG_DRAW.SetColour(Ogre::ColourValue(0.8f, 0.8f, 0.0f, 1.0f));
  153. }
  154. else DEBUG_DRAW.SetColour(Ogre::ColourValue(0.5, 0.5, 0.5, 1));
  155. for (unsigned int k = 0; k < queue_size; ++ k){
  156. if (k > 0) text += ", ";
  157. text +=
  158. "("
  159. + Ogre::StringConverter::toString(script_entity_[j].queue[k].priority)
  160. + ")" + script_entity_[j].queue[k].function;
  161. if (script_entity_[j].queue[k].wait == true){
  162. if (script_entity_[j].queue[k].seconds_to_wait != 0){
  163. text +=
  164. ":wait("+ Ogre::StringConverter::toString(
  165. script_entity_[j].queue[k].seconds_to_wait
  166. ) + ")";
  167. }
  168. }
  169. }
  170. DEBUG_DRAW.Text(20.0f, static_cast<float>(y), text);
  171. y += 16;
  172. }
  173. }
  174. }
  175. }
  176. }
  177. // Before updating entities, call on_update on the system timer.
  178. RunString("Timer.update()");
  179. for (unsigned int i = 0; i < script_entity_.size(); ++ i){
  180. if (script_entity_[i].type == type){
  181. // One script of an entity is run each cycle, the first in the queue. If it yields
  182. // without waiting for anything, as the ones that loop for ever, or until a flag
  183. // changes, do, it doesn't take the cycle of the rest: the next one is run too. In the
  184. // original game the scripts of an entity that have different priorities all run.
  185. for (size_t script_index = 0; script_index < script_entity_[i].queue.size(); ++ script_index){
  186. bool yielded = false;
  187. current_script_id_.entity = script_entity_[i].name;
  188. current_script_id_.function = script_entity_[i].queue[script_index].function;
  189. if (script_entity_[i].queue[script_index].wait == false){
  190. if (script_entity_[i].queue[script_index].yield == false){
  191. LOG_TRIVIAL(
  192. "[SCRIPT] Start script \"" + current_script_id_.function
  193. + "\" for entity \"" + current_script_id_.entity + "\"."
  194. );
  195. for (const ScriptId& waiting : script_entity_[i].queue[script_index].paused_scripts_start)
  196. ContinueScriptExecution(waiting);
  197. script_entity_[i].queue[script_index].paused_scripts_start.clear();
  198. sol::object table = GetTableByEntityName(
  199. type, current_script_id_.entity,
  200. script_entity_[i].queue[script_index].state
  201. );
  202. sol::object function;
  203. if (table.get_type() == sol::type::table)
  204. function = table.as<sol::table>()[current_script_id_.function];
  205. if (
  206. table.get_type() == sol::type::table
  207. && function.get_type() == sol::type::function
  208. ){
  209. int ret = 0;
  210. lua_State* thread = script_entity_[i].queue[script_index].state;
  211. sol::coroutine coroutine(thread, sol::function(function));
  212. auto result = coroutine(
  213. table, script_entity_[i].queue[script_index].argument1,
  214. script_entity_[i].queue[script_index].argument2,
  215. script_entity_[i].queue[script_index].argument3
  216. );
  217. if (result.valid()){
  218. // The coroutine yields with the bound function
  219. // return value on top of the thread stack; a
  220. // completed script leaves its return value there.
  221. if (lua_gettop(thread) > 0 && lua_isnumber(thread, -1))
  222. ret = static_cast<int>(lua_tointeger(thread, -1));
  223. lua_settop(thread, 0);
  224. }
  225. else{
  226. sol::error error = result;
  227. std::string msg = "LUA error in entity " + script_entity_[i].name
  228. + " (" + current_script_id_.entity + ") " + " in function "
  229. + script_entity_[i].queue[script_index].function + " ("
  230. + current_script_id_.function + ")";
  231. if (lua_tostring(thread, -1) != nullptr){
  232. msg = msg + ". Details: " + std::string(
  233. lua_tostring(thread, -1)
  234. );
  235. }
  236. msg = msg + ". Exception: " + error.what();
  237. LOG_ERROR(msg);
  238. lua_settop(thread, 0);
  239. }
  240. if (ret == 0){
  241. LOG_TRIVIAL(
  242. "[SCRIPT] Script \"" + current_script_id_.function
  243. + "\" for entity \"" + current_script_id_.entity + "\" finished."
  244. );
  245. if (script_entity_[i].queue[script_index].function != "on_update")
  246. RemoveEntityScript(script_entity_[i], script_index);
  247. }
  248. else if (ret == 1){
  249. LOG_TRIVIAL(
  250. "[SCRIPT] Script \"" + current_script_id_.function
  251. + "\" for entity \"" + current_script_id_.entity
  252. + "\" not paused and will be continued next cycle."
  253. );
  254. script_entity_[i].queue[script_index].yield = true;
  255. yielded = true;
  256. }
  257. else{
  258. LOG_TRIVIAL(
  259. "[SCRIPT] Script \"" + current_script_id_.function
  260. + "\" for entity \"" + current_script_id_.entity
  261. + "\" not finished yet."
  262. );
  263. script_entity_[i].queue[script_index].yield = true;
  264. script_entity_[i].queue[script_index].wait = true;
  265. }
  266. }
  267. else{
  268. LOG_WARNING(
  269. "Script \"" + current_script_id_.function + "\" for entity \""
  270. + current_script_id_.entity + "\" doesn't exist."
  271. );
  272. RemoveEntityScript(script_entity_[i], script_index);
  273. }
  274. }
  275. else{
  276. LOG_TRIVIAL(
  277. "[SCRIPT] Continue function \"" + current_script_id_.function
  278. + "\" for entity \"" + current_script_id_.entity + "\"."
  279. );
  280. int ret = 0;
  281. lua_State* thread = script_entity_[i].queue[script_index].state;
  282. // sol.hpp bundles a compat53 shim: on LuaJIT this maps
  283. // to the native 2-argument lua_resume.
  284. int status = lua_resume(thread, nullptr, 0);
  285. if (status == LUA_YIELD || status == 0){
  286. if (lua_gettop(thread) > 0 && lua_isnumber(thread, -1))
  287. ret = static_cast<int>(lua_tointeger(thread, -1));
  288. lua_settop(thread, 0);
  289. }
  290. else{
  291. const char* error = lua_tostring(thread, -1);
  292. LOG_WARNING(
  293. Ogre::String(error != nullptr ? error : "unknown lua error")
  294. );
  295. lua_settop(thread, 0);
  296. }
  297. if (ret == 0){ // Finished.
  298. LOG_TRIVIAL(
  299. "[SCRIPT] Script \"" + current_script_id_.function
  300. + "\" for entity \"" + current_script_id_.entity + "\" finished."
  301. );
  302. // Stop yield for on_update.
  303. script_entity_[i].queue[script_index].yield = false;
  304. if (script_entity_[i].queue[script_index].function != "on_update")
  305. RemoveEntityScript(script_entity_[i], script_index);
  306. }
  307. else if (ret == 1){
  308. LOG_TRIVIAL(
  309. "[SCRIPT] Script \"" + current_script_id_.function
  310. + "\" for entity \"" + current_script_id_.entity
  311. + "\" not paused and will be continued next cycle."
  312. );
  313. yielded = true;
  314. }
  315. else{
  316. LOG_TRIVIAL(
  317. "[SCRIPT] Script \"" + current_script_id_.function
  318. + "\" for entity \"" + current_script_id_.entity
  319. + "\" not finished yet."
  320. );
  321. script_entity_[i].queue[script_index].wait = true;
  322. }
  323. }
  324. }
  325. else if (script_entity_[i].queue[script_index].seconds_to_wait > 0){
  326. script_entity_[i].queue[script_index].seconds_to_wait
  327. -= Timer::getSingleton().GetGameTimeDelta();
  328. script_entity_[i].queue[script_index].seconds_to_wait
  329. = (script_entity_[i].queue[script_index].seconds_to_wait < 0)
  330. ? 0 : script_entity_[i].queue[script_index].seconds_to_wait;
  331. if (script_entity_[i].queue[script_index].seconds_to_wait == 0)
  332. script_entity_[i].queue[script_index].wait = false;
  333. }
  334. if (!yielded){
  335. // The scripts of an entity don't wait for each other in the original game. If
  336. // the first one is waiting (for another script to end, for example) and a
  337. // script that someone waits to start (request_start_sync) is queued behind
  338. // it, that script has to start, or the two would wait for each other forever
  339. // (the lines of mrkt3 do this with Aerith).
  340. bool start_waited_script = false;
  341. for (size_t next = script_index + 1; next < script_entity_[i].queue.size(); ++ next){
  342. const QueueScript& queued = script_entity_[i].queue[next];
  343. if (!queued.yield && !queued.wait && !queued.paused_scripts_start.empty()){
  344. script_index = next - 1;
  345. start_waited_script = true;
  346. break;
  347. }
  348. }
  349. if (!start_waited_script) break;
  350. }
  351. }
  352. }
  353. }
  354. }
  355. void ScriptManager::UpdateDebug(){}
  356. void ScriptManager::OnResize(){}
  357. void ScriptManager::ClearField(){}
  358. void ScriptManager::ClearBattle(){
  359. // Remove all battle script entities.
  360. for (unsigned int i = 0; i < script_entity_.size(); ++ i){
  361. if (script_entity_[i].type == BATTLE){
  362. while(script_entity_[i].queue.size() > 0)
  363. ScriptManager::RemoveEntityTopScript(script_entity_[i]);
  364. script_entity_.erase(script_entity_.begin() + i);
  365. i --;
  366. }
  367. }
  368. }
  369. void ScriptManager::ClearWorld(){}
  370. void ScriptManager::RunString(const Ogre::String& lua){
  371. int pre_eval_index = lua_gettop(lua_state_);
  372. if (luaL_dostring(lua_state_, lua.c_str()) == 1)
  373. LOG_ERROR("ScriptManager::RunString error: " + Ogre::String(lua_tostring(lua_state_, -1)));
  374. else{
  375. int index = lua_gettop(lua_state_);
  376. if (index > 0 && index != pre_eval_index){
  377. auto str = lua_tostring(lua_state_, index);
  378. LOG_CONSOLE(
  379. str != nullptr ? str : "ScriptManager::RunString: (nullptr; try tostring(...)?)"
  380. );
  381. lua_pop(lua_state_, 1);
  382. }
  383. }
  384. }
  385. float ScriptManager::EvaluateNumber(const Ogre::String& expression, const float default_value){
  386. const int pre_eval_index = lua_gettop(lua_state_);
  387. float result = default_value;
  388. if (luaL_dostring(lua_state_, ("return " + expression).c_str()) != 0){
  389. LOG_ERROR("ScriptManager::EvaluateNumber error: " + Ogre::String(lua_tostring(lua_state_, -1)));
  390. }
  391. else if (lua_gettop(lua_state_) > pre_eval_index && lua_isnumber(lua_state_, -1)){
  392. result = static_cast<float>(lua_tonumber(lua_state_, -1));
  393. }
  394. lua_settop(lua_state_, pre_eval_index);
  395. return result;
  396. }
  397. void ScriptManager::RunFile(const Ogre::String& file){
  398. if (luaL_dofile(lua_state_, ("./data/" + file).c_str()) == 1)
  399. LOG_ERROR(Ogre::String(lua_tostring(lua_state_, -1)));
  400. }
  401. void ScriptManager::AddEntity(
  402. const ScriptManager::Type type, const Ogre::String& entity_name, Entity* entity
  403. ){
  404. for (unsigned int i = 0; i < script_entity_.size(); ++ i){
  405. if (script_entity_[i].type == type && script_entity_[i].name == entity_name){
  406. LOG_ERROR(
  407. "Script \"" + script_entity_type[type] + "\" entity \""
  408. + entity_name + "\" already exist in script manager."
  409. );
  410. return;
  411. }
  412. }
  413. sol::object table = GetTableByEntityName(type, entity_name, lua_state_);
  414. if (table.get_type() == sol::type::table){
  415. ScriptEntity script_entity;
  416. script_entity.name = entity_name;
  417. script_entity.type = type;
  418. // Initialize entity field for model entity.
  419. if (entity != nullptr) table.as<sol::table>()["entity"] = entity;
  420. // Check the "on_start" script
  421. sol::object on_start = table.as<sol::table>()["on_start"];
  422. if (on_start.get_type() == sol::type::function){
  423. QueueScript script;
  424. script.function = "on_start";
  425. script.priority = 1;
  426. script.state = lua_newthread(lua_state_);
  427. // The thread must not be garbage collected,
  428. // so it need to be stored.
  429. script.state_id = luaL_ref(lua_state_, LUA_REGISTRYINDEX);
  430. script.seconds_to_wait = 0;
  431. script.wait = false;
  432. script.yield = false;
  433. script_entity.queue.push_back(script);
  434. }
  435. // Check the "on_update" script.
  436. sol::object on_update = table.as<sol::table>()["on_update"];
  437. if (on_update.get_type() == sol::type::function){
  438. QueueScript script;
  439. script.function = "on_update";
  440. script.priority = 999;
  441. script.state = lua_newthread(lua_state_);
  442. // The thread must not be garbage collected,
  443. // so it need to be stored.
  444. script.state_id = luaL_ref(lua_state_, LUA_REGISTRYINDEX);
  445. script.seconds_to_wait = 0;
  446. script.wait = false;
  447. script.yield = false;
  448. script_entity.queue.push_back(script);
  449. }
  450. script_entity_.push_back(script_entity);
  451. }
  452. }
  453. void ScriptManager::RemoveEntity(const ScriptManager::Type type, const Ogre::String& entity_name){
  454. for (unsigned int i = 0; i < script_entity_.size(); ++ i){
  455. if (script_entity_[i].type == type && script_entity_[i].name == entity_name){
  456. while(script_entity_[i].queue.size() > 0)
  457. ScriptManager::RemoveEntityTopScript(script_entity_[i]);
  458. script_entity_.erase(script_entity_.begin() + i);
  459. return;
  460. }
  461. }
  462. }
  463. void ScriptManager::RemoveEntityScript(ScriptEntity& entity, const size_t index){
  464. if (entity.queue.size() > index){
  465. // Delete the thread.
  466. luaL_unref(lua_state_, LUA_REGISTRYINDEX, entity.queue[index].state_id);
  467. for (const ScriptId& waiting : entity.queue[index].paused_scripts_end)
  468. ContinueScriptExecution(waiting);
  469. entity.queue[index].paused_scripts_end.clear();
  470. entity.queue.erase(entity.queue.begin() + index);
  471. }
  472. }
  473. void ScriptManager::RemoveEntityTopScript(ScriptEntity& entity){RemoveEntityScript(entity, 0);}
  474. sol::object ScriptManager::GetTableByEntityName(
  475. const ScriptManager::Type type, const Ogre::String& name, lua_State* state
  476. ) const{
  477. // Get the real table by name
  478. Ogre::StringVector table_path = StringTokenise(name, ".");
  479. sol::state_view lua(state);
  480. sol::object table = lua.globals();
  481. switch(type){
  482. case ScriptManager::SYSTEM:
  483. table = table.as<sol::table>()[system_table_name_]; break;
  484. case ScriptManager::ENTITY:
  485. table = table.as<sol::table>()[entity_table_name_]; break;
  486. case ScriptManager::UI:
  487. table = table.as<sol::table>()[ui_table_name_]; break;
  488. case ScriptManager::BATTLE:
  489. table = table.as<sol::table>()[battle_table_name_]; break;
  490. }
  491. if (table.get_type() != sol::type::table) return sol::make_object(state, sol::nil);
  492. for (unsigned int i = 0; i < table_path.size(); ++ i){
  493. table = table.as<sol::table>()[table_path[i]];
  494. if (table.get_type() != sol::type::table) return sol::make_object(state, sol::nil);
  495. }
  496. return table;
  497. }
  498. QueueScript* ScriptManager::GetScriptByScriptId(const ScriptId& script) const{
  499. for (unsigned int i = 0; i < script_entity_.size(); ++ i){
  500. if (script.entity == script_entity_[i].name){
  501. for (unsigned int j = 0; j < script_entity_[i].queue.size(); ++ j){
  502. if (script.function == script_entity_[i].queue[j].function)
  503. return (QueueScript*) &(script_entity_[i].queue[j]);
  504. }
  505. return nullptr;
  506. }
  507. }
  508. return nullptr;
  509. }
  510. ScriptEntity* ScriptManager::GetScriptEntityByName(
  511. const Type type, const Ogre::String& entity_name
  512. ) const{
  513. for (unsigned int i = 0; i < script_entity_.size(); ++ i){
  514. if (script_entity_[i].type == type && script_entity_[i].name == entity_name)
  515. return (ScriptEntity*) &(script_entity_[i]);
  516. }
  517. return nullptr;
  518. }
  519. const ScriptId ScriptManager::GetCurrentScriptId() const{return current_script_id_;}
  520. void ScriptManager::ContinueScriptExecution(const ScriptId& script){
  521. QueueScript* script_pointer = GetScriptByScriptId(script);
  522. if (script_pointer == nullptr){
  523. // The script that waited for this is already gone, for example because the field changed
  524. // or the script was cancelled, so there is nothing to continue.
  525. LOG_TRIVIAL(
  526. "There is no script \"" + script.function + "\" for entity \""
  527. + script.entity + "\" to continue. It has already ended."
  528. );
  529. return;
  530. }
  531. script_pointer->wait = false;
  532. }
  533. int ScriptManager::ScriptWait(const float seconds){
  534. LOG_TRIVIAL(
  535. "script:wait: We set script wait for "
  536. + Ogre::StringConverter::toString(seconds) + " seconds."
  537. );
  538. QueueScript* script = GetScriptByScriptId(current_script_id_);
  539. if (script == nullptr){
  540. LOG_ERROR("script:wait: Currently no any script running.");
  541. return 1;
  542. }
  543. if (seconds == 0) return 1;
  544. script->seconds_to_wait = seconds;
  545. return -1;
  546. }
  547. void ScriptManager::ScriptRequest(
  548. const Type type, const char* entity, const char* function, const int priority
  549. ){
  550. LOG_TRIVIAL(
  551. "[SCRIPT] script:request: Request function \"" + Ogre::String(function) + "\" for entity \""
  552. + Ogre::String(entity) + "\" with priority " + Ogre::StringConverter::toString(priority) + "."
  553. );
  554. ScriptEntity* script_entity = GetScriptEntityByName(type, Ogre::String(entity));
  555. if (script_entity == nullptr){
  556. LOG_WARNING(
  557. "[SCRIPT] script:request: Entity \"" + Ogre::String(entity) + "\" doesn't exist."
  558. );
  559. return;
  560. }
  561. bool added = ScriptRequest(script_entity, function, priority, "", "", false, false);
  562. if (added == false){
  563. LOG_WARNING(
  564. "Script '" + Ogre::String(function) + "' for entity '"
  565. + Ogre::String(entity) + "' doesn't exist."
  566. );
  567. }
  568. }
  569. int ScriptManager::ScriptRequestStartSync(
  570. const Type type, const char* entity, const char* function, const int priority
  571. ){
  572. LOG_TRIVIAL(
  573. "[SCRIPT] script:request_start_sync: Request function \""
  574. + Ogre::String(function) + "\" for entity \"" + Ogre::String(entity)
  575. + "\" with priority " + Ogre::StringConverter::toString(priority) + "."
  576. );
  577. ScriptEntity* script_entity = GetScriptEntityByName(type, Ogre::String(entity));
  578. if (script_entity == nullptr){
  579. LOG_ERROR(
  580. "[SCRIPT] script:request_start_sync: Entity \"" + Ogre::String(entity)
  581. + "\" doesn't exist.");
  582. return 1;
  583. }
  584. // A script that already started can't be waited for to start: nothing would resume the caller.
  585. for (const QueueScript& queued : script_entity->queue){
  586. if (queued.function == function && queued.yield){
  587. LOG_TRIVIAL(
  588. "[SCRIPT] script:request_start_sync: Function \"" + Ogre::String(function)
  589. + "\" for entity \"" + Ogre::String(entity) + "\" already started."
  590. );
  591. return 1;
  592. }
  593. }
  594. bool added = ScriptRequest(script_entity, function, priority, "", "", true, false);
  595. if (added == false){
  596. LOG_WARNING(
  597. "Script '" + Ogre::String(function) + "' for entity '"
  598. + Ogre::String(entity) + "' doesn't exist."
  599. );
  600. return 1;
  601. }
  602. return -1;
  603. }
  604. int ScriptManager::ScriptRequestEndSync(
  605. const Type type, const char* entity, const char* function, const int priority
  606. ){
  607. LOG_TRIVIAL(
  608. "[SCRIPT] script:request_end_sync: Request function \""
  609. + Ogre::String(function) + "\" for entity \"" + Ogre::String(entity)
  610. + "\" with priority " + Ogre::StringConverter::toString(priority) + "."
  611. );
  612. ScriptEntity* script_entity = GetScriptEntityByName(type, Ogre::String(entity));
  613. if (script_entity == nullptr){
  614. LOG_ERROR(
  615. "[SCRIPT] script:request_end_sync: Entity \"" + Ogre::String(entity)
  616. + "\" doesn't exist."
  617. );
  618. return 1;
  619. }
  620. bool added = ScriptRequest(script_entity, function, priority, "", "", false, true);
  621. if (added == false){
  622. LOG_WARNING(
  623. "Script '" + Ogre::String(function) + "' for entity '"
  624. + Ogre::String(entity) + "' doesn't exist."
  625. );
  626. return 1;
  627. }
  628. return -1;
  629. }
  630. bool ScriptManager::ScriptRequest(
  631. ScriptEntity* script_entity, const Ogre::String& function, const int priority,
  632. const Ogre::String& argument1, const Ogre::String& argument2, bool start_sync,
  633. bool end_sync, const Ogre::String& argument3, bool allow_duplicate
  634. ){
  635. if (script_entity == nullptr) return false;
  636. sol::object table
  637. = GetTableByEntityName(script_entity->type, script_entity->name, lua_state_);
  638. sol::object table_function;
  639. if (table.get_type() == sol::type::table)
  640. table_function = table.as<sol::table>()[function];
  641. if (table_function.get_type() == sol::type::function){
  642. QueueScript script;
  643. script.function = function;
  644. script.argument1 = argument1;
  645. script.argument2 = argument2;
  646. script.argument3 = argument3;
  647. script.priority = priority;
  648. script.state = lua_newthread(lua_state_);
  649. // The thread must not be garbage collected,
  650. // so it need to be stored.
  651. script.state_id = luaL_ref(lua_state_, LUA_REGISTRYINDEX);
  652. script.seconds_to_wait = 0;
  653. script.wait = false;
  654. script.yield = false;
  655. if (start_sync == true) script.paused_scripts_start.push_back(GetCurrentScriptId());
  656. if (end_sync == true) script.paused_scripts_end.push_back(GetCurrentScriptId());
  657. // If the script is already queued or running, don't queue it again. Whoever waits for the
  658. // request must wait for the existing script, because nothing else would resume it.
  659. if (allow_duplicate == false){
  660. for (int i = 0; i < script_entity->queue.size(); i ++){
  661. if (script_entity->queue[i].function == function){
  662. script_entity->resort = true;
  663. QueueScript& existing = script_entity->queue[i];
  664. for (const ScriptId& waiting : script.paused_scripts_end)
  665. existing.paused_scripts_end.push_back(waiting);
  666. // A script that already started isn't waited for. See ScriptRequestStartSync.
  667. if (!existing.yield){
  668. for (const ScriptId& waiting : script.paused_scripts_start)
  669. existing.paused_scripts_start.push_back(waiting);
  670. }
  671. luaL_unref(lua_state_, LUA_REGISTRYINDEX, script.state_id);
  672. return true;
  673. }
  674. }
  675. }
  676. // A script that is only polling (a loop that waits for a key or a flag, with no pause)
  677. // is replaced by the request of one with a higher priority, as the scenes do to stop the
  678. // loops of the keys (the mimic of the parade of junin1a).
  679. if (function != "on_update" && function != "on_start" && function != "on_button"){
  680. for (QueueScript& other : script_entity->queue){
  681. if (
  682. other.priority > priority && other.yield && !other.wait
  683. && other.function != "on_update" && other.function != "on_start"
  684. && other.function != "on_button"
  685. ) other.replaced = true;
  686. }
  687. }
  688. script_entity->queue.push_back(script);
  689. script_entity->resort = true;
  690. return true;
  691. }
  692. return false;
  693. }
  694. void ScriptManager::UpdateField(){}
  695. void ScriptManager::UpdateBattle(){}
  696. void ScriptManager::UpdateWorld(){}