serverenvironment.cpp 67 KB

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