client.cpp 52 KB

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