serverenvironment.cpp 68 KB

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