client.cpp 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997
  1. /*
  2. Minetest
  3. Copyright (C) 2013 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 <iostream>
  17. #include <algorithm>
  18. #include <sstream>
  19. #include <cmath>
  20. #include <IFileSystem.h>
  21. #include "client.h"
  22. #include "network/clientopcodes.h"
  23. #include "network/connection.h"
  24. #include "network/networkpacket.h"
  25. #include "threading/mutex_auto_lock.h"
  26. #include "client/clientevent.h"
  27. #include "client/renderingengine.h"
  28. #include "util/auth.h"
  29. #include "util/directiontables.h"
  30. #include "util/pointedthing.h"
  31. #include "util/serialize.h"
  32. #include "util/string.h"
  33. #include "util/srp.h"
  34. #include "filesys.h"
  35. #include "mapblock_mesh.h"
  36. #include "mapblock.h"
  37. #include "minimap.h"
  38. #include "mods.h"
  39. #include "profiler.h"
  40. #include "shader.h"
  41. #include "gettext.h"
  42. #include "clientmap.h"
  43. #include "clientmedia.h"
  44. #include "version.h"
  45. #include "database-sqlite3.h"
  46. #include "serialization.h"
  47. #include "guiscalingfilter.h"
  48. #include "script/scripting_client.h"
  49. #include "game.h"
  50. #include "chatmessage.h"
  51. #include "translation.h"
  52. extern gui::IGUIEnvironment* guienv;
  53. /*
  54. Client
  55. */
  56. Client::Client(
  57. const char *playername,
  58. const std::string &password,
  59. const std::string &address_name,
  60. MapDrawControl &control,
  61. IWritableTextureSource *tsrc,
  62. IWritableShaderSource *shsrc,
  63. IWritableItemDefManager *itemdef,
  64. IWritableNodeDefManager *nodedef,
  65. ISoundManager *sound,
  66. MtEventManager *event,
  67. bool ipv6,
  68. GameUIFlags *game_ui_flags
  69. ):
  70. m_tsrc(tsrc),
  71. m_shsrc(shsrc),
  72. m_itemdef(itemdef),
  73. m_nodedef(nodedef),
  74. m_sound(sound),
  75. m_event(event),
  76. m_mesh_update_thread(this),
  77. m_env(
  78. new ClientMap(this, control, 666),
  79. tsrc, this
  80. ),
  81. m_particle_manager(&m_env),
  82. m_con(new con::Connection(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this)),
  83. m_address_name(address_name),
  84. m_server_ser_ver(SER_FMT_VER_INVALID),
  85. m_last_chat_message_sent(time(NULL)),
  86. m_password(password),
  87. m_chosen_auth_mech(AUTH_MECHANISM_NONE),
  88. m_media_downloader(new ClientMediaDownloader()),
  89. m_state(LC_Created),
  90. m_game_ui_flags(game_ui_flags)
  91. {
  92. // Add local player
  93. m_env.setLocalPlayer(new LocalPlayer(this, playername));
  94. if (g_settings->getBool("enable_minimap")) {
  95. m_minimap = new Minimap(this);
  96. }
  97. m_cache_save_interval = g_settings->getU16("server_map_save_interval");
  98. m_modding_enabled = g_settings->getBool("enable_client_modding");
  99. m_script = new ClientScripting(this);
  100. m_env.setScript(m_script);
  101. m_script->setEnv(&m_env);
  102. }
  103. void Client::loadMods()
  104. {
  105. // Load builtin
  106. scanModIntoMemory(BUILTIN_MOD_NAME, getBuiltinLuaPath());
  107. // If modding is not enabled, don't load mods, just builtin
  108. if (!m_modding_enabled) {
  109. return;
  110. }
  111. ClientModConfiguration modconf(getClientModsLuaPath());
  112. m_mods = modconf.getMods();
  113. std::vector<ModSpec> unsatisfied_mods = modconf.getUnsatisfiedMods();
  114. // complain about mods with unsatisfied dependencies
  115. if (!modconf.isConsistent()) {
  116. modconf.printUnsatisfiedModsError();
  117. }
  118. // Print mods
  119. infostream << "Client Loading mods: ";
  120. for (const ModSpec &mod : m_mods)
  121. infostream << mod.name << " ";
  122. infostream << std::endl;
  123. // Load and run "mod" scripts
  124. for (const ModSpec &mod : m_mods) {
  125. if (!string_allowed(mod.name, MODNAME_ALLOWED_CHARS)) {
  126. throw ModError("Error loading mod \"" + mod.name +
  127. "\": Mod name does not follow naming conventions: "
  128. "Only characters [a-z0-9_] are allowed.");
  129. }
  130. scanModIntoMemory(mod.name, mod.path);
  131. }
  132. }
  133. void Client::scanModSubfolder(const std::string &mod_name, const std::string &mod_path,
  134. std::string mod_subpath)
  135. {
  136. std::string full_path = mod_path + DIR_DELIM + mod_subpath;
  137. std::vector<fs::DirListNode> mod = fs::GetDirListing(full_path);
  138. for (const fs::DirListNode &j : mod) {
  139. std::string filename = j.name;
  140. if (j.dir) {
  141. scanModSubfolder(mod_name, mod_path, mod_subpath
  142. + filename + DIR_DELIM);
  143. continue;
  144. }
  145. std::replace( mod_subpath.begin(), mod_subpath.end(), DIR_DELIM_CHAR, '/');
  146. m_mod_files[mod_name + ":" + mod_subpath + filename] = full_path + filename;
  147. }
  148. }
  149. void Client::initMods()
  150. {
  151. m_script->loadModFromMemory(BUILTIN_MOD_NAME);
  152. // If modding is not enabled, don't load mods, just builtin
  153. if (!m_modding_enabled) {
  154. return;
  155. }
  156. // Load and run "mod" scripts
  157. for (const ModSpec &mod : m_mods)
  158. m_script->loadModFromMemory(mod.name);
  159. }
  160. const std::string &Client::getBuiltinLuaPath()
  161. {
  162. static const std::string builtin_dir = porting::path_share + DIR_DELIM + "builtin";
  163. return builtin_dir;
  164. }
  165. const std::string &Client::getClientModsLuaPath()
  166. {
  167. static const std::string clientmods_dir = porting::path_share + DIR_DELIM + "clientmods";
  168. return clientmods_dir;
  169. }
  170. const std::vector<ModSpec>& Client::getMods() const
  171. {
  172. static std::vector<ModSpec> client_modspec_temp;
  173. return client_modspec_temp;
  174. }
  175. const ModSpec* Client::getModSpec(const std::string &modname) const
  176. {
  177. return NULL;
  178. }
  179. void Client::Stop()
  180. {
  181. m_shutdown = true;
  182. // Don't disable this part when modding is disabled, it's used in builtin
  183. m_script->on_shutdown();
  184. //request all client managed threads to stop
  185. m_mesh_update_thread.stop();
  186. // Save local server map
  187. if (m_localdb) {
  188. infostream << "Local map saving ended." << std::endl;
  189. m_localdb->endSave();
  190. }
  191. delete m_script;
  192. }
  193. bool Client::isShutdown()
  194. {
  195. return m_shutdown || !m_mesh_update_thread.isRunning();
  196. }
  197. Client::~Client()
  198. {
  199. m_shutdown = true;
  200. m_con->Disconnect();
  201. m_mesh_update_thread.stop();
  202. m_mesh_update_thread.wait();
  203. while (!m_mesh_update_thread.m_queue_out.empty()) {
  204. MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
  205. delete r.mesh;
  206. }
  207. delete m_inventory_from_server;
  208. // Delete detached inventories
  209. for (auto &m_detached_inventorie : m_detached_inventories) {
  210. delete m_detached_inventorie.second;
  211. }
  212. // cleanup 3d model meshes on client shutdown
  213. while (RenderingEngine::get_mesh_cache()->getMeshCount() != 0) {
  214. scene::IAnimatedMesh *mesh = RenderingEngine::get_mesh_cache()->getMeshByIndex(0);
  215. if (mesh)
  216. RenderingEngine::get_mesh_cache()->removeMesh(mesh);
  217. }
  218. delete m_minimap;
  219. }
  220. void Client::connect(Address address, bool is_local_server)
  221. {
  222. initLocalMapSaving(address, m_address_name, is_local_server);
  223. m_con->SetTimeoutMs(0);
  224. m_con->Connect(address);
  225. }
  226. void Client::step(float dtime)
  227. {
  228. // Limit a bit
  229. if(dtime > 2.0)
  230. dtime = 2.0;
  231. if(m_ignore_damage_timer > dtime)
  232. m_ignore_damage_timer -= dtime;
  233. else
  234. m_ignore_damage_timer = 0.0;
  235. m_animation_time += dtime;
  236. if(m_animation_time > 60.0)
  237. m_animation_time -= 60.0;
  238. m_time_of_day_update_timer += dtime;
  239. ReceiveAll();
  240. /*
  241. Packet counter
  242. */
  243. {
  244. float &counter = m_packetcounter_timer;
  245. counter -= dtime;
  246. if(counter <= 0.0)
  247. {
  248. counter = 20.0;
  249. infostream << "Client packetcounter (" << m_packetcounter_timer
  250. << "):"<<std::endl;
  251. m_packetcounter.print(infostream);
  252. m_packetcounter.clear();
  253. }
  254. }
  255. // UGLY hack to fix 2 second startup delay caused by non existent
  256. // server client startup synchronization in local server or singleplayer mode
  257. static bool initial_step = true;
  258. if (initial_step) {
  259. initial_step = false;
  260. }
  261. else if(m_state == LC_Created) {
  262. float &counter = m_connection_reinit_timer;
  263. counter -= dtime;
  264. if(counter <= 0.0) {
  265. counter = 2.0;
  266. LocalPlayer *myplayer = m_env.getLocalPlayer();
  267. FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
  268. u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
  269. CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
  270. if (proto_version_min < 25) {
  271. // Send TOSERVER_INIT_LEGACY
  272. // [0] u16 TOSERVER_INIT_LEGACY
  273. // [2] u8 SER_FMT_VER_HIGHEST_READ
  274. // [3] u8[20] player_name
  275. // [23] u8[28] password (new in some version)
  276. // [51] u16 minimum supported network protocol version (added sometime)
  277. // [53] u16 maximum supported network protocol version (added later than the previous one)
  278. char pName[PLAYERNAME_SIZE];
  279. char pPassword[PASSWORD_SIZE];
  280. memset(pName, 0, PLAYERNAME_SIZE * sizeof(char));
  281. memset(pPassword, 0, PASSWORD_SIZE * sizeof(char));
  282. std::string hashed_password = translate_password(myplayer->getName(), m_password);
  283. snprintf(pName, PLAYERNAME_SIZE, "%s", myplayer->getName());
  284. snprintf(pPassword, PASSWORD_SIZE, "%s", hashed_password.c_str());
  285. sendLegacyInit(pName, pPassword);
  286. }
  287. if (CLIENT_PROTOCOL_VERSION_MAX >= 25)
  288. sendInit(myplayer->getName());
  289. }
  290. // Not connected, return
  291. return;
  292. }
  293. /*
  294. Do stuff if connected
  295. */
  296. /*
  297. Run Map's timers and unload unused data
  298. */
  299. const float map_timer_and_unload_dtime = 5.25;
  300. if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
  301. ScopeProfiler sp(g_profiler, "Client: map timer and unload");
  302. std::vector<v3s16> deleted_blocks;
  303. m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
  304. g_settings->getFloat("client_unload_unused_data_timeout"),
  305. g_settings->getS32("client_mapblock_limit"),
  306. &deleted_blocks);
  307. /*
  308. Send info to server
  309. NOTE: This loop is intentionally iterated the way it is.
  310. */
  311. std::vector<v3s16>::iterator i = deleted_blocks.begin();
  312. std::vector<v3s16> sendlist;
  313. for(;;) {
  314. if(sendlist.size() == 255 || i == deleted_blocks.end()) {
  315. if(sendlist.empty())
  316. break;
  317. /*
  318. [0] u16 command
  319. [2] u8 count
  320. [3] v3s16 pos_0
  321. [3+6] v3s16 pos_1
  322. ...
  323. */
  324. sendDeletedBlocks(sendlist);
  325. if(i == deleted_blocks.end())
  326. break;
  327. sendlist.clear();
  328. }
  329. sendlist.push_back(*i);
  330. ++i;
  331. }
  332. }
  333. /*
  334. Send pending messages on out chat queue
  335. */
  336. if (!m_out_chat_queue.empty() && canSendChatMessage()) {
  337. sendChatMessage(m_out_chat_queue.front());
  338. m_out_chat_queue.pop();
  339. }
  340. /*
  341. Handle environment
  342. */
  343. // Control local player (0ms)
  344. LocalPlayer *player = m_env.getLocalPlayer();
  345. assert(player);
  346. player->applyControl(dtime, &m_env);
  347. // Step environment
  348. m_env.step(dtime);
  349. m_sound->step(dtime);
  350. /*
  351. Get events
  352. */
  353. while (m_env.hasClientEnvEvents()) {
  354. ClientEnvEvent envEvent = m_env.getClientEnvEvent();
  355. if (envEvent.type == CEE_PLAYER_DAMAGE) {
  356. if (m_ignore_damage_timer <= 0) {
  357. u8 damage = envEvent.player_damage.amount;
  358. if (envEvent.player_damage.send_to_server)
  359. sendDamage(damage);
  360. // Add to ClientEvent queue
  361. ClientEvent *event = new ClientEvent();
  362. event->type = CE_PLAYER_DAMAGE;
  363. event->player_damage.amount = damage;
  364. m_client_event_queue.push(event);
  365. }
  366. }
  367. // Protocol v29 or greater obsoleted this event
  368. else if (envEvent.type == CEE_PLAYER_BREATH && m_proto_ver < 29) {
  369. u16 breath = envEvent.player_breath.amount;
  370. sendBreath(breath);
  371. }
  372. }
  373. /*
  374. Print some info
  375. */
  376. float &counter = m_avg_rtt_timer;
  377. counter += dtime;
  378. if(counter >= 10) {
  379. counter = 0.0;
  380. // connectedAndInitialized() is true, peer exists.
  381. float avg_rtt = getRTT();
  382. infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
  383. }
  384. /*
  385. Send player position to server
  386. */
  387. {
  388. float &counter = m_playerpos_send_timer;
  389. counter += dtime;
  390. if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
  391. {
  392. counter = 0.0;
  393. sendPlayerPos();
  394. }
  395. }
  396. /*
  397. Replace updated meshes
  398. */
  399. {
  400. int num_processed_meshes = 0;
  401. while (!m_mesh_update_thread.m_queue_out.empty())
  402. {
  403. num_processed_meshes++;
  404. MinimapMapblock *minimap_mapblock = NULL;
  405. bool do_mapper_update = true;
  406. MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
  407. MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
  408. if (block) {
  409. // Delete the old mesh
  410. delete block->mesh;
  411. block->mesh = nullptr;
  412. if (r.mesh) {
  413. minimap_mapblock = r.mesh->moveMinimapMapblock();
  414. if (minimap_mapblock == NULL)
  415. do_mapper_update = false;
  416. bool is_empty = true;
  417. for (int l = 0; l < MAX_TILE_LAYERS; l++)
  418. if (r.mesh->getMesh(l)->getMeshBufferCount() != 0)
  419. is_empty = false;
  420. if (is_empty)
  421. delete r.mesh;
  422. else
  423. // Replace with the new mesh
  424. block->mesh = r.mesh;
  425. }
  426. } else {
  427. delete r.mesh;
  428. }
  429. if (m_minimap && do_mapper_update)
  430. m_minimap->addBlock(r.p, minimap_mapblock);
  431. if (r.ack_block_to_server) {
  432. /*
  433. Acknowledge block
  434. [0] u8 count
  435. [1] v3s16 pos_0
  436. */
  437. sendGotBlocks(r.p);
  438. }
  439. }
  440. if (num_processed_meshes > 0)
  441. g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
  442. }
  443. /*
  444. Load fetched media
  445. */
  446. if (m_media_downloader && m_media_downloader->isStarted()) {
  447. m_media_downloader->step(this);
  448. if (m_media_downloader->isDone()) {
  449. delete m_media_downloader;
  450. m_media_downloader = NULL;
  451. }
  452. }
  453. /*
  454. If the server didn't update the inventory in a while, revert
  455. the local inventory (so the player notices the lag problem
  456. and knows something is wrong).
  457. */
  458. if(m_inventory_from_server)
  459. {
  460. float interval = 10.0;
  461. float count_before = floor(m_inventory_from_server_age / interval);
  462. m_inventory_from_server_age += dtime;
  463. float count_after = floor(m_inventory_from_server_age / interval);
  464. if(count_after != count_before)
  465. {
  466. // Do this every <interval> seconds after TOCLIENT_INVENTORY
  467. // Reset the locally changed inventory to the authoritative inventory
  468. LocalPlayer *player = m_env.getLocalPlayer();
  469. player->inventory = *m_inventory_from_server;
  470. m_inventory_updated = true;
  471. }
  472. }
  473. /*
  474. Update positions of sounds attached to objects
  475. */
  476. {
  477. for (auto &m_sounds_to_object : m_sounds_to_objects) {
  478. int client_id = m_sounds_to_object.first;
  479. u16 object_id = m_sounds_to_object.second;
  480. ClientActiveObject *cao = m_env.getActiveObject(object_id);
  481. if (!cao)
  482. continue;
  483. m_sound->updateSoundPosition(client_id, cao->getPosition());
  484. }
  485. }
  486. /*
  487. Handle removed remotely initiated sounds
  488. */
  489. m_removed_sounds_check_timer += dtime;
  490. if(m_removed_sounds_check_timer >= 2.32) {
  491. m_removed_sounds_check_timer = 0;
  492. // Find removed sounds and clear references to them
  493. std::vector<s32> removed_server_ids;
  494. for (std::unordered_map<s32, int>::iterator i = m_sounds_server_to_client.begin();
  495. i != m_sounds_server_to_client.end();) {
  496. s32 server_id = i->first;
  497. int client_id = i->second;
  498. ++i;
  499. if(!m_sound->soundExists(client_id)) {
  500. m_sounds_server_to_client.erase(server_id);
  501. m_sounds_client_to_server.erase(client_id);
  502. m_sounds_to_objects.erase(client_id);
  503. removed_server_ids.push_back(server_id);
  504. }
  505. }
  506. // Sync to server
  507. if(!removed_server_ids.empty()) {
  508. sendRemovedSounds(removed_server_ids);
  509. }
  510. }
  511. m_mod_storage_save_timer -= dtime;
  512. if (m_mod_storage_save_timer <= 0.0f) {
  513. verbosestream << "Saving registered mod storages." << std::endl;
  514. m_mod_storage_save_timer = g_settings->getFloat("server_map_save_interval");
  515. for (std::unordered_map<std::string, ModMetadata *>::const_iterator
  516. it = m_mod_storages.begin(); it != m_mod_storages.end(); ++it) {
  517. if (it->second->isModified()) {
  518. it->second->save(getModStoragePath());
  519. }
  520. }
  521. }
  522. // Write server map
  523. if (m_localdb && m_localdb_save_interval.step(dtime,
  524. m_cache_save_interval)) {
  525. m_localdb->endSave();
  526. m_localdb->beginSave();
  527. }
  528. }
  529. bool Client::loadMedia(const std::string &data, const std::string &filename)
  530. {
  531. // Silly irrlicht's const-incorrectness
  532. Buffer<char> data_rw(data.c_str(), data.size());
  533. std::string name;
  534. const char *image_ext[] = {
  535. ".png", ".jpg", ".bmp", ".tga",
  536. ".pcx", ".ppm", ".psd", ".wal", ".rgb",
  537. NULL
  538. };
  539. name = removeStringEnd(filename, image_ext);
  540. if (!name.empty()) {
  541. verbosestream<<"Client: Attempting to load image "
  542. <<"file \""<<filename<<"\""<<std::endl;
  543. io::IFileSystem *irrfs = RenderingEngine::get_filesystem();
  544. video::IVideoDriver *vdrv = RenderingEngine::get_video_driver();
  545. // Create an irrlicht memory file
  546. io::IReadFile *rfile = irrfs->createMemoryReadFile(
  547. *data_rw, data_rw.getSize(), "_tempreadfile");
  548. FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
  549. // Read image
  550. video::IImage *img = vdrv->createImageFromFile(rfile);
  551. if (!img) {
  552. errorstream<<"Client: Cannot create image from data of "
  553. <<"file \""<<filename<<"\""<<std::endl;
  554. rfile->drop();
  555. return false;
  556. }
  557. m_tsrc->insertSourceImage(filename, img);
  558. img->drop();
  559. rfile->drop();
  560. return true;
  561. }
  562. const char *sound_ext[] = {
  563. ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
  564. ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
  565. ".ogg", NULL
  566. };
  567. name = removeStringEnd(filename, sound_ext);
  568. if (!name.empty()) {
  569. verbosestream<<"Client: Attempting to load sound "
  570. <<"file \""<<filename<<"\""<<std::endl;
  571. m_sound->loadSoundData(name, data);
  572. return true;
  573. }
  574. const char *model_ext[] = {
  575. ".x", ".b3d", ".md2", ".obj",
  576. NULL
  577. };
  578. name = removeStringEnd(filename, model_ext);
  579. if (!name.empty()) {
  580. verbosestream<<"Client: Storing model into memory: "
  581. <<"\""<<filename<<"\""<<std::endl;
  582. if(m_mesh_data.count(filename))
  583. errorstream<<"Multiple models with name \""<<filename.c_str()
  584. <<"\" found; replacing previous model"<<std::endl;
  585. m_mesh_data[filename] = data;
  586. return true;
  587. }
  588. const char *translate_ext[] = {
  589. ".tr", NULL
  590. };
  591. name = removeStringEnd(filename, translate_ext);
  592. if (!name.empty()) {
  593. verbosestream << "Client: Loading translation: "
  594. << "\"" << filename << "\"" << std::endl;
  595. g_translations->loadTranslation(data);
  596. return true;
  597. }
  598. errorstream << "Client: Don't know how to load file \""
  599. << filename << "\"" << std::endl;
  600. return false;
  601. }
  602. // Virtual methods from con::PeerHandler
  603. void Client::peerAdded(con::Peer *peer)
  604. {
  605. infostream << "Client::peerAdded(): peer->id="
  606. << peer->id << std::endl;
  607. }
  608. void Client::deletingPeer(con::Peer *peer, bool timeout)
  609. {
  610. infostream << "Client::deletingPeer(): "
  611. "Server Peer is getting deleted "
  612. << "(timeout=" << timeout << ")" << std::endl;
  613. if (timeout) {
  614. m_access_denied = true;
  615. m_access_denied_reason = gettext("Connection timed out.");
  616. }
  617. }
  618. /*
  619. u16 command
  620. u16 number of files requested
  621. for each file {
  622. u16 length of name
  623. string name
  624. }
  625. */
  626. void Client::request_media(const std::vector<std::string> &file_requests)
  627. {
  628. std::ostringstream os(std::ios_base::binary);
  629. writeU16(os, TOSERVER_REQUEST_MEDIA);
  630. size_t file_requests_size = file_requests.size();
  631. FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
  632. // Packet dynamicly resized
  633. NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
  634. pkt << (u16) (file_requests_size & 0xFFFF);
  635. for (const std::string &file_request : file_requests) {
  636. pkt << file_request;
  637. }
  638. Send(&pkt);
  639. infostream << "Client: Sending media request list to server ("
  640. << file_requests.size() << " files. packet size)" << std::endl;
  641. }
  642. void Client::initLocalMapSaving(const Address &address,
  643. const std::string &hostname,
  644. bool is_local_server)
  645. {
  646. if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
  647. return;
  648. }
  649. const std::string world_path = porting::path_user
  650. + DIR_DELIM + "worlds"
  651. + DIR_DELIM + "server_"
  652. + hostname + "_" + std::to_string(address.getPort());
  653. fs::CreateAllDirs(world_path);
  654. m_localdb = new MapDatabaseSQLite3(world_path);
  655. m_localdb->beginSave();
  656. actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
  657. }
  658. void Client::ReceiveAll()
  659. {
  660. u64 start_ms = porting::getTimeMs();
  661. for(;;)
  662. {
  663. // Limit time even if there would be huge amounts of data to
  664. // process
  665. if(porting::getTimeMs() > start_ms + 100)
  666. break;
  667. try {
  668. Receive();
  669. g_profiler->graphAdd("client_received_packets", 1);
  670. }
  671. catch(con::NoIncomingDataException &e) {
  672. break;
  673. }
  674. catch(con::InvalidIncomingDataException &e) {
  675. infostream<<"Client::ReceiveAll(): "
  676. "InvalidIncomingDataException: what()="
  677. <<e.what()<<std::endl;
  678. }
  679. }
  680. }
  681. void Client::Receive()
  682. {
  683. NetworkPacket pkt;
  684. m_con->Receive(&pkt);
  685. ProcessData(&pkt);
  686. }
  687. inline void Client::handleCommand(NetworkPacket* pkt)
  688. {
  689. const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
  690. (this->*opHandle.handler)(pkt);
  691. }
  692. /*
  693. sender_peer_id given to this shall be quaranteed to be a valid peer
  694. */
  695. void Client::ProcessData(NetworkPacket *pkt)
  696. {
  697. ToClientCommand command = (ToClientCommand) pkt->getCommand();
  698. u32 sender_peer_id = pkt->getPeerId();
  699. //infostream<<"Client: received command="<<command<<std::endl;
  700. m_packetcounter.add((u16)command);
  701. /*
  702. If this check is removed, be sure to change the queue
  703. system to know the ids
  704. */
  705. if(sender_peer_id != PEER_ID_SERVER) {
  706. infostream << "Client::ProcessData(): Discarding data not "
  707. "coming from server: peer_id=" << sender_peer_id
  708. << std::endl;
  709. return;
  710. }
  711. // Command must be handled into ToClientCommandHandler
  712. if (command >= TOCLIENT_NUM_MSG_TYPES) {
  713. infostream << "Client: Ignoring unknown command "
  714. << command << std::endl;
  715. return;
  716. }
  717. /*
  718. * Those packets are handled before m_server_ser_ver is set, it's normal
  719. * But we must use the new ToClientConnectionState in the future,
  720. * as a byte mask
  721. */
  722. if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
  723. handleCommand(pkt);
  724. return;
  725. }
  726. if(m_server_ser_ver == SER_FMT_VER_INVALID) {
  727. infostream << "Client: Server serialization"
  728. " format invalid or not initialized."
  729. " Skipping incoming command=" << command << std::endl;
  730. return;
  731. }
  732. /*
  733. Handle runtime commands
  734. */
  735. handleCommand(pkt);
  736. }
  737. void Client::Send(NetworkPacket* pkt)
  738. {
  739. m_con->Send(PEER_ID_SERVER,
  740. serverCommandFactoryTable[pkt->getCommand()].channel,
  741. pkt,
  742. serverCommandFactoryTable[pkt->getCommand()].reliable);
  743. }
  744. // Will fill up 12 + 12 + 4 + 4 + 4 bytes
  745. void writePlayerPos(LocalPlayer *myplayer, ClientMap *clientMap, NetworkPacket *pkt)
  746. {
  747. v3f pf = myplayer->getPosition() * 100;
  748. v3f sf = myplayer->getSpeed() * 100;
  749. s32 pitch = myplayer->getPitch() * 100;
  750. s32 yaw = myplayer->getYaw() * 100;
  751. u32 keyPressed = myplayer->keyPressed;
  752. // scaled by 80, so that pi can fit into a u8
  753. u8 fov = clientMap->getCameraFov() * 80;
  754. u8 wanted_range = MYMIN(255,
  755. std::ceil(clientMap->getControl().wanted_range / MAP_BLOCKSIZE));
  756. v3s32 position(pf.X, pf.Y, pf.Z);
  757. v3s32 speed(sf.X, sf.Y, sf.Z);
  758. /*
  759. Format:
  760. [0] v3s32 position*100
  761. [12] v3s32 speed*100
  762. [12+12] s32 pitch*100
  763. [12+12+4] s32 yaw*100
  764. [12+12+4+4] u32 keyPressed
  765. [12+12+4+4+4] u8 fov*80
  766. [12+12+4+4+4+1] u8 ceil(wanted_range / MAP_BLOCKSIZE)
  767. */
  768. *pkt << position << speed << pitch << yaw << keyPressed;
  769. *pkt << fov << wanted_range;
  770. }
  771. void Client::interact(u8 action, const PointedThing& pointed)
  772. {
  773. if(m_state != LC_Ready) {
  774. errorstream << "Client::interact() "
  775. "Canceled (not connected)"
  776. << std::endl;
  777. return;
  778. }
  779. LocalPlayer *myplayer = m_env.getLocalPlayer();
  780. if (myplayer == NULL)
  781. return;
  782. /*
  783. [0] u16 command
  784. [2] u8 action
  785. [3] u16 item
  786. [5] u32 length of the next item (plen)
  787. [9] serialized PointedThing
  788. [9 + plen] player position information
  789. actions:
  790. 0: start digging (from undersurface) or use
  791. 1: stop digging (all parameters ignored)
  792. 2: digging completed
  793. 3: place block or item (to abovesurface)
  794. 4: use item
  795. 5: perform secondary action of item
  796. */
  797. NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
  798. pkt << action;
  799. pkt << (u16)getPlayerItem();
  800. std::ostringstream tmp_os(std::ios::binary);
  801. pointed.serialize(tmp_os);
  802. pkt.putLongString(tmp_os.str());
  803. writePlayerPos(myplayer, &m_env.getClientMap(), &pkt);
  804. Send(&pkt);
  805. }
  806. void Client::deleteAuthData()
  807. {
  808. if (!m_auth_data)
  809. return;
  810. switch (m_chosen_auth_mech) {
  811. case AUTH_MECHANISM_FIRST_SRP:
  812. break;
  813. case AUTH_MECHANISM_SRP:
  814. case AUTH_MECHANISM_LEGACY_PASSWORD:
  815. srp_user_delete((SRPUser *) m_auth_data);
  816. m_auth_data = NULL;
  817. break;
  818. case AUTH_MECHANISM_NONE:
  819. break;
  820. }
  821. m_chosen_auth_mech = AUTH_MECHANISM_NONE;
  822. }
  823. AuthMechanism Client::choseAuthMech(const u32 mechs)
  824. {
  825. if (mechs & AUTH_MECHANISM_SRP)
  826. return AUTH_MECHANISM_SRP;
  827. if (mechs & AUTH_MECHANISM_FIRST_SRP)
  828. return AUTH_MECHANISM_FIRST_SRP;
  829. if (mechs & AUTH_MECHANISM_LEGACY_PASSWORD)
  830. return AUTH_MECHANISM_LEGACY_PASSWORD;
  831. return AUTH_MECHANISM_NONE;
  832. }
  833. void Client::sendLegacyInit(const char* playerName, const char* playerPassword)
  834. {
  835. NetworkPacket pkt(TOSERVER_INIT_LEGACY,
  836. 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
  837. u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
  838. CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
  839. pkt << (u8) SER_FMT_VER_HIGHEST_READ;
  840. pkt.putRawString(playerName,PLAYERNAME_SIZE);
  841. pkt.putRawString(playerPassword, PASSWORD_SIZE);
  842. pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
  843. Send(&pkt);
  844. }
  845. void Client::sendInit(const std::string &playerName)
  846. {
  847. NetworkPacket pkt(TOSERVER_INIT, 1 + 2 + 2 + (1 + playerName.size()));
  848. // we don't support network compression yet
  849. u16 supp_comp_modes = NETPROTO_COMPRESSION_NONE;
  850. u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
  851. CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
  852. pkt << (u8) SER_FMT_VER_HIGHEST_READ << (u16) supp_comp_modes;
  853. pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
  854. pkt << playerName;
  855. Send(&pkt);
  856. }
  857. void Client::startAuth(AuthMechanism chosen_auth_mechanism)
  858. {
  859. m_chosen_auth_mech = chosen_auth_mechanism;
  860. switch (chosen_auth_mechanism) {
  861. case AUTH_MECHANISM_FIRST_SRP: {
  862. // send srp verifier to server
  863. std::string verifier;
  864. std::string salt;
  865. generate_srp_verifier_and_salt(getPlayerName(), m_password,
  866. &verifier, &salt);
  867. NetworkPacket resp_pkt(TOSERVER_FIRST_SRP, 0);
  868. resp_pkt << salt << verifier << (u8)((m_password.empty()) ? 1 : 0);
  869. Send(&resp_pkt);
  870. break;
  871. }
  872. case AUTH_MECHANISM_SRP:
  873. case AUTH_MECHANISM_LEGACY_PASSWORD: {
  874. u8 based_on = 1;
  875. if (chosen_auth_mechanism == AUTH_MECHANISM_LEGACY_PASSWORD) {
  876. m_password = translate_password(getPlayerName(), m_password);
  877. based_on = 0;
  878. }
  879. std::string playername_u = lowercase(getPlayerName());
  880. m_auth_data = srp_user_new(SRP_SHA256, SRP_NG_2048,
  881. getPlayerName().c_str(), playername_u.c_str(),
  882. (const unsigned char *) m_password.c_str(),
  883. m_password.length(), NULL, NULL);
  884. char *bytes_A = 0;
  885. size_t len_A = 0;
  886. SRP_Result res = srp_user_start_authentication(
  887. (struct SRPUser *) m_auth_data, NULL, NULL, 0,
  888. (unsigned char **) &bytes_A, &len_A);
  889. FATAL_ERROR_IF(res != SRP_OK, "Creating local SRP user failed.");
  890. NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_A, 0);
  891. resp_pkt << std::string(bytes_A, len_A) << based_on;
  892. Send(&resp_pkt);
  893. break;
  894. }
  895. case AUTH_MECHANISM_NONE:
  896. break; // not handled in this method
  897. }
  898. }
  899. void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
  900. {
  901. NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
  902. pkt << (u8) blocks.size();
  903. for (const v3s16 &block : blocks) {
  904. pkt << block;
  905. }
  906. Send(&pkt);
  907. }
  908. void Client::sendGotBlocks(v3s16 block)
  909. {
  910. NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6);
  911. pkt << (u8) 1 << block;
  912. Send(&pkt);
  913. }
  914. void Client::sendRemovedSounds(std::vector<s32> &soundList)
  915. {
  916. size_t server_ids = soundList.size();
  917. assert(server_ids <= 0xFFFF);
  918. NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
  919. pkt << (u16) (server_ids & 0xFFFF);
  920. for (int sound_id : soundList)
  921. pkt << sound_id;
  922. Send(&pkt);
  923. }
  924. void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
  925. const StringMap &fields)
  926. {
  927. size_t fields_size = fields.size();
  928. FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
  929. NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
  930. pkt << p << formname << (u16) (fields_size & 0xFFFF);
  931. StringMap::const_iterator it;
  932. for (it = fields.begin(); it != fields.end(); ++it) {
  933. const std::string &name = it->first;
  934. const std::string &value = it->second;
  935. pkt << name;
  936. pkt.putLongString(value);
  937. }
  938. Send(&pkt);
  939. }
  940. void Client::sendInventoryFields(const std::string &formname,
  941. const StringMap &fields)
  942. {
  943. size_t fields_size = fields.size();
  944. FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
  945. NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
  946. pkt << formname << (u16) (fields_size & 0xFFFF);
  947. StringMap::const_iterator it;
  948. for (it = fields.begin(); it != fields.end(); ++it) {
  949. const std::string &name = it->first;
  950. const std::string &value = it->second;
  951. pkt << name;
  952. pkt.putLongString(value);
  953. }
  954. Send(&pkt);
  955. }
  956. void Client::sendInventoryAction(InventoryAction *a)
  957. {
  958. std::ostringstream os(std::ios_base::binary);
  959. a->serialize(os);
  960. // Make data buffer
  961. std::string s = os.str();
  962. NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
  963. pkt.putRawString(s.c_str(),s.size());
  964. Send(&pkt);
  965. }
  966. bool Client::canSendChatMessage() const
  967. {
  968. u32 now = time(NULL);
  969. float time_passed = now - m_last_chat_message_sent;
  970. float virt_chat_message_allowance = m_chat_message_allowance + time_passed *
  971. (CLIENT_CHAT_MESSAGE_LIMIT_PER_10S / 8.0f);
  972. if (virt_chat_message_allowance < 1.0f)
  973. return false;
  974. return true;
  975. }
  976. void Client::sendChatMessage(const std::wstring &message)
  977. {
  978. const s16 max_queue_size = g_settings->getS16("max_out_chat_queue_size");
  979. if (canSendChatMessage()) {
  980. u32 now = time(NULL);
  981. float time_passed = now - m_last_chat_message_sent;
  982. m_last_chat_message_sent = time(NULL);
  983. m_chat_message_allowance += time_passed * (CLIENT_CHAT_MESSAGE_LIMIT_PER_10S / 8.0f);
  984. if (m_chat_message_allowance > CLIENT_CHAT_MESSAGE_LIMIT_PER_10S)
  985. m_chat_message_allowance = CLIENT_CHAT_MESSAGE_LIMIT_PER_10S;
  986. m_chat_message_allowance -= 1.0f;
  987. NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
  988. pkt << message;
  989. Send(&pkt);
  990. } else if (m_out_chat_queue.size() < (u16) max_queue_size || max_queue_size == -1) {
  991. m_out_chat_queue.push(message);
  992. } else {
  993. infostream << "Could not queue chat message because maximum out chat queue size ("
  994. << max_queue_size << ") is reached." << std::endl;
  995. }
  996. }
  997. void Client::clearOutChatQueue()
  998. {
  999. m_out_chat_queue = std::queue<std::wstring>();
  1000. }
  1001. void Client::sendChangePassword(const std::string &oldpassword,
  1002. const std::string &newpassword)
  1003. {
  1004. LocalPlayer *player = m_env.getLocalPlayer();
  1005. if (player == NULL)
  1006. return;
  1007. std::string playername = player->getName();
  1008. if (m_proto_ver >= 25) {
  1009. // get into sudo mode and then send new password to server
  1010. m_password = oldpassword;
  1011. m_new_password = newpassword;
  1012. startAuth(choseAuthMech(m_sudo_auth_methods));
  1013. } else {
  1014. std::string oldpwd = translate_password(playername, oldpassword);
  1015. std::string newpwd = translate_password(playername, newpassword);
  1016. NetworkPacket pkt(TOSERVER_PASSWORD_LEGACY, 2 * PASSWORD_SIZE);
  1017. for (u8 i = 0; i < PASSWORD_SIZE; i++) {
  1018. pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
  1019. }
  1020. for (u8 i = 0; i < PASSWORD_SIZE; i++) {
  1021. pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
  1022. }
  1023. Send(&pkt);
  1024. }
  1025. }
  1026. void Client::sendDamage(u8 damage)
  1027. {
  1028. NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u8));
  1029. pkt << damage;
  1030. Send(&pkt);
  1031. }
  1032. void Client::sendBreath(u16 breath)
  1033. {
  1034. // Protocol v29 make this obsolete
  1035. if (m_proto_ver >= 29)
  1036. return;
  1037. NetworkPacket pkt(TOSERVER_BREATH, sizeof(u16));
  1038. pkt << breath;
  1039. Send(&pkt);
  1040. }
  1041. void Client::sendRespawn()
  1042. {
  1043. NetworkPacket pkt(TOSERVER_RESPAWN, 0);
  1044. Send(&pkt);
  1045. }
  1046. void Client::sendReady()
  1047. {
  1048. NetworkPacket pkt(TOSERVER_CLIENT_READY,
  1049. 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash));
  1050. pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
  1051. << (u8) 0 << (u16) strlen(g_version_hash);
  1052. pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
  1053. Send(&pkt);
  1054. }
  1055. void Client::sendPlayerPos()
  1056. {
  1057. LocalPlayer *myplayer = m_env.getLocalPlayer();
  1058. if(myplayer == NULL)
  1059. return;
  1060. ClientMap &map = m_env.getClientMap();
  1061. u8 camera_fov = map.getCameraFov();
  1062. u8 wanted_range = map.getControl().wanted_range;
  1063. // Save bandwidth by only updating position when something changed
  1064. if(myplayer->last_position == myplayer->getPosition() &&
  1065. myplayer->last_speed == myplayer->getSpeed() &&
  1066. myplayer->last_pitch == myplayer->getPitch() &&
  1067. myplayer->last_yaw == myplayer->getYaw() &&
  1068. myplayer->last_keyPressed == myplayer->keyPressed &&
  1069. myplayer->last_camera_fov == camera_fov &&
  1070. myplayer->last_wanted_range == wanted_range)
  1071. return;
  1072. myplayer->last_position = myplayer->getPosition();
  1073. myplayer->last_speed = myplayer->getSpeed();
  1074. myplayer->last_pitch = myplayer->getPitch();
  1075. myplayer->last_yaw = myplayer->getYaw();
  1076. myplayer->last_keyPressed = myplayer->keyPressed;
  1077. myplayer->last_camera_fov = camera_fov;
  1078. myplayer->last_wanted_range = wanted_range;
  1079. //infostream << "Sending Player Position information" << std::endl;
  1080. u16 our_peer_id;
  1081. {
  1082. //MutexAutoLock lock(m_con_mutex); //bulk comment-out
  1083. our_peer_id = m_con->GetPeerID();
  1084. }
  1085. // Set peer id if not set already
  1086. if(myplayer->peer_id == PEER_ID_INEXISTENT)
  1087. myplayer->peer_id = our_peer_id;
  1088. assert(myplayer->peer_id == our_peer_id);
  1089. NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4 + 1 + 1);
  1090. writePlayerPos(myplayer, &map, &pkt);
  1091. Send(&pkt);
  1092. }
  1093. void Client::sendPlayerItem(u16 item)
  1094. {
  1095. LocalPlayer *myplayer = m_env.getLocalPlayer();
  1096. if(myplayer == NULL)
  1097. return;
  1098. u16 our_peer_id = m_con->GetPeerID();
  1099. // Set peer id if not set already
  1100. if(myplayer->peer_id == PEER_ID_INEXISTENT)
  1101. myplayer->peer_id = our_peer_id;
  1102. assert(myplayer->peer_id == our_peer_id);
  1103. NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
  1104. pkt << item;
  1105. Send(&pkt);
  1106. }
  1107. void Client::removeNode(v3s16 p)
  1108. {
  1109. std::map<v3s16, MapBlock*> modified_blocks;
  1110. try {
  1111. m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
  1112. }
  1113. catch(InvalidPositionException &e) {
  1114. }
  1115. for (const auto &modified_block : modified_blocks) {
  1116. addUpdateMeshTaskWithEdge(modified_block.first, false, true);
  1117. }
  1118. }
  1119. /**
  1120. * Helper function for Client Side Modding
  1121. * Flavour is applied there, this should not be used for core engine
  1122. * @param p
  1123. * @param is_valid_position
  1124. * @return
  1125. */
  1126. MapNode Client::getNode(v3s16 p, bool *is_valid_position)
  1127. {
  1128. if (checkCSMFlavourLimit(CSMFlavourLimit::CSM_FL_LOOKUP_NODES)) {
  1129. v3s16 ppos = floatToInt(m_env.getLocalPlayer()->getPosition(), BS);
  1130. if ((u32) ppos.getDistanceFrom(p) > m_csm_noderange_limit) {
  1131. *is_valid_position = false;
  1132. return {};
  1133. }
  1134. }
  1135. return m_env.getMap().getNodeNoEx(p, is_valid_position);
  1136. }
  1137. void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
  1138. {
  1139. //TimeTaker timer1("Client::addNode()");
  1140. std::map<v3s16, MapBlock*> modified_blocks;
  1141. try {
  1142. //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
  1143. m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
  1144. }
  1145. catch(InvalidPositionException &e) {
  1146. }
  1147. for (const auto &modified_block : modified_blocks) {
  1148. addUpdateMeshTaskWithEdge(modified_block.first, false, true);
  1149. }
  1150. }
  1151. void Client::setPlayerControl(PlayerControl &control)
  1152. {
  1153. LocalPlayer *player = m_env.getLocalPlayer();
  1154. assert(player);
  1155. player->control = control;
  1156. }
  1157. void Client::selectPlayerItem(u16 item)
  1158. {
  1159. m_playeritem = item;
  1160. m_inventory_updated = true;
  1161. sendPlayerItem(item);
  1162. }
  1163. // Returns true if the inventory of the local player has been
  1164. // updated from the server. If it is true, it is set to false.
  1165. bool Client::getLocalInventoryUpdated()
  1166. {
  1167. bool updated = m_inventory_updated;
  1168. m_inventory_updated = false;
  1169. return updated;
  1170. }
  1171. // Copies the inventory of the local player to parameter
  1172. void Client::getLocalInventory(Inventory &dst)
  1173. {
  1174. LocalPlayer *player = m_env.getLocalPlayer();
  1175. assert(player);
  1176. dst = player->inventory;
  1177. }
  1178. Inventory* Client::getInventory(const InventoryLocation &loc)
  1179. {
  1180. switch(loc.type){
  1181. case InventoryLocation::UNDEFINED:
  1182. {}
  1183. break;
  1184. case InventoryLocation::CURRENT_PLAYER:
  1185. {
  1186. LocalPlayer *player = m_env.getLocalPlayer();
  1187. assert(player);
  1188. return &player->inventory;
  1189. }
  1190. break;
  1191. case InventoryLocation::PLAYER:
  1192. {
  1193. // Check if we are working with local player inventory
  1194. LocalPlayer *player = m_env.getLocalPlayer();
  1195. if (!player || strcmp(player->getName(), loc.name.c_str()) != 0)
  1196. return NULL;
  1197. return &player->inventory;
  1198. }
  1199. break;
  1200. case InventoryLocation::NODEMETA:
  1201. {
  1202. NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
  1203. if(!meta)
  1204. return NULL;
  1205. return meta->getInventory();
  1206. }
  1207. break;
  1208. case InventoryLocation::DETACHED:
  1209. {
  1210. if (m_detached_inventories.count(loc.name) == 0)
  1211. return NULL;
  1212. return m_detached_inventories[loc.name];
  1213. }
  1214. break;
  1215. default:
  1216. FATAL_ERROR("Invalid inventory location type.");
  1217. break;
  1218. }
  1219. return NULL;
  1220. }
  1221. void Client::inventoryAction(InventoryAction *a)
  1222. {
  1223. /*
  1224. Send it to the server
  1225. */
  1226. sendInventoryAction(a);
  1227. /*
  1228. Predict some local inventory changes
  1229. */
  1230. a->clientApply(this, this);
  1231. // Remove it
  1232. delete a;
  1233. }
  1234. float Client::getAnimationTime()
  1235. {
  1236. return m_animation_time;
  1237. }
  1238. int Client::getCrackLevel()
  1239. {
  1240. return m_crack_level;
  1241. }
  1242. v3s16 Client::getCrackPos()
  1243. {
  1244. return m_crack_pos;
  1245. }
  1246. void Client::setCrack(int level, v3s16 pos)
  1247. {
  1248. int old_crack_level = m_crack_level;
  1249. v3s16 old_crack_pos = m_crack_pos;
  1250. m_crack_level = level;
  1251. m_crack_pos = pos;
  1252. if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
  1253. {
  1254. // remove old crack
  1255. addUpdateMeshTaskForNode(old_crack_pos, false, true);
  1256. }
  1257. if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
  1258. {
  1259. // add new crack
  1260. addUpdateMeshTaskForNode(pos, false, true);
  1261. }
  1262. }
  1263. u16 Client::getHP()
  1264. {
  1265. LocalPlayer *player = m_env.getLocalPlayer();
  1266. assert(player);
  1267. return player->hp;
  1268. }
  1269. bool Client::getChatMessage(std::wstring &res)
  1270. {
  1271. if (m_chat_queue.empty())
  1272. return false;
  1273. ChatMessage *chatMessage = m_chat_queue.front();
  1274. m_chat_queue.pop();
  1275. res = L"";
  1276. switch (chatMessage->type) {
  1277. case CHATMESSAGE_TYPE_RAW:
  1278. case CHATMESSAGE_TYPE_ANNOUNCE:
  1279. case CHATMESSAGE_TYPE_SYSTEM:
  1280. res = chatMessage->message;
  1281. break;
  1282. case CHATMESSAGE_TYPE_NORMAL: {
  1283. if (!chatMessage->sender.empty())
  1284. res = L"<" + chatMessage->sender + L"> " + chatMessage->message;
  1285. else
  1286. res = chatMessage->message;
  1287. break;
  1288. }
  1289. default:
  1290. break;
  1291. }
  1292. delete chatMessage;
  1293. return true;
  1294. }
  1295. void Client::typeChatMessage(const std::wstring &message)
  1296. {
  1297. // Discard empty line
  1298. if (message.empty())
  1299. return;
  1300. // If message was ate by script API, don't send it to server
  1301. if (m_script->on_sending_message(wide_to_utf8(message))) {
  1302. return;
  1303. }
  1304. // Send to others
  1305. sendChatMessage(message);
  1306. // Show locally
  1307. if (message[0] != L'/') {
  1308. // compatibility code
  1309. if (m_proto_ver < 29) {
  1310. LocalPlayer *player = m_env.getLocalPlayer();
  1311. assert(player);
  1312. std::wstring name = narrow_to_wide(player->getName());
  1313. pushToChatQueue(new ChatMessage(CHATMESSAGE_TYPE_NORMAL, message, name));
  1314. }
  1315. }
  1316. }
  1317. void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
  1318. {
  1319. // Check if the block exists to begin with. In the case when a non-existing
  1320. // neighbor is automatically added, it may not. In that case we don't want
  1321. // to tell the mesh update thread about it.
  1322. MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
  1323. if (b == NULL)
  1324. return;
  1325. m_mesh_update_thread.updateBlock(&m_env.getMap(), p, ack_to_server, urgent);
  1326. }
  1327. void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
  1328. {
  1329. try{
  1330. addUpdateMeshTask(blockpos, ack_to_server, urgent);
  1331. }
  1332. catch(InvalidPositionException &e){}
  1333. // Leading edge
  1334. for (int i=0;i<6;i++)
  1335. {
  1336. try{
  1337. v3s16 p = blockpos + g_6dirs[i];
  1338. addUpdateMeshTask(p, false, urgent);
  1339. }
  1340. catch(InvalidPositionException &e){}
  1341. }
  1342. }
  1343. void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
  1344. {
  1345. {
  1346. v3s16 p = nodepos;
  1347. infostream<<"Client::addUpdateMeshTaskForNode(): "
  1348. <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
  1349. <<std::endl;
  1350. }
  1351. v3s16 blockpos = getNodeBlockPos(nodepos);
  1352. v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
  1353. try{
  1354. addUpdateMeshTask(blockpos, ack_to_server, urgent);
  1355. }
  1356. catch(InvalidPositionException &e) {}
  1357. // Leading edge
  1358. if(nodepos.X == blockpos_relative.X){
  1359. try{
  1360. v3s16 p = blockpos + v3s16(-1,0,0);
  1361. addUpdateMeshTask(p, false, urgent);
  1362. }
  1363. catch(InvalidPositionException &e){}
  1364. }
  1365. if(nodepos.Y == blockpos_relative.Y){
  1366. try{
  1367. v3s16 p = blockpos + v3s16(0,-1,0);
  1368. addUpdateMeshTask(p, false, urgent);
  1369. }
  1370. catch(InvalidPositionException &e){}
  1371. }
  1372. if(nodepos.Z == blockpos_relative.Z){
  1373. try{
  1374. v3s16 p = blockpos + v3s16(0,0,-1);
  1375. addUpdateMeshTask(p, false, urgent);
  1376. }
  1377. catch(InvalidPositionException &e){}
  1378. }
  1379. }
  1380. ClientEvent *Client::getClientEvent()
  1381. {
  1382. FATAL_ERROR_IF(m_client_event_queue.empty(),
  1383. "Cannot getClientEvent, queue is empty.");
  1384. ClientEvent *event = m_client_event_queue.front();
  1385. m_client_event_queue.pop();
  1386. return event;
  1387. }
  1388. bool Client::connectedToServer()
  1389. {
  1390. return m_con->Connected();
  1391. }
  1392. const Address Client::getServerAddress()
  1393. {
  1394. return m_con->GetPeerAddress(PEER_ID_SERVER);
  1395. }
  1396. float Client::mediaReceiveProgress()
  1397. {
  1398. if (m_media_downloader)
  1399. return m_media_downloader->getProgress();
  1400. return 1.0; // downloader only exists when not yet done
  1401. }
  1402. typedef struct TextureUpdateArgs {
  1403. gui::IGUIEnvironment *guienv;
  1404. u64 last_time_ms;
  1405. u16 last_percent;
  1406. const wchar_t* text_base;
  1407. ITextureSource *tsrc;
  1408. } TextureUpdateArgs;
  1409. void texture_update_progress(void *args, u32 progress, u32 max_progress)
  1410. {
  1411. TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
  1412. u16 cur_percent = ceil(progress / (double) max_progress * 100.);
  1413. // update the loading menu -- if neccessary
  1414. bool do_draw = false;
  1415. u64 time_ms = targs->last_time_ms;
  1416. if (cur_percent != targs->last_percent) {
  1417. targs->last_percent = cur_percent;
  1418. time_ms = porting::getTimeMs();
  1419. // only draw when the user will notice something:
  1420. do_draw = (time_ms - targs->last_time_ms > 100);
  1421. }
  1422. if (do_draw) {
  1423. targs->last_time_ms = time_ms;
  1424. std::basic_stringstream<wchar_t> strm;
  1425. strm << targs->text_base << " " << targs->last_percent << "%...";
  1426. RenderingEngine::draw_load_screen(strm.str(), targs->guienv, targs->tsrc, 0,
  1427. 72 + (u16) ((18. / 100.) * (double) targs->last_percent), true);
  1428. }
  1429. }
  1430. void Client::afterContentReceived()
  1431. {
  1432. infostream<<"Client::afterContentReceived() started"<<std::endl;
  1433. assert(m_itemdef_received); // pre-condition
  1434. assert(m_nodedef_received); // pre-condition
  1435. assert(mediaReceived()); // pre-condition
  1436. const wchar_t* text = wgettext("Loading textures...");
  1437. // Clear cached pre-scaled 2D GUI images, as this cache
  1438. // might have images with the same name but different
  1439. // content from previous sessions.
  1440. guiScalingCacheClear();
  1441. // Rebuild inherited images and recreate textures
  1442. infostream<<"- Rebuilding images and textures"<<std::endl;
  1443. RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 70);
  1444. m_tsrc->rebuildImagesAndTextures();
  1445. delete[] text;
  1446. // Rebuild shaders
  1447. infostream<<"- Rebuilding shaders"<<std::endl;
  1448. text = wgettext("Rebuilding shaders...");
  1449. RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 71);
  1450. m_shsrc->rebuildShaders();
  1451. delete[] text;
  1452. // Update node aliases
  1453. infostream<<"- Updating node aliases"<<std::endl;
  1454. text = wgettext("Initializing nodes...");
  1455. RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 72);
  1456. m_nodedef->updateAliases(m_itemdef);
  1457. std::string texture_path = g_settings->get("texture_path");
  1458. if (!texture_path.empty() && fs::IsDir(texture_path))
  1459. m_nodedef->applyTextureOverrides(texture_path + DIR_DELIM + "override.txt");
  1460. m_nodedef->setNodeRegistrationStatus(true);
  1461. m_nodedef->runNodeResolveCallbacks();
  1462. delete[] text;
  1463. // Update node textures and assign shaders to each tile
  1464. infostream<<"- Updating node textures"<<std::endl;
  1465. TextureUpdateArgs tu_args;
  1466. tu_args.guienv = guienv;
  1467. tu_args.last_time_ms = porting::getTimeMs();
  1468. tu_args.last_percent = 0;
  1469. tu_args.text_base = wgettext("Initializing nodes");
  1470. tu_args.tsrc = m_tsrc;
  1471. m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
  1472. delete[] tu_args.text_base;
  1473. // Start mesh update thread after setting up content definitions
  1474. infostream<<"- Starting mesh update thread"<<std::endl;
  1475. m_mesh_update_thread.start();
  1476. m_state = LC_Ready;
  1477. sendReady();
  1478. if (g_settings->getBool("enable_client_modding")) {
  1479. m_script->on_client_ready(m_env.getLocalPlayer());
  1480. m_script->on_connect();
  1481. }
  1482. text = wgettext("Done!");
  1483. RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 100);
  1484. infostream<<"Client::afterContentReceived() done"<<std::endl;
  1485. delete[] text;
  1486. }
  1487. float Client::getRTT()
  1488. {
  1489. return m_con->getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
  1490. }
  1491. float Client::getCurRate()
  1492. {
  1493. return (m_con->getLocalStat(con::CUR_INC_RATE) +
  1494. m_con->getLocalStat(con::CUR_DL_RATE));
  1495. }
  1496. void Client::makeScreenshot()
  1497. {
  1498. irr::video::IVideoDriver *driver = RenderingEngine::get_video_driver();
  1499. irr::video::IImage* const raw_image = driver->createScreenShot();
  1500. if (!raw_image)
  1501. return;
  1502. time_t t = time(NULL);
  1503. struct tm *tm = localtime(&t);
  1504. char timetstamp_c[64];
  1505. strftime(timetstamp_c, sizeof(timetstamp_c), "%Y%m%d_%H%M%S", tm);
  1506. std::string filename_base = g_settings->get("screenshot_path")
  1507. + DIR_DELIM
  1508. + std::string("screenshot_")
  1509. + std::string(timetstamp_c);
  1510. std::string filename_ext = "." + g_settings->get("screenshot_format");
  1511. std::string filename;
  1512. u32 quality = (u32)g_settings->getS32("screenshot_quality");
  1513. quality = MYMIN(MYMAX(quality, 0), 100) / 100.0 * 255;
  1514. // Try to find a unique filename
  1515. unsigned serial = 0;
  1516. while (serial < SCREENSHOT_MAX_SERIAL_TRIES) {
  1517. filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") + filename_ext;
  1518. std::ifstream tmp(filename.c_str());
  1519. if (!tmp.good())
  1520. break; // File did not apparently exist, we'll go with it
  1521. serial++;
  1522. }
  1523. if (serial == SCREENSHOT_MAX_SERIAL_TRIES) {
  1524. infostream << "Could not find suitable filename for screenshot" << std::endl;
  1525. } else {
  1526. irr::video::IImage* const image =
  1527. driver->createImage(video::ECF_R8G8B8, raw_image->getDimension());
  1528. if (image) {
  1529. raw_image->copyTo(image);
  1530. std::ostringstream sstr;
  1531. if (driver->writeImageToFile(image, filename.c_str(), quality)) {
  1532. sstr << "Saved screenshot to '" << filename << "'";
  1533. } else {
  1534. sstr << "Failed to save screenshot '" << filename << "'";
  1535. }
  1536. pushToChatQueue(new ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
  1537. narrow_to_wide(sstr.str())));
  1538. infostream << sstr.str() << std::endl;
  1539. image->drop();
  1540. }
  1541. }
  1542. raw_image->drop();
  1543. }
  1544. bool Client::shouldShowMinimap() const
  1545. {
  1546. return !m_minimap_disabled_by_server;
  1547. }
  1548. void Client::pushToEventQueue(ClientEvent *event)
  1549. {
  1550. m_client_event_queue.push(event);
  1551. }
  1552. void Client::showGameChat(const bool show)
  1553. {
  1554. m_game_ui_flags->show_chat = show;
  1555. }
  1556. void Client::showGameHud(const bool show)
  1557. {
  1558. m_game_ui_flags->show_hud = show;
  1559. }
  1560. void Client::showMinimap(const bool show)
  1561. {
  1562. m_game_ui_flags->show_minimap = show;
  1563. }
  1564. void Client::showProfiler(const bool show)
  1565. {
  1566. m_game_ui_flags->show_profiler_graph = show;
  1567. }
  1568. void Client::showGameFog(const bool show)
  1569. {
  1570. m_game_ui_flags->force_fog_off = !show;
  1571. }
  1572. void Client::showGameDebug(const bool show)
  1573. {
  1574. m_game_ui_flags->show_debug = show;
  1575. }
  1576. // IGameDef interface
  1577. // Under envlock
  1578. IItemDefManager* Client::getItemDefManager()
  1579. {
  1580. return m_itemdef;
  1581. }
  1582. INodeDefManager* Client::getNodeDefManager()
  1583. {
  1584. return m_nodedef;
  1585. }
  1586. ICraftDefManager* Client::getCraftDefManager()
  1587. {
  1588. return NULL;
  1589. //return m_craftdef;
  1590. }
  1591. ITextureSource* Client::getTextureSource()
  1592. {
  1593. return m_tsrc;
  1594. }
  1595. IShaderSource* Client::getShaderSource()
  1596. {
  1597. return m_shsrc;
  1598. }
  1599. u16 Client::allocateUnknownNodeId(const std::string &name)
  1600. {
  1601. errorstream << "Client::allocateUnknownNodeId(): "
  1602. << "Client cannot allocate node IDs" << std::endl;
  1603. FATAL_ERROR("Client allocated unknown node");
  1604. return CONTENT_IGNORE;
  1605. }
  1606. ISoundManager* Client::getSoundManager()
  1607. {
  1608. return m_sound;
  1609. }
  1610. MtEventManager* Client::getEventManager()
  1611. {
  1612. return m_event;
  1613. }
  1614. ParticleManager* Client::getParticleManager()
  1615. {
  1616. return &m_particle_manager;
  1617. }
  1618. scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
  1619. {
  1620. StringMap::const_iterator it = m_mesh_data.find(filename);
  1621. if (it == m_mesh_data.end()) {
  1622. errorstream << "Client::getMesh(): Mesh not found: \"" << filename
  1623. << "\"" << std::endl;
  1624. return NULL;
  1625. }
  1626. const std::string &data = it->second;
  1627. // Create the mesh, remove it from cache and return it
  1628. // This allows unique vertex colors and other properties for each instance
  1629. Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
  1630. io::IReadFile *rfile = RenderingEngine::get_filesystem()->createMemoryReadFile(
  1631. *data_rw, data_rw.getSize(), filename.c_str());
  1632. FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
  1633. scene::IAnimatedMesh *mesh = RenderingEngine::get_scene_manager()->getMesh(rfile);
  1634. rfile->drop();
  1635. // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch
  1636. // of uniquely named instances and re-use them
  1637. mesh->grab();
  1638. RenderingEngine::get_mesh_cache()->removeMesh(mesh);
  1639. return mesh;
  1640. }
  1641. const std::string* Client::getModFile(const std::string &filename)
  1642. {
  1643. StringMap::const_iterator it = m_mod_files.find(filename);
  1644. if (it == m_mod_files.end()) {
  1645. errorstream << "Client::getModFile(): File not found: \"" << filename
  1646. << "\"" << std::endl;
  1647. return NULL;
  1648. }
  1649. return &it->second;
  1650. }
  1651. bool Client::registerModStorage(ModMetadata *storage)
  1652. {
  1653. if (m_mod_storages.find(storage->getModName()) != m_mod_storages.end()) {
  1654. errorstream << "Unable to register same mod storage twice. Storage name: "
  1655. << storage->getModName() << std::endl;
  1656. return false;
  1657. }
  1658. m_mod_storages[storage->getModName()] = storage;
  1659. return true;
  1660. }
  1661. void Client::unregisterModStorage(const std::string &name)
  1662. {
  1663. std::unordered_map<std::string, ModMetadata *>::const_iterator it =
  1664. m_mod_storages.find(name);
  1665. if (it != m_mod_storages.end()) {
  1666. // Save unconditionaly on unregistration
  1667. it->second->save(getModStoragePath());
  1668. m_mod_storages.erase(name);
  1669. }
  1670. }
  1671. std::string Client::getModStoragePath() const
  1672. {
  1673. return porting::path_user + DIR_DELIM + "client" + DIR_DELIM + "mod_storage";
  1674. }