client.cpp 48 KB

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