serverenvironment.cpp 65 KB

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