serverenvironment.cpp 63 KB

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