serverenvironment.cpp 73 KB

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