serverenvironment.cpp 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232
  1. /*
  2. Minetest
  3. Copyright (C) 2010-2017 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #include "serverenvironment.h"
  17. #include "content_sao.h"
  18. #include "settings.h"
  19. #include "log.h"
  20. #include "mapblock.h"
  21. #include "nodedef.h"
  22. #include "nodemetadata.h"
  23. #include "gamedef.h"
  24. #include "map.h"
  25. #include "profiler.h"
  26. #include "raycast.h"
  27. #include "remoteplayer.h"
  28. #include "scripting_server.h"
  29. #include "server.h"
  30. #include "util/serialize.h"
  31. #include "util/basic_macros.h"
  32. #include "util/pointedthing.h"
  33. #include "threading/mutex_auto_lock.h"
  34. #include "filesys.h"
  35. #include "gameparams.h"
  36. #include "database-dummy.h"
  37. #include "database-files.h"
  38. #include "database-sqlite3.h"
  39. #if USE_POSTGRESQL
  40. #include "database-postgresql.h"
  41. #endif
  42. #define LBM_NAME_ALLOWED_CHARS "abcdefghijklmnopqrstuvwxyz0123456789_:"
  43. // A number that is much smaller than the timeout for particle spawners should/could ever be
  44. #define PARTICLE_SPAWNER_NO_EXPIRY -1024.f
  45. /*
  46. ABMWithState
  47. */
  48. ABMWithState::ABMWithState(ActiveBlockModifier *abm_):
  49. abm(abm_)
  50. {
  51. // Initialize timer to random value to spread processing
  52. float itv = abm->getTriggerInterval();
  53. itv = MYMAX(0.001, itv); // No less than 1ms
  54. int minval = MYMAX(-0.51*itv, -60); // Clamp to
  55. int maxval = MYMIN(0.51*itv, 60); // +-60 seconds
  56. timer = myrand_range(minval, maxval);
  57. }
  58. /*
  59. LBMManager
  60. */
  61. void LBMContentMapping::deleteContents()
  62. {
  63. for (auto &it : lbm_list) {
  64. delete it;
  65. }
  66. }
  67. void LBMContentMapping::addLBM(LoadingBlockModifierDef *lbm_def, IGameDef *gamedef)
  68. {
  69. // Add the lbm_def to the LBMContentMapping.
  70. // Unknown names get added to the global NameIdMapping.
  71. INodeDefManager *nodedef = gamedef->ndef();
  72. lbm_list.push_back(lbm_def);
  73. for (const std::string &nodeTrigger: lbm_def->trigger_contents) {
  74. std::set<content_t> c_ids;
  75. bool found = nodedef->getIds(nodeTrigger, c_ids);
  76. if (!found) {
  77. content_t c_id = gamedef->allocateUnknownNodeId(nodeTrigger);
  78. if (c_id == CONTENT_IGNORE) {
  79. // Seems it can't be allocated.
  80. warningstream << "Could not internalize node name \"" << nodeTrigger
  81. << "\" while loading LBM \"" << lbm_def->name << "\"." << std::endl;
  82. continue;
  83. }
  84. c_ids.insert(c_id);
  85. }
  86. for (content_t c_id : c_ids) {
  87. map[c_id].push_back(lbm_def);
  88. }
  89. }
  90. }
  91. const std::vector<LoadingBlockModifierDef *> *
  92. LBMContentMapping::lookup(content_t c) const
  93. {
  94. lbm_map::const_iterator it = map.find(c);
  95. if (it == map.end())
  96. return NULL;
  97. // This first dereferences the iterator, returning
  98. // a std::vector<LoadingBlockModifierDef *>
  99. // reference, then we convert it to a pointer.
  100. return &(it->second);
  101. }
  102. LBMManager::~LBMManager()
  103. {
  104. for (auto &m_lbm_def : m_lbm_defs) {
  105. delete m_lbm_def.second;
  106. }
  107. for (auto &it : m_lbm_lookup) {
  108. (it.second).deleteContents();
  109. }
  110. }
  111. void LBMManager::addLBMDef(LoadingBlockModifierDef *lbm_def)
  112. {
  113. // Precondition, in query mode the map isn't used anymore
  114. FATAL_ERROR_IF(m_query_mode,
  115. "attempted to modify LBMManager in query mode");
  116. if (!string_allowed(lbm_def->name, LBM_NAME_ALLOWED_CHARS)) {
  117. throw ModError("Error adding LBM \"" + lbm_def->name +
  118. "\": Does not follow naming conventions: "
  119. "Only characters [a-z0-9_:] are allowed.");
  120. }
  121. m_lbm_defs[lbm_def->name] = lbm_def;
  122. }
  123. void LBMManager::loadIntroductionTimes(const std::string &times,
  124. IGameDef *gamedef, u32 now)
  125. {
  126. m_query_mode = true;
  127. // name -> time map.
  128. // Storing it in a map first instead of
  129. // handling the stuff directly in the loop
  130. // removes all duplicate entries.
  131. // TODO make this std::unordered_map
  132. std::map<std::string, u32> introduction_times;
  133. /*
  134. The introduction times string consists of name~time entries,
  135. with each entry terminated by a semicolon. The time is decimal.
  136. */
  137. size_t idx = 0;
  138. size_t idx_new;
  139. while ((idx_new = times.find(';', idx)) != std::string::npos) {
  140. std::string entry = times.substr(idx, idx_new - idx);
  141. std::vector<std::string> components = str_split(entry, '~');
  142. if (components.size() != 2)
  143. throw SerializationError("Introduction times entry \""
  144. + entry + "\" requires exactly one '~'!");
  145. const std::string &name = components[0];
  146. u32 time = from_string<u32>(components[1]);
  147. introduction_times[name] = time;
  148. idx = idx_new + 1;
  149. }
  150. // Put stuff from introduction_times into m_lbm_lookup
  151. for (std::map<std::string, u32>::const_iterator it = introduction_times.begin();
  152. it != introduction_times.end(); ++it) {
  153. const std::string &name = it->first;
  154. u32 time = it->second;
  155. std::map<std::string, LoadingBlockModifierDef *>::iterator def_it =
  156. m_lbm_defs.find(name);
  157. if (def_it == m_lbm_defs.end()) {
  158. // This seems to be an LBM entry for
  159. // an LBM we haven't loaded. Discard it.
  160. continue;
  161. }
  162. LoadingBlockModifierDef *lbm_def = def_it->second;
  163. if (lbm_def->run_at_every_load) {
  164. // This seems to be an LBM entry for
  165. // an LBM that runs at every load.
  166. // Don't add it just yet.
  167. continue;
  168. }
  169. m_lbm_lookup[time].addLBM(lbm_def, gamedef);
  170. // Erase the entry so that we know later
  171. // what elements didn't get put into m_lbm_lookup
  172. m_lbm_defs.erase(name);
  173. }
  174. // Now also add the elements from m_lbm_defs to m_lbm_lookup
  175. // that weren't added in the previous step.
  176. // They are introduced first time to this world,
  177. // or are run at every load (introducement time hardcoded to U32_MAX).
  178. LBMContentMapping &lbms_we_introduce_now = m_lbm_lookup[now];
  179. LBMContentMapping &lbms_running_always = m_lbm_lookup[U32_MAX];
  180. for (auto &m_lbm_def : m_lbm_defs) {
  181. if (m_lbm_def.second->run_at_every_load) {
  182. lbms_running_always.addLBM(m_lbm_def.second, gamedef);
  183. } else {
  184. lbms_we_introduce_now.addLBM(m_lbm_def.second, gamedef);
  185. }
  186. }
  187. // Clear the list, so that we don't delete remaining elements
  188. // twice in the destructor
  189. m_lbm_defs.clear();
  190. }
  191. std::string LBMManager::createIntroductionTimesString()
  192. {
  193. // Precondition, we must be in query mode
  194. FATAL_ERROR_IF(!m_query_mode,
  195. "attempted to query on non fully set up LBMManager");
  196. std::ostringstream oss;
  197. for (const auto &it : m_lbm_lookup) {
  198. u32 time = it.first;
  199. const std::vector<LoadingBlockModifierDef *> &lbm_list = it.second.lbm_list;
  200. for (const auto &lbm_def : lbm_list) {
  201. // Don't add if the LBM runs at every load,
  202. // then introducement time is hardcoded
  203. // and doesn't need to be stored
  204. if (lbm_def->run_at_every_load)
  205. continue;
  206. oss << lbm_def->name << "~" << time << ";";
  207. }
  208. }
  209. return oss.str();
  210. }
  211. void LBMManager::applyLBMs(ServerEnvironment *env, MapBlock *block, u32 stamp)
  212. {
  213. // Precondition, we need m_lbm_lookup to be initialized
  214. FATAL_ERROR_IF(!m_query_mode,
  215. "attempted to query on non fully set up LBMManager");
  216. v3s16 pos_of_block = block->getPosRelative();
  217. v3s16 pos;
  218. MapNode n;
  219. content_t c;
  220. lbm_lookup_map::const_iterator it = getLBMsIntroducedAfter(stamp);
  221. for (pos.X = 0; pos.X < MAP_BLOCKSIZE; pos.X++)
  222. for (pos.Y = 0; pos.Y < MAP_BLOCKSIZE; pos.Y++)
  223. for (pos.Z = 0; pos.Z < MAP_BLOCKSIZE; pos.Z++)
  224. {
  225. n = block->getNodeNoEx(pos);
  226. c = n.getContent();
  227. for (LBMManager::lbm_lookup_map::const_iterator iit = it;
  228. iit != m_lbm_lookup.end(); ++iit) {
  229. const std::vector<LoadingBlockModifierDef *> *lbm_list =
  230. iit->second.lookup(c);
  231. if (!lbm_list)
  232. continue;
  233. for (auto lbmdef : *lbm_list) {
  234. lbmdef->trigger(env, pos + pos_of_block, n);
  235. }
  236. }
  237. }
  238. }
  239. /*
  240. ActiveBlockList
  241. */
  242. void fillRadiusBlock(v3s16 p0, s16 r, std::set<v3s16> &list)
  243. {
  244. v3s16 p;
  245. for(p.X=p0.X-r; p.X<=p0.X+r; p.X++)
  246. for(p.Y=p0.Y-r; p.Y<=p0.Y+r; p.Y++)
  247. for(p.Z=p0.Z-r; p.Z<=p0.Z+r; p.Z++)
  248. {
  249. // limit to a sphere
  250. if (p.getDistanceFrom(p0) <= r) {
  251. // Set in list
  252. list.insert(p);
  253. }
  254. }
  255. }
  256. void ActiveBlockList::update(std::vector<v3s16> &active_positions,
  257. s16 radius,
  258. std::set<v3s16> &blocks_removed,
  259. std::set<v3s16> &blocks_added)
  260. {
  261. /*
  262. Create the new list
  263. */
  264. std::set<v3s16> newlist = m_forceloaded_list;
  265. for (const v3s16 &active_position : active_positions) {
  266. fillRadiusBlock(active_position, radius, newlist);
  267. }
  268. /*
  269. Find out which blocks on the old list are not on the new list
  270. */
  271. // Go through old list
  272. for (v3s16 p : m_list) {
  273. // If not on new list, it's been removed
  274. if (newlist.find(p) == newlist.end())
  275. blocks_removed.insert(p);
  276. }
  277. /*
  278. Find out which blocks on the new list are not on the old list
  279. */
  280. // Go through new list
  281. for (v3s16 p : newlist) {
  282. // If not on old list, it's been added
  283. if(m_list.find(p) == m_list.end())
  284. blocks_added.insert(p);
  285. }
  286. /*
  287. Update m_list
  288. */
  289. m_list.clear();
  290. for (v3s16 p : newlist) {
  291. m_list.insert(p);
  292. }
  293. }
  294. /*
  295. ServerEnvironment
  296. */
  297. ServerEnvironment::ServerEnvironment(ServerMap *map,
  298. ServerScripting *scriptIface, Server *server,
  299. const std::string &path_world):
  300. Environment(server),
  301. m_map(map),
  302. m_script(scriptIface),
  303. m_server(server),
  304. m_path_world(path_world)
  305. {
  306. // Determine which database backend to use
  307. std::string conf_path = path_world + DIR_DELIM + "world.mt";
  308. Settings conf;
  309. bool succeeded = conf.readConfigFile(conf_path.c_str());
  310. if (!succeeded || !conf.exists("player_backend")) {
  311. // fall back to files
  312. conf.set("player_backend", "files");
  313. warningstream << "/!\\ You are using old player file backend. "
  314. << "This backend is deprecated and will be removed in next release /!\\"
  315. << std::endl << "Switching to SQLite3 or PostgreSQL is advised, "
  316. << "please read http://wiki.minetest.net/Database_backends." << std::endl;
  317. if (!conf.updateConfigFile(conf_path.c_str())) {
  318. errorstream << "ServerEnvironment::ServerEnvironment(): "
  319. << "Failed to update world.mt!" << std::endl;
  320. }
  321. }
  322. std::string name;
  323. conf.getNoEx("player_backend", name);
  324. m_player_database = openPlayerDatabase(name, path_world, conf);
  325. }
  326. ServerEnvironment::~ServerEnvironment()
  327. {
  328. // Clear active block list.
  329. // This makes the next one delete all active objects.
  330. m_active_blocks.clear();
  331. // Convert all objects to static and delete the active objects
  332. deactivateFarObjects(true);
  333. // Drop/delete map
  334. m_map->drop();
  335. // Delete ActiveBlockModifiers
  336. for (ABMWithState &m_abm : m_abms) {
  337. delete m_abm.abm;
  338. }
  339. // Deallocate players
  340. for (RemotePlayer *m_player : m_players) {
  341. delete m_player;
  342. }
  343. delete m_player_database;
  344. }
  345. Map & ServerEnvironment::getMap()
  346. {
  347. return *m_map;
  348. }
  349. ServerMap & ServerEnvironment::getServerMap()
  350. {
  351. return *m_map;
  352. }
  353. RemotePlayer *ServerEnvironment::getPlayer(const u16 peer_id)
  354. {
  355. for (RemotePlayer *player : m_players) {
  356. if (player->peer_id == peer_id)
  357. return player;
  358. }
  359. return NULL;
  360. }
  361. RemotePlayer *ServerEnvironment::getPlayer(const char* name)
  362. {
  363. for (RemotePlayer *player : m_players) {
  364. if (strcmp(player->getName(), name) == 0)
  365. return player;
  366. }
  367. return NULL;
  368. }
  369. void ServerEnvironment::addPlayer(RemotePlayer *player)
  370. {
  371. /*
  372. Check that peer_ids are unique.
  373. Also check that names are unique.
  374. Exception: there can be multiple players with peer_id=0
  375. */
  376. // If peer id is non-zero, it has to be unique.
  377. if (player->peer_id != 0)
  378. FATAL_ERROR_IF(getPlayer(player->peer_id) != NULL, "Peer id not unique");
  379. // Name has to be unique.
  380. FATAL_ERROR_IF(getPlayer(player->getName()) != NULL, "Player name not unique");
  381. // Add.
  382. m_players.push_back(player);
  383. }
  384. void ServerEnvironment::removePlayer(RemotePlayer *player)
  385. {
  386. for (std::vector<RemotePlayer *>::iterator it = m_players.begin();
  387. it != m_players.end(); ++it) {
  388. if ((*it) == player) {
  389. delete *it;
  390. m_players.erase(it);
  391. return;
  392. }
  393. }
  394. }
  395. bool ServerEnvironment::removePlayerFromDatabase(const std::string &name)
  396. {
  397. return m_player_database->removePlayer(name);
  398. }
  399. bool ServerEnvironment::line_of_sight(v3f pos1, v3f pos2, float stepsize, v3s16 *p)
  400. {
  401. float distance = pos1.getDistanceFrom(pos2);
  402. //calculate normalized direction vector
  403. v3f normalized_vector = v3f((pos2.X - pos1.X)/distance,
  404. (pos2.Y - pos1.Y)/distance,
  405. (pos2.Z - pos1.Z)/distance);
  406. //find out if there's a node on path between pos1 and pos2
  407. for (float i = 1; i < distance; i += stepsize) {
  408. v3s16 pos = floatToInt(v3f(normalized_vector.X * i,
  409. normalized_vector.Y * i,
  410. normalized_vector.Z * i) +pos1,BS);
  411. MapNode n = getMap().getNodeNoEx(pos);
  412. if(n.param0 != CONTENT_AIR) {
  413. if (p) {
  414. *p = pos;
  415. }
  416. return false;
  417. }
  418. }
  419. return true;
  420. }
  421. void ServerEnvironment::kickAllPlayers(AccessDeniedCode reason,
  422. const std::string &str_reason, bool reconnect)
  423. {
  424. for (RemotePlayer *player : m_players) {
  425. m_server->DenyAccessVerCompliant(player->peer_id,
  426. player->protocol_version, reason, str_reason, reconnect);
  427. }
  428. }
  429. void ServerEnvironment::saveLoadedPlayers()
  430. {
  431. std::string players_path = m_path_world + DIR_DELIM + "players";
  432. fs::CreateDir(players_path);
  433. for (RemotePlayer *player : m_players) {
  434. if (player->checkModified() || (player->getPlayerSAO() &&
  435. player->getPlayerSAO()->extendedAttributesModified())) {
  436. try {
  437. m_player_database->savePlayer(player);
  438. } catch (DatabaseException &e) {
  439. errorstream << "Failed to save player " << player->getName() << " exception: "
  440. << e.what() << std::endl;
  441. throw;
  442. }
  443. }
  444. }
  445. }
  446. void ServerEnvironment::savePlayer(RemotePlayer *player)
  447. {
  448. try {
  449. m_player_database->savePlayer(player);
  450. } catch (DatabaseException &e) {
  451. errorstream << "Failed to save player " << player->getName() << " exception: "
  452. << e.what() << std::endl;
  453. throw;
  454. }
  455. }
  456. PlayerSAO *ServerEnvironment::loadPlayer(RemotePlayer *player, bool *new_player,
  457. u16 peer_id, bool is_singleplayer)
  458. {
  459. PlayerSAO *playersao = new PlayerSAO(this, player, peer_id, is_singleplayer);
  460. // Create player if it doesn't exist
  461. if (!m_player_database->loadPlayer(player, playersao)) {
  462. *new_player = true;
  463. // Set player position
  464. infostream << "Server: Finding spawn place for player \""
  465. << player->getName() << "\"" << std::endl;
  466. playersao->setBasePosition(m_server->findSpawnPos());
  467. // Make sure the player is saved
  468. player->setModified(true);
  469. } else {
  470. // If the player exists, ensure that they respawn inside legal bounds
  471. // This fixes an assert crash when the player can't be added
  472. // to the environment
  473. ServerMap &map = getServerMap();
  474. if (map.getMapgenParams()->saoPosOverLimit(playersao->getBasePosition())) {
  475. actionstream << "Respawn position for player \""
  476. << player->getName() << "\" outside limits, resetting" << std::endl;
  477. playersao->setBasePosition(m_server->findSpawnPos());
  478. }
  479. }
  480. // Add player to environment
  481. addPlayer(player);
  482. /* Clean up old HUD elements from previous sessions */
  483. player->clearHud();
  484. /* Add object to environment */
  485. addActiveObject(playersao);
  486. return playersao;
  487. }
  488. void ServerEnvironment::saveMeta()
  489. {
  490. std::string path = m_path_world + DIR_DELIM "env_meta.txt";
  491. // Open file and serialize
  492. std::ostringstream ss(std::ios_base::binary);
  493. Settings args;
  494. args.setU64("game_time", m_game_time);
  495. args.setU64("time_of_day", getTimeOfDay());
  496. args.setU64("last_clear_objects_time", m_last_clear_objects_time);
  497. args.setU64("lbm_introduction_times_version", 1);
  498. args.set("lbm_introduction_times",
  499. m_lbm_mgr.createIntroductionTimesString());
  500. args.setU64("day_count", m_day_count);
  501. args.writeLines(ss);
  502. ss<<"EnvArgsEnd\n";
  503. if(!fs::safeWriteToFile(path, ss.str()))
  504. {
  505. infostream<<"ServerEnvironment::saveMeta(): Failed to write "
  506. <<path<<std::endl;
  507. throw SerializationError("Couldn't save env meta");
  508. }
  509. }
  510. void ServerEnvironment::loadMeta()
  511. {
  512. std::string path = m_path_world + DIR_DELIM "env_meta.txt";
  513. // Open file and deserialize
  514. std::ifstream is(path.c_str(), std::ios_base::binary);
  515. if (!is.good()) {
  516. infostream << "ServerEnvironment::loadMeta(): Failed to open "
  517. << path << std::endl;
  518. throw SerializationError("Couldn't load env meta");
  519. }
  520. Settings args;
  521. if (!args.parseConfigLines(is, "EnvArgsEnd")) {
  522. throw SerializationError("ServerEnvironment::loadMeta(): "
  523. "EnvArgsEnd not found!");
  524. }
  525. try {
  526. m_game_time = args.getU64("game_time");
  527. } catch (SettingNotFoundException &e) {
  528. // Getting this is crucial, otherwise timestamps are useless
  529. throw SerializationError("Couldn't load env meta game_time");
  530. }
  531. setTimeOfDay(args.exists("time_of_day") ?
  532. // set day to early morning by default
  533. args.getU64("time_of_day") : 5250);
  534. m_last_clear_objects_time = args.exists("last_clear_objects_time") ?
  535. // If missing, do as if clearObjects was never called
  536. args.getU64("last_clear_objects_time") : 0;
  537. std::string lbm_introduction_times;
  538. try {
  539. u64 ver = args.getU64("lbm_introduction_times_version");
  540. if (ver == 1) {
  541. lbm_introduction_times = args.get("lbm_introduction_times");
  542. } else {
  543. infostream << "ServerEnvironment::loadMeta(): Non-supported"
  544. << " introduction time version " << ver << std::endl;
  545. }
  546. } catch (SettingNotFoundException &e) {
  547. // No problem, this is expected. Just continue with an empty string
  548. }
  549. m_lbm_mgr.loadIntroductionTimes(lbm_introduction_times, m_server, m_game_time);
  550. m_day_count = args.exists("day_count") ?
  551. args.getU64("day_count") : 0;
  552. }
  553. void ServerEnvironment::loadDefaultMeta()
  554. {
  555. m_lbm_mgr.loadIntroductionTimes("", m_server, m_game_time);
  556. }
  557. struct ActiveABM
  558. {
  559. ActiveBlockModifier *abm;
  560. int chance;
  561. std::set<content_t> required_neighbors;
  562. };
  563. class ABMHandler
  564. {
  565. private:
  566. ServerEnvironment *m_env;
  567. std::vector<std::vector<ActiveABM> *> m_aabms;
  568. public:
  569. ABMHandler(std::vector<ABMWithState> &abms,
  570. float dtime_s, ServerEnvironment *env,
  571. bool use_timers):
  572. m_env(env)
  573. {
  574. if(dtime_s < 0.001)
  575. return;
  576. INodeDefManager *ndef = env->getGameDef()->ndef();
  577. for (ABMWithState &abmws : abms) {
  578. ActiveBlockModifier *abm = abmws.abm;
  579. float trigger_interval = abm->getTriggerInterval();
  580. if(trigger_interval < 0.001)
  581. trigger_interval = 0.001;
  582. float actual_interval = dtime_s;
  583. if(use_timers){
  584. abmws.timer += dtime_s;
  585. if(abmws.timer < trigger_interval)
  586. continue;
  587. abmws.timer -= trigger_interval;
  588. actual_interval = trigger_interval;
  589. }
  590. float chance = abm->getTriggerChance();
  591. if(chance == 0)
  592. chance = 1;
  593. ActiveABM aabm;
  594. aabm.abm = abm;
  595. if (abm->getSimpleCatchUp()) {
  596. float intervals = actual_interval / trigger_interval;
  597. if(intervals == 0)
  598. continue;
  599. aabm.chance = chance / intervals;
  600. if(aabm.chance == 0)
  601. aabm.chance = 1;
  602. } else {
  603. aabm.chance = chance;
  604. }
  605. // Trigger neighbors
  606. const std::set<std::string> &required_neighbors_s =
  607. abm->getRequiredNeighbors();
  608. for (const std::string &required_neighbor_s : required_neighbors_s) {
  609. ndef->getIds(required_neighbor_s, aabm.required_neighbors);
  610. }
  611. // Trigger contents
  612. const std::set<std::string> &contents_s = abm->getTriggerContents();
  613. for (const std::string &content_s : contents_s) {
  614. std::set<content_t> ids;
  615. ndef->getIds(content_s, ids);
  616. for (content_t c : ids) {
  617. if (c >= m_aabms.size())
  618. m_aabms.resize(c + 256, NULL);
  619. if (!m_aabms[c])
  620. m_aabms[c] = new std::vector<ActiveABM>;
  621. m_aabms[c]->push_back(aabm);
  622. }
  623. }
  624. }
  625. }
  626. ~ABMHandler()
  627. {
  628. for (auto &aabms : m_aabms)
  629. delete aabms;
  630. }
  631. // Find out how many objects the given block and its neighbours contain.
  632. // Returns the number of objects in the block, and also in 'wider' the
  633. // number of objects in the block and all its neighbours. The latter
  634. // may an estimate if any neighbours are unloaded.
  635. u32 countObjects(MapBlock *block, ServerMap * map, u32 &wider)
  636. {
  637. wider = 0;
  638. u32 wider_unknown_count = 0;
  639. for(s16 x=-1; x<=1; x++)
  640. for(s16 y=-1; y<=1; y++)
  641. for(s16 z=-1; z<=1; z++)
  642. {
  643. MapBlock *block2 = map->getBlockNoCreateNoEx(
  644. block->getPos() + v3s16(x,y,z));
  645. if(block2==NULL){
  646. wider_unknown_count++;
  647. continue;
  648. }
  649. wider += block2->m_static_objects.m_active.size()
  650. + block2->m_static_objects.m_stored.size();
  651. }
  652. // Extrapolate
  653. u32 active_object_count = block->m_static_objects.m_active.size();
  654. u32 wider_known_count = 3*3*3 - wider_unknown_count;
  655. wider += wider_unknown_count * wider / wider_known_count;
  656. return active_object_count;
  657. }
  658. void apply(MapBlock *block)
  659. {
  660. if(m_aabms.empty() || block->isDummy())
  661. return;
  662. ServerMap *map = &m_env->getServerMap();
  663. u32 active_object_count_wider;
  664. u32 active_object_count = this->countObjects(block, map, active_object_count_wider);
  665. m_env->m_added_objects = 0;
  666. v3s16 p0;
  667. for(p0.X=0; p0.X<MAP_BLOCKSIZE; p0.X++)
  668. for(p0.Y=0; p0.Y<MAP_BLOCKSIZE; p0.Y++)
  669. for(p0.Z=0; p0.Z<MAP_BLOCKSIZE; p0.Z++)
  670. {
  671. const MapNode &n = block->getNodeUnsafe(p0);
  672. content_t c = n.getContent();
  673. if (c >= m_aabms.size() || !m_aabms[c])
  674. continue;
  675. v3s16 p = p0 + block->getPosRelative();
  676. for (ActiveABM &aabm : *m_aabms[c]) {
  677. if (myrand() % aabm.chance != 0)
  678. continue;
  679. // Check neighbors
  680. if (!aabm.required_neighbors.empty()) {
  681. v3s16 p1;
  682. for(p1.X = p0.X-1; p1.X <= p0.X+1; p1.X++)
  683. for(p1.Y = p0.Y-1; p1.Y <= p0.Y+1; p1.Y++)
  684. for(p1.Z = p0.Z-1; p1.Z <= p0.Z+1; p1.Z++)
  685. {
  686. if(p1 == p0)
  687. continue;
  688. content_t c;
  689. if (block->isValidPosition(p1)) {
  690. // if the neighbor is found on the same map block
  691. // get it straight from there
  692. const MapNode &n = block->getNodeUnsafe(p1);
  693. c = n.getContent();
  694. } else {
  695. // otherwise consult the map
  696. MapNode n = map->getNodeNoEx(p1 + block->getPosRelative());
  697. c = n.getContent();
  698. }
  699. std::set<content_t>::const_iterator k;
  700. k = aabm.required_neighbors.find(c);
  701. if(k != aabm.required_neighbors.end()){
  702. goto neighbor_found;
  703. }
  704. }
  705. // No required neighbor found
  706. continue;
  707. }
  708. neighbor_found:
  709. // Call all the trigger variations
  710. aabm.abm->trigger(m_env, p, n);
  711. aabm.abm->trigger(m_env, p, n,
  712. active_object_count, active_object_count_wider);
  713. // Count surrounding objects again if the abms added any
  714. if(m_env->m_added_objects > 0) {
  715. active_object_count = countObjects(block, map, active_object_count_wider);
  716. m_env->m_added_objects = 0;
  717. }
  718. }
  719. }
  720. }
  721. };
  722. void ServerEnvironment::activateBlock(MapBlock *block, u32 additional_dtime)
  723. {
  724. // Reset usage timer immediately, otherwise a block that becomes active
  725. // again at around the same time as it would normally be unloaded will
  726. // get unloaded incorrectly. (I think this still leaves a small possibility
  727. // of a race condition between this and server::AsyncRunStep, which only
  728. // some kind of synchronisation will fix, but it at least reduces the window
  729. // of opportunity for it to break from seconds to nanoseconds)
  730. block->resetUsageTimer();
  731. // Get time difference
  732. u32 dtime_s = 0;
  733. u32 stamp = block->getTimestamp();
  734. if (m_game_time > stamp && stamp != BLOCK_TIMESTAMP_UNDEFINED)
  735. dtime_s = m_game_time - stamp;
  736. dtime_s += additional_dtime;
  737. /*infostream<<"ServerEnvironment::activateBlock(): block timestamp: "
  738. <<stamp<<", game time: "<<m_game_time<<std::endl;*/
  739. // Remove stored static objects if clearObjects was called since block's timestamp
  740. if (stamp == BLOCK_TIMESTAMP_UNDEFINED || stamp < m_last_clear_objects_time) {
  741. block->m_static_objects.m_stored.clear();
  742. // do not set changed flag to avoid unnecessary mapblock writes
  743. }
  744. // Set current time as timestamp
  745. block->setTimestampNoChangedFlag(m_game_time);
  746. /*infostream<<"ServerEnvironment::activateBlock(): block is "
  747. <<dtime_s<<" seconds old."<<std::endl;*/
  748. // Activate stored objects
  749. activateObjects(block, dtime_s);
  750. /* Handle LoadingBlockModifiers */
  751. m_lbm_mgr.applyLBMs(this, block, stamp);
  752. // Run node timers
  753. std::vector<NodeTimer> elapsed_timers =
  754. block->m_node_timers.step((float)dtime_s);
  755. if (!elapsed_timers.empty()) {
  756. MapNode n;
  757. for (const NodeTimer &elapsed_timer : elapsed_timers) {
  758. n = block->getNodeNoEx(elapsed_timer.position);
  759. v3s16 p = elapsed_timer.position + block->getPosRelative();
  760. if (m_script->node_on_timer(p, n, elapsed_timer.elapsed))
  761. block->setNodeTimer(NodeTimer(elapsed_timer.timeout, 0,
  762. elapsed_timer.position));
  763. }
  764. }
  765. /* Handle ActiveBlockModifiers */
  766. ABMHandler abmhandler(m_abms, dtime_s, this, false);
  767. abmhandler.apply(block);
  768. }
  769. void ServerEnvironment::addActiveBlockModifier(ActiveBlockModifier *abm)
  770. {
  771. m_abms.emplace_back(abm);
  772. }
  773. void ServerEnvironment::addLoadingBlockModifierDef(LoadingBlockModifierDef *lbm)
  774. {
  775. m_lbm_mgr.addLBMDef(lbm);
  776. }
  777. bool ServerEnvironment::setNode(v3s16 p, const MapNode &n)
  778. {
  779. INodeDefManager *ndef = m_server->ndef();
  780. MapNode n_old = m_map->getNodeNoEx(p);
  781. // Call destructor
  782. if (ndef->get(n_old).has_on_destruct)
  783. m_script->node_on_destruct(p, n_old);
  784. // Replace node
  785. if (!m_map->addNodeWithEvent(p, n))
  786. return false;
  787. // Update active VoxelManipulator if a mapgen thread
  788. m_map->updateVManip(p);
  789. // Call post-destructor
  790. if (ndef->get(n_old).has_after_destruct)
  791. m_script->node_after_destruct(p, n_old);
  792. // Call constructor
  793. if (ndef->get(n).has_on_construct)
  794. m_script->node_on_construct(p, n);
  795. return true;
  796. }
  797. bool ServerEnvironment::removeNode(v3s16 p)
  798. {
  799. INodeDefManager *ndef = m_server->ndef();
  800. MapNode n_old = m_map->getNodeNoEx(p);
  801. // Call destructor
  802. if (ndef->get(n_old).has_on_destruct)
  803. m_script->node_on_destruct(p, n_old);
  804. // Replace with air
  805. // This is slightly optimized compared to addNodeWithEvent(air)
  806. if (!m_map->removeNodeWithEvent(p))
  807. return false;
  808. // Update active VoxelManipulator if a mapgen thread
  809. m_map->updateVManip(p);
  810. // Call post-destructor
  811. if (ndef->get(n_old).has_after_destruct)
  812. m_script->node_after_destruct(p, n_old);
  813. // Air doesn't require constructor
  814. return true;
  815. }
  816. bool ServerEnvironment::swapNode(v3s16 p, const MapNode &n)
  817. {
  818. if (!m_map->addNodeWithEvent(p, n, false))
  819. return false;
  820. // Update active VoxelManipulator if a mapgen thread
  821. m_map->updateVManip(p);
  822. return true;
  823. }
  824. void ServerEnvironment::getObjectsInsideRadius(std::vector<u16> &objects, v3f pos,
  825. float radius)
  826. {
  827. for (auto &activeObject : m_active_objects) {
  828. ServerActiveObject* obj = activeObject.second;
  829. u16 id = activeObject.first;
  830. v3f objectpos = obj->getBasePosition();
  831. if (objectpos.getDistanceFrom(pos) > radius)
  832. continue;
  833. objects.push_back(id);
  834. }
  835. }
  836. void ServerEnvironment::clearObjects(ClearObjectsMode mode)
  837. {
  838. infostream << "ServerEnvironment::clearObjects(): "
  839. << "Removing all active objects" << std::endl;
  840. std::vector<u16> objects_to_remove;
  841. for (auto &it : m_active_objects) {
  842. ServerActiveObject* obj = it.second;
  843. if (obj->getType() == ACTIVEOBJECT_TYPE_PLAYER)
  844. continue;
  845. u16 id = it.first;
  846. // Delete static object if block is loaded
  847. if (obj->m_static_exists) {
  848. MapBlock *block = m_map->getBlockNoCreateNoEx(obj->m_static_block);
  849. if (block) {
  850. block->m_static_objects.remove(id);
  851. block->raiseModified(MOD_STATE_WRITE_NEEDED,
  852. MOD_REASON_CLEAR_ALL_OBJECTS);
  853. obj->m_static_exists = false;
  854. }
  855. }
  856. // If known by some client, don't delete immediately
  857. if (obj->m_known_by_count > 0) {
  858. obj->m_pending_deactivation = true;
  859. obj->m_removed = true;
  860. continue;
  861. }
  862. // Tell the object about removal
  863. obj->removingFromEnvironment();
  864. // Deregister in scripting api
  865. m_script->removeObjectReference(obj);
  866. // Delete active object
  867. if (obj->environmentDeletes())
  868. delete obj;
  869. // Id to be removed from m_active_objects
  870. objects_to_remove.push_back(id);
  871. }
  872. // Remove references from m_active_objects
  873. for (u16 i : objects_to_remove) {
  874. m_active_objects.erase(i);
  875. }
  876. // Get list of loaded blocks
  877. std::vector<v3s16> loaded_blocks;
  878. infostream << "ServerEnvironment::clearObjects(): "
  879. << "Listing all loaded blocks" << std::endl;
  880. m_map->listAllLoadedBlocks(loaded_blocks);
  881. infostream << "ServerEnvironment::clearObjects(): "
  882. << "Done listing all loaded blocks: "
  883. << loaded_blocks.size()<<std::endl;
  884. // Get list of loadable blocks
  885. std::vector<v3s16> loadable_blocks;
  886. if (mode == CLEAR_OBJECTS_MODE_FULL) {
  887. infostream << "ServerEnvironment::clearObjects(): "
  888. << "Listing all loadable blocks" << std::endl;
  889. m_map->listAllLoadableBlocks(loadable_blocks);
  890. infostream << "ServerEnvironment::clearObjects(): "
  891. << "Done listing all loadable blocks: "
  892. << loadable_blocks.size() << std::endl;
  893. } else {
  894. loadable_blocks = loaded_blocks;
  895. }
  896. infostream << "ServerEnvironment::clearObjects(): "
  897. << "Now clearing objects in " << loadable_blocks.size()
  898. << " blocks" << std::endl;
  899. // Grab a reference on each loaded block to avoid unloading it
  900. for (v3s16 p : loaded_blocks) {
  901. MapBlock *block = m_map->getBlockNoCreateNoEx(p);
  902. assert(block != NULL);
  903. block->refGrab();
  904. }
  905. // Remove objects in all loadable blocks
  906. u32 unload_interval = U32_MAX;
  907. if (mode == CLEAR_OBJECTS_MODE_FULL) {
  908. unload_interval = g_settings->getS32("max_clearobjects_extra_loaded_blocks");
  909. unload_interval = MYMAX(unload_interval, 1);
  910. }
  911. u32 report_interval = loadable_blocks.size() / 10;
  912. u32 num_blocks_checked = 0;
  913. u32 num_blocks_cleared = 0;
  914. u32 num_objs_cleared = 0;
  915. for (auto i = loadable_blocks.begin();
  916. i != loadable_blocks.end(); ++i) {
  917. v3s16 p = *i;
  918. MapBlock *block = m_map->emergeBlock(p, false);
  919. if (!block) {
  920. errorstream << "ServerEnvironment::clearObjects(): "
  921. << "Failed to emerge block " << PP(p) << std::endl;
  922. continue;
  923. }
  924. u32 num_stored = block->m_static_objects.m_stored.size();
  925. u32 num_active = block->m_static_objects.m_active.size();
  926. if (num_stored != 0 || num_active != 0) {
  927. block->m_static_objects.m_stored.clear();
  928. block->m_static_objects.m_active.clear();
  929. block->raiseModified(MOD_STATE_WRITE_NEEDED,
  930. MOD_REASON_CLEAR_ALL_OBJECTS);
  931. num_objs_cleared += num_stored + num_active;
  932. num_blocks_cleared++;
  933. }
  934. num_blocks_checked++;
  935. if (report_interval != 0 &&
  936. num_blocks_checked % report_interval == 0) {
  937. float percent = 100.0 * (float)num_blocks_checked /
  938. loadable_blocks.size();
  939. infostream << "ServerEnvironment::clearObjects(): "
  940. << "Cleared " << num_objs_cleared << " objects"
  941. << " in " << num_blocks_cleared << " blocks ("
  942. << percent << "%)" << std::endl;
  943. }
  944. if (num_blocks_checked % unload_interval == 0) {
  945. m_map->unloadUnreferencedBlocks();
  946. }
  947. }
  948. m_map->unloadUnreferencedBlocks();
  949. // Drop references that were added above
  950. for (v3s16 p : loaded_blocks) {
  951. MapBlock *block = m_map->getBlockNoCreateNoEx(p);
  952. assert(block);
  953. block->refDrop();
  954. }
  955. m_last_clear_objects_time = m_game_time;
  956. infostream << "ServerEnvironment::clearObjects(): "
  957. << "Finished: Cleared " << num_objs_cleared << " objects"
  958. << " in " << num_blocks_cleared << " blocks" << std::endl;
  959. }
  960. void ServerEnvironment::step(float dtime)
  961. {
  962. /* Step time of day */
  963. stepTimeOfDay(dtime);
  964. // Update this one
  965. // NOTE: This is kind of funny on a singleplayer game, but doesn't
  966. // really matter that much.
  967. static thread_local const float server_step =
  968. g_settings->getFloat("dedicated_server_step");
  969. m_recommended_send_interval = server_step;
  970. /*
  971. Increment game time
  972. */
  973. {
  974. m_game_time_fraction_counter += dtime;
  975. u32 inc_i = (u32)m_game_time_fraction_counter;
  976. m_game_time += inc_i;
  977. m_game_time_fraction_counter -= (float)inc_i;
  978. }
  979. /*
  980. Handle players
  981. */
  982. {
  983. ScopeProfiler sp(g_profiler, "SEnv: handle players avg", SPT_AVG);
  984. for (RemotePlayer *player : m_players) {
  985. // Ignore disconnected players
  986. if (player->peer_id == 0)
  987. continue;
  988. // Move
  989. player->move(dtime, this, 100 * BS);
  990. }
  991. }
  992. /*
  993. Manage active block list
  994. */
  995. if (m_active_blocks_management_interval.step(dtime, m_cache_active_block_mgmt_interval)) {
  996. ScopeProfiler sp(g_profiler, "SEnv: manage act. block list avg per interval", SPT_AVG);
  997. /*
  998. Get player block positions
  999. */
  1000. std::vector<v3s16> players_blockpos;
  1001. for (RemotePlayer *player: m_players) {
  1002. // Ignore disconnected players
  1003. if (player->peer_id == 0)
  1004. continue;
  1005. PlayerSAO *playersao = player->getPlayerSAO();
  1006. assert(playersao);
  1007. players_blockpos.push_back(
  1008. getNodeBlockPos(floatToInt(playersao->getBasePosition(), BS)));
  1009. }
  1010. /*
  1011. Update list of active blocks, collecting changes
  1012. */
  1013. static thread_local const s16 active_block_range =
  1014. g_settings->getS16("active_block_range");
  1015. std::set<v3s16> blocks_removed;
  1016. std::set<v3s16> blocks_added;
  1017. m_active_blocks.update(players_blockpos, active_block_range,
  1018. blocks_removed, blocks_added);
  1019. /*
  1020. Handle removed blocks
  1021. */
  1022. // Convert active objects that are no more in active blocks to static
  1023. deactivateFarObjects(false);
  1024. for (const v3s16 &p: blocks_removed) {
  1025. MapBlock *block = m_map->getBlockNoCreateNoEx(p);
  1026. if (!block)
  1027. continue;
  1028. // Set current time as timestamp (and let it set ChangedFlag)
  1029. block->setTimestamp(m_game_time);
  1030. }
  1031. /*
  1032. Handle added blocks
  1033. */
  1034. for (const v3s16 &p: blocks_added) {
  1035. MapBlock *block = m_map->getBlockOrEmerge(p);
  1036. if (!block) {
  1037. m_active_blocks.m_list.erase(p);
  1038. continue;
  1039. }
  1040. activateBlock(block);
  1041. }
  1042. }
  1043. /*
  1044. Mess around in active blocks
  1045. */
  1046. if (m_active_blocks_nodemetadata_interval.step(dtime, m_cache_nodetimer_interval)) {
  1047. ScopeProfiler sp(g_profiler, "SEnv: mess in act. blocks avg per interval", SPT_AVG);
  1048. float dtime = m_cache_nodetimer_interval;
  1049. for (const v3s16 &p: m_active_blocks.m_list) {
  1050. MapBlock *block = m_map->getBlockNoCreateNoEx(p);
  1051. if (!block)
  1052. continue;
  1053. // Reset block usage timer
  1054. block->resetUsageTimer();
  1055. // Set current time as timestamp
  1056. block->setTimestampNoChangedFlag(m_game_time);
  1057. // If time has changed much from the one on disk,
  1058. // set block to be saved when it is unloaded
  1059. if(block->getTimestamp() > block->getDiskTimestamp() + 60)
  1060. block->raiseModified(MOD_STATE_WRITE_AT_UNLOAD,
  1061. MOD_REASON_BLOCK_EXPIRED);
  1062. // Run node timers
  1063. std::vector<NodeTimer> elapsed_timers = block->m_node_timers.step(dtime);
  1064. if (!elapsed_timers.empty()) {
  1065. MapNode n;
  1066. v3s16 p2;
  1067. for (const NodeTimer &elapsed_timer: elapsed_timers) {
  1068. n = block->getNodeNoEx(elapsed_timer.position);
  1069. p2 = elapsed_timer.position + block->getPosRelative();
  1070. if (m_script->node_on_timer(p2, n, elapsed_timer.elapsed)) {
  1071. block->setNodeTimer(NodeTimer(
  1072. elapsed_timer.timeout, 0, elapsed_timer.position));
  1073. }
  1074. }
  1075. }
  1076. }
  1077. }
  1078. if (m_active_block_modifier_interval.step(dtime, m_cache_abm_interval))
  1079. do { // breakable
  1080. if (m_active_block_interval_overload_skip > 0) {
  1081. ScopeProfiler sp(g_profiler, "SEnv: ABM overload skips");
  1082. m_active_block_interval_overload_skip--;
  1083. break;
  1084. }
  1085. ScopeProfiler sp(g_profiler, "SEnv: modify in blocks avg per interval", SPT_AVG);
  1086. TimeTaker timer("modify in active blocks per interval");
  1087. // Initialize handling of ActiveBlockModifiers
  1088. ABMHandler abmhandler(m_abms, m_cache_abm_interval, this, true);
  1089. for (const v3s16 &p : m_active_blocks.m_list) {
  1090. MapBlock *block = m_map->getBlockNoCreateNoEx(p);
  1091. if (!block)
  1092. continue;
  1093. // Set current time as timestamp
  1094. block->setTimestampNoChangedFlag(m_game_time);
  1095. /* Handle ActiveBlockModifiers */
  1096. abmhandler.apply(block);
  1097. }
  1098. u32 time_ms = timer.stop(true);
  1099. u32 max_time_ms = 200;
  1100. if (time_ms > max_time_ms) {
  1101. warningstream<<"active block modifiers took "
  1102. <<time_ms<<"ms (longer than "
  1103. <<max_time_ms<<"ms)"<<std::endl;
  1104. m_active_block_interval_overload_skip = (time_ms / max_time_ms) + 1;
  1105. }
  1106. }while(0);
  1107. /*
  1108. Step script environment (run global on_step())
  1109. */
  1110. m_script->environment_Step(dtime);
  1111. /*
  1112. Step active objects
  1113. */
  1114. {
  1115. ScopeProfiler sp(g_profiler, "SEnv: step act. objs avg", SPT_AVG);
  1116. //TimeTaker timer("Step active objects");
  1117. g_profiler->avg("SEnv: num of objects", m_active_objects.size());
  1118. // This helps the objects to send data at the same time
  1119. bool send_recommended = false;
  1120. m_send_recommended_timer += dtime;
  1121. if(m_send_recommended_timer > getSendRecommendedInterval())
  1122. {
  1123. m_send_recommended_timer -= getSendRecommendedInterval();
  1124. send_recommended = true;
  1125. }
  1126. for (auto &ao_it : m_active_objects) {
  1127. ServerActiveObject* obj = ao_it.second;
  1128. // Don't step if is to be removed or stored statically
  1129. if(obj->m_removed || obj->m_pending_deactivation)
  1130. continue;
  1131. // Step object
  1132. obj->step(dtime, send_recommended);
  1133. // Read messages from object
  1134. while(!obj->m_messages_out.empty())
  1135. {
  1136. m_active_object_messages.push(
  1137. obj->m_messages_out.front());
  1138. obj->m_messages_out.pop();
  1139. }
  1140. }
  1141. }
  1142. /*
  1143. Manage active objects
  1144. */
  1145. if (m_object_management_interval.step(dtime, 0.5)) {
  1146. ScopeProfiler sp(g_profiler, "SEnv: remove removed objs avg /.5s", SPT_AVG);
  1147. /*
  1148. Remove objects that satisfy (m_removed && m_known_by_count==0)
  1149. */
  1150. removeRemovedObjects();
  1151. }
  1152. /*
  1153. Manage particle spawner expiration
  1154. */
  1155. if (m_particle_management_interval.step(dtime, 1.0)) {
  1156. for (std::unordered_map<u32, float>::iterator i = m_particle_spawners.begin();
  1157. i != m_particle_spawners.end(); ) {
  1158. //non expiring spawners
  1159. if (i->second == PARTICLE_SPAWNER_NO_EXPIRY) {
  1160. ++i;
  1161. continue;
  1162. }
  1163. i->second -= 1.0f;
  1164. if (i->second <= 0.f)
  1165. m_particle_spawners.erase(i++);
  1166. else
  1167. ++i;
  1168. }
  1169. }
  1170. }
  1171. u32 ServerEnvironment::addParticleSpawner(float exptime)
  1172. {
  1173. // Timers with lifetime 0 do not expire
  1174. float time = exptime > 0.f ? exptime : PARTICLE_SPAWNER_NO_EXPIRY;
  1175. u32 id = 0;
  1176. for (;;) { // look for unused particlespawner id
  1177. id++;
  1178. std::unordered_map<u32, float>::iterator f = m_particle_spawners.find(id);
  1179. if (f == m_particle_spawners.end()) {
  1180. m_particle_spawners[id] = time;
  1181. break;
  1182. }
  1183. }
  1184. return id;
  1185. }
  1186. u32 ServerEnvironment::addParticleSpawner(float exptime, u16 attached_id)
  1187. {
  1188. u32 id = addParticleSpawner(exptime);
  1189. m_particle_spawner_attachments[id] = attached_id;
  1190. if (ServerActiveObject *obj = getActiveObject(attached_id)) {
  1191. obj->attachParticleSpawner(id);
  1192. }
  1193. return id;
  1194. }
  1195. void ServerEnvironment::deleteParticleSpawner(u32 id, bool remove_from_object)
  1196. {
  1197. m_particle_spawners.erase(id);
  1198. const auto &it = m_particle_spawner_attachments.find(id);
  1199. if (it != m_particle_spawner_attachments.end()) {
  1200. u16 obj_id = it->second;
  1201. ServerActiveObject *sao = getActiveObject(obj_id);
  1202. if (sao != NULL && remove_from_object) {
  1203. sao->detachParticleSpawner(id);
  1204. }
  1205. m_particle_spawner_attachments.erase(id);
  1206. }
  1207. }
  1208. ServerActiveObject* ServerEnvironment::getActiveObject(u16 id)
  1209. {
  1210. ServerActiveObjectMap::const_iterator n = m_active_objects.find(id);
  1211. return (n != m_active_objects.end() ? n->second : NULL);
  1212. }
  1213. bool isFreeServerActiveObjectId(u16 id, ServerActiveObjectMap &objects)
  1214. {
  1215. if (id == 0)
  1216. return false;
  1217. return objects.find(id) == objects.end();
  1218. }
  1219. u16 getFreeServerActiveObjectId(ServerActiveObjectMap &objects)
  1220. {
  1221. //try to reuse id's as late as possible
  1222. static u16 last_used_id = 0;
  1223. u16 startid = last_used_id;
  1224. for(;;)
  1225. {
  1226. last_used_id ++;
  1227. if(isFreeServerActiveObjectId(last_used_id, objects))
  1228. return last_used_id;
  1229. if(last_used_id == startid)
  1230. return 0;
  1231. }
  1232. }
  1233. u16 ServerEnvironment::addActiveObject(ServerActiveObject *object)
  1234. {
  1235. assert(object); // Pre-condition
  1236. m_added_objects++;
  1237. u16 id = addActiveObjectRaw(object, true, 0);
  1238. return id;
  1239. }
  1240. /*
  1241. Finds out what new objects have been added to
  1242. inside a radius around a position
  1243. */
  1244. void ServerEnvironment::getAddedActiveObjects(PlayerSAO *playersao, s16 radius,
  1245. s16 player_radius,
  1246. std::set<u16> &current_objects,
  1247. std::queue<u16> &added_objects)
  1248. {
  1249. f32 radius_f = radius * BS;
  1250. f32 player_radius_f = player_radius * BS;
  1251. if (player_radius_f < 0)
  1252. player_radius_f = 0;
  1253. /*
  1254. Go through the object list,
  1255. - discard m_removed objects,
  1256. - discard objects that are too far away,
  1257. - discard objects that are found in current_objects.
  1258. - add remaining objects to added_objects
  1259. */
  1260. for (auto &ao_it : m_active_objects) {
  1261. u16 id = ao_it.first;
  1262. // Get object
  1263. ServerActiveObject *object = ao_it.second;
  1264. if (object == NULL)
  1265. continue;
  1266. // Discard if removed or deactivating
  1267. if(object->m_removed || object->m_pending_deactivation)
  1268. continue;
  1269. f32 distance_f = object->getBasePosition().
  1270. getDistanceFrom(playersao->getBasePosition());
  1271. if (object->getType() == ACTIVEOBJECT_TYPE_PLAYER) {
  1272. // Discard if too far
  1273. if (distance_f > player_radius_f && player_radius_f != 0)
  1274. continue;
  1275. } else if (distance_f > radius_f)
  1276. continue;
  1277. // Discard if already on current_objects
  1278. std::set<u16>::iterator n;
  1279. n = current_objects.find(id);
  1280. if(n != current_objects.end())
  1281. continue;
  1282. // Add to added_objects
  1283. added_objects.push(id);
  1284. }
  1285. }
  1286. /*
  1287. Finds out what objects have been removed from
  1288. inside a radius around a position
  1289. */
  1290. void ServerEnvironment::getRemovedActiveObjects(PlayerSAO *playersao, s16 radius,
  1291. s16 player_radius,
  1292. std::set<u16> &current_objects,
  1293. std::queue<u16> &removed_objects)
  1294. {
  1295. f32 radius_f = radius * BS;
  1296. f32 player_radius_f = player_radius * BS;
  1297. if (player_radius_f < 0)
  1298. player_radius_f = 0;
  1299. /*
  1300. Go through current_objects; object is removed if:
  1301. - object is not found in m_active_objects (this is actually an
  1302. error condition; objects should be set m_removed=true and removed
  1303. only after all clients have been informed about removal), or
  1304. - object has m_removed=true, or
  1305. - object is too far away
  1306. */
  1307. for (u16 id : current_objects) {
  1308. ServerActiveObject *object = getActiveObject(id);
  1309. if (object == NULL) {
  1310. infostream << "ServerEnvironment::getRemovedActiveObjects():"
  1311. << " object in current_objects is NULL" << std::endl;
  1312. removed_objects.push(id);
  1313. continue;
  1314. }
  1315. if (object->m_removed || object->m_pending_deactivation) {
  1316. removed_objects.push(id);
  1317. continue;
  1318. }
  1319. f32 distance_f = object->getBasePosition().getDistanceFrom(playersao->getBasePosition());
  1320. if (object->getType() == ACTIVEOBJECT_TYPE_PLAYER) {
  1321. if (distance_f <= player_radius_f || player_radius_f == 0)
  1322. continue;
  1323. } else if (distance_f <= radius_f)
  1324. continue;
  1325. // Object is no longer visible
  1326. removed_objects.push(id);
  1327. }
  1328. }
  1329. void ServerEnvironment::setStaticForActiveObjectsInBlock(
  1330. v3s16 blockpos, bool static_exists, v3s16 static_block)
  1331. {
  1332. MapBlock *block = m_map->getBlockNoCreateNoEx(blockpos);
  1333. if (!block)
  1334. return;
  1335. for (auto &so_it : block->m_static_objects.m_active) {
  1336. // Get the ServerActiveObject counterpart to this StaticObject
  1337. ServerActiveObjectMap::const_iterator ao_it = m_active_objects.find(so_it.first);
  1338. if (ao_it == m_active_objects.end()) {
  1339. // If this ever happens, there must be some kind of nasty bug.
  1340. errorstream << "ServerEnvironment::setStaticForObjectsInBlock(): "
  1341. "Object from MapBlock::m_static_objects::m_active not found "
  1342. "in m_active_objects";
  1343. continue;
  1344. }
  1345. ServerActiveObject *sao = ao_it->second;
  1346. sao->m_static_exists = static_exists;
  1347. sao->m_static_block = static_block;
  1348. }
  1349. }
  1350. ActiveObjectMessage ServerEnvironment::getActiveObjectMessage()
  1351. {
  1352. if(m_active_object_messages.empty())
  1353. return ActiveObjectMessage(0);
  1354. ActiveObjectMessage message = m_active_object_messages.front();
  1355. m_active_object_messages.pop();
  1356. return message;
  1357. }
  1358. void ServerEnvironment::getSelectedActiveObjects(
  1359. const core::line3d<f32> &shootline_on_map,
  1360. std::vector<PointedThing> &objects)
  1361. {
  1362. std::vector<u16> objectIds;
  1363. getObjectsInsideRadius(objectIds, shootline_on_map.start,
  1364. shootline_on_map.getLength() + 10.0f);
  1365. const v3f line_vector = shootline_on_map.getVector();
  1366. for (u16 objectId : objectIds) {
  1367. ServerActiveObject* obj = getActiveObject(objectId);
  1368. aabb3f selection_box;
  1369. if (!obj->getSelectionBox(&selection_box))
  1370. continue;
  1371. v3f pos = obj->getBasePosition();
  1372. aabb3f offsetted_box(selection_box.MinEdge + pos,
  1373. selection_box.MaxEdge + pos);
  1374. v3f current_intersection;
  1375. v3s16 current_normal;
  1376. if (boxLineCollision(offsetted_box, shootline_on_map.start, line_vector,
  1377. &current_intersection, &current_normal)) {
  1378. objects.emplace_back(
  1379. (s16) objectId, current_intersection, current_normal,
  1380. (current_intersection - shootline_on_map.start).getLengthSQ());
  1381. }
  1382. }
  1383. }
  1384. /*
  1385. ************ Private methods *************
  1386. */
  1387. u16 ServerEnvironment::addActiveObjectRaw(ServerActiveObject *object,
  1388. bool set_changed, u32 dtime_s)
  1389. {
  1390. assert(object); // Pre-condition
  1391. if(object->getId() == 0){
  1392. u16 new_id = getFreeServerActiveObjectId(m_active_objects);
  1393. if(new_id == 0)
  1394. {
  1395. errorstream<<"ServerEnvironment::addActiveObjectRaw(): "
  1396. <<"no free ids available"<<std::endl;
  1397. if(object->environmentDeletes())
  1398. delete object;
  1399. return 0;
  1400. }
  1401. object->setId(new_id);
  1402. }
  1403. else{
  1404. verbosestream<<"ServerEnvironment::addActiveObjectRaw(): "
  1405. <<"supplied with id "<<object->getId()<<std::endl;
  1406. }
  1407. if(!isFreeServerActiveObjectId(object->getId(), m_active_objects)) {
  1408. errorstream<<"ServerEnvironment::addActiveObjectRaw(): "
  1409. <<"id is not free ("<<object->getId()<<")"<<std::endl;
  1410. if(object->environmentDeletes())
  1411. delete object;
  1412. return 0;
  1413. }
  1414. if (objectpos_over_limit(object->getBasePosition())) {
  1415. v3f p = object->getBasePosition();
  1416. warningstream << "ServerEnvironment::addActiveObjectRaw(): "
  1417. << "object position (" << p.X << "," << p.Y << "," << p.Z
  1418. << ") outside maximum range" << std::endl;
  1419. if (object->environmentDeletes())
  1420. delete object;
  1421. return 0;
  1422. }
  1423. /*infostream<<"ServerEnvironment::addActiveObjectRaw(): "
  1424. <<"added (id="<<object->getId()<<")"<<std::endl;*/
  1425. m_active_objects[object->getId()] = object;
  1426. verbosestream<<"ServerEnvironment::addActiveObjectRaw(): "
  1427. <<"Added id="<<object->getId()<<"; there are now "
  1428. <<m_active_objects.size()<<" active objects."
  1429. <<std::endl;
  1430. // Register reference in scripting api (must be done before post-init)
  1431. m_script->addObjectReference(object);
  1432. // Post-initialize object
  1433. object->addedToEnvironment(dtime_s);
  1434. // Add static data to block
  1435. if(object->isStaticAllowed())
  1436. {
  1437. // Add static object to active static list of the block
  1438. v3f objectpos = object->getBasePosition();
  1439. std::string staticdata;
  1440. object->getStaticData(&staticdata);
  1441. StaticObject s_obj(object->getType(), objectpos, staticdata);
  1442. // Add to the block where the object is located in
  1443. v3s16 blockpos = getNodeBlockPos(floatToInt(objectpos, BS));
  1444. MapBlock *block = m_map->emergeBlock(blockpos);
  1445. if(block){
  1446. block->m_static_objects.m_active[object->getId()] = s_obj;
  1447. object->m_static_exists = true;
  1448. object->m_static_block = blockpos;
  1449. if(set_changed)
  1450. block->raiseModified(MOD_STATE_WRITE_NEEDED,
  1451. MOD_REASON_ADD_ACTIVE_OBJECT_RAW);
  1452. } else {
  1453. v3s16 p = floatToInt(objectpos, BS);
  1454. errorstream<<"ServerEnvironment::addActiveObjectRaw(): "
  1455. <<"could not emerge block for storing id="<<object->getId()
  1456. <<" statically (pos="<<PP(p)<<")"<<std::endl;
  1457. }
  1458. }
  1459. return object->getId();
  1460. }
  1461. /*
  1462. Remove objects that satisfy (m_removed && m_known_by_count==0)
  1463. */
  1464. void ServerEnvironment::removeRemovedObjects()
  1465. {
  1466. std::vector<u16> objects_to_remove;
  1467. for (auto &ao_it : m_active_objects) {
  1468. u16 id = ao_it.first;
  1469. ServerActiveObject* obj = ao_it.second;
  1470. // This shouldn't happen but check it
  1471. if(obj == NULL)
  1472. {
  1473. infostream<<"NULL object found in ServerEnvironment"
  1474. <<" while finding removed objects. id="<<id<<std::endl;
  1475. // Id to be removed from m_active_objects
  1476. objects_to_remove.push_back(id);
  1477. continue;
  1478. }
  1479. /*
  1480. We will delete objects that are marked as removed or thatare
  1481. waiting for deletion after deactivation
  1482. */
  1483. if (!obj->m_removed && !obj->m_pending_deactivation)
  1484. continue;
  1485. /*
  1486. Delete static data from block if is marked as removed
  1487. */
  1488. if(obj->m_static_exists && obj->m_removed)
  1489. {
  1490. MapBlock *block = m_map->emergeBlock(obj->m_static_block, false);
  1491. if (block) {
  1492. block->m_static_objects.remove(id);
  1493. block->raiseModified(MOD_STATE_WRITE_NEEDED,
  1494. MOD_REASON_REMOVE_OBJECTS_REMOVE);
  1495. obj->m_static_exists = false;
  1496. } else {
  1497. infostream<<"Failed to emerge block from which an object to "
  1498. <<"be removed was loaded from. id="<<id<<std::endl;
  1499. }
  1500. }
  1501. // If m_known_by_count > 0, don't actually remove. On some future
  1502. // invocation this will be 0, which is when removal will continue.
  1503. if(obj->m_known_by_count > 0)
  1504. continue;
  1505. /*
  1506. Move static data from active to stored if not marked as removed
  1507. */
  1508. if(obj->m_static_exists && !obj->m_removed){
  1509. MapBlock *block = m_map->emergeBlock(obj->m_static_block, false);
  1510. if (block) {
  1511. std::map<u16, StaticObject>::iterator i =
  1512. block->m_static_objects.m_active.find(id);
  1513. if(i != block->m_static_objects.m_active.end()){
  1514. block->m_static_objects.m_stored.push_back(i->second);
  1515. block->m_static_objects.m_active.erase(id);
  1516. block->raiseModified(MOD_STATE_WRITE_NEEDED,
  1517. MOD_REASON_REMOVE_OBJECTS_DEACTIVATE);
  1518. }
  1519. } else {
  1520. infostream<<"Failed to emerge block from which an object to "
  1521. <<"be deactivated was loaded from. id="<<id<<std::endl;
  1522. }
  1523. }
  1524. // Tell the object about removal
  1525. obj->removingFromEnvironment();
  1526. // Deregister in scripting api
  1527. m_script->removeObjectReference(obj);
  1528. // Delete
  1529. if(obj->environmentDeletes())
  1530. delete obj;
  1531. // Id to be removed from m_active_objects
  1532. objects_to_remove.push_back(id);
  1533. }
  1534. // Remove references from m_active_objects
  1535. for (u16 i : objects_to_remove) {
  1536. m_active_objects.erase(i);
  1537. }
  1538. }
  1539. static void print_hexdump(std::ostream &o, const std::string &data)
  1540. {
  1541. const int linelength = 16;
  1542. for(int l=0; ; l++){
  1543. int i0 = linelength * l;
  1544. bool at_end = false;
  1545. int thislinelength = linelength;
  1546. if(i0 + thislinelength > (int)data.size()){
  1547. thislinelength = data.size() - i0;
  1548. at_end = true;
  1549. }
  1550. for(int di=0; di<linelength; di++){
  1551. int i = i0 + di;
  1552. char buf[4];
  1553. if(di<thislinelength)
  1554. snprintf(buf, 4, "%.2x ", data[i]);
  1555. else
  1556. snprintf(buf, 4, " ");
  1557. o<<buf;
  1558. }
  1559. o<<" ";
  1560. for(int di=0; di<thislinelength; di++){
  1561. int i = i0 + di;
  1562. if(data[i] >= 32)
  1563. o<<data[i];
  1564. else
  1565. o<<".";
  1566. }
  1567. o<<std::endl;
  1568. if(at_end)
  1569. break;
  1570. }
  1571. }
  1572. /*
  1573. Convert stored objects from blocks near the players to active.
  1574. */
  1575. void ServerEnvironment::activateObjects(MapBlock *block, u32 dtime_s)
  1576. {
  1577. if(block == NULL)
  1578. return;
  1579. // Ignore if no stored objects (to not set changed flag)
  1580. if(block->m_static_objects.m_stored.empty())
  1581. return;
  1582. verbosestream<<"ServerEnvironment::activateObjects(): "
  1583. <<"activating objects of block "<<PP(block->getPos())
  1584. <<" ("<<block->m_static_objects.m_stored.size()
  1585. <<" objects)"<<std::endl;
  1586. bool large_amount = (block->m_static_objects.m_stored.size() > g_settings->getU16("max_objects_per_block"));
  1587. if (large_amount) {
  1588. errorstream<<"suspiciously large amount of objects detected: "
  1589. <<block->m_static_objects.m_stored.size()<<" in "
  1590. <<PP(block->getPos())
  1591. <<"; removing all of them."<<std::endl;
  1592. // Clear stored list
  1593. block->m_static_objects.m_stored.clear();
  1594. block->raiseModified(MOD_STATE_WRITE_NEEDED,
  1595. MOD_REASON_TOO_MANY_OBJECTS);
  1596. return;
  1597. }
  1598. // Activate stored objects
  1599. std::vector<StaticObject> new_stored;
  1600. for (const StaticObject &s_obj : block->m_static_objects.m_stored) {
  1601. // Create an active object from the data
  1602. ServerActiveObject *obj = ServerActiveObject::create
  1603. ((ActiveObjectType) s_obj.type, this, 0, s_obj.pos, s_obj.data);
  1604. // If couldn't create object, store static data back.
  1605. if(obj == NULL) {
  1606. errorstream<<"ServerEnvironment::activateObjects(): "
  1607. <<"failed to create active object from static object "
  1608. <<"in block "<<PP(s_obj.pos/BS)
  1609. <<" type="<<(int)s_obj.type<<" data:"<<std::endl;
  1610. print_hexdump(verbosestream, s_obj.data);
  1611. new_stored.push_back(s_obj);
  1612. continue;
  1613. }
  1614. verbosestream<<"ServerEnvironment::activateObjects(): "
  1615. <<"activated static object pos="<<PP(s_obj.pos/BS)
  1616. <<" type="<<(int)s_obj.type<<std::endl;
  1617. // This will also add the object to the active static list
  1618. addActiveObjectRaw(obj, false, dtime_s);
  1619. }
  1620. // Clear stored list
  1621. block->m_static_objects.m_stored.clear();
  1622. // Add leftover failed stuff to stored list
  1623. for (const StaticObject &s_obj : new_stored) {
  1624. block->m_static_objects.m_stored.push_back(s_obj);
  1625. }
  1626. // Turn the active counterparts of activated objects not pending for
  1627. // deactivation
  1628. for (auto &i : block->m_static_objects.m_active) {
  1629. u16 id = i.first;
  1630. ServerActiveObject *object = getActiveObject(id);
  1631. assert(object);
  1632. object->m_pending_deactivation = false;
  1633. }
  1634. /*
  1635. Note: Block hasn't really been modified here.
  1636. The objects have just been activated and moved from the stored
  1637. static list to the active static list.
  1638. As such, the block is essentially the same.
  1639. Thus, do not call block->raiseModified(MOD_STATE_WRITE_NEEDED).
  1640. Otherwise there would be a huge amount of unnecessary I/O.
  1641. */
  1642. }
  1643. /*
  1644. Convert objects that are not standing inside active blocks to static.
  1645. If m_known_by_count != 0, active object is not deleted, but static
  1646. data is still updated.
  1647. If force_delete is set, active object is deleted nevertheless. It
  1648. shall only be set so in the destructor of the environment.
  1649. If block wasn't generated (not in memory or on disk),
  1650. */
  1651. void ServerEnvironment::deactivateFarObjects(bool _force_delete)
  1652. {
  1653. std::vector<u16> objects_to_remove;
  1654. for (auto &ao_it : m_active_objects) {
  1655. // force_delete might be overriden per object
  1656. bool force_delete = _force_delete;
  1657. ServerActiveObject* obj = ao_it.second;
  1658. assert(obj);
  1659. // Do not deactivate if static data creation not allowed
  1660. if(!force_delete && !obj->isStaticAllowed())
  1661. continue;
  1662. // If pending deactivation, let removeRemovedObjects() do it
  1663. if(!force_delete && obj->m_pending_deactivation)
  1664. continue;
  1665. u16 id = ao_it.first;
  1666. v3f objectpos = obj->getBasePosition();
  1667. // The block in which the object resides in
  1668. v3s16 blockpos_o = getNodeBlockPos(floatToInt(objectpos, BS));
  1669. // If object's static data is stored in a deactivated block and object
  1670. // is actually located in an active block, re-save to the block in
  1671. // which the object is actually located in.
  1672. if(!force_delete &&
  1673. obj->m_static_exists &&
  1674. !m_active_blocks.contains(obj->m_static_block) &&
  1675. m_active_blocks.contains(blockpos_o))
  1676. {
  1677. v3s16 old_static_block = obj->m_static_block;
  1678. // Save to block where object is located
  1679. MapBlock *block = m_map->emergeBlock(blockpos_o, false);
  1680. if(!block){
  1681. errorstream<<"ServerEnvironment::deactivateFarObjects(): "
  1682. <<"Could not save object id="<<id
  1683. <<" to it's current block "<<PP(blockpos_o)
  1684. <<std::endl;
  1685. continue;
  1686. }
  1687. std::string staticdata_new;
  1688. obj->getStaticData(&staticdata_new);
  1689. StaticObject s_obj(obj->getType(), objectpos, staticdata_new);
  1690. block->m_static_objects.insert(id, s_obj);
  1691. obj->m_static_block = blockpos_o;
  1692. block->raiseModified(MOD_STATE_WRITE_NEEDED,
  1693. MOD_REASON_STATIC_DATA_ADDED);
  1694. // Delete from block where object was located
  1695. block = m_map->emergeBlock(old_static_block, false);
  1696. if(!block){
  1697. errorstream<<"ServerEnvironment::deactivateFarObjects(): "
  1698. <<"Could not delete object id="<<id
  1699. <<" from it's previous block "<<PP(old_static_block)
  1700. <<std::endl;
  1701. continue;
  1702. }
  1703. block->m_static_objects.remove(id);
  1704. block->raiseModified(MOD_STATE_WRITE_NEEDED,
  1705. MOD_REASON_STATIC_DATA_REMOVED);
  1706. continue;
  1707. }
  1708. // If block is active, don't remove
  1709. if(!force_delete && m_active_blocks.contains(blockpos_o))
  1710. continue;
  1711. verbosestream<<"ServerEnvironment::deactivateFarObjects(): "
  1712. <<"deactivating object id="<<id<<" on inactive block "
  1713. <<PP(blockpos_o)<<std::endl;
  1714. // If known by some client, don't immediately delete.
  1715. bool pending_delete = (obj->m_known_by_count > 0 && !force_delete);
  1716. /*
  1717. Update the static data
  1718. */
  1719. if(obj->isStaticAllowed())
  1720. {
  1721. // Create new static object
  1722. std::string staticdata_new;
  1723. obj->getStaticData(&staticdata_new);
  1724. StaticObject s_obj(obj->getType(), objectpos, staticdata_new);
  1725. bool stays_in_same_block = false;
  1726. bool data_changed = true;
  1727. if (obj->m_static_exists) {
  1728. if (obj->m_static_block == blockpos_o)
  1729. stays_in_same_block = true;
  1730. MapBlock *block = m_map->emergeBlock(obj->m_static_block, false);
  1731. if (block) {
  1732. std::map<u16, StaticObject>::iterator n =
  1733. block->m_static_objects.m_active.find(id);
  1734. if (n != block->m_static_objects.m_active.end()) {
  1735. StaticObject static_old = n->second;
  1736. float save_movem = obj->getMinimumSavedMovement();
  1737. if (static_old.data == staticdata_new &&
  1738. (static_old.pos - objectpos).getLength() < save_movem)
  1739. data_changed = false;
  1740. } else {
  1741. errorstream<<"ServerEnvironment::deactivateFarObjects(): "
  1742. <<"id="<<id<<" m_static_exists=true but "
  1743. <<"static data doesn't actually exist in "
  1744. <<PP(obj->m_static_block)<<std::endl;
  1745. }
  1746. }
  1747. }
  1748. bool shall_be_written = (!stays_in_same_block || data_changed);
  1749. // Delete old static object
  1750. if(obj->m_static_exists)
  1751. {
  1752. MapBlock *block = m_map->emergeBlock(obj->m_static_block, false);
  1753. if(block)
  1754. {
  1755. block->m_static_objects.remove(id);
  1756. obj->m_static_exists = false;
  1757. // Only mark block as modified if data changed considerably
  1758. if(shall_be_written)
  1759. block->raiseModified(MOD_STATE_WRITE_NEEDED,
  1760. MOD_REASON_STATIC_DATA_CHANGED);
  1761. }
  1762. }
  1763. // Add to the block where the object is located in
  1764. v3s16 blockpos = getNodeBlockPos(floatToInt(objectpos, BS));
  1765. // Get or generate the block
  1766. MapBlock *block = NULL;
  1767. try{
  1768. block = m_map->emergeBlock(blockpos);
  1769. } catch(InvalidPositionException &e){
  1770. // Handled via NULL pointer
  1771. // NOTE: emergeBlock's failure is usually determined by it
  1772. // actually returning NULL
  1773. }
  1774. if(block)
  1775. {
  1776. if (block->m_static_objects.m_stored.size() >= g_settings->getU16("max_objects_per_block")) {
  1777. warningstream << "ServerEnv: Trying to store id = " << obj->getId()
  1778. << " statically but block " << PP(blockpos)
  1779. << " already contains "
  1780. << block->m_static_objects.m_stored.size()
  1781. << " objects."
  1782. << " Forcing delete." << std::endl;
  1783. force_delete = true;
  1784. } else {
  1785. // If static counterpart already exists in target block,
  1786. // remove it first.
  1787. // This shouldn't happen because the object is removed from
  1788. // the previous block before this according to
  1789. // obj->m_static_block, but happens rarely for some unknown
  1790. // reason. Unsuccessful attempts have been made to find
  1791. // said reason.
  1792. if(id && block->m_static_objects.m_active.find(id) != block->m_static_objects.m_active.end()){
  1793. warningstream<<"ServerEnv: Performing hack #83274"
  1794. <<std::endl;
  1795. block->m_static_objects.remove(id);
  1796. }
  1797. // Store static data
  1798. u16 store_id = pending_delete ? id : 0;
  1799. block->m_static_objects.insert(store_id, s_obj);
  1800. // Only mark block as modified if data changed considerably
  1801. if(shall_be_written)
  1802. block->raiseModified(MOD_STATE_WRITE_NEEDED,
  1803. MOD_REASON_STATIC_DATA_CHANGED);
  1804. obj->m_static_exists = true;
  1805. obj->m_static_block = block->getPos();
  1806. }
  1807. }
  1808. else{
  1809. if(!force_delete){
  1810. v3s16 p = floatToInt(objectpos, BS);
  1811. errorstream<<"ServerEnv: Could not find or generate "
  1812. <<"a block for storing id="<<obj->getId()
  1813. <<" statically (pos="<<PP(p)<<")"<<std::endl;
  1814. continue;
  1815. }
  1816. }
  1817. }
  1818. /*
  1819. If known by some client, set pending deactivation.
  1820. Otherwise delete it immediately.
  1821. */
  1822. if(pending_delete && !force_delete)
  1823. {
  1824. verbosestream<<"ServerEnvironment::deactivateFarObjects(): "
  1825. <<"object id="<<id<<" is known by clients"
  1826. <<"; not deleting yet"<<std::endl;
  1827. obj->m_pending_deactivation = true;
  1828. continue;
  1829. }
  1830. verbosestream<<"ServerEnvironment::deactivateFarObjects(): "
  1831. <<"object id="<<id<<" is not known by clients"
  1832. <<"; deleting"<<std::endl;
  1833. // Tell the object about removal
  1834. obj->removingFromEnvironment();
  1835. // Deregister in scripting api
  1836. m_script->removeObjectReference(obj);
  1837. // Delete active object
  1838. if(obj->environmentDeletes())
  1839. delete obj;
  1840. // Id to be removed from m_active_objects
  1841. objects_to_remove.push_back(id);
  1842. }
  1843. // Remove references from m_active_objects
  1844. for (u16 i : objects_to_remove) {
  1845. m_active_objects.erase(i);
  1846. }
  1847. }
  1848. PlayerDatabase *ServerEnvironment::openPlayerDatabase(const std::string &name,
  1849. const std::string &savedir, const Settings &conf)
  1850. {
  1851. if (name == "sqlite3")
  1852. return new PlayerDatabaseSQLite3(savedir);
  1853. if (name == "dummy")
  1854. return new Database_Dummy();
  1855. #if USE_POSTGRESQL
  1856. if (name == "postgresql") {
  1857. std::string connect_string;
  1858. conf.getNoEx("pgsql_player_connection", connect_string);
  1859. return new PlayerDatabasePostgreSQL(connect_string);
  1860. }
  1861. #endif
  1862. if (name == "files")
  1863. return new PlayerDatabaseFiles(savedir + DIR_DELIM + "players");
  1864. throw BaseException(std::string("Database backend ") + name + " not supported.");
  1865. }
  1866. bool ServerEnvironment::migratePlayersDatabase(const GameParams &game_params,
  1867. const Settings &cmd_args)
  1868. {
  1869. std::string migrate_to = cmd_args.get("migrate-players");
  1870. Settings world_mt;
  1871. std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
  1872. if (!world_mt.readConfigFile(world_mt_path.c_str())) {
  1873. errorstream << "Cannot read world.mt!" << std::endl;
  1874. return false;
  1875. }
  1876. if (!world_mt.exists("player_backend")) {
  1877. errorstream << "Please specify your current backend in world.mt:"
  1878. << std::endl
  1879. << " player_backend = {files|sqlite3|postgresql}"
  1880. << std::endl;
  1881. return false;
  1882. }
  1883. std::string backend = world_mt.get("player_backend");
  1884. if (backend == migrate_to) {
  1885. errorstream << "Cannot migrate: new backend is same"
  1886. << " as the old one" << std::endl;
  1887. return false;
  1888. }
  1889. const std::string players_backup_path = game_params.world_path + DIR_DELIM
  1890. + "players.bak";
  1891. if (backend == "files") {
  1892. // Create backup directory
  1893. fs::CreateDir(players_backup_path);
  1894. }
  1895. try {
  1896. PlayerDatabase *srcdb = ServerEnvironment::openPlayerDatabase(backend,
  1897. game_params.world_path, world_mt);
  1898. PlayerDatabase *dstdb = ServerEnvironment::openPlayerDatabase(migrate_to,
  1899. game_params.world_path, world_mt);
  1900. std::vector<std::string> player_list;
  1901. srcdb->listPlayers(player_list);
  1902. for (std::vector<std::string>::const_iterator it = player_list.begin();
  1903. it != player_list.end(); ++it) {
  1904. actionstream << "Migrating player " << it->c_str() << std::endl;
  1905. RemotePlayer player(it->c_str(), NULL);
  1906. PlayerSAO playerSAO(NULL, &player, 15000, false);
  1907. srcdb->loadPlayer(&player, &playerSAO);
  1908. playerSAO.finalize(&player, std::set<std::string>());
  1909. player.setPlayerSAO(&playerSAO);
  1910. dstdb->savePlayer(&player);
  1911. // For files source, move player files to backup dir
  1912. if (backend == "files") {
  1913. fs::Rename(
  1914. game_params.world_path + DIR_DELIM + "players" + DIR_DELIM + (*it),
  1915. players_backup_path + DIR_DELIM + (*it));
  1916. }
  1917. }
  1918. actionstream << "Successfully migrated " << player_list.size() << " players"
  1919. << std::endl;
  1920. world_mt.set("player_backend", migrate_to);
  1921. if (!world_mt.updateConfigFile(world_mt_path.c_str()))
  1922. errorstream << "Failed to update world.mt!" << std::endl;
  1923. else
  1924. actionstream << "world.mt updated" << std::endl;
  1925. // When migration is finished from file backend, remove players directory if empty
  1926. if (backend == "files") {
  1927. fs::DeleteSingleFileOrEmptyDirectory(game_params.world_path + DIR_DELIM
  1928. + "players");
  1929. }
  1930. delete srcdb;
  1931. delete dstdb;
  1932. } catch (BaseException &e) {
  1933. errorstream << "An error occured during migration: " << e.what() << std::endl;
  1934. return false;
  1935. }
  1936. return true;
  1937. }