game.cpp 136 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798
  1. /*
  2. Minetest
  3. Copyright (C) 2010-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 "game.h"
  17. #include <iomanip>
  18. #include <cmath>
  19. #include "client/renderingengine.h"
  20. #include "camera.h"
  21. #include "client.h"
  22. #include "client/clientevent.h"
  23. #include "client/inputhandler.h"
  24. #include "client/tile.h" // For TextureSource
  25. #include "client/keys.h"
  26. #include "client/joystick_controller.h"
  27. #include "clientmap.h"
  28. #include "clouds.h"
  29. #include "config.h"
  30. #include "content_cao.h"
  31. #include "event_manager.h"
  32. #include "fontengine.h"
  33. #include "itemdef.h"
  34. #include "log.h"
  35. #include "filesys.h"
  36. #include "gettext.h"
  37. #include "guiChatConsole.h"
  38. #include "guiFormSpecMenu.h"
  39. #include "guiKeyChangeMenu.h"
  40. #include "guiPasswordChange.h"
  41. #include "guiVolumeChange.h"
  42. #include "mainmenumanager.h"
  43. #include "mapblock.h"
  44. #include "minimap.h"
  45. #include "nodedef.h" // Needed for determining pointing to nodes
  46. #include "nodemetadata.h"
  47. #include "particles.h"
  48. #include "profiler.h"
  49. #include "quicktune_shortcutter.h"
  50. #include "raycast.h"
  51. #include "server.h"
  52. #include "settings.h"
  53. #include "shader.h"
  54. #include "sky.h"
  55. #include "subgame.h"
  56. #include "tool.h"
  57. #include "translation.h"
  58. #include "util/basic_macros.h"
  59. #include "util/directiontables.h"
  60. #include "util/pointedthing.h"
  61. #include "irrlicht_changes/static_text.h"
  62. #include "version.h"
  63. #include "script/scripting_client.h"
  64. #if USE_SOUND
  65. #include "sound_openal.h"
  66. #endif
  67. /*
  68. Text input system
  69. */
  70. struct TextDestNodeMetadata : public TextDest
  71. {
  72. TextDestNodeMetadata(v3s16 p, Client *client)
  73. {
  74. m_p = p;
  75. m_client = client;
  76. }
  77. // This is deprecated I guess? -celeron55
  78. void gotText(const std::wstring &text)
  79. {
  80. std::string ntext = wide_to_utf8(text);
  81. infostream << "Submitting 'text' field of node at (" << m_p.X << ","
  82. << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
  83. StringMap fields;
  84. fields["text"] = ntext;
  85. m_client->sendNodemetaFields(m_p, "", fields);
  86. }
  87. void gotText(const StringMap &fields)
  88. {
  89. m_client->sendNodemetaFields(m_p, "", fields);
  90. }
  91. v3s16 m_p;
  92. Client *m_client;
  93. };
  94. struct TextDestPlayerInventory : public TextDest
  95. {
  96. TextDestPlayerInventory(Client *client)
  97. {
  98. m_client = client;
  99. m_formname = "";
  100. }
  101. TextDestPlayerInventory(Client *client, const std::string &formname)
  102. {
  103. m_client = client;
  104. m_formname = formname;
  105. }
  106. void gotText(const StringMap &fields)
  107. {
  108. m_client->sendInventoryFields(m_formname, fields);
  109. }
  110. Client *m_client;
  111. };
  112. struct LocalFormspecHandler : public TextDest
  113. {
  114. LocalFormspecHandler(const std::string &formname)
  115. {
  116. m_formname = formname;
  117. }
  118. LocalFormspecHandler(const std::string &formname, Client *client):
  119. m_client(client)
  120. {
  121. m_formname = formname;
  122. }
  123. void gotText(const StringMap &fields)
  124. {
  125. if (m_formname == "MT_PAUSE_MENU") {
  126. if (fields.find("btn_sound") != fields.end()) {
  127. g_gamecallback->changeVolume();
  128. return;
  129. }
  130. if (fields.find("btn_key_config") != fields.end()) {
  131. g_gamecallback->keyConfig();
  132. return;
  133. }
  134. if (fields.find("btn_exit_menu") != fields.end()) {
  135. g_gamecallback->disconnect();
  136. return;
  137. }
  138. if (fields.find("btn_exit_os") != fields.end()) {
  139. g_gamecallback->exitToOS();
  140. #ifndef __ANDROID__
  141. RenderingEngine::get_raw_device()->closeDevice();
  142. #endif
  143. return;
  144. }
  145. if (fields.find("btn_change_password") != fields.end()) {
  146. g_gamecallback->changePassword();
  147. return;
  148. }
  149. if (fields.find("quit") != fields.end()) {
  150. return;
  151. }
  152. if (fields.find("btn_continue") != fields.end()) {
  153. return;
  154. }
  155. }
  156. // Don't disable this part when modding is disabled, it's used in builtin
  157. if (m_client && m_client->getScript())
  158. m_client->getScript()->on_formspec_input(m_formname, fields);
  159. }
  160. Client *m_client = nullptr;
  161. };
  162. /* Form update callback */
  163. static const std::string empty_string = "";
  164. class NodeMetadataFormSource: public IFormSource
  165. {
  166. public:
  167. NodeMetadataFormSource(ClientMap *map, v3s16 p):
  168. m_map(map),
  169. m_p(p)
  170. {
  171. }
  172. const std::string &getForm() const
  173. {
  174. NodeMetadata *meta = m_map->getNodeMetadata(m_p);
  175. if (!meta)
  176. return empty_string;
  177. return meta->getString("formspec");
  178. }
  179. virtual std::string resolveText(const std::string &str)
  180. {
  181. NodeMetadata *meta = m_map->getNodeMetadata(m_p);
  182. if (!meta)
  183. return str;
  184. return meta->resolveString(str);
  185. }
  186. ClientMap *m_map;
  187. v3s16 m_p;
  188. };
  189. class PlayerInventoryFormSource: public IFormSource
  190. {
  191. public:
  192. PlayerInventoryFormSource(Client *client):
  193. m_client(client)
  194. {
  195. }
  196. const std::string &getForm() const
  197. {
  198. LocalPlayer *player = m_client->getEnv().getLocalPlayer();
  199. return player->inventory_formspec;
  200. }
  201. Client *m_client;
  202. };
  203. /* Profiler display */
  204. void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
  205. u32 show_profiler, u32 show_profiler_max, s32 screen_height)
  206. {
  207. if (show_profiler == 0) {
  208. guitext_profiler->setVisible(false);
  209. } else {
  210. std::ostringstream os(std::ios_base::binary);
  211. g_profiler->printPage(os, show_profiler, show_profiler_max);
  212. std::wstring text = translate_string(utf8_to_wide(os.str()));
  213. setStaticText(guitext_profiler, text.c_str());
  214. guitext_profiler->setVisible(true);
  215. s32 w = fe->getTextWidth(text);
  216. if (w < 400)
  217. w = 400;
  218. unsigned text_height = fe->getTextHeight();
  219. core::position2di upper_left, lower_right;
  220. upper_left.X = 6;
  221. upper_left.Y = (text_height + 5) * 2;
  222. lower_right.X = 12 + w;
  223. lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
  224. if (lower_right.Y > screen_height * 2 / 3)
  225. lower_right.Y = screen_height * 2 / 3;
  226. core::rect<s32> rect(upper_left, lower_right);
  227. guitext_profiler->setRelativePosition(rect);
  228. guitext_profiler->setVisible(true);
  229. }
  230. }
  231. class ProfilerGraph
  232. {
  233. private:
  234. struct Piece {
  235. Profiler::GraphValues values;
  236. };
  237. struct Meta {
  238. float min;
  239. float max;
  240. video::SColor color;
  241. Meta(float initial = 0,
  242. video::SColor color = video::SColor(255, 255, 255, 255)):
  243. min(initial),
  244. max(initial),
  245. color(color)
  246. {}
  247. };
  248. std::deque<Piece> m_log;
  249. public:
  250. u32 m_log_max_size = 200;
  251. ProfilerGraph() = default;
  252. void put(const Profiler::GraphValues &values)
  253. {
  254. Piece piece;
  255. piece.values = values;
  256. m_log.push_back(piece);
  257. while (m_log.size() > m_log_max_size)
  258. m_log.erase(m_log.begin());
  259. }
  260. void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
  261. gui::IGUIFont *font) const
  262. {
  263. // Do *not* use UNORDERED_MAP here as the order needs
  264. // to be the same for each call to prevent flickering
  265. std::map<std::string, Meta> m_meta;
  266. for (const Piece &piece : m_log) {
  267. for (const auto &i : piece.values) {
  268. const std::string &id = i.first;
  269. const float &value = i.second;
  270. std::map<std::string, Meta>::iterator j = m_meta.find(id);
  271. if (j == m_meta.end()) {
  272. m_meta[id] = Meta(value);
  273. continue;
  274. }
  275. if (value < j->second.min)
  276. j->second.min = value;
  277. if (value > j->second.max)
  278. j->second.max = value;
  279. }
  280. }
  281. // Assign colors
  282. static const video::SColor usable_colors[] = {
  283. video::SColor(255, 255, 100, 100),
  284. video::SColor(255, 90, 225, 90),
  285. video::SColor(255, 100, 100, 255),
  286. video::SColor(255, 255, 150, 50),
  287. video::SColor(255, 220, 220, 100)
  288. };
  289. static const u32 usable_colors_count =
  290. sizeof(usable_colors) / sizeof(*usable_colors);
  291. u32 next_color_i = 0;
  292. for (auto &i : m_meta) {
  293. Meta &meta = i.second;
  294. video::SColor color(255, 200, 200, 200);
  295. if (next_color_i < usable_colors_count)
  296. color = usable_colors[next_color_i++];
  297. meta.color = color;
  298. }
  299. s32 graphh = 50;
  300. s32 textx = x_left + m_log_max_size + 15;
  301. s32 textx2 = textx + 200 - 15;
  302. s32 meta_i = 0;
  303. for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
  304. i != m_meta.end(); ++i) {
  305. const std::string &id = i->first;
  306. const Meta &meta = i->second;
  307. s32 x = x_left;
  308. s32 y = y_bottom - meta_i * 50;
  309. float show_min = meta.min;
  310. float show_max = meta.max;
  311. if (show_min >= -0.0001 && show_max >= -0.0001) {
  312. if (show_min <= show_max * 0.5)
  313. show_min = 0;
  314. }
  315. s32 texth = 15;
  316. char buf[10];
  317. snprintf(buf, 10, "%.3g", show_max);
  318. font->draw(utf8_to_wide(buf).c_str(),
  319. core::rect<s32>(textx, y - graphh,
  320. textx2, y - graphh + texth),
  321. meta.color);
  322. snprintf(buf, 10, "%.3g", show_min);
  323. font->draw(utf8_to_wide(buf).c_str(),
  324. core::rect<s32>(textx, y - texth,
  325. textx2, y),
  326. meta.color);
  327. font->draw(utf8_to_wide(id).c_str(),
  328. core::rect<s32>(textx, y - graphh / 2 - texth / 2,
  329. textx2, y - graphh / 2 + texth / 2),
  330. meta.color);
  331. s32 graph1y = y;
  332. s32 graph1h = graphh;
  333. bool relativegraph = (show_min != 0 && show_min != show_max);
  334. float lastscaledvalue = 0.0;
  335. bool lastscaledvalue_exists = false;
  336. for (const Piece &piece : m_log) {
  337. float value = 0;
  338. bool value_exists = false;
  339. Profiler::GraphValues::const_iterator k =
  340. piece.values.find(id);
  341. if (k != piece.values.end()) {
  342. value = k->second;
  343. value_exists = true;
  344. }
  345. if (!value_exists) {
  346. x++;
  347. lastscaledvalue_exists = false;
  348. continue;
  349. }
  350. float scaledvalue = 1.0;
  351. if (show_max != show_min)
  352. scaledvalue = (value - show_min) / (show_max - show_min);
  353. if (scaledvalue == 1.0 && value == 0) {
  354. x++;
  355. lastscaledvalue_exists = false;
  356. continue;
  357. }
  358. if (relativegraph) {
  359. if (lastscaledvalue_exists) {
  360. s32 ivalue1 = lastscaledvalue * graph1h;
  361. s32 ivalue2 = scaledvalue * graph1h;
  362. driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
  363. v2s32(x, graph1y - ivalue2), meta.color);
  364. }
  365. lastscaledvalue = scaledvalue;
  366. lastscaledvalue_exists = true;
  367. } else {
  368. s32 ivalue = scaledvalue * graph1h;
  369. driver->draw2DLine(v2s32(x, graph1y),
  370. v2s32(x, graph1y - ivalue), meta.color);
  371. }
  372. x++;
  373. }
  374. meta_i++;
  375. }
  376. }
  377. };
  378. class NodeDugEvent: public MtEvent
  379. {
  380. public:
  381. v3s16 p;
  382. MapNode n;
  383. NodeDugEvent(v3s16 p, MapNode n):
  384. p(p),
  385. n(n)
  386. {}
  387. const char *getType() const
  388. {
  389. return "NodeDug";
  390. }
  391. };
  392. class SoundMaker
  393. {
  394. ISoundManager *m_sound;
  395. INodeDefManager *m_ndef;
  396. public:
  397. bool makes_footstep_sound;
  398. float m_player_step_timer;
  399. SimpleSoundSpec m_player_step_sound;
  400. SimpleSoundSpec m_player_leftpunch_sound;
  401. SimpleSoundSpec m_player_rightpunch_sound;
  402. SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
  403. m_sound(sound),
  404. m_ndef(ndef),
  405. makes_footstep_sound(true),
  406. m_player_step_timer(0)
  407. {
  408. }
  409. void playPlayerStep()
  410. {
  411. if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
  412. m_player_step_timer = 0.03;
  413. if (makes_footstep_sound)
  414. m_sound->playSound(m_player_step_sound, false);
  415. }
  416. }
  417. static void viewBobbingStep(MtEvent *e, void *data)
  418. {
  419. SoundMaker *sm = (SoundMaker *)data;
  420. sm->playPlayerStep();
  421. }
  422. static void playerRegainGround(MtEvent *e, void *data)
  423. {
  424. SoundMaker *sm = (SoundMaker *)data;
  425. sm->playPlayerStep();
  426. }
  427. static void playerJump(MtEvent *e, void *data)
  428. {
  429. //SoundMaker *sm = (SoundMaker*)data;
  430. }
  431. static void cameraPunchLeft(MtEvent *e, void *data)
  432. {
  433. SoundMaker *sm = (SoundMaker *)data;
  434. sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
  435. }
  436. static void cameraPunchRight(MtEvent *e, void *data)
  437. {
  438. SoundMaker *sm = (SoundMaker *)data;
  439. sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
  440. }
  441. static void nodeDug(MtEvent *e, void *data)
  442. {
  443. SoundMaker *sm = (SoundMaker *)data;
  444. NodeDugEvent *nde = (NodeDugEvent *)e;
  445. sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
  446. }
  447. static void playerDamage(MtEvent *e, void *data)
  448. {
  449. SoundMaker *sm = (SoundMaker *)data;
  450. sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
  451. }
  452. static void playerFallingDamage(MtEvent *e, void *data)
  453. {
  454. SoundMaker *sm = (SoundMaker *)data;
  455. sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
  456. }
  457. void registerReceiver(MtEventManager *mgr)
  458. {
  459. mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
  460. mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
  461. mgr->reg("PlayerJump", SoundMaker::playerJump, this);
  462. mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
  463. mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
  464. mgr->reg("NodeDug", SoundMaker::nodeDug, this);
  465. mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
  466. mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
  467. }
  468. void step(float dtime)
  469. {
  470. m_player_step_timer -= dtime;
  471. }
  472. };
  473. // Locally stored sounds don't need to be preloaded because of this
  474. class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
  475. {
  476. std::set<std::string> m_fetched;
  477. private:
  478. void paths_insert(std::set<std::string> &dst_paths,
  479. const std::string &base,
  480. const std::string &name)
  481. {
  482. dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".ogg");
  483. dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".0.ogg");
  484. dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".1.ogg");
  485. dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".2.ogg");
  486. dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".3.ogg");
  487. dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".4.ogg");
  488. dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".5.ogg");
  489. dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".6.ogg");
  490. dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".7.ogg");
  491. dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".8.ogg");
  492. dst_paths.insert(base + DIR_DELIM + "sounds" + DIR_DELIM + name + ".9.ogg");
  493. }
  494. public:
  495. void fetchSounds(const std::string &name,
  496. std::set<std::string> &dst_paths,
  497. std::set<std::string> &dst_datas)
  498. {
  499. if (m_fetched.count(name))
  500. return;
  501. m_fetched.insert(name);
  502. paths_insert(dst_paths, porting::path_share, name);
  503. paths_insert(dst_paths, porting::path_user, name);
  504. }
  505. };
  506. // before 1.8 there isn't a "integer interface", only float
  507. #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
  508. typedef f32 SamplerLayer_t;
  509. #else
  510. typedef s32 SamplerLayer_t;
  511. #endif
  512. class GameGlobalShaderConstantSetter : public IShaderConstantSetter
  513. {
  514. Sky *m_sky;
  515. bool *m_force_fog_off;
  516. f32 *m_fog_range;
  517. bool m_fog_enabled;
  518. CachedPixelShaderSetting<float, 4> m_sky_bg_color;
  519. CachedPixelShaderSetting<float> m_fog_distance;
  520. CachedVertexShaderSetting<float> m_animation_timer_vertex;
  521. CachedPixelShaderSetting<float> m_animation_timer_pixel;
  522. CachedPixelShaderSetting<float, 3> m_day_light;
  523. CachedPixelShaderSetting<float, 3> m_eye_position_pixel;
  524. CachedVertexShaderSetting<float, 3> m_eye_position_vertex;
  525. CachedPixelShaderSetting<float, 3> m_minimap_yaw;
  526. CachedPixelShaderSetting<SamplerLayer_t> m_base_texture;
  527. CachedPixelShaderSetting<SamplerLayer_t> m_normal_texture;
  528. CachedPixelShaderSetting<SamplerLayer_t> m_texture_flags;
  529. Client *m_client;
  530. public:
  531. void onSettingsChange(const std::string &name)
  532. {
  533. if (name == "enable_fog")
  534. m_fog_enabled = g_settings->getBool("enable_fog");
  535. }
  536. static void settingsCallback(const std::string &name, void *userdata)
  537. {
  538. reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
  539. }
  540. void setSky(Sky *sky) { m_sky = sky; }
  541. GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
  542. f32 *fog_range, Client *client) :
  543. m_sky(sky),
  544. m_force_fog_off(force_fog_off),
  545. m_fog_range(fog_range),
  546. m_sky_bg_color("skyBgColor"),
  547. m_fog_distance("fogDistance"),
  548. m_animation_timer_vertex("animationTimer"),
  549. m_animation_timer_pixel("animationTimer"),
  550. m_day_light("dayLight"),
  551. m_eye_position_pixel("eyePosition"),
  552. m_eye_position_vertex("eyePosition"),
  553. m_minimap_yaw("yawVec"),
  554. m_base_texture("baseTexture"),
  555. m_normal_texture("normalTexture"),
  556. m_texture_flags("textureFlags"),
  557. m_client(client)
  558. {
  559. g_settings->registerChangedCallback("enable_fog", settingsCallback, this);
  560. m_fog_enabled = g_settings->getBool("enable_fog");
  561. }
  562. ~GameGlobalShaderConstantSetter()
  563. {
  564. g_settings->deregisterChangedCallback("enable_fog", settingsCallback, this);
  565. }
  566. virtual void onSetConstants(video::IMaterialRendererServices *services,
  567. bool is_highlevel)
  568. {
  569. if (!is_highlevel)
  570. return;
  571. // Background color
  572. video::SColor bgcolor = m_sky->getBgColor();
  573. video::SColorf bgcolorf(bgcolor);
  574. float bgcolorfa[4] = {
  575. bgcolorf.r,
  576. bgcolorf.g,
  577. bgcolorf.b,
  578. bgcolorf.a,
  579. };
  580. m_sky_bg_color.set(bgcolorfa, services);
  581. // Fog distance
  582. float fog_distance = 10000 * BS;
  583. if (m_fog_enabled && !*m_force_fog_off)
  584. fog_distance = *m_fog_range;
  585. m_fog_distance.set(&fog_distance, services);
  586. u32 daynight_ratio = (float)m_client->getEnv().getDayNightRatio();
  587. video::SColorf sunlight;
  588. get_sunlight_color(&sunlight, daynight_ratio);
  589. float dnc[3] = {
  590. sunlight.r,
  591. sunlight.g,
  592. sunlight.b };
  593. m_day_light.set(dnc, services);
  594. u32 animation_timer = porting::getTimeMs() % 100000;
  595. float animation_timer_f = (float)animation_timer / 100000.f;
  596. m_animation_timer_vertex.set(&animation_timer_f, services);
  597. m_animation_timer_pixel.set(&animation_timer_f, services);
  598. float eye_position_array[3];
  599. v3f epos = m_client->getEnv().getLocalPlayer()->getEyePosition();
  600. #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
  601. eye_position_array[0] = epos.X;
  602. eye_position_array[1] = epos.Y;
  603. eye_position_array[2] = epos.Z;
  604. #else
  605. epos.getAs3Values(eye_position_array);
  606. #endif
  607. m_eye_position_pixel.set(eye_position_array, services);
  608. m_eye_position_vertex.set(eye_position_array, services);
  609. if (m_client->getMinimap()) {
  610. float minimap_yaw_array[3];
  611. v3f minimap_yaw = m_client->getMinimap()->getYawVec();
  612. #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
  613. minimap_yaw_array[0] = minimap_yaw.X;
  614. minimap_yaw_array[1] = minimap_yaw.Y;
  615. minimap_yaw_array[2] = minimap_yaw.Z;
  616. #else
  617. minimap_yaw.getAs3Values(minimap_yaw_array);
  618. #endif
  619. m_minimap_yaw.set(minimap_yaw_array, services);
  620. }
  621. SamplerLayer_t base_tex = 0,
  622. normal_tex = 1,
  623. flags_tex = 2;
  624. m_base_texture.set(&base_tex, services);
  625. m_normal_texture.set(&normal_tex, services);
  626. m_texture_flags.set(&flags_tex, services);
  627. }
  628. };
  629. class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactory
  630. {
  631. Sky *m_sky;
  632. bool *m_force_fog_off;
  633. f32 *m_fog_range;
  634. Client *m_client;
  635. std::vector<GameGlobalShaderConstantSetter *> created_nosky;
  636. public:
  637. GameGlobalShaderConstantSetterFactory(bool *force_fog_off,
  638. f32 *fog_range, Client *client) :
  639. m_sky(NULL),
  640. m_force_fog_off(force_fog_off),
  641. m_fog_range(fog_range),
  642. m_client(client)
  643. {}
  644. void setSky(Sky *sky) {
  645. m_sky = sky;
  646. for (GameGlobalShaderConstantSetter *ggscs : created_nosky) {
  647. ggscs->setSky(m_sky);
  648. }
  649. created_nosky.clear();
  650. }
  651. virtual IShaderConstantSetter* create()
  652. {
  653. GameGlobalShaderConstantSetter *scs = new GameGlobalShaderConstantSetter(
  654. m_sky, m_force_fog_off, m_fog_range, m_client);
  655. if (!m_sky)
  656. created_nosky.push_back(scs);
  657. return scs;
  658. }
  659. };
  660. bool nodePlacementPrediction(Client &client, const ItemDefinition &playeritem_def,
  661. const ItemStack &playeritem, v3s16 nodepos, v3s16 neighbourpos)
  662. {
  663. std::string prediction = playeritem_def.node_placement_prediction;
  664. INodeDefManager *nodedef = client.ndef();
  665. ClientMap &map = client.getEnv().getClientMap();
  666. MapNode node;
  667. bool is_valid_position;
  668. node = map.getNodeNoEx(nodepos, &is_valid_position);
  669. if (!is_valid_position)
  670. return false;
  671. if (!prediction.empty() && !nodedef->get(node).rightclickable) {
  672. verbosestream << "Node placement prediction for "
  673. << playeritem_def.name << " is "
  674. << prediction << std::endl;
  675. v3s16 p = neighbourpos;
  676. // Place inside node itself if buildable_to
  677. MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
  678. if (is_valid_position)
  679. {
  680. if (nodedef->get(n_under).buildable_to)
  681. p = nodepos;
  682. else {
  683. node = map.getNodeNoEx(p, &is_valid_position);
  684. if (is_valid_position &&!nodedef->get(node).buildable_to)
  685. return false;
  686. }
  687. }
  688. // Find id of predicted node
  689. content_t id;
  690. bool found = nodedef->getId(prediction, id);
  691. if (!found) {
  692. errorstream << "Node placement prediction failed for "
  693. << playeritem_def.name << " (places "
  694. << prediction
  695. << ") - Name not known" << std::endl;
  696. return false;
  697. }
  698. const ContentFeatures &predicted_f = nodedef->get(id);
  699. // Predict param2 for facedir and wallmounted nodes
  700. u8 param2 = 0;
  701. if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
  702. predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED) {
  703. v3s16 dir = nodepos - neighbourpos;
  704. if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
  705. param2 = dir.Y < 0 ? 1 : 0;
  706. } else if (abs(dir.X) > abs(dir.Z)) {
  707. param2 = dir.X < 0 ? 3 : 2;
  708. } else {
  709. param2 = dir.Z < 0 ? 5 : 4;
  710. }
  711. }
  712. if (predicted_f.param_type_2 == CPT2_FACEDIR ||
  713. predicted_f.param_type_2 == CPT2_COLORED_FACEDIR) {
  714. v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
  715. if (abs(dir.X) > abs(dir.Z)) {
  716. param2 = dir.X < 0 ? 3 : 1;
  717. } else {
  718. param2 = dir.Z < 0 ? 2 : 0;
  719. }
  720. }
  721. assert(param2 <= 5);
  722. //Check attachment if node is in group attached_node
  723. if (((ItemGroupList) predicted_f.groups)["attached_node"] != 0) {
  724. static v3s16 wallmounted_dirs[8] = {
  725. v3s16(0, 1, 0),
  726. v3s16(0, -1, 0),
  727. v3s16(1, 0, 0),
  728. v3s16(-1, 0, 0),
  729. v3s16(0, 0, 1),
  730. v3s16(0, 0, -1),
  731. };
  732. v3s16 pp;
  733. if (predicted_f.param_type_2 == CPT2_WALLMOUNTED ||
  734. predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)
  735. pp = p + wallmounted_dirs[param2];
  736. else
  737. pp = p + v3s16(0, -1, 0);
  738. if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
  739. return false;
  740. }
  741. // Apply color
  742. if ((predicted_f.param_type_2 == CPT2_COLOR
  743. || predicted_f.param_type_2 == CPT2_COLORED_FACEDIR
  744. || predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) {
  745. const std::string &indexstr = playeritem.metadata.getString(
  746. "palette_index", 0);
  747. if (!indexstr.empty()) {
  748. s32 index = mystoi(indexstr);
  749. if (predicted_f.param_type_2 == CPT2_COLOR) {
  750. param2 = index;
  751. } else if (predicted_f.param_type_2
  752. == CPT2_COLORED_WALLMOUNTED) {
  753. // param2 = pure palette index + other
  754. param2 = (index & 0xf8) | (param2 & 0x07);
  755. } else if (predicted_f.param_type_2
  756. == CPT2_COLORED_FACEDIR) {
  757. // param2 = pure palette index + other
  758. param2 = (index & 0xe0) | (param2 & 0x1f);
  759. }
  760. }
  761. }
  762. // Add node to client map
  763. MapNode n(id, 0, param2);
  764. try {
  765. LocalPlayer *player = client.getEnv().getLocalPlayer();
  766. // Dont place node when player would be inside new node
  767. // NOTE: This is to be eventually implemented by a mod as client-side Lua
  768. if (!nodedef->get(n).walkable ||
  769. g_settings->getBool("enable_build_where_you_stand") ||
  770. (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
  771. (nodedef->get(n).walkable &&
  772. neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
  773. neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
  774. // This triggers the required mesh update too
  775. client.addNode(p, n);
  776. return true;
  777. }
  778. } catch (InvalidPositionException &e) {
  779. errorstream << "Node placement prediction failed for "
  780. << playeritem_def.name << " (places "
  781. << prediction
  782. << ") - Position not loaded" << std::endl;
  783. }
  784. }
  785. return false;
  786. }
  787. static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
  788. Client *client, JoystickController *joystick,
  789. IFormSource *fs_src, TextDest *txt_dest)
  790. {
  791. if (*cur_formspec == 0) {
  792. *cur_formspec = new GUIFormSpecMenu(joystick, guiroot, -1, &g_menumgr,
  793. client, client->getTextureSource(), fs_src, txt_dest);
  794. (*cur_formspec)->doPause = false;
  795. /*
  796. Caution: do not call (*cur_formspec)->drop() here --
  797. the reference might outlive the menu, so we will
  798. periodically check if *cur_formspec is the only
  799. remaining reference (i.e. the menu was removed)
  800. and delete it in that case.
  801. */
  802. } else {
  803. (*cur_formspec)->setFormSource(fs_src);
  804. (*cur_formspec)->setTextDest(txt_dest);
  805. }
  806. }
  807. #ifdef __ANDROID__
  808. #define SIZE_TAG "size[11,5.5]"
  809. #else
  810. #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
  811. #endif
  812. /******************************************************************************/
  813. static void updateChat(Client &client, f32 dtime, bool show_debug,
  814. const v2u32 &screensize, bool show_chat, u32 show_profiler,
  815. ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
  816. {
  817. // Add chat log output for errors to be shown in chat
  818. static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
  819. // Get new messages from error log buffer
  820. while (!chat_log_error_buf.empty()) {
  821. std::wstring error_message = utf8_to_wide(chat_log_error_buf.get());
  822. if (!g_settings->getBool("disable_escape_sequences")) {
  823. error_message = L"\x1b(c@red)" + error_message + L"\x1b(c@white)";
  824. }
  825. chat_backend.addMessage(L"", error_message);
  826. }
  827. // Get new messages from client
  828. std::wstring message;
  829. while (client.getChatMessage(message)) {
  830. chat_backend.addUnparsedMessage(message);
  831. }
  832. // Remove old messages
  833. chat_backend.step(dtime);
  834. // Display all messages in a static text element
  835. unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
  836. EnrichedString recent_chat = chat_backend.getRecentChat();
  837. unsigned int line_height = g_fontengine->getLineHeight();
  838. setStaticText(guitext_chat, recent_chat);
  839. // Update gui element size and position
  840. s32 chat_y = 5;
  841. if (show_debug)
  842. chat_y += 3 * line_height;
  843. // first pass to calculate height of text to be set
  844. const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize();
  845. s32 width = std::min(g_fontengine->getTextWidth(recent_chat.c_str()) + 10,
  846. window_size.X - 20);
  847. core::rect<s32> rect(10, chat_y, width, chat_y + window_size.Y);
  848. guitext_chat->setRelativePosition(rect);
  849. //now use real height of text and adjust rect according to this size
  850. rect = core::rect<s32>(10, chat_y, width,
  851. chat_y + guitext_chat->getTextHeight());
  852. guitext_chat->setRelativePosition(rect);
  853. // Don't show chat if disabled or empty or profiler is enabled
  854. guitext_chat->setVisible(
  855. show_chat && recent_chat_count != 0 && !show_profiler);
  856. }
  857. /****************************************************************************
  858. Fast key cache for main game loop
  859. ****************************************************************************/
  860. /* This is faster than using getKeySetting with the tradeoff that functions
  861. * using it must make sure that it's initialised before using it and there is
  862. * no error handling (for example bounds checking). This is really intended for
  863. * use only in the main running loop of the client (the_game()) where the faster
  864. * (up to 10x faster) key lookup is an asset. Other parts of the codebase
  865. * (e.g. formspecs) should continue using getKeySetting().
  866. */
  867. struct KeyCache {
  868. KeyCache()
  869. {
  870. handler = NULL;
  871. populate();
  872. populate_nonchanging();
  873. }
  874. void populate();
  875. // Keys that are not settings dependent
  876. void populate_nonchanging();
  877. KeyPress key[KeyType::INTERNAL_ENUM_COUNT];
  878. InputHandler *handler;
  879. };
  880. void KeyCache::populate_nonchanging()
  881. {
  882. key[KeyType::ESC] = EscapeKey;
  883. }
  884. void KeyCache::populate()
  885. {
  886. key[KeyType::FORWARD] = getKeySetting("keymap_forward");
  887. key[KeyType::BACKWARD] = getKeySetting("keymap_backward");
  888. key[KeyType::LEFT] = getKeySetting("keymap_left");
  889. key[KeyType::RIGHT] = getKeySetting("keymap_right");
  890. key[KeyType::JUMP] = getKeySetting("keymap_jump");
  891. key[KeyType::SPECIAL1] = getKeySetting("keymap_special1");
  892. key[KeyType::SNEAK] = getKeySetting("keymap_sneak");
  893. key[KeyType::AUTOFORWARD] = getKeySetting("keymap_autoforward");
  894. key[KeyType::DROP] = getKeySetting("keymap_drop");
  895. key[KeyType::INVENTORY] = getKeySetting("keymap_inventory");
  896. key[KeyType::CHAT] = getKeySetting("keymap_chat");
  897. key[KeyType::CMD] = getKeySetting("keymap_cmd");
  898. key[KeyType::CMD_LOCAL] = getKeySetting("keymap_cmd_local");
  899. key[KeyType::CONSOLE] = getKeySetting("keymap_console");
  900. key[KeyType::MINIMAP] = getKeySetting("keymap_minimap");
  901. key[KeyType::FREEMOVE] = getKeySetting("keymap_freemove");
  902. key[KeyType::FASTMOVE] = getKeySetting("keymap_fastmove");
  903. key[KeyType::NOCLIP] = getKeySetting("keymap_noclip");
  904. key[KeyType::HOTBAR_PREV] = getKeySetting("keymap_hotbar_previous");
  905. key[KeyType::HOTBAR_NEXT] = getKeySetting("keymap_hotbar_next");
  906. key[KeyType::MUTE] = getKeySetting("keymap_mute");
  907. key[KeyType::INC_VOLUME] = getKeySetting("keymap_increase_volume");
  908. key[KeyType::DEC_VOLUME] = getKeySetting("keymap_decrease_volume");
  909. key[KeyType::CINEMATIC] = getKeySetting("keymap_cinematic");
  910. key[KeyType::SCREENSHOT] = getKeySetting("keymap_screenshot");
  911. key[KeyType::TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
  912. key[KeyType::TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
  913. key[KeyType::TOGGLE_FORCE_FOG_OFF]
  914. = getKeySetting("keymap_toggle_force_fog_off");
  915. key[KeyType::TOGGLE_UPDATE_CAMERA]
  916. = getKeySetting("keymap_toggle_update_camera");
  917. key[KeyType::TOGGLE_DEBUG]
  918. = getKeySetting("keymap_toggle_debug");
  919. key[KeyType::TOGGLE_PROFILER]
  920. = getKeySetting("keymap_toggle_profiler");
  921. key[KeyType::CAMERA_MODE]
  922. = getKeySetting("keymap_camera_mode");
  923. key[KeyType::INCREASE_VIEWING_RANGE]
  924. = getKeySetting("keymap_increase_viewing_range_min");
  925. key[KeyType::DECREASE_VIEWING_RANGE]
  926. = getKeySetting("keymap_decrease_viewing_range_min");
  927. key[KeyType::RANGESELECT]
  928. = getKeySetting("keymap_rangeselect");
  929. key[KeyType::ZOOM] = getKeySetting("keymap_zoom");
  930. key[KeyType::QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
  931. key[KeyType::QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
  932. key[KeyType::QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
  933. key[KeyType::QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
  934. for (int i = 0; i < 23; i++) {
  935. std::string slot_key_name = "keymap_slot" + std::to_string(i + 1);
  936. key[KeyType::SLOT_1 + i] = getKeySetting(slot_key_name.c_str());
  937. }
  938. if (handler) {
  939. // First clear all keys, then re-add the ones we listen for
  940. handler->dontListenForKeys();
  941. for (const KeyPress &k : key) {
  942. handler->listenForKey(k);
  943. }
  944. handler->listenForKey(EscapeKey);
  945. handler->listenForKey(CancelKey);
  946. }
  947. }
  948. /****************************************************************************
  949. ****************************************************************************/
  950. const float object_hit_delay = 0.2;
  951. struct FpsControl {
  952. u32 last_time, busy_time, sleep_time;
  953. };
  954. /* The reason the following structs are not anonymous structs within the
  955. * class is that they are not used by the majority of member functions and
  956. * many functions that do require objects of thse types do not modify them
  957. * (so they can be passed as a const qualified parameter)
  958. */
  959. struct CameraOrientation {
  960. f32 camera_yaw; // "right/left"
  961. f32 camera_pitch; // "up/down"
  962. };
  963. struct GameRunData {
  964. u16 dig_index;
  965. u16 new_playeritem;
  966. PointedThing pointed_old;
  967. bool digging;
  968. bool ldown_for_dig;
  969. bool dig_instantly;
  970. bool digging_blocked;
  971. bool left_punch;
  972. bool update_wielded_item_trigger;
  973. bool reset_jump_timer;
  974. float nodig_delay_timer;
  975. float dig_time;
  976. float dig_time_complete;
  977. float repeat_rightclick_timer;
  978. float object_hit_delay_timer;
  979. float time_from_last_punch;
  980. ClientActiveObject *selected_object;
  981. float jump_timer;
  982. float damage_flash;
  983. float update_draw_list_timer;
  984. float statustext_time;
  985. f32 fog_range;
  986. v3f update_draw_list_last_cam_dir;
  987. u32 profiler_current_page;
  988. u32 profiler_max_page; // Number of pages
  989. float time_of_day;
  990. float time_of_day_smooth;
  991. };
  992. struct Jitter {
  993. f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
  994. };
  995. struct RunStats {
  996. u32 drawtime;
  997. Jitter dtime_jitter, busy_time_jitter;
  998. };
  999. class Game;
  1000. struct ClientEventHandler
  1001. {
  1002. void (Game::*handler)(ClientEvent *, CameraOrientation *);
  1003. };
  1004. /****************************************************************************
  1005. THE GAME
  1006. ****************************************************************************/
  1007. /* This is not intended to be a public class. If a public class becomes
  1008. * desirable then it may be better to create another 'wrapper' class that
  1009. * hides most of the stuff in this class (nothing in this class is required
  1010. * by any other file) but exposes the public methods/data only.
  1011. */
  1012. class Game {
  1013. public:
  1014. Game();
  1015. ~Game();
  1016. bool startup(bool *kill,
  1017. bool random_input,
  1018. InputHandler *input,
  1019. const std::string &map_dir,
  1020. const std::string &playername,
  1021. const std::string &password,
  1022. // If address is "", local server is used and address is updated
  1023. std::string *address,
  1024. u16 port,
  1025. std::string &error_message,
  1026. bool *reconnect,
  1027. ChatBackend *chat_backend,
  1028. const SubgameSpec &gamespec, // Used for local game
  1029. bool simple_singleplayer_mode);
  1030. void run();
  1031. void shutdown();
  1032. protected:
  1033. void extendedResourceCleanup();
  1034. // Basic initialisation
  1035. bool init(const std::string &map_dir, std::string *address,
  1036. u16 port,
  1037. const SubgameSpec &gamespec);
  1038. bool initSound();
  1039. bool createSingleplayerServer(const std::string &map_dir,
  1040. const SubgameSpec &gamespec, u16 port, std::string *address);
  1041. // Client creation
  1042. bool createClient(const std::string &playername,
  1043. const std::string &password, std::string *address, u16 port);
  1044. bool initGui();
  1045. // Client connection
  1046. bool connectToServer(const std::string &playername,
  1047. const std::string &password, std::string *address, u16 port,
  1048. bool *connect_ok, bool *aborted);
  1049. bool getServerContent(bool *aborted);
  1050. // Main loop
  1051. void updateInteractTimers(f32 dtime);
  1052. bool checkConnection();
  1053. bool handleCallbacks();
  1054. void processQueues();
  1055. void updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
  1056. void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
  1057. void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
  1058. // Input related
  1059. void processUserInput(f32 dtime);
  1060. void processKeyInput();
  1061. void processItemSelection(u16 *new_playeritem);
  1062. void dropSelectedItem(bool single_item = false);
  1063. void openInventory();
  1064. void openConsole(float scale, const wchar_t *line=NULL);
  1065. void toggleFreeMove();
  1066. void toggleFreeMoveAlt();
  1067. void toggleFast();
  1068. void toggleNoClip();
  1069. void toggleCinematic();
  1070. void toggleAutoforward();
  1071. void toggleChat();
  1072. void toggleHud();
  1073. void toggleMinimap(bool shift_pressed);
  1074. void toggleFog();
  1075. void toggleDebug();
  1076. void toggleUpdateCamera();
  1077. void toggleProfiler();
  1078. void increaseViewRange();
  1079. void decreaseViewRange();
  1080. void toggleFullViewRange();
  1081. void updateCameraDirection(CameraOrientation *cam, float dtime);
  1082. void updateCameraOrientation(CameraOrientation *cam, float dtime);
  1083. void updatePlayerControl(const CameraOrientation &cam);
  1084. void step(f32 *dtime);
  1085. void processClientEvents(CameraOrientation *cam);
  1086. void updateCamera(u32 busy_time, f32 dtime);
  1087. void updateSound(f32 dtime);
  1088. void processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug);
  1089. /*!
  1090. * Returns the object or node the player is pointing at.
  1091. * Also updates the selected thing in the Hud.
  1092. *
  1093. * @param[in] shootline the shootline, starting from
  1094. * the camera position. This also gives the maximal distance
  1095. * of the search.
  1096. * @param[in] liquids_pointable if false, liquids are ignored
  1097. * @param[in] look_for_object if false, objects are ignored
  1098. * @param[in] camera_offset offset of the camera
  1099. * @param[out] selected_object the selected object or
  1100. * NULL if not found
  1101. */
  1102. PointedThing updatePointedThing(
  1103. const core::line3d<f32> &shootline, bool liquids_pointable,
  1104. bool look_for_object, const v3s16 &camera_offset);
  1105. void handlePointingAtNothing(const ItemStack &playerItem);
  1106. void handlePointingAtNode(const PointedThing &pointed,
  1107. const ItemDefinition &playeritem_def, const ItemStack &playeritem,
  1108. const ToolCapabilities &playeritem_toolcap, f32 dtime);
  1109. void handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
  1110. const v3f &player_position, bool show_debug);
  1111. void handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
  1112. const ToolCapabilities &playeritem_toolcap, f32 dtime);
  1113. void updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
  1114. const CameraOrientation &cam);
  1115. void updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam);
  1116. void updateProfilerGraphs(ProfilerGraph *graph);
  1117. // Misc
  1118. void limitFps(FpsControl *fps_timings, f32 *dtime);
  1119. void showOverlayMessage(const char *msg, float dtime, int percent,
  1120. bool draw_clouds = true);
  1121. static void settingChangedCallback(const std::string &setting_name, void *data);
  1122. void readSettings();
  1123. inline bool getLeftClicked()
  1124. {
  1125. return input->getLeftClicked() ||
  1126. input->joystick.getWasKeyDown(KeyType::MOUSE_L);
  1127. }
  1128. inline bool getRightClicked()
  1129. {
  1130. return input->getRightClicked() ||
  1131. input->joystick.getWasKeyDown(KeyType::MOUSE_R);
  1132. }
  1133. inline bool isLeftPressed()
  1134. {
  1135. return input->getLeftState() ||
  1136. input->joystick.isKeyDown(KeyType::MOUSE_L);
  1137. }
  1138. inline bool isRightPressed()
  1139. {
  1140. return input->getRightState() ||
  1141. input->joystick.isKeyDown(KeyType::MOUSE_R);
  1142. }
  1143. inline bool getLeftReleased()
  1144. {
  1145. return input->getLeftReleased() ||
  1146. input->joystick.wasKeyReleased(KeyType::MOUSE_L);
  1147. }
  1148. inline bool isKeyDown(GameKeyType k)
  1149. {
  1150. return input->isKeyDown(keycache.key[k]) || input->joystick.isKeyDown(k);
  1151. }
  1152. inline bool wasKeyDown(GameKeyType k)
  1153. {
  1154. return input->wasKeyDown(keycache.key[k]) || input->joystick.wasKeyDown(k);
  1155. }
  1156. #ifdef __ANDROID__
  1157. void handleAndroidChatInput();
  1158. #endif
  1159. private:
  1160. void showPauseMenu();
  1161. // ClientEvent handlers
  1162. void handleClientEvent_None(ClientEvent *event, CameraOrientation *cam);
  1163. void handleClientEvent_PlayerDamage(ClientEvent *event, CameraOrientation *cam);
  1164. void handleClientEvent_PlayerForceMove(ClientEvent *event, CameraOrientation *cam);
  1165. void handleClientEvent_Deathscreen(ClientEvent *event, CameraOrientation *cam);
  1166. void handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation *cam);
  1167. void handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrientation *cam);
  1168. void handleClientEvent_HandleParticleEvent(ClientEvent *event,
  1169. CameraOrientation *cam);
  1170. void handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam);
  1171. void handleClientEvent_HudRemove(ClientEvent *event, CameraOrientation *cam);
  1172. void handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *cam);
  1173. void handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam);
  1174. void handleClientEvent_OverrideDayNigthRatio(ClientEvent *event,
  1175. CameraOrientation *cam);
  1176. void handleClientEvent_CloudParams(ClientEvent *event, CameraOrientation *cam);
  1177. static const ClientEventHandler clientEventHandler[CLIENTEVENT_MAX];
  1178. InputHandler *input;
  1179. Client *client;
  1180. Server *server;
  1181. IWritableTextureSource *texture_src;
  1182. IWritableShaderSource *shader_src;
  1183. // When created, these will be filled with data received from the server
  1184. IWritableItemDefManager *itemdef_manager;
  1185. IWritableNodeDefManager *nodedef_manager;
  1186. GameOnDemandSoundFetcher soundfetcher; // useful when testing
  1187. ISoundManager *sound;
  1188. bool sound_is_dummy = false;
  1189. SoundMaker *soundmaker;
  1190. ChatBackend *chat_backend;
  1191. GUIFormSpecMenu *current_formspec;
  1192. //default: "". If other than "", empty show_formspec packets will only close the formspec when the formname matches
  1193. std::string cur_formname;
  1194. EventManager *eventmgr;
  1195. QuicktuneShortcutter *quicktune;
  1196. GUIChatConsole *gui_chat_console; // Free using ->Drop()
  1197. MapDrawControl *draw_control;
  1198. Camera *camera;
  1199. Clouds *clouds; // Free using ->Drop()
  1200. Sky *sky; // Free using ->Drop()
  1201. Inventory *local_inventory;
  1202. Hud *hud;
  1203. Minimap *mapper;
  1204. GameRunData runData;
  1205. GameUIFlags flags;
  1206. /* 'cache'
  1207. This class does take ownership/responsibily for cleaning up etc of any of
  1208. these items (e.g. device)
  1209. */
  1210. IrrlichtDevice *device;
  1211. video::IVideoDriver *driver;
  1212. scene::ISceneManager *smgr;
  1213. bool *kill;
  1214. std::string *error_message;
  1215. bool *reconnect_requested;
  1216. scene::ISceneNode *skybox;
  1217. bool random_input;
  1218. bool simple_singleplayer_mode;
  1219. /* End 'cache' */
  1220. /* Pre-calculated values
  1221. */
  1222. int crack_animation_length;
  1223. /* GUI stuff
  1224. */
  1225. gui::IGUIStaticText *guitext; // First line of debug text
  1226. gui::IGUIStaticText *guitext2; // Second line of debug text
  1227. gui::IGUIStaticText *guitext3; // Third line of debug text
  1228. gui::IGUIStaticText *guitext_info; // At the middle of the screen
  1229. gui::IGUIStaticText *guitext_status;
  1230. gui::IGUIStaticText *guitext_chat; // Chat text
  1231. gui::IGUIStaticText *guitext_profiler; // Profiler text
  1232. std::wstring infotext;
  1233. std::wstring m_statustext;
  1234. KeyCache keycache;
  1235. IntervalLimiter profiler_interval;
  1236. /*
  1237. * TODO: Local caching of settings is not optimal and should at some stage
  1238. * be updated to use a global settings object for getting thse values
  1239. * (as opposed to the this local caching). This can be addressed in
  1240. * a later release.
  1241. */
  1242. bool m_cache_doubletap_jump;
  1243. bool m_cache_enable_clouds;
  1244. bool m_cache_enable_joysticks;
  1245. bool m_cache_enable_particles;
  1246. bool m_cache_enable_fog;
  1247. bool m_cache_enable_noclip;
  1248. bool m_cache_enable_free_move;
  1249. f32 m_cache_mouse_sensitivity;
  1250. f32 m_cache_joystick_frustum_sensitivity;
  1251. f32 m_repeat_right_click_time;
  1252. f32 m_cache_cam_smoothing;
  1253. f32 m_cache_fog_start;
  1254. bool m_invert_mouse = false;
  1255. bool m_first_loop_after_window_activation = false;
  1256. bool m_camera_offset_changed = false;
  1257. #ifdef __ANDROID__
  1258. bool m_cache_hold_aux1;
  1259. bool m_android_chat_open;
  1260. #endif
  1261. };
  1262. Game::Game() :
  1263. client(NULL),
  1264. server(NULL),
  1265. texture_src(NULL),
  1266. shader_src(NULL),
  1267. itemdef_manager(NULL),
  1268. nodedef_manager(NULL),
  1269. sound(NULL),
  1270. soundmaker(NULL),
  1271. chat_backend(NULL),
  1272. current_formspec(NULL),
  1273. cur_formname(""),
  1274. eventmgr(NULL),
  1275. quicktune(NULL),
  1276. gui_chat_console(NULL),
  1277. draw_control(NULL),
  1278. camera(NULL),
  1279. clouds(NULL),
  1280. sky(NULL),
  1281. local_inventory(NULL),
  1282. hud(NULL),
  1283. mapper(NULL)
  1284. {
  1285. g_settings->registerChangedCallback("doubletap_jump",
  1286. &settingChangedCallback, this);
  1287. g_settings->registerChangedCallback("enable_clouds",
  1288. &settingChangedCallback, this);
  1289. g_settings->registerChangedCallback("doubletap_joysticks",
  1290. &settingChangedCallback, this);
  1291. g_settings->registerChangedCallback("enable_particles",
  1292. &settingChangedCallback, this);
  1293. g_settings->registerChangedCallback("enable_fog",
  1294. &settingChangedCallback, this);
  1295. g_settings->registerChangedCallback("mouse_sensitivity",
  1296. &settingChangedCallback, this);
  1297. g_settings->registerChangedCallback("joystick_frustum_sensitivity",
  1298. &settingChangedCallback, this);
  1299. g_settings->registerChangedCallback("repeat_rightclick_time",
  1300. &settingChangedCallback, this);
  1301. g_settings->registerChangedCallback("noclip",
  1302. &settingChangedCallback, this);
  1303. g_settings->registerChangedCallback("free_move",
  1304. &settingChangedCallback, this);
  1305. g_settings->registerChangedCallback("cinematic",
  1306. &settingChangedCallback, this);
  1307. g_settings->registerChangedCallback("cinematic_camera_smoothing",
  1308. &settingChangedCallback, this);
  1309. g_settings->registerChangedCallback("camera_smoothing",
  1310. &settingChangedCallback, this);
  1311. readSettings();
  1312. #ifdef __ANDROID__
  1313. m_cache_hold_aux1 = false; // This is initialised properly later
  1314. #endif
  1315. }
  1316. /****************************************************************************
  1317. MinetestApp Public
  1318. ****************************************************************************/
  1319. Game::~Game()
  1320. {
  1321. delete client;
  1322. delete soundmaker;
  1323. if (!sound_is_dummy)
  1324. delete sound;
  1325. delete server; // deleted first to stop all server threads
  1326. delete hud;
  1327. delete local_inventory;
  1328. delete camera;
  1329. delete quicktune;
  1330. delete eventmgr;
  1331. delete texture_src;
  1332. delete shader_src;
  1333. delete nodedef_manager;
  1334. delete itemdef_manager;
  1335. delete draw_control;
  1336. extendedResourceCleanup();
  1337. g_settings->deregisterChangedCallback("doubletap_jump",
  1338. &settingChangedCallback, this);
  1339. g_settings->deregisterChangedCallback("enable_clouds",
  1340. &settingChangedCallback, this);
  1341. g_settings->deregisterChangedCallback("enable_particles",
  1342. &settingChangedCallback, this);
  1343. g_settings->deregisterChangedCallback("enable_fog",
  1344. &settingChangedCallback, this);
  1345. g_settings->deregisterChangedCallback("mouse_sensitivity",
  1346. &settingChangedCallback, this);
  1347. g_settings->deregisterChangedCallback("repeat_rightclick_time",
  1348. &settingChangedCallback, this);
  1349. g_settings->deregisterChangedCallback("noclip",
  1350. &settingChangedCallback, this);
  1351. g_settings->deregisterChangedCallback("free_move",
  1352. &settingChangedCallback, this);
  1353. g_settings->deregisterChangedCallback("cinematic",
  1354. &settingChangedCallback, this);
  1355. g_settings->deregisterChangedCallback("cinematic_camera_smoothing",
  1356. &settingChangedCallback, this);
  1357. g_settings->deregisterChangedCallback("camera_smoothing",
  1358. &settingChangedCallback, this);
  1359. }
  1360. bool Game::startup(bool *kill,
  1361. bool random_input,
  1362. InputHandler *input,
  1363. const std::string &map_dir,
  1364. const std::string &playername,
  1365. const std::string &password,
  1366. std::string *address, // can change if simple_singleplayer_mode
  1367. u16 port,
  1368. std::string &error_message,
  1369. bool *reconnect,
  1370. ChatBackend *chat_backend,
  1371. const SubgameSpec &gamespec,
  1372. bool simple_singleplayer_mode)
  1373. {
  1374. // "cache"
  1375. this->device = RenderingEngine::get_raw_device();
  1376. this->kill = kill;
  1377. this->error_message = &error_message;
  1378. this->reconnect_requested = reconnect;
  1379. this->random_input = random_input;
  1380. this->input = input;
  1381. this->chat_backend = chat_backend;
  1382. this->simple_singleplayer_mode = simple_singleplayer_mode;
  1383. keycache.handler = input;
  1384. keycache.populate();
  1385. driver = device->getVideoDriver();
  1386. smgr = RenderingEngine::get_scene_manager();
  1387. RenderingEngine::get_scene_manager()->getParameters()->
  1388. setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
  1389. memset(&runData, 0, sizeof(runData));
  1390. runData.time_from_last_punch = 10.0;
  1391. runData.profiler_max_page = 3;
  1392. runData.update_wielded_item_trigger = true;
  1393. memset(&flags, 0, sizeof(flags));
  1394. flags.show_chat = true;
  1395. flags.show_hud = true;
  1396. flags.show_debug = g_settings->getBool("show_debug");
  1397. m_invert_mouse = g_settings->getBool("invert_mouse");
  1398. m_first_loop_after_window_activation = true;
  1399. g_translations->clear();
  1400. if (!init(map_dir, address, port, gamespec))
  1401. return false;
  1402. if (!createClient(playername, password, address, port))
  1403. return false;
  1404. return true;
  1405. }
  1406. void Game::run()
  1407. {
  1408. ProfilerGraph graph;
  1409. RunStats stats = { 0 };
  1410. CameraOrientation cam_view_target = { 0 };
  1411. CameraOrientation cam_view = { 0 };
  1412. FpsControl draw_times = { 0 };
  1413. f32 dtime; // in seconds
  1414. /* Clear the profiler */
  1415. Profiler::GraphValues dummyvalues;
  1416. g_profiler->graphGet(dummyvalues);
  1417. draw_times.last_time = RenderingEngine::get_timer_time();
  1418. set_light_table(g_settings->getFloat("display_gamma"));
  1419. #ifdef __ANDROID__
  1420. m_cache_hold_aux1 = g_settings->getBool("fast_move")
  1421. && client->checkPrivilege("fast");
  1422. #endif
  1423. irr::core::dimension2d<u32> previous_screen_size(g_settings->getU16("screen_w"),
  1424. g_settings->getU16("screen_h"));
  1425. while (RenderingEngine::run()
  1426. && !(*kill || g_gamecallback->shutdown_requested
  1427. || (server && server->getShutdownRequested()))) {
  1428. const irr::core::dimension2d<u32> &current_screen_size =
  1429. RenderingEngine::get_video_driver()->getScreenSize();
  1430. // Verify if window size has changed and save it if it's the case
  1431. // Ensure evaluating settings->getBool after verifying screensize
  1432. // First condition is cheaper
  1433. if (previous_screen_size != current_screen_size &&
  1434. current_screen_size != irr::core::dimension2d<u32>(0,0) &&
  1435. g_settings->getBool("autosave_screensize")) {
  1436. g_settings->setU16("screen_w", current_screen_size.Width);
  1437. g_settings->setU16("screen_h", current_screen_size.Height);
  1438. previous_screen_size = current_screen_size;
  1439. }
  1440. /* Must be called immediately after a device->run() call because it
  1441. * uses device->getTimer()->getTime()
  1442. */
  1443. limitFps(&draw_times, &dtime);
  1444. updateStats(&stats, draw_times, dtime);
  1445. updateInteractTimers(dtime);
  1446. if (!checkConnection())
  1447. break;
  1448. if (!handleCallbacks())
  1449. break;
  1450. processQueues();
  1451. infotext = L"";
  1452. hud->resizeHotbar();
  1453. updateProfilers(stats, draw_times, dtime);
  1454. processUserInput(dtime);
  1455. // Update camera before player movement to avoid camera lag of one frame
  1456. updateCameraDirection(&cam_view_target, dtime);
  1457. cam_view.camera_yaw += (cam_view_target.camera_yaw -
  1458. cam_view.camera_yaw) * m_cache_cam_smoothing;
  1459. cam_view.camera_pitch += (cam_view_target.camera_pitch -
  1460. cam_view.camera_pitch) * m_cache_cam_smoothing;
  1461. updatePlayerControl(cam_view);
  1462. step(&dtime);
  1463. processClientEvents(&cam_view_target);
  1464. updateCamera(draw_times.busy_time, dtime);
  1465. updateSound(dtime);
  1466. processPlayerInteraction(dtime, flags.show_hud, flags.show_debug);
  1467. updateFrame(&graph, &stats, dtime, cam_view);
  1468. updateProfilerGraphs(&graph);
  1469. // Update if minimap has been disabled by the server
  1470. flags.show_minimap &= client->shouldShowMinimap();
  1471. }
  1472. }
  1473. void Game::shutdown()
  1474. {
  1475. #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8
  1476. if (g_settings->get("3d_mode") == "pageflip") {
  1477. driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
  1478. }
  1479. #endif
  1480. if (current_formspec)
  1481. current_formspec->quitMenu();
  1482. showOverlayMessage("Shutting down...", 0, 0, false);
  1483. if (clouds)
  1484. clouds->drop();
  1485. if (gui_chat_console)
  1486. gui_chat_console->drop();
  1487. if (sky)
  1488. sky->drop();
  1489. /* cleanup menus */
  1490. while (g_menumgr.menuCount() > 0) {
  1491. g_menumgr.m_stack.front()->setVisible(false);
  1492. g_menumgr.deletingMenu(g_menumgr.m_stack.front());
  1493. }
  1494. if (current_formspec) {
  1495. current_formspec->drop();
  1496. current_formspec = NULL;
  1497. }
  1498. chat_backend->addMessage(L"", L"# Disconnected.");
  1499. chat_backend->addMessage(L"", L"");
  1500. if (client) {
  1501. client->Stop();
  1502. while (!client->isShutdown()) {
  1503. assert(texture_src != NULL);
  1504. assert(shader_src != NULL);
  1505. texture_src->processQueue();
  1506. shader_src->processQueue();
  1507. sleep_ms(100);
  1508. }
  1509. }
  1510. }
  1511. /****************************************************************************/
  1512. /****************************************************************************
  1513. Startup
  1514. ****************************************************************************/
  1515. /****************************************************************************/
  1516. bool Game::init(
  1517. const std::string &map_dir,
  1518. std::string *address,
  1519. u16 port,
  1520. const SubgameSpec &gamespec)
  1521. {
  1522. texture_src = createTextureSource();
  1523. showOverlayMessage("Loading...", 0, 0);
  1524. shader_src = createShaderSource();
  1525. itemdef_manager = createItemDefManager();
  1526. nodedef_manager = createNodeDefManager();
  1527. eventmgr = new EventManager();
  1528. quicktune = new QuicktuneShortcutter();
  1529. if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
  1530. && eventmgr && quicktune))
  1531. return false;
  1532. if (!initSound())
  1533. return false;
  1534. // Create a server if not connecting to an existing one
  1535. if (address->empty()) {
  1536. if (!createSingleplayerServer(map_dir, gamespec, port, address))
  1537. return false;
  1538. }
  1539. return true;
  1540. }
  1541. bool Game::initSound()
  1542. {
  1543. #if USE_SOUND
  1544. if (g_settings->getBool("enable_sound")) {
  1545. infostream << "Attempting to use OpenAL audio" << std::endl;
  1546. sound = createOpenALSoundManager(&soundfetcher);
  1547. if (!sound)
  1548. infostream << "Failed to initialize OpenAL audio" << std::endl;
  1549. } else
  1550. infostream << "Sound disabled." << std::endl;
  1551. #endif
  1552. if (!sound) {
  1553. infostream << "Using dummy audio." << std::endl;
  1554. sound = &dummySoundManager;
  1555. sound_is_dummy = true;
  1556. }
  1557. soundmaker = new SoundMaker(sound, nodedef_manager);
  1558. if (!soundmaker)
  1559. return false;
  1560. soundmaker->registerReceiver(eventmgr);
  1561. return true;
  1562. }
  1563. bool Game::createSingleplayerServer(const std::string &map_dir,
  1564. const SubgameSpec &gamespec, u16 port, std::string *address)
  1565. {
  1566. showOverlayMessage("Creating server...", 0, 5);
  1567. std::string bind_str = g_settings->get("bind_address");
  1568. Address bind_addr(0, 0, 0, 0, port);
  1569. if (g_settings->getBool("ipv6_server")) {
  1570. bind_addr.setAddress((IPv6AddressBytes *) NULL);
  1571. }
  1572. try {
  1573. bind_addr.Resolve(bind_str.c_str());
  1574. } catch (ResolveError &e) {
  1575. infostream << "Resolving bind address \"" << bind_str
  1576. << "\" failed: " << e.what()
  1577. << " -- Listening on all addresses." << std::endl;
  1578. }
  1579. if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
  1580. *error_message = "Unable to listen on " +
  1581. bind_addr.serializeString() +
  1582. " because IPv6 is disabled";
  1583. errorstream << *error_message << std::endl;
  1584. return false;
  1585. }
  1586. server = new Server(map_dir, gamespec, simple_singleplayer_mode,
  1587. bind_addr.isIPv6(), false);
  1588. server->start(bind_addr);
  1589. return true;
  1590. }
  1591. bool Game::createClient(const std::string &playername,
  1592. const std::string &password, std::string *address, u16 port)
  1593. {
  1594. showOverlayMessage("Creating client...", 0, 10);
  1595. draw_control = new MapDrawControl;
  1596. if (!draw_control)
  1597. return false;
  1598. bool could_connect, connect_aborted;
  1599. if (!connectToServer(playername, password, address, port,
  1600. &could_connect, &connect_aborted))
  1601. return false;
  1602. if (!could_connect) {
  1603. if (error_message->empty() && !connect_aborted) {
  1604. // Should not happen if error messages are set properly
  1605. *error_message = "Connection failed for unknown reason";
  1606. errorstream << *error_message << std::endl;
  1607. }
  1608. return false;
  1609. }
  1610. if (!getServerContent(&connect_aborted)) {
  1611. if (error_message->empty() && !connect_aborted) {
  1612. // Should not happen if error messages are set properly
  1613. *error_message = "Connection failed for unknown reason";
  1614. errorstream << *error_message << std::endl;
  1615. }
  1616. return false;
  1617. }
  1618. GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
  1619. &flags.force_fog_off, &runData.fog_range, client);
  1620. shader_src->addShaderConstantSetterFactory(scsf);
  1621. // Update cached textures, meshes and materials
  1622. client->afterContentReceived();
  1623. /* Camera
  1624. */
  1625. camera = new Camera(*draw_control, client);
  1626. if (!camera || !camera->successfullyCreated(*error_message))
  1627. return false;
  1628. client->setCamera(camera);
  1629. /* Clouds
  1630. */
  1631. if (m_cache_enable_clouds) {
  1632. clouds = new Clouds(smgr, -1, time(0));
  1633. if (!clouds) {
  1634. *error_message = "Memory allocation error (clouds)";
  1635. errorstream << *error_message << std::endl;
  1636. return false;
  1637. }
  1638. }
  1639. /* Skybox
  1640. */
  1641. sky = new Sky(-1, texture_src);
  1642. scsf->setSky(sky);
  1643. skybox = NULL; // This is used/set later on in the main run loop
  1644. local_inventory = new Inventory(itemdef_manager);
  1645. if (!(sky && local_inventory)) {
  1646. *error_message = "Memory allocation error (sky or local inventory)";
  1647. errorstream << *error_message << std::endl;
  1648. return false;
  1649. }
  1650. /* Pre-calculated values
  1651. */
  1652. video::ITexture *t = texture_src->getTexture("crack_anylength.png");
  1653. if (t) {
  1654. v2u32 size = t->getOriginalSize();
  1655. crack_animation_length = size.Y / size.X;
  1656. } else {
  1657. crack_animation_length = 5;
  1658. }
  1659. if (!initGui())
  1660. return false;
  1661. /* Set window caption
  1662. */
  1663. std::wstring str = utf8_to_wide(PROJECT_NAME_C);
  1664. str += L" ";
  1665. str += utf8_to_wide(g_version_hash);
  1666. str += L" [";
  1667. str += driver->getName();
  1668. str += L"]";
  1669. device->setWindowCaption(str.c_str());
  1670. LocalPlayer *player = client->getEnv().getLocalPlayer();
  1671. player->hurt_tilt_timer = 0;
  1672. player->hurt_tilt_strength = 0;
  1673. hud = new Hud(guienv, client, player, local_inventory);
  1674. if (!hud) {
  1675. *error_message = "Memory error: could not create HUD";
  1676. errorstream << *error_message << std::endl;
  1677. return false;
  1678. }
  1679. mapper = client->getMinimap();
  1680. if (mapper)
  1681. mapper->setMinimapMode(MINIMAP_MODE_OFF);
  1682. return true;
  1683. }
  1684. bool Game::initGui()
  1685. {
  1686. // First line of debug text
  1687. guitext = addStaticText(guienv,
  1688. utf8_to_wide(PROJECT_NAME_C).c_str(),
  1689. core::rect<s32>(0, 0, 0, 0),
  1690. false, false, guiroot);
  1691. // Second line of debug text
  1692. guitext2 = addStaticText(guienv,
  1693. L"",
  1694. core::rect<s32>(0, 0, 0, 0),
  1695. false, false, guiroot);
  1696. // Third line of debug text
  1697. guitext3 = addStaticText(guienv,
  1698. L"",
  1699. core::rect<s32>(0, 0, 0, 0),
  1700. false, false, guiroot);
  1701. // At the middle of the screen
  1702. // Object infos are shown in this
  1703. guitext_info = addStaticText(guienv,
  1704. L"",
  1705. core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
  1706. false, true, guiroot);
  1707. // Status text (displays info when showing and hiding GUI stuff, etc.)
  1708. guitext_status = addStaticText(guienv,
  1709. L"<Status>",
  1710. core::rect<s32>(0, 0, 0, 0),
  1711. false, false, guiroot);
  1712. guitext_status->setVisible(false);
  1713. // Chat text
  1714. guitext_chat = addStaticText(
  1715. guienv,
  1716. L"",
  1717. core::rect<s32>(0, 0, 0, 0),
  1718. //false, false); // Disable word wrap as of now
  1719. false, true, guiroot);
  1720. // Remove stale "recent" chat messages from previous connections
  1721. chat_backend->clearRecentChat();
  1722. // Chat backend and console
  1723. gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
  1724. -1, chat_backend, client, &g_menumgr);
  1725. if (!gui_chat_console) {
  1726. *error_message = "Could not allocate memory for chat console";
  1727. errorstream << *error_message << std::endl;
  1728. return false;
  1729. }
  1730. // Profiler text (size is updated when text is updated)
  1731. guitext_profiler = addStaticText(guienv,
  1732. L"<Profiler>",
  1733. core::rect<s32>(0, 0, 0, 0),
  1734. false, false, guiroot);
  1735. guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
  1736. guitext_profiler->setVisible(false);
  1737. guitext_profiler->setWordWrap(true);
  1738. #ifdef HAVE_TOUCHSCREENGUI
  1739. if (g_touchscreengui)
  1740. g_touchscreengui->init(texture_src);
  1741. #endif
  1742. return true;
  1743. }
  1744. bool Game::connectToServer(const std::string &playername,
  1745. const std::string &password, std::string *address, u16 port,
  1746. bool *connect_ok, bool *aborted)
  1747. {
  1748. *connect_ok = false; // Let's not be overly optimistic
  1749. *aborted = false;
  1750. bool local_server_mode = false;
  1751. showOverlayMessage("Resolving address...", 0, 15);
  1752. Address connect_address(0, 0, 0, 0, port);
  1753. try {
  1754. connect_address.Resolve(address->c_str());
  1755. if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
  1756. //connect_address.Resolve("localhost");
  1757. if (connect_address.isIPv6()) {
  1758. IPv6AddressBytes addr_bytes;
  1759. addr_bytes.bytes[15] = 1;
  1760. connect_address.setAddress(&addr_bytes);
  1761. } else {
  1762. connect_address.setAddress(127, 0, 0, 1);
  1763. }
  1764. local_server_mode = true;
  1765. }
  1766. } catch (ResolveError &e) {
  1767. *error_message = std::string("Couldn't resolve address: ") + e.what();
  1768. errorstream << *error_message << std::endl;
  1769. return false;
  1770. }
  1771. if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
  1772. *error_message = "Unable to connect to " +
  1773. connect_address.serializeString() +
  1774. " because IPv6 is disabled";
  1775. errorstream << *error_message << std::endl;
  1776. return false;
  1777. }
  1778. client = new Client(playername.c_str(), password, *address,
  1779. *draw_control, texture_src, shader_src,
  1780. itemdef_manager, nodedef_manager, sound, eventmgr,
  1781. connect_address.isIPv6(), &flags);
  1782. if (!client)
  1783. return false;
  1784. infostream << "Connecting to server at ";
  1785. connect_address.print(&infostream);
  1786. infostream << std::endl;
  1787. client->connect(connect_address,
  1788. simple_singleplayer_mode || local_server_mode);
  1789. /*
  1790. Wait for server to accept connection
  1791. */
  1792. try {
  1793. input->clear();
  1794. FpsControl fps_control = { 0 };
  1795. f32 dtime;
  1796. f32 wait_time = 0; // in seconds
  1797. fps_control.last_time = RenderingEngine::get_timer_time();
  1798. client->loadMods();
  1799. client->initMods();
  1800. while (RenderingEngine::run()) {
  1801. limitFps(&fps_control, &dtime);
  1802. // Update client and server
  1803. client->step(dtime);
  1804. if (server != NULL)
  1805. server->step(dtime);
  1806. // End condition
  1807. if (client->getState() == LC_Init) {
  1808. *connect_ok = true;
  1809. break;
  1810. }
  1811. // Break conditions
  1812. if (client->accessDenied()) {
  1813. *error_message = "Access denied. Reason: "
  1814. + client->accessDeniedReason();
  1815. *reconnect_requested = client->reconnectRequested();
  1816. errorstream << *error_message << std::endl;
  1817. break;
  1818. }
  1819. if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
  1820. *aborted = true;
  1821. infostream << "Connect aborted [Escape]" << std::endl;
  1822. break;
  1823. }
  1824. wait_time += dtime;
  1825. // Only time out if we aren't waiting for the server we started
  1826. if ((!address->empty()) && (wait_time > 10)) {
  1827. bool sent_old_init = g_settings->getFlag("send_pre_v25_init");
  1828. // If no pre v25 init was sent, and no answer was received,
  1829. // but the low level connection could be established
  1830. // (meaning that we have a peer id), then we probably wanted
  1831. // to connect to a legacy server. In this case, tell the user
  1832. // to enable the option to be able to connect.
  1833. if (!sent_old_init &&
  1834. (client->getProtoVersion() == 0) &&
  1835. client->connectedToServer()) {
  1836. *error_message = "Connection failure: init packet not "
  1837. "recognized by server.\n"
  1838. "Most likely the server uses an old protocol version (<v25).\n"
  1839. "Please ask the server owner to update to 0.4.13 or later.\n"
  1840. "To still connect to the server in the meantime,\n"
  1841. "you can enable the 'send_pre_v25_init' setting by editing minetest.conf,\n"
  1842. "or by enabling the 'Client -> Network -> Support older Servers'\n"
  1843. "entry in the advanced settings menu.";
  1844. } else {
  1845. *error_message = "Connection timed out.";
  1846. }
  1847. errorstream << *error_message << std::endl;
  1848. break;
  1849. }
  1850. // Update status
  1851. showOverlayMessage("Connecting to server...", dtime, 20);
  1852. }
  1853. } catch (con::PeerNotFoundException &e) {
  1854. // TODO: Should something be done here? At least an info/error
  1855. // message?
  1856. return false;
  1857. }
  1858. return true;
  1859. }
  1860. bool Game::getServerContent(bool *aborted)
  1861. {
  1862. input->clear();
  1863. FpsControl fps_control = { 0 };
  1864. f32 dtime; // in seconds
  1865. fps_control.last_time = RenderingEngine::get_timer_time();
  1866. while (RenderingEngine::run()) {
  1867. limitFps(&fps_control, &dtime);
  1868. // Update client and server
  1869. client->step(dtime);
  1870. if (server != NULL)
  1871. server->step(dtime);
  1872. // End condition
  1873. if (client->mediaReceived() && client->itemdefReceived() &&
  1874. client->nodedefReceived()) {
  1875. break;
  1876. }
  1877. // Error conditions
  1878. if (!checkConnection())
  1879. return false;
  1880. if (client->getState() < LC_Init) {
  1881. *error_message = "Client disconnected";
  1882. errorstream << *error_message << std::endl;
  1883. return false;
  1884. }
  1885. if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
  1886. *aborted = true;
  1887. infostream << "Connect aborted [Escape]" << std::endl;
  1888. return false;
  1889. }
  1890. // Display status
  1891. int progress = 25;
  1892. if (!client->itemdefReceived()) {
  1893. const wchar_t *text = wgettext("Item definitions...");
  1894. progress = 25;
  1895. RenderingEngine::draw_load_screen(text, guienv, texture_src,
  1896. dtime, progress);
  1897. delete[] text;
  1898. } else if (!client->nodedefReceived()) {
  1899. const wchar_t *text = wgettext("Node definitions...");
  1900. progress = 30;
  1901. RenderingEngine::draw_load_screen(text, guienv, texture_src,
  1902. dtime, progress);
  1903. delete[] text;
  1904. } else {
  1905. std::stringstream message;
  1906. std::fixed(message);
  1907. message.precision(0);
  1908. message << gettext("Media...") << " " << (client->mediaReceiveProgress()*100) << "%";
  1909. message.precision(2);
  1910. if ((USE_CURL == 0) ||
  1911. (!g_settings->getBool("enable_remote_media_server"))) {
  1912. float cur = client->getCurRate();
  1913. std::string cur_unit = gettext("KiB/s");
  1914. if (cur > 900) {
  1915. cur /= 1024.0;
  1916. cur_unit = gettext("MiB/s");
  1917. }
  1918. message << " (" << cur << ' ' << cur_unit << ")";
  1919. }
  1920. progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
  1921. RenderingEngine::draw_load_screen(utf8_to_wide(message.str()), guienv,
  1922. texture_src, dtime, progress);
  1923. }
  1924. }
  1925. return true;
  1926. }
  1927. /****************************************************************************/
  1928. /****************************************************************************
  1929. Run
  1930. ****************************************************************************/
  1931. /****************************************************************************/
  1932. inline void Game::updateInteractTimers(f32 dtime)
  1933. {
  1934. if (runData.nodig_delay_timer >= 0)
  1935. runData.nodig_delay_timer -= dtime;
  1936. if (runData.object_hit_delay_timer >= 0)
  1937. runData.object_hit_delay_timer -= dtime;
  1938. runData.time_from_last_punch += dtime;
  1939. }
  1940. /* returns false if game should exit, otherwise true
  1941. */
  1942. inline bool Game::checkConnection()
  1943. {
  1944. if (client->accessDenied()) {
  1945. *error_message = "Access denied. Reason: "
  1946. + client->accessDeniedReason();
  1947. *reconnect_requested = client->reconnectRequested();
  1948. errorstream << *error_message << std::endl;
  1949. return false;
  1950. }
  1951. return true;
  1952. }
  1953. /* returns false if game should exit, otherwise true
  1954. */
  1955. inline bool Game::handleCallbacks()
  1956. {
  1957. if (g_gamecallback->disconnect_requested) {
  1958. g_gamecallback->disconnect_requested = false;
  1959. return false;
  1960. }
  1961. if (g_gamecallback->changepassword_requested) {
  1962. (new GUIPasswordChange(guienv, guiroot, -1,
  1963. &g_menumgr, client))->drop();
  1964. g_gamecallback->changepassword_requested = false;
  1965. }
  1966. if (g_gamecallback->changevolume_requested) {
  1967. (new GUIVolumeChange(guienv, guiroot, -1,
  1968. &g_menumgr))->drop();
  1969. g_gamecallback->changevolume_requested = false;
  1970. }
  1971. if (g_gamecallback->keyconfig_requested) {
  1972. (new GUIKeyChangeMenu(guienv, guiroot, -1,
  1973. &g_menumgr))->drop();
  1974. g_gamecallback->keyconfig_requested = false;
  1975. }
  1976. if (g_gamecallback->keyconfig_changed) {
  1977. keycache.populate(); // update the cache with new settings
  1978. g_gamecallback->keyconfig_changed = false;
  1979. }
  1980. return true;
  1981. }
  1982. void Game::processQueues()
  1983. {
  1984. texture_src->processQueue();
  1985. itemdef_manager->processQueue(client);
  1986. shader_src->processQueue();
  1987. }
  1988. void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime)
  1989. {
  1990. float profiler_print_interval =
  1991. g_settings->getFloat("profiler_print_interval");
  1992. bool print_to_log = true;
  1993. if (profiler_print_interval == 0) {
  1994. print_to_log = false;
  1995. profiler_print_interval = 5;
  1996. }
  1997. if (profiler_interval.step(dtime, profiler_print_interval)) {
  1998. if (print_to_log) {
  1999. infostream << "Profiler:" << std::endl;
  2000. g_profiler->print(infostream);
  2001. }
  2002. update_profiler_gui(guitext_profiler, g_fontengine,
  2003. runData.profiler_current_page, runData.profiler_max_page,
  2004. driver->getScreenSize().Height);
  2005. g_profiler->clear();
  2006. }
  2007. addProfilerGraphs(stats, draw_times, dtime);
  2008. }
  2009. void Game::addProfilerGraphs(const RunStats &stats,
  2010. const FpsControl &draw_times, f32 dtime)
  2011. {
  2012. g_profiler->graphAdd("mainloop_other",
  2013. draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
  2014. if (draw_times.sleep_time != 0)
  2015. g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
  2016. g_profiler->graphAdd("mainloop_dtime", dtime);
  2017. g_profiler->add("Elapsed time", dtime);
  2018. g_profiler->avg("FPS", 1. / dtime);
  2019. }
  2020. void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
  2021. f32 dtime)
  2022. {
  2023. f32 jitter;
  2024. Jitter *jp;
  2025. /* Time average and jitter calculation
  2026. */
  2027. jp = &stats->dtime_jitter;
  2028. jp->avg = jp->avg * 0.96 + dtime * 0.04;
  2029. jitter = dtime - jp->avg;
  2030. if (jitter > jp->max)
  2031. jp->max = jitter;
  2032. jp->counter += dtime;
  2033. if (jp->counter > 0.0) {
  2034. jp->counter -= 3.0;
  2035. jp->max_sample = jp->max;
  2036. jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
  2037. jp->max = 0.0;
  2038. }
  2039. /* Busytime average and jitter calculation
  2040. */
  2041. jp = &stats->busy_time_jitter;
  2042. jp->avg = jp->avg + draw_times.busy_time * 0.02;
  2043. jitter = draw_times.busy_time - jp->avg;
  2044. if (jitter > jp->max)
  2045. jp->max = jitter;
  2046. if (jitter < jp->min)
  2047. jp->min = jitter;
  2048. jp->counter += dtime;
  2049. if (jp->counter > 0.0) {
  2050. jp->counter -= 3.0;
  2051. jp->max_sample = jp->max;
  2052. jp->min_sample = jp->min;
  2053. jp->max = 0.0;
  2054. jp->min = 0.0;
  2055. }
  2056. }
  2057. /****************************************************************************
  2058. Input handling
  2059. ****************************************************************************/
  2060. void Game::processUserInput(f32 dtime)
  2061. {
  2062. // Reset input if window not active or some menu is active
  2063. if (!device->isWindowActive() || isMenuActive() || guienv->hasFocus(gui_chat_console)) {
  2064. input->clear();
  2065. #ifdef HAVE_TOUCHSCREENGUI
  2066. g_touchscreengui->hide();
  2067. #endif
  2068. }
  2069. #ifdef HAVE_TOUCHSCREENGUI
  2070. else if (g_touchscreengui) {
  2071. /* on touchscreengui step may generate own input events which ain't
  2072. * what we want in case we just did clear them */
  2073. g_touchscreengui->step(dtime);
  2074. }
  2075. #endif
  2076. if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
  2077. gui_chat_console->closeConsoleAtOnce();
  2078. }
  2079. // Input handler step() (used by the random input generator)
  2080. input->step(dtime);
  2081. #ifdef __ANDROID__
  2082. if (current_formspec != NULL)
  2083. current_formspec->getAndroidUIInput();
  2084. else
  2085. handleAndroidChatInput();
  2086. #endif
  2087. // Increase timer for double tap of "keymap_jump"
  2088. if (m_cache_doubletap_jump && runData.jump_timer <= 0.2f)
  2089. runData.jump_timer += dtime;
  2090. processKeyInput();
  2091. processItemSelection(&runData.new_playeritem);
  2092. }
  2093. void Game::processKeyInput()
  2094. {
  2095. if (wasKeyDown(KeyType::DROP)) {
  2096. dropSelectedItem(isKeyDown(KeyType::SNEAK));
  2097. } else if (wasKeyDown(KeyType::AUTOFORWARD)) {
  2098. toggleAutoforward();
  2099. } else if (wasKeyDown(KeyType::INVENTORY)) {
  2100. openInventory();
  2101. } else if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
  2102. if (!gui_chat_console->isOpenInhibited()) {
  2103. showPauseMenu();
  2104. }
  2105. } else if (wasKeyDown(KeyType::CHAT)) {
  2106. openConsole(0.2, L"");
  2107. } else if (wasKeyDown(KeyType::CMD)) {
  2108. openConsole(0.2, L"/");
  2109. } else if (wasKeyDown(KeyType::CMD_LOCAL)) {
  2110. openConsole(0.2, L".");
  2111. } else if (wasKeyDown(KeyType::CONSOLE)) {
  2112. openConsole(core::clamp(g_settings->getFloat("console_height"), 0.1f, 1.0f));
  2113. } else if (wasKeyDown(KeyType::FREEMOVE)) {
  2114. toggleFreeMove();
  2115. } else if (wasKeyDown(KeyType::JUMP)) {
  2116. toggleFreeMoveAlt();
  2117. } else if (wasKeyDown(KeyType::FASTMOVE)) {
  2118. toggleFast();
  2119. } else if (wasKeyDown(KeyType::NOCLIP)) {
  2120. toggleNoClip();
  2121. } else if (wasKeyDown(KeyType::MUTE)) {
  2122. float volume = g_settings->getFloat("sound_volume");
  2123. if (volume < 0.001f) {
  2124. g_settings->setFloat("sound_volume", 1.0f);
  2125. m_statustext = narrow_to_wide(gettext("Volume changed to 100%"));
  2126. } else {
  2127. g_settings->setFloat("sound_volume", 0.0f);
  2128. m_statustext = narrow_to_wide(gettext("Volume changed to 0%"));
  2129. }
  2130. runData.statustext_time = 0;
  2131. } else if (wasKeyDown(KeyType::INC_VOLUME)) {
  2132. float new_volume = rangelim(g_settings->getFloat("sound_volume") + 0.1f, 0.0f, 1.0f);
  2133. char buf[100];
  2134. g_settings->setFloat("sound_volume", new_volume);
  2135. snprintf(buf, sizeof(buf), gettext("Volume changed to %d%%"), myround(new_volume * 100));
  2136. m_statustext = narrow_to_wide(buf);
  2137. runData.statustext_time = 0;
  2138. } else if (wasKeyDown(KeyType::DEC_VOLUME)) {
  2139. float new_volume = rangelim(g_settings->getFloat("sound_volume") - 0.1f, 0.0f, 1.0f);
  2140. char buf[100];
  2141. g_settings->setFloat("sound_volume", new_volume);
  2142. snprintf(buf, sizeof(buf), gettext("Volume changed to %d%%"), myround(new_volume * 100));
  2143. m_statustext = narrow_to_wide(buf);
  2144. runData.statustext_time = 0;
  2145. } else if (wasKeyDown(KeyType::CINEMATIC)) {
  2146. toggleCinematic();
  2147. } else if (wasKeyDown(KeyType::SCREENSHOT)) {
  2148. client->makeScreenshot();
  2149. } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
  2150. toggleHud();
  2151. } else if (wasKeyDown(KeyType::MINIMAP)) {
  2152. toggleMinimap(isKeyDown(KeyType::SNEAK));
  2153. } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
  2154. toggleChat();
  2155. } else if (wasKeyDown(KeyType::TOGGLE_FORCE_FOG_OFF)) {
  2156. toggleFog();
  2157. } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
  2158. toggleUpdateCamera();
  2159. } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
  2160. toggleDebug();
  2161. } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
  2162. toggleProfiler();
  2163. } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
  2164. increaseViewRange();
  2165. } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
  2166. decreaseViewRange();
  2167. } else if (wasKeyDown(KeyType::RANGESELECT)) {
  2168. toggleFullViewRange();
  2169. } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
  2170. quicktune->next();
  2171. } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
  2172. quicktune->prev();
  2173. } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
  2174. quicktune->inc();
  2175. } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
  2176. quicktune->dec();
  2177. }
  2178. if (!isKeyDown(KeyType::JUMP) && runData.reset_jump_timer) {
  2179. runData.reset_jump_timer = false;
  2180. runData.jump_timer = 0.0f;
  2181. }
  2182. if (quicktune->hasMessage()) {
  2183. m_statustext = utf8_to_wide(quicktune->getMessage());
  2184. runData.statustext_time = 0.0f;
  2185. }
  2186. }
  2187. void Game::processItemSelection(u16 *new_playeritem)
  2188. {
  2189. LocalPlayer *player = client->getEnv().getLocalPlayer();
  2190. /* Item selection using mouse wheel
  2191. */
  2192. *new_playeritem = client->getPlayerItem();
  2193. s32 wheel = input->getMouseWheel();
  2194. u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
  2195. player->hud_hotbar_itemcount - 1);
  2196. s32 dir = wheel;
  2197. if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN) ||
  2198. wasKeyDown(KeyType::HOTBAR_NEXT)) {
  2199. dir = -1;
  2200. }
  2201. if (input->joystick.wasKeyDown(KeyType::SCROLL_UP) ||
  2202. wasKeyDown(KeyType::HOTBAR_PREV)) {
  2203. dir = 1;
  2204. }
  2205. if (dir < 0)
  2206. *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
  2207. else if (dir > 0)
  2208. *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
  2209. // else dir == 0
  2210. /* Item selection using hotbar slot keys
  2211. */
  2212. for (u16 i = 0; i < 23; i++) {
  2213. if (wasKeyDown((GameKeyType) (KeyType::SLOT_1 + i))) {
  2214. if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
  2215. *new_playeritem = i;
  2216. infostream << "Selected item: " << new_playeritem << std::endl;
  2217. }
  2218. break;
  2219. }
  2220. }
  2221. }
  2222. void Game::dropSelectedItem(bool single_item)
  2223. {
  2224. IDropAction *a = new IDropAction();
  2225. a->count = single_item ? 1 : 0;
  2226. a->from_inv.setCurrentPlayer();
  2227. a->from_list = "main";
  2228. a->from_i = client->getPlayerItem();
  2229. client->inventoryAction(a);
  2230. }
  2231. void Game::openInventory()
  2232. {
  2233. /*
  2234. * Don't permit to open inventory is CAO or player doesn't exists.
  2235. * This prevent showing an empty inventory at player load
  2236. */
  2237. LocalPlayer *player = client->getEnv().getLocalPlayer();
  2238. if (!player || !player->getCAO())
  2239. return;
  2240. infostream << "the_game: " << "Launching inventory" << std::endl;
  2241. PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
  2242. TextDest *txt_dst = new TextDestPlayerInventory(client);
  2243. create_formspec_menu(&current_formspec, client, &input->joystick, fs_src, txt_dst);
  2244. cur_formname = "";
  2245. InventoryLocation inventoryloc;
  2246. inventoryloc.setCurrentPlayer();
  2247. current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
  2248. }
  2249. void Game::openConsole(float scale, const wchar_t *line)
  2250. {
  2251. assert(scale > 0.0f && scale <= 1.0f);
  2252. #ifdef __ANDROID__
  2253. porting::showInputDialog(gettext("ok"), "", "", 2);
  2254. m_android_chat_open = true;
  2255. #else
  2256. if (gui_chat_console->isOpenInhibited())
  2257. return;
  2258. gui_chat_console->openConsole(scale);
  2259. if (line) {
  2260. gui_chat_console->setCloseOnEnter(true);
  2261. gui_chat_console->replaceAndAddToHistory(line);
  2262. }
  2263. #endif
  2264. }
  2265. #ifdef __ANDROID__
  2266. void Game::handleAndroidChatInput()
  2267. {
  2268. if (m_android_chat_open && porting::getInputDialogState() == 0) {
  2269. std::string text = porting::getInputDialogValue();
  2270. client->typeChatMessage(utf8_to_wide(text));
  2271. }
  2272. }
  2273. #endif
  2274. void Game::toggleFreeMove()
  2275. {
  2276. static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
  2277. bool free_move = !g_settings->getBool("free_move");
  2278. g_settings->set("free_move", bool_to_cstr(free_move));
  2279. runData.statustext_time = 0;
  2280. m_statustext = msg[free_move];
  2281. if (free_move && !client->checkPrivilege("fly"))
  2282. m_statustext += L" (note: no 'fly' privilege)";
  2283. }
  2284. void Game::toggleFreeMoveAlt()
  2285. {
  2286. if (m_cache_doubletap_jump && runData.jump_timer < 0.2f)
  2287. toggleFreeMove();
  2288. runData.reset_jump_timer = true;
  2289. }
  2290. void Game::toggleFast()
  2291. {
  2292. static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
  2293. bool fast_move = !g_settings->getBool("fast_move");
  2294. g_settings->set("fast_move", bool_to_cstr(fast_move));
  2295. runData.statustext_time = 0;
  2296. m_statustext = msg[fast_move];
  2297. bool has_fast_privs = client->checkPrivilege("fast");
  2298. if (fast_move && !has_fast_privs)
  2299. m_statustext += L" (note: no 'fast' privilege)";
  2300. #ifdef __ANDROID__
  2301. m_cache_hold_aux1 = fast_move && has_fast_privs;
  2302. #endif
  2303. }
  2304. void Game::toggleNoClip()
  2305. {
  2306. static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
  2307. bool noclip = !g_settings->getBool("noclip");
  2308. g_settings->set("noclip", bool_to_cstr(noclip));
  2309. runData.statustext_time = 0;
  2310. m_statustext = msg[noclip];
  2311. if (noclip && !client->checkPrivilege("noclip"))
  2312. m_statustext += L" (note: no 'noclip' privilege)";
  2313. }
  2314. void Game::toggleCinematic()
  2315. {
  2316. static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
  2317. bool cinematic = !g_settings->getBool("cinematic");
  2318. g_settings->set("cinematic", bool_to_cstr(cinematic));
  2319. runData.statustext_time = 0;
  2320. m_statustext = msg[cinematic];
  2321. }
  2322. // Autoforward by toggling continuous forward.
  2323. void Game::toggleAutoforward()
  2324. {
  2325. static const wchar_t *msg[] = { L"autoforward disabled", L"autoforward enabled" };
  2326. bool autoforward_enabled = !g_settings->getBool("continuous_forward");
  2327. g_settings->set("continuous_forward", bool_to_cstr(autoforward_enabled));
  2328. runData.statustext_time = 0;
  2329. m_statustext = msg[autoforward_enabled ? 1 : 0];
  2330. }
  2331. void Game::toggleChat()
  2332. {
  2333. static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
  2334. flags.show_chat = !flags.show_chat;
  2335. runData.statustext_time = 0;
  2336. m_statustext = msg[flags.show_chat];
  2337. }
  2338. void Game::toggleHud()
  2339. {
  2340. static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
  2341. flags.show_hud = !flags.show_hud;
  2342. runData.statustext_time = 0;
  2343. m_statustext = msg[flags.show_hud];
  2344. }
  2345. void Game::toggleMinimap(bool shift_pressed)
  2346. {
  2347. if (!mapper || !flags.show_hud || !g_settings->getBool("enable_minimap"))
  2348. return;
  2349. if (shift_pressed) {
  2350. mapper->toggleMinimapShape();
  2351. return;
  2352. }
  2353. u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
  2354. MinimapMode mode = MINIMAP_MODE_OFF;
  2355. if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
  2356. mode = mapper->getMinimapMode();
  2357. mode = (MinimapMode)((int)mode + 1);
  2358. // If radar is disabled and in, or switching to, radar mode
  2359. if (!(hud_flags & HUD_FLAG_MINIMAP_RADAR_VISIBLE) && mode > 3)
  2360. mode = MINIMAP_MODE_OFF;
  2361. }
  2362. flags.show_minimap = true;
  2363. switch (mode) {
  2364. case MINIMAP_MODE_SURFACEx1:
  2365. m_statustext = L"Minimap in surface mode, Zoom x1";
  2366. break;
  2367. case MINIMAP_MODE_SURFACEx2:
  2368. m_statustext = L"Minimap in surface mode, Zoom x2";
  2369. break;
  2370. case MINIMAP_MODE_SURFACEx4:
  2371. m_statustext = L"Minimap in surface mode, Zoom x4";
  2372. break;
  2373. case MINIMAP_MODE_RADARx1:
  2374. m_statustext = L"Minimap in radar mode, Zoom x1";
  2375. break;
  2376. case MINIMAP_MODE_RADARx2:
  2377. m_statustext = L"Minimap in radar mode, Zoom x2";
  2378. break;
  2379. case MINIMAP_MODE_RADARx4:
  2380. m_statustext = L"Minimap in radar mode, Zoom x4";
  2381. break;
  2382. default:
  2383. mode = MINIMAP_MODE_OFF;
  2384. flags.show_minimap = false;
  2385. m_statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
  2386. L"Minimap hidden" : L"Minimap disabled by server";
  2387. }
  2388. runData.statustext_time = 0;
  2389. mapper->setMinimapMode(mode);
  2390. }
  2391. void Game::toggleFog()
  2392. {
  2393. static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
  2394. flags.force_fog_off = !flags.force_fog_off;
  2395. runData.statustext_time = 0;
  2396. m_statustext = msg[flags.force_fog_off];
  2397. }
  2398. void Game::toggleDebug()
  2399. {
  2400. // Initial / 4x toggle: Chat only
  2401. // 1x toggle: Debug text with chat
  2402. // 2x toggle: Debug text with profiler graph
  2403. // 3x toggle: Debug text and wireframe
  2404. if (!flags.show_debug) {
  2405. flags.show_debug = true;
  2406. flags.show_profiler_graph = false;
  2407. draw_control->show_wireframe = false;
  2408. m_statustext = L"Debug info shown";
  2409. } else if (!flags.show_profiler_graph && !draw_control->show_wireframe) {
  2410. flags.show_profiler_graph = true;
  2411. m_statustext = L"Profiler graph shown";
  2412. } else if (!draw_control->show_wireframe && client->checkPrivilege("debug")) {
  2413. flags.show_profiler_graph = false;
  2414. draw_control->show_wireframe = true;
  2415. m_statustext = L"Wireframe shown";
  2416. } else {
  2417. flags.show_debug = false;
  2418. flags.show_profiler_graph = false;
  2419. draw_control->show_wireframe = false;
  2420. if (client->checkPrivilege("debug")) {
  2421. m_statustext = L"Debug info, profiler graph, and wireframe hidden";
  2422. } else {
  2423. m_statustext = L"Debug info and profiler graph hidden";
  2424. }
  2425. }
  2426. runData.statustext_time = 0;
  2427. }
  2428. void Game::toggleUpdateCamera()
  2429. {
  2430. static const wchar_t *msg[] = {
  2431. L"Camera update enabled",
  2432. L"Camera update disabled"
  2433. };
  2434. flags.disable_camera_update = !flags.disable_camera_update;
  2435. runData.statustext_time = 0;
  2436. m_statustext = msg[flags.disable_camera_update];
  2437. }
  2438. void Game::toggleProfiler()
  2439. {
  2440. runData.profiler_current_page =
  2441. (runData.profiler_current_page + 1) % (runData.profiler_max_page + 1);
  2442. // FIXME: This updates the profiler with incomplete values
  2443. update_profiler_gui(guitext_profiler, g_fontengine, runData.profiler_current_page,
  2444. runData.profiler_max_page, driver->getScreenSize().Height);
  2445. if (runData.profiler_current_page != 0) {
  2446. std::wstringstream sstr;
  2447. sstr << "Profiler shown (page " << runData.profiler_current_page
  2448. << " of " << runData.profiler_max_page << ")";
  2449. m_statustext = sstr.str();
  2450. } else {
  2451. m_statustext = L"Profiler hidden";
  2452. }
  2453. runData.statustext_time = 0;
  2454. }
  2455. void Game::increaseViewRange()
  2456. {
  2457. s16 range = g_settings->getS16("viewing_range");
  2458. s16 range_new = range + 10;
  2459. if (range_new > 4000) {
  2460. range_new = 4000;
  2461. m_statustext = utf8_to_wide("Viewing range is at maximum: "
  2462. + itos(range_new));
  2463. } else {
  2464. m_statustext = utf8_to_wide("Viewing range changed to "
  2465. + itos(range_new));
  2466. }
  2467. g_settings->set("viewing_range", itos(range_new));
  2468. runData.statustext_time = 0;
  2469. }
  2470. void Game::decreaseViewRange()
  2471. {
  2472. s16 range = g_settings->getS16("viewing_range");
  2473. s16 range_new = range - 10;
  2474. if (range_new < 20) {
  2475. range_new = 20;
  2476. m_statustext = utf8_to_wide("Viewing range is at minimum: "
  2477. + itos(range_new));
  2478. } else {
  2479. m_statustext = utf8_to_wide("Viewing range changed to "
  2480. + itos(range_new));
  2481. }
  2482. g_settings->set("viewing_range", itos(range_new));
  2483. runData.statustext_time = 0;
  2484. }
  2485. void Game::toggleFullViewRange()
  2486. {
  2487. static const wchar_t *msg[] = {
  2488. L"Normal view range",
  2489. L"Infinite view range"
  2490. };
  2491. draw_control->range_all = !draw_control->range_all;
  2492. infostream << msg[draw_control->range_all] << std::endl;
  2493. m_statustext = msg[draw_control->range_all];
  2494. runData.statustext_time = 0;
  2495. }
  2496. void Game::updateCameraDirection(CameraOrientation *cam, float dtime)
  2497. {
  2498. if ((device->isWindowActive() && device->isWindowFocused()
  2499. && !isMenuActive()) || random_input) {
  2500. #ifndef __ANDROID__
  2501. if (!random_input) {
  2502. // Mac OSX gets upset if this is set every frame
  2503. if (device->getCursorControl()->isVisible())
  2504. device->getCursorControl()->setVisible(false);
  2505. }
  2506. #endif
  2507. if (m_first_loop_after_window_activation)
  2508. m_first_loop_after_window_activation = false;
  2509. else
  2510. updateCameraOrientation(cam, dtime);
  2511. input->setMousePos((driver->getScreenSize().Width / 2),
  2512. (driver->getScreenSize().Height / 2));
  2513. } else {
  2514. #ifndef ANDROID
  2515. // Mac OSX gets upset if this is set every frame
  2516. if (!device->getCursorControl()->isVisible())
  2517. device->getCursorControl()->setVisible(true);
  2518. #endif
  2519. m_first_loop_after_window_activation = true;
  2520. }
  2521. }
  2522. void Game::updateCameraOrientation(CameraOrientation *cam, float dtime)
  2523. {
  2524. #ifdef HAVE_TOUCHSCREENGUI
  2525. if (g_touchscreengui) {
  2526. cam->camera_yaw += g_touchscreengui->getYawChange();
  2527. cam->camera_pitch = g_touchscreengui->getPitch();
  2528. } else {
  2529. #endif
  2530. s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
  2531. s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
  2532. if (m_invert_mouse || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
  2533. dy = -dy;
  2534. }
  2535. cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
  2536. cam->camera_pitch += dy * m_cache_mouse_sensitivity;
  2537. #ifdef HAVE_TOUCHSCREENGUI
  2538. }
  2539. #endif
  2540. if (m_cache_enable_joysticks) {
  2541. f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
  2542. cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) * c;
  2543. cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * c;
  2544. }
  2545. cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
  2546. }
  2547. void Game::updatePlayerControl(const CameraOrientation &cam)
  2548. {
  2549. //TimeTaker tt("update player control", NULL, PRECISION_NANO);
  2550. // DO NOT use the isKeyDown method for the forward, backward, left, right
  2551. // buttons, as the code that uses the controls needs to be able to
  2552. // distinguish between the two in order to know when to use joysticks.
  2553. PlayerControl control(
  2554. input->isKeyDown(keycache.key[KeyType::FORWARD]),
  2555. input->isKeyDown(keycache.key[KeyType::BACKWARD]),
  2556. input->isKeyDown(keycache.key[KeyType::LEFT]),
  2557. input->isKeyDown(keycache.key[KeyType::RIGHT]),
  2558. isKeyDown(KeyType::JUMP),
  2559. isKeyDown(KeyType::SPECIAL1),
  2560. isKeyDown(KeyType::SNEAK),
  2561. isKeyDown(KeyType::ZOOM),
  2562. isLeftPressed(),
  2563. isRightPressed(),
  2564. cam.camera_pitch,
  2565. cam.camera_yaw,
  2566. input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
  2567. input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
  2568. );
  2569. u32 keypress_bits =
  2570. ( (u32)(isKeyDown(KeyType::FORWARD) & 0x1) << 0) |
  2571. ( (u32)(isKeyDown(KeyType::BACKWARD) & 0x1) << 1) |
  2572. ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) |
  2573. ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) |
  2574. ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) |
  2575. ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) |
  2576. ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) |
  2577. ( (u32)(isLeftPressed() & 0x1) << 7) |
  2578. ( (u32)(isRightPressed() & 0x1) << 8
  2579. );
  2580. #ifdef ANDROID
  2581. /* For Android, simulate holding down AUX1 (fast move) if the user has
  2582. * the fast_move setting toggled on. If there is an aux1 key defined for
  2583. * Android then its meaning is inverted (i.e. holding aux1 means walk and
  2584. * not fast)
  2585. */
  2586. if (m_cache_hold_aux1) {
  2587. control.aux1 = control.aux1 ^ true;
  2588. keypress_bits ^= ((u32)(1U << 5));
  2589. }
  2590. #endif
  2591. client->setPlayerControl(control);
  2592. LocalPlayer *player = client->getEnv().getLocalPlayer();
  2593. player->keyPressed = keypress_bits;
  2594. //tt.stop();
  2595. }
  2596. inline void Game::step(f32 *dtime)
  2597. {
  2598. bool can_be_and_is_paused =
  2599. (simple_singleplayer_mode && g_menumgr.pausesGame());
  2600. if (can_be_and_is_paused) { // This is for a singleplayer server
  2601. *dtime = 0; // No time passes
  2602. } else {
  2603. if (server != NULL) {
  2604. //TimeTaker timer("server->step(dtime)");
  2605. server->step(*dtime);
  2606. }
  2607. //TimeTaker timer("client.step(dtime)");
  2608. client->step(*dtime);
  2609. }
  2610. }
  2611. const ClientEventHandler Game::clientEventHandler[CLIENTEVENT_MAX] = {
  2612. {&Game::handleClientEvent_None},
  2613. {&Game::handleClientEvent_PlayerDamage},
  2614. {&Game::handleClientEvent_PlayerForceMove},
  2615. {&Game::handleClientEvent_Deathscreen},
  2616. {&Game::handleClientEvent_ShowFormSpec},
  2617. {&Game::handleClientEvent_ShowLocalFormSpec},
  2618. {&Game::handleClientEvent_HandleParticleEvent},
  2619. {&Game::handleClientEvent_HandleParticleEvent},
  2620. {&Game::handleClientEvent_HandleParticleEvent},
  2621. {&Game::handleClientEvent_HudAdd},
  2622. {&Game::handleClientEvent_HudRemove},
  2623. {&Game::handleClientEvent_HudChange},
  2624. {&Game::handleClientEvent_SetSky},
  2625. {&Game::handleClientEvent_OverrideDayNigthRatio},
  2626. {&Game::handleClientEvent_CloudParams},
  2627. };
  2628. void Game::handleClientEvent_None(ClientEvent *event, CameraOrientation *cam)
  2629. {
  2630. FATAL_ERROR("ClientEvent type None received");
  2631. }
  2632. void Game::handleClientEvent_PlayerDamage(ClientEvent *event, CameraOrientation *cam)
  2633. {
  2634. if (client->getHP() == 0)
  2635. return;
  2636. if (client->moddingEnabled()) {
  2637. client->getScript()->on_damage_taken(event->player_damage.amount);
  2638. }
  2639. runData.damage_flash += 95.0 + 3.2 * event->player_damage.amount;
  2640. runData.damage_flash = MYMIN(runData.damage_flash, 127.0);
  2641. LocalPlayer *player = client->getEnv().getLocalPlayer();
  2642. player->hurt_tilt_timer = 1.5;
  2643. player->hurt_tilt_strength =
  2644. rangelim(event->player_damage.amount / 4, 1.0, 4.0);
  2645. client->event()->put(new SimpleTriggerEvent("PlayerDamage"));
  2646. }
  2647. void Game::handleClientEvent_PlayerForceMove(ClientEvent *event, CameraOrientation *cam)
  2648. {
  2649. cam->camera_yaw = event->player_force_move.yaw;
  2650. cam->camera_pitch = event->player_force_move.pitch;
  2651. }
  2652. void Game::handleClientEvent_Deathscreen(ClientEvent *event, CameraOrientation *cam)
  2653. {
  2654. // This should be enabled for death formspec in builtin
  2655. client->getScript()->on_death();
  2656. LocalPlayer *player = client->getEnv().getLocalPlayer();
  2657. /* Handle visualization */
  2658. runData.damage_flash = 0;
  2659. player->hurt_tilt_timer = 0;
  2660. player->hurt_tilt_strength = 0;
  2661. }
  2662. void Game::handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation *cam)
  2663. {
  2664. if (event->show_formspec.formspec->empty()) {
  2665. if (current_formspec && (event->show_formspec.formname->empty()
  2666. || *(event->show_formspec.formname) == cur_formname)) {
  2667. current_formspec->quitMenu();
  2668. }
  2669. } else {
  2670. FormspecFormSource *fs_src =
  2671. new FormspecFormSource(*(event->show_formspec.formspec));
  2672. TextDestPlayerInventory *txt_dst =
  2673. new TextDestPlayerInventory(client, *(event->show_formspec.formname));
  2674. create_formspec_menu(&current_formspec, client, &input->joystick,
  2675. fs_src, txt_dst);
  2676. cur_formname = *(event->show_formspec.formname);
  2677. }
  2678. delete event->show_formspec.formspec;
  2679. delete event->show_formspec.formname;
  2680. }
  2681. void Game::handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrientation *cam)
  2682. {
  2683. FormspecFormSource *fs_src = new FormspecFormSource(*event->show_formspec.formspec);
  2684. LocalFormspecHandler *txt_dst =
  2685. new LocalFormspecHandler(*event->show_formspec.formname, client);
  2686. create_formspec_menu(&current_formspec, client, &input->joystick, fs_src, txt_dst);
  2687. delete event->show_formspec.formspec;
  2688. delete event->show_formspec.formname;
  2689. }
  2690. void Game::handleClientEvent_HandleParticleEvent(ClientEvent *event,
  2691. CameraOrientation *cam)
  2692. {
  2693. LocalPlayer *player = client->getEnv().getLocalPlayer();
  2694. client->getParticleManager()->handleParticleEvent(event, client, player);
  2695. }
  2696. void Game::handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam)
  2697. {
  2698. LocalPlayer *player = client->getEnv().getLocalPlayer();
  2699. u32 id = event->hudadd.id;
  2700. HudElement *e = player->getHud(id);
  2701. if (e != NULL) {
  2702. delete event->hudadd.pos;
  2703. delete event->hudadd.name;
  2704. delete event->hudadd.scale;
  2705. delete event->hudadd.text;
  2706. delete event->hudadd.align;
  2707. delete event->hudadd.offset;
  2708. delete event->hudadd.world_pos;
  2709. delete event->hudadd.size;
  2710. return;
  2711. }
  2712. e = new HudElement;
  2713. e->type = (HudElementType)event->hudadd.type;
  2714. e->pos = *event->hudadd.pos;
  2715. e->name = *event->hudadd.name;
  2716. e->scale = *event->hudadd.scale;
  2717. e->text = *event->hudadd.text;
  2718. e->number = event->hudadd.number;
  2719. e->item = event->hudadd.item;
  2720. e->dir = event->hudadd.dir;
  2721. e->align = *event->hudadd.align;
  2722. e->offset = *event->hudadd.offset;
  2723. e->world_pos = *event->hudadd.world_pos;
  2724. e->size = *event->hudadd.size;
  2725. u32 new_id = player->addHud(e);
  2726. //if this isn't true our huds aren't consistent
  2727. sanity_check(new_id == id);
  2728. delete event->hudadd.pos;
  2729. delete event->hudadd.name;
  2730. delete event->hudadd.scale;
  2731. delete event->hudadd.text;
  2732. delete event->hudadd.align;
  2733. delete event->hudadd.offset;
  2734. delete event->hudadd.world_pos;
  2735. delete event->hudadd.size;
  2736. }
  2737. void Game::handleClientEvent_HudRemove(ClientEvent *event, CameraOrientation *cam)
  2738. {
  2739. LocalPlayer *player = client->getEnv().getLocalPlayer();
  2740. HudElement *e = player->removeHud(event->hudrm.id);
  2741. delete e;
  2742. }
  2743. void Game::handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *cam)
  2744. {
  2745. LocalPlayer *player = client->getEnv().getLocalPlayer();
  2746. u32 id = event->hudchange.id;
  2747. HudElement *e = player->getHud(id);
  2748. if (e == NULL) {
  2749. delete event->hudchange.v3fdata;
  2750. delete event->hudchange.v2fdata;
  2751. delete event->hudchange.sdata;
  2752. delete event->hudchange.v2s32data;
  2753. return;
  2754. }
  2755. switch (event->hudchange.stat) {
  2756. case HUD_STAT_POS:
  2757. e->pos = *event->hudchange.v2fdata;
  2758. break;
  2759. case HUD_STAT_NAME:
  2760. e->name = *event->hudchange.sdata;
  2761. break;
  2762. case HUD_STAT_SCALE:
  2763. e->scale = *event->hudchange.v2fdata;
  2764. break;
  2765. case HUD_STAT_TEXT:
  2766. e->text = *event->hudchange.sdata;
  2767. break;
  2768. case HUD_STAT_NUMBER:
  2769. e->number = event->hudchange.data;
  2770. break;
  2771. case HUD_STAT_ITEM:
  2772. e->item = event->hudchange.data;
  2773. break;
  2774. case HUD_STAT_DIR:
  2775. e->dir = event->hudchange.data;
  2776. break;
  2777. case HUD_STAT_ALIGN:
  2778. e->align = *event->hudchange.v2fdata;
  2779. break;
  2780. case HUD_STAT_OFFSET:
  2781. e->offset = *event->hudchange.v2fdata;
  2782. break;
  2783. case HUD_STAT_WORLD_POS:
  2784. e->world_pos = *event->hudchange.v3fdata;
  2785. break;
  2786. case HUD_STAT_SIZE:
  2787. e->size = *event->hudchange.v2s32data;
  2788. break;
  2789. }
  2790. delete event->hudchange.v3fdata;
  2791. delete event->hudchange.v2fdata;
  2792. delete event->hudchange.sdata;
  2793. delete event->hudchange.v2s32data;
  2794. }
  2795. void Game::handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam)
  2796. {
  2797. sky->setVisible(false);
  2798. // Whether clouds are visible in front of a custom skybox
  2799. sky->setCloudsEnabled(event->set_sky.clouds);
  2800. if (skybox) {
  2801. skybox->remove();
  2802. skybox = NULL;
  2803. }
  2804. // Handle according to type
  2805. if (*event->set_sky.type == "regular") {
  2806. sky->setVisible(true);
  2807. sky->setCloudsEnabled(true);
  2808. } else if (*event->set_sky.type == "skybox" &&
  2809. event->set_sky.params->size() == 6) {
  2810. sky->setFallbackBgColor(*event->set_sky.bgcolor);
  2811. skybox = RenderingEngine::get_scene_manager()->addSkyBoxSceneNode(
  2812. texture_src->getTextureForMesh((*event->set_sky.params)[0]),
  2813. texture_src->getTextureForMesh((*event->set_sky.params)[1]),
  2814. texture_src->getTextureForMesh((*event->set_sky.params)[2]),
  2815. texture_src->getTextureForMesh((*event->set_sky.params)[3]),
  2816. texture_src->getTextureForMesh((*event->set_sky.params)[4]),
  2817. texture_src->getTextureForMesh((*event->set_sky.params)[5]));
  2818. }
  2819. // Handle everything else as plain color
  2820. else {
  2821. if (*event->set_sky.type != "plain")
  2822. infostream << "Unknown sky type: "
  2823. << (*event->set_sky.type) << std::endl;
  2824. sky->setFallbackBgColor(*event->set_sky.bgcolor);
  2825. }
  2826. delete event->set_sky.bgcolor;
  2827. delete event->set_sky.type;
  2828. delete event->set_sky.params;
  2829. }
  2830. void Game::handleClientEvent_OverrideDayNigthRatio(ClientEvent *event,
  2831. CameraOrientation *cam)
  2832. {
  2833. client->getEnv().setDayNightRatioOverride(
  2834. event->override_day_night_ratio.do_override,
  2835. event->override_day_night_ratio.ratio_f * 1000.0f);
  2836. }
  2837. void Game::handleClientEvent_CloudParams(ClientEvent *event, CameraOrientation *cam)
  2838. {
  2839. if (!clouds)
  2840. return;
  2841. clouds->setDensity(event->cloud_params.density);
  2842. clouds->setColorBright(video::SColor(event->cloud_params.color_bright));
  2843. clouds->setColorAmbient(video::SColor(event->cloud_params.color_ambient));
  2844. clouds->setHeight(event->cloud_params.height);
  2845. clouds->setThickness(event->cloud_params.thickness);
  2846. clouds->setSpeed(v2f(event->cloud_params.speed_x, event->cloud_params.speed_y));
  2847. }
  2848. void Game::processClientEvents(CameraOrientation *cam)
  2849. {
  2850. while (client->hasClientEvents()) {
  2851. std::unique_ptr<ClientEvent> event(client->getClientEvent());
  2852. FATAL_ERROR_IF(event->type >= CLIENTEVENT_MAX, "Invalid clientevent type");
  2853. const ClientEventHandler& evHandler = clientEventHandler[event->type];
  2854. (this->*evHandler.handler)(event.get(), cam);
  2855. }
  2856. }
  2857. void Game::updateCamera(u32 busy_time, f32 dtime)
  2858. {
  2859. LocalPlayer *player = client->getEnv().getLocalPlayer();
  2860. /*
  2861. For interaction purposes, get info about the held item
  2862. - What item is it?
  2863. - Is it a usable item?
  2864. - Can it point to liquids?
  2865. */
  2866. ItemStack playeritem;
  2867. {
  2868. InventoryList *mlist = local_inventory->getList("main");
  2869. if (mlist && client->getPlayerItem() < mlist->getSize())
  2870. playeritem = mlist->getItem(client->getPlayerItem());
  2871. }
  2872. if (playeritem.getDefinition(itemdef_manager).name.empty()) { // override the hand
  2873. InventoryList *hlist = local_inventory->getList("hand");
  2874. if (hlist)
  2875. playeritem = hlist->getItem(0);
  2876. }
  2877. ToolCapabilities playeritem_toolcap =
  2878. playeritem.getToolCapabilities(itemdef_manager);
  2879. v3s16 old_camera_offset = camera->getOffset();
  2880. if (wasKeyDown(KeyType::CAMERA_MODE)) {
  2881. GenericCAO *playercao = player->getCAO();
  2882. // If playercao not loaded, don't change camera
  2883. if (!playercao)
  2884. return;
  2885. camera->toggleCameraMode();
  2886. playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
  2887. playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
  2888. }
  2889. float full_punch_interval = playeritem_toolcap.full_punch_interval;
  2890. float tool_reload_ratio = runData.time_from_last_punch / full_punch_interval;
  2891. tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
  2892. camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio);
  2893. camera->step(dtime);
  2894. v3f camera_position = camera->getPosition();
  2895. v3f camera_direction = camera->getDirection();
  2896. f32 camera_fov = camera->getFovMax();
  2897. v3s16 camera_offset = camera->getOffset();
  2898. m_camera_offset_changed = (camera_offset != old_camera_offset);
  2899. if (!flags.disable_camera_update) {
  2900. client->getEnv().getClientMap().updateCamera(camera_position,
  2901. camera_direction, camera_fov, camera_offset);
  2902. if (m_camera_offset_changed) {
  2903. client->updateCameraOffset(camera_offset);
  2904. client->getEnv().updateCameraOffset(camera_offset);
  2905. if (clouds)
  2906. clouds->updateCameraOffset(camera_offset);
  2907. }
  2908. }
  2909. }
  2910. void Game::updateSound(f32 dtime)
  2911. {
  2912. // Update sound listener
  2913. v3s16 camera_offset = camera->getOffset();
  2914. sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
  2915. v3f(0, 0, 0), // velocity
  2916. camera->getDirection(),
  2917. camera->getCameraNode()->getUpVector());
  2918. // Check if volume is in the proper range, else fix it.
  2919. float old_volume = g_settings->getFloat("sound_volume");
  2920. float new_volume = rangelim(old_volume, 0.0f, 1.0f);
  2921. sound->setListenerGain(new_volume);
  2922. if (old_volume != new_volume) {
  2923. g_settings->setFloat("sound_volume", new_volume);
  2924. }
  2925. LocalPlayer *player = client->getEnv().getLocalPlayer();
  2926. // Tell the sound maker whether to make footstep sounds
  2927. soundmaker->makes_footstep_sound = player->makes_footstep_sound;
  2928. // Update sound maker
  2929. if (player->makes_footstep_sound)
  2930. soundmaker->step(dtime);
  2931. ClientMap &map = client->getEnv().getClientMap();
  2932. MapNode n = map.getNodeNoEx(player->getFootstepNodePos());
  2933. soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
  2934. }
  2935. void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
  2936. {
  2937. LocalPlayer *player = client->getEnv().getLocalPlayer();
  2938. ItemStack playeritem;
  2939. {
  2940. InventoryList *mlist = local_inventory->getList("main");
  2941. if (mlist && client->getPlayerItem() < mlist->getSize())
  2942. playeritem = mlist->getItem(client->getPlayerItem());
  2943. }
  2944. const ItemDefinition &playeritem_def =
  2945. playeritem.getDefinition(itemdef_manager);
  2946. InventoryList *hlist = local_inventory->getList("hand");
  2947. const ItemDefinition &hand_def =
  2948. hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
  2949. v3f player_position = player->getPosition();
  2950. v3f camera_position = camera->getPosition();
  2951. v3f camera_direction = camera->getDirection();
  2952. v3s16 camera_offset = camera->getOffset();
  2953. /*
  2954. Calculate what block is the crosshair pointing to
  2955. */
  2956. f32 d = playeritem_def.range; // max. distance
  2957. f32 d_hand = hand_def.range;
  2958. if (d < 0 && d_hand >= 0)
  2959. d = d_hand;
  2960. else if (d < 0)
  2961. d = 4.0;
  2962. core::line3d<f32> shootline;
  2963. if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
  2964. shootline = core::line3d<f32>(camera_position,
  2965. camera_position + camera_direction * BS * d);
  2966. } else {
  2967. // prevent player pointing anything in front-view
  2968. shootline = core::line3d<f32>(camera_position,camera_position);
  2969. }
  2970. #ifdef HAVE_TOUCHSCREENGUI
  2971. if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
  2972. shootline = g_touchscreengui->getShootline();
  2973. // Scale shootline to the acual distance the player can reach
  2974. shootline.end = shootline.start
  2975. + shootline.getVector().normalize() * BS * d;
  2976. shootline.start += intToFloat(camera_offset, BS);
  2977. shootline.end += intToFloat(camera_offset, BS);
  2978. }
  2979. #endif
  2980. PointedThing pointed = updatePointedThing(shootline,
  2981. playeritem_def.liquids_pointable,
  2982. !runData.ldown_for_dig,
  2983. camera_offset);
  2984. if (pointed != runData.pointed_old) {
  2985. infostream << "Pointing at " << pointed.dump() << std::endl;
  2986. hud->updateSelectionMesh(camera_offset);
  2987. }
  2988. if (runData.digging_blocked && !isLeftPressed()) {
  2989. // allow digging again if button is not pressed
  2990. runData.digging_blocked = false;
  2991. }
  2992. /*
  2993. Stop digging when
  2994. - releasing left mouse button
  2995. - pointing away from node
  2996. */
  2997. if (runData.digging) {
  2998. if (getLeftReleased()) {
  2999. infostream << "Left button released"
  3000. << " (stopped digging)" << std::endl;
  3001. runData.digging = false;
  3002. } else if (pointed != runData.pointed_old) {
  3003. if (pointed.type == POINTEDTHING_NODE
  3004. && runData.pointed_old.type == POINTEDTHING_NODE
  3005. && pointed.node_undersurface
  3006. == runData.pointed_old.node_undersurface) {
  3007. // Still pointing to the same node, but a different face.
  3008. // Don't reset.
  3009. } else {
  3010. infostream << "Pointing away from node"
  3011. << " (stopped digging)" << std::endl;
  3012. runData.digging = false;
  3013. hud->updateSelectionMesh(camera_offset);
  3014. }
  3015. }
  3016. if (!runData.digging) {
  3017. client->interact(1, runData.pointed_old);
  3018. client->setCrack(-1, v3s16(0, 0, 0));
  3019. runData.dig_time = 0.0;
  3020. }
  3021. } else if (runData.dig_instantly && getLeftReleased()) {
  3022. // Remove e.g. torches faster when clicking instead of holding LMB
  3023. runData.nodig_delay_timer = 0;
  3024. runData.dig_instantly = false;
  3025. }
  3026. if (!runData.digging && runData.ldown_for_dig && !isLeftPressed()) {
  3027. runData.ldown_for_dig = false;
  3028. }
  3029. runData.left_punch = false;
  3030. soundmaker->m_player_leftpunch_sound.name = "";
  3031. // Prepare for repeating, unless we're not supposed to
  3032. if (isRightPressed() && !g_settings->getBool("safe_dig_and_place"))
  3033. runData.repeat_rightclick_timer += dtime;
  3034. else
  3035. runData.repeat_rightclick_timer = 0;
  3036. if (playeritem_def.usable && isLeftPressed()) {
  3037. if (getLeftClicked() && (!client->moddingEnabled()
  3038. || !client->getScript()->on_item_use(playeritem, pointed)))
  3039. client->interact(4, pointed);
  3040. } else if (pointed.type == POINTEDTHING_NODE) {
  3041. ToolCapabilities playeritem_toolcap =
  3042. playeritem.getToolCapabilities(itemdef_manager);
  3043. if (playeritem.name.empty() && hand_def.tool_capabilities != NULL) {
  3044. playeritem_toolcap = *hand_def.tool_capabilities;
  3045. }
  3046. handlePointingAtNode(pointed, playeritem_def, playeritem,
  3047. playeritem_toolcap, dtime);
  3048. } else if (pointed.type == POINTEDTHING_OBJECT) {
  3049. handlePointingAtObject(pointed, playeritem, player_position, show_debug);
  3050. } else if (isLeftPressed()) {
  3051. // When button is held down in air, show continuous animation
  3052. runData.left_punch = true;
  3053. } else if (getRightClicked()) {
  3054. handlePointingAtNothing(playeritem);
  3055. }
  3056. runData.pointed_old = pointed;
  3057. if (runData.left_punch || getLeftClicked())
  3058. camera->setDigging(0); // left click animation
  3059. input->resetLeftClicked();
  3060. input->resetRightClicked();
  3061. input->joystick.clearWasKeyDown(KeyType::MOUSE_L);
  3062. input->joystick.clearWasKeyDown(KeyType::MOUSE_R);
  3063. input->resetLeftReleased();
  3064. input->resetRightReleased();
  3065. input->joystick.clearWasKeyReleased(KeyType::MOUSE_L);
  3066. input->joystick.clearWasKeyReleased(KeyType::MOUSE_R);
  3067. }
  3068. PointedThing Game::updatePointedThing(
  3069. const core::line3d<f32> &shootline,
  3070. bool liquids_pointable,
  3071. bool look_for_object,
  3072. const v3s16 &camera_offset)
  3073. {
  3074. std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
  3075. selectionboxes->clear();
  3076. hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
  3077. static thread_local const bool show_entity_selectionbox = g_settings->getBool(
  3078. "show_entity_selectionbox");
  3079. ClientEnvironment &env = client->getEnv();
  3080. ClientMap &map = env.getClientMap();
  3081. INodeDefManager *nodedef = map.getNodeDefManager();
  3082. runData.selected_object = NULL;
  3083. RaycastState s(shootline, look_for_object, liquids_pointable);
  3084. PointedThing result;
  3085. env.continueRaycast(&s, &result);
  3086. if (result.type == POINTEDTHING_OBJECT) {
  3087. runData.selected_object = client->getEnv().getActiveObject(result.object_id);
  3088. aabb3f selection_box;
  3089. if (show_entity_selectionbox && runData.selected_object->doShowSelectionBox() &&
  3090. runData.selected_object->getSelectionBox(&selection_box)) {
  3091. v3f pos = runData.selected_object->getPosition();
  3092. selectionboxes->push_back(aabb3f(selection_box));
  3093. hud->setSelectionPos(pos, camera_offset);
  3094. }
  3095. } else if (result.type == POINTEDTHING_NODE) {
  3096. // Update selection boxes
  3097. MapNode n = map.getNodeNoEx(result.node_undersurface);
  3098. std::vector<aabb3f> boxes;
  3099. n.getSelectionBoxes(nodedef, &boxes,
  3100. n.getNeighbors(result.node_undersurface, &map));
  3101. f32 d = 0.002 * BS;
  3102. for (std::vector<aabb3f>::const_iterator i = boxes.begin();
  3103. i != boxes.end(); ++i) {
  3104. aabb3f box = *i;
  3105. box.MinEdge -= v3f(d, d, d);
  3106. box.MaxEdge += v3f(d, d, d);
  3107. selectionboxes->push_back(box);
  3108. }
  3109. hud->setSelectionPos(intToFloat(result.node_undersurface, BS),
  3110. camera_offset);
  3111. hud->setSelectedFaceNormal(v3f(
  3112. result.intersection_normal.X,
  3113. result.intersection_normal.Y,
  3114. result.intersection_normal.Z));
  3115. }
  3116. // Update selection mesh light level and vertex colors
  3117. if (!selectionboxes->empty()) {
  3118. v3f pf = hud->getSelectionPos();
  3119. v3s16 p = floatToInt(pf, BS);
  3120. // Get selection mesh light level
  3121. MapNode n = map.getNodeNoEx(p);
  3122. u16 node_light = getInteriorLight(n, -1, nodedef);
  3123. u16 light_level = node_light;
  3124. for (const v3s16 &dir : g_6dirs) {
  3125. n = map.getNodeNoEx(p + dir);
  3126. node_light = getInteriorLight(n, -1, nodedef);
  3127. if (node_light > light_level)
  3128. light_level = node_light;
  3129. }
  3130. u32 daynight_ratio = client->getEnv().getDayNightRatio();
  3131. video::SColor c;
  3132. final_color_blend(&c, light_level, daynight_ratio);
  3133. // Modify final color a bit with time
  3134. u32 timer = porting::getTimeMs() % 5000;
  3135. float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5));
  3136. float sin_r = 0.08 * sin(timerf);
  3137. float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
  3138. float sin_b = 0.08 * sin(timerf + irr::core::PI);
  3139. c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
  3140. c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
  3141. c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
  3142. // Set mesh final color
  3143. hud->setSelectionMeshColor(c);
  3144. }
  3145. return result;
  3146. }
  3147. void Game::handlePointingAtNothing(const ItemStack &playerItem)
  3148. {
  3149. infostream << "Right Clicked in Air" << std::endl;
  3150. PointedThing fauxPointed;
  3151. fauxPointed.type = POINTEDTHING_NOTHING;
  3152. client->interact(5, fauxPointed);
  3153. }
  3154. void Game::handlePointingAtNode(const PointedThing &pointed,
  3155. const ItemDefinition &playeritem_def, const ItemStack &playeritem,
  3156. const ToolCapabilities &playeritem_toolcap, f32 dtime)
  3157. {
  3158. v3s16 nodepos = pointed.node_undersurface;
  3159. v3s16 neighbourpos = pointed.node_abovesurface;
  3160. /*
  3161. Check information text of node
  3162. */
  3163. ClientMap &map = client->getEnv().getClientMap();
  3164. if (runData.nodig_delay_timer <= 0.0 && isLeftPressed()
  3165. && !runData.digging_blocked
  3166. && client->checkPrivilege("interact")) {
  3167. handleDigging(pointed, nodepos, playeritem_toolcap, dtime);
  3168. }
  3169. // This should be done after digging handling
  3170. NodeMetadata *meta = map.getNodeMetadata(nodepos);
  3171. if (meta) {
  3172. infotext = unescape_translate(utf8_to_wide(meta->getString("infotext")));
  3173. } else {
  3174. MapNode n = map.getNodeNoEx(nodepos);
  3175. if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
  3176. infotext = L"Unknown node: ";
  3177. infotext += utf8_to_wide(nodedef_manager->get(n).name);
  3178. }
  3179. }
  3180. if ((getRightClicked() ||
  3181. runData.repeat_rightclick_timer >= m_repeat_right_click_time) &&
  3182. client->checkPrivilege("interact")) {
  3183. runData.repeat_rightclick_timer = 0;
  3184. infostream << "Ground right-clicked" << std::endl;
  3185. if (meta && !meta->getString("formspec").empty() && !random_input
  3186. && !isKeyDown(KeyType::SNEAK)) {
  3187. // Report right click to server
  3188. if (nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
  3189. client->interact(3, pointed);
  3190. }
  3191. infostream << "Launching custom inventory view" << std::endl;
  3192. InventoryLocation inventoryloc;
  3193. inventoryloc.setNodeMeta(nodepos);
  3194. NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
  3195. &client->getEnv().getClientMap(), nodepos);
  3196. TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
  3197. create_formspec_menu(&current_formspec, client,
  3198. &input->joystick, fs_src, txt_dst);
  3199. cur_formname = "";
  3200. current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
  3201. } else {
  3202. // Report right click to server
  3203. camera->setDigging(1); // right click animation (always shown for feedback)
  3204. // If the wielded item has node placement prediction,
  3205. // make that happen
  3206. bool placed = nodePlacementPrediction(*client,
  3207. playeritem_def, playeritem,
  3208. nodepos, neighbourpos);
  3209. if (placed) {
  3210. // Report to server
  3211. client->interact(3, pointed);
  3212. // Read the sound
  3213. soundmaker->m_player_rightpunch_sound =
  3214. playeritem_def.sound_place;
  3215. if (client->moddingEnabled())
  3216. client->getScript()->on_placenode(pointed, playeritem_def);
  3217. } else {
  3218. soundmaker->m_player_rightpunch_sound =
  3219. SimpleSoundSpec();
  3220. if (playeritem_def.node_placement_prediction.empty() ||
  3221. nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
  3222. client->interact(3, pointed); // Report to server
  3223. } else {
  3224. soundmaker->m_player_rightpunch_sound =
  3225. playeritem_def.sound_place_failed;
  3226. }
  3227. }
  3228. }
  3229. }
  3230. }
  3231. void Game::handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
  3232. const v3f &player_position, bool show_debug)
  3233. {
  3234. infotext = unescape_translate(
  3235. utf8_to_wide(runData.selected_object->infoText()));
  3236. if (show_debug) {
  3237. if (!infotext.empty()) {
  3238. infotext += L"\n";
  3239. }
  3240. infotext += utf8_to_wide(runData.selected_object->debugInfoText());
  3241. }
  3242. if (isLeftPressed()) {
  3243. bool do_punch = false;
  3244. bool do_punch_damage = false;
  3245. if (runData.object_hit_delay_timer <= 0.0) {
  3246. do_punch = true;
  3247. do_punch_damage = true;
  3248. runData.object_hit_delay_timer = object_hit_delay;
  3249. }
  3250. if (getLeftClicked())
  3251. do_punch = true;
  3252. if (do_punch) {
  3253. infostream << "Left-clicked object" << std::endl;
  3254. runData.left_punch = true;
  3255. }
  3256. if (do_punch_damage) {
  3257. // Report direct punch
  3258. v3f objpos = runData.selected_object->getPosition();
  3259. v3f dir = (objpos - player_position).normalize();
  3260. ItemStack item = playeritem;
  3261. if (playeritem.name.empty()) {
  3262. InventoryList *hlist = local_inventory->getList("hand");
  3263. if (hlist) {
  3264. item = hlist->getItem(0);
  3265. }
  3266. }
  3267. bool disable_send = runData.selected_object->directReportPunch(
  3268. dir, &item, runData.time_from_last_punch);
  3269. runData.time_from_last_punch = 0;
  3270. if (!disable_send)
  3271. client->interact(0, pointed);
  3272. }
  3273. } else if (getRightClicked()) {
  3274. infostream << "Right-clicked object" << std::endl;
  3275. client->interact(3, pointed); // place
  3276. }
  3277. }
  3278. void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
  3279. const ToolCapabilities &playeritem_toolcap, f32 dtime)
  3280. {
  3281. LocalPlayer *player = client->getEnv().getLocalPlayer();
  3282. ClientMap &map = client->getEnv().getClientMap();
  3283. MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
  3284. // NOTE: Similar piece of code exists on the server side for
  3285. // cheat detection.
  3286. // Get digging parameters
  3287. DigParams params = getDigParams(nodedef_manager->get(n).groups,
  3288. &playeritem_toolcap);
  3289. // If can't dig, try hand
  3290. if (!params.diggable) {
  3291. InventoryList *hlist = local_inventory->getList("hand");
  3292. const ItemDefinition &hand =
  3293. hlist ? hlist->getItem(0).getDefinition(itemdef_manager) : itemdef_manager->get("");
  3294. const ToolCapabilities *tp = hand.tool_capabilities;
  3295. if (tp)
  3296. params = getDigParams(nodedef_manager->get(n).groups, tp);
  3297. }
  3298. if (!params.diggable) {
  3299. // I guess nobody will wait for this long
  3300. runData.dig_time_complete = 10000000.0;
  3301. } else {
  3302. runData.dig_time_complete = params.time;
  3303. if (m_cache_enable_particles) {
  3304. const ContentFeatures &features = client->getNodeDefManager()->get(n);
  3305. client->getParticleManager()->addPunchingParticles(client,
  3306. player, nodepos, n, features);
  3307. }
  3308. }
  3309. if (!runData.digging) {
  3310. infostream << "Started digging" << std::endl;
  3311. runData.dig_instantly = runData.dig_time_complete == 0;
  3312. if (client->moddingEnabled() && client->getScript()->on_punchnode(nodepos, n))
  3313. return;
  3314. client->interact(0, pointed);
  3315. runData.digging = true;
  3316. runData.ldown_for_dig = true;
  3317. }
  3318. if (!runData.dig_instantly) {
  3319. runData.dig_index = (float)crack_animation_length
  3320. * runData.dig_time
  3321. / runData.dig_time_complete;
  3322. } else {
  3323. // This is for e.g. torches
  3324. runData.dig_index = crack_animation_length;
  3325. }
  3326. SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
  3327. if (sound_dig.exists() && params.diggable) {
  3328. if (sound_dig.name == "__group") {
  3329. if (!params.main_group.empty()) {
  3330. soundmaker->m_player_leftpunch_sound.gain = 0.5;
  3331. soundmaker->m_player_leftpunch_sound.name =
  3332. std::string("default_dig_") +
  3333. params.main_group;
  3334. }
  3335. } else {
  3336. soundmaker->m_player_leftpunch_sound = sound_dig;
  3337. }
  3338. }
  3339. // Don't show cracks if not diggable
  3340. if (runData.dig_time_complete >= 100000.0) {
  3341. } else if (runData.dig_index < crack_animation_length) {
  3342. //TimeTaker timer("client.setTempMod");
  3343. //infostream<<"dig_index="<<dig_index<<std::endl;
  3344. client->setCrack(runData.dig_index, nodepos);
  3345. } else {
  3346. infostream << "Digging completed" << std::endl;
  3347. client->setCrack(-1, v3s16(0, 0, 0));
  3348. runData.dig_time = 0;
  3349. runData.digging = false;
  3350. // we successfully dug, now block it from repeating if we want to be safe
  3351. if (g_settings->getBool("safe_dig_and_place"))
  3352. runData.digging_blocked = true;
  3353. runData.nodig_delay_timer =
  3354. runData.dig_time_complete / (float)crack_animation_length;
  3355. // We don't want a corresponding delay to very time consuming nodes
  3356. // and nodes without digging time (e.g. torches) get a fixed delay.
  3357. if (runData.nodig_delay_timer > 0.3)
  3358. runData.nodig_delay_timer = 0.3;
  3359. else if (runData.dig_instantly)
  3360. runData.nodig_delay_timer = 0.15;
  3361. bool is_valid_position;
  3362. MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
  3363. if (is_valid_position) {
  3364. if (client->moddingEnabled() &&
  3365. client->getScript()->on_dignode(nodepos, wasnode)) {
  3366. return;
  3367. }
  3368. client->removeNode(nodepos);
  3369. }
  3370. client->interact(2, pointed);
  3371. if (m_cache_enable_particles) {
  3372. const ContentFeatures &features =
  3373. client->getNodeDefManager()->get(wasnode);
  3374. client->getParticleManager()->addDiggingParticles(client,
  3375. player, nodepos, wasnode, features);
  3376. }
  3377. // Send event to trigger sound
  3378. MtEvent *e = new NodeDugEvent(nodepos, wasnode);
  3379. client->event()->put(e);
  3380. }
  3381. if (runData.dig_time_complete < 100000.0) {
  3382. runData.dig_time += dtime;
  3383. } else {
  3384. runData.dig_time = 0;
  3385. client->setCrack(-1, nodepos);
  3386. }
  3387. camera->setDigging(0); // left click animation
  3388. }
  3389. void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
  3390. const CameraOrientation &cam)
  3391. {
  3392. LocalPlayer *player = client->getEnv().getLocalPlayer();
  3393. /*
  3394. Fog range
  3395. */
  3396. if (draw_control->range_all) {
  3397. runData.fog_range = 100000 * BS;
  3398. } else {
  3399. runData.fog_range = draw_control->wanted_range * BS;
  3400. }
  3401. /*
  3402. Calculate general brightness
  3403. */
  3404. u32 daynight_ratio = client->getEnv().getDayNightRatio();
  3405. float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
  3406. float direct_brightness;
  3407. bool sunlight_seen;
  3408. if (m_cache_enable_noclip && m_cache_enable_free_move) {
  3409. direct_brightness = time_brightness;
  3410. sunlight_seen = true;
  3411. } else {
  3412. ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
  3413. float old_brightness = sky->getBrightness();
  3414. direct_brightness = client->getEnv().getClientMap()
  3415. .getBackgroundBrightness(MYMIN(runData.fog_range * 1.2, 60 * BS),
  3416. daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
  3417. / 255.0;
  3418. }
  3419. float time_of_day_smooth = runData.time_of_day_smooth;
  3420. float time_of_day = client->getEnv().getTimeOfDayF();
  3421. static const float maxsm = 0.05;
  3422. static const float todsm = 0.05;
  3423. if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
  3424. fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
  3425. fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
  3426. time_of_day_smooth = time_of_day;
  3427. if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
  3428. time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
  3429. + (time_of_day + 1.0) * todsm;
  3430. else
  3431. time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
  3432. + time_of_day * todsm;
  3433. runData.time_of_day = time_of_day;
  3434. runData.time_of_day_smooth = time_of_day_smooth;
  3435. sky->update(time_of_day_smooth, time_brightness, direct_brightness,
  3436. sunlight_seen, camera->getCameraMode(), player->getYaw(),
  3437. player->getPitch());
  3438. /*
  3439. Update clouds
  3440. */
  3441. if (clouds) {
  3442. if (sky->getCloudsVisible()) {
  3443. clouds->setVisible(true);
  3444. clouds->step(dtime);
  3445. // camera->getPosition is not enough for 3rd person views
  3446. v3f camera_node_position = camera->getCameraNode()->getPosition();
  3447. v3s16 camera_offset = camera->getOffset();
  3448. camera_node_position.X = camera_node_position.X + camera_offset.X * BS;
  3449. camera_node_position.Y = camera_node_position.Y + camera_offset.Y * BS;
  3450. camera_node_position.Z = camera_node_position.Z + camera_offset.Z * BS;
  3451. clouds->update(camera_node_position,
  3452. sky->getCloudColor());
  3453. if (clouds->isCameraInsideCloud() && m_cache_enable_fog &&
  3454. !flags.force_fog_off) {
  3455. // if inside clouds, and fog enabled, use that as sky
  3456. // color(s)
  3457. video::SColor clouds_dark = clouds->getColor()
  3458. .getInterpolated(video::SColor(255, 0, 0, 0), 0.9);
  3459. sky->overrideColors(clouds_dark, clouds->getColor());
  3460. sky->setBodiesVisible(false);
  3461. runData.fog_range = std::fmin(runData.fog_range * 0.5f, 32.0f * BS);
  3462. // do not draw clouds after all
  3463. clouds->setVisible(false);
  3464. }
  3465. } else {
  3466. clouds->setVisible(false);
  3467. }
  3468. }
  3469. /*
  3470. Update particles
  3471. */
  3472. client->getParticleManager()->step(dtime);
  3473. /*
  3474. Fog
  3475. */
  3476. if (m_cache_enable_fog && !flags.force_fog_off) {
  3477. driver->setFog(
  3478. sky->getBgColor(),
  3479. video::EFT_FOG_LINEAR,
  3480. runData.fog_range * m_cache_fog_start,
  3481. runData.fog_range * 1.0,
  3482. 0.01,
  3483. false, // pixel fog
  3484. true // range fog
  3485. );
  3486. } else {
  3487. driver->setFog(
  3488. sky->getBgColor(),
  3489. video::EFT_FOG_LINEAR,
  3490. 100000 * BS,
  3491. 110000 * BS,
  3492. 0.01,
  3493. false, // pixel fog
  3494. false // range fog
  3495. );
  3496. }
  3497. /*
  3498. Get chat messages from client
  3499. */
  3500. v2u32 screensize = driver->getScreenSize();
  3501. updateChat(*client, dtime, flags.show_debug, screensize,
  3502. flags.show_chat, runData.profiler_current_page,
  3503. *chat_backend, guitext_chat);
  3504. /*
  3505. Inventory
  3506. */
  3507. if (client->getPlayerItem() != runData.new_playeritem)
  3508. client->selectPlayerItem(runData.new_playeritem);
  3509. // Update local inventory if it has changed
  3510. if (client->getLocalInventoryUpdated()) {
  3511. //infostream<<"Updating local inventory"<<std::endl;
  3512. client->getLocalInventory(*local_inventory);
  3513. runData.update_wielded_item_trigger = true;
  3514. }
  3515. if (runData.update_wielded_item_trigger) {
  3516. // Update wielded tool
  3517. InventoryList *mlist = local_inventory->getList("main");
  3518. if (mlist && (client->getPlayerItem() < mlist->getSize())) {
  3519. ItemStack item = mlist->getItem(client->getPlayerItem());
  3520. if (item.getDefinition(itemdef_manager).name.empty()) { // override the hand
  3521. InventoryList *hlist = local_inventory->getList("hand");
  3522. if (hlist)
  3523. item = hlist->getItem(0);
  3524. }
  3525. camera->wield(item);
  3526. }
  3527. runData.update_wielded_item_trigger = false;
  3528. }
  3529. /*
  3530. Update block draw list every 200ms or when camera direction has
  3531. changed much
  3532. */
  3533. runData.update_draw_list_timer += dtime;
  3534. v3f camera_direction = camera->getDirection();
  3535. if (runData.update_draw_list_timer >= 0.2
  3536. || runData.update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
  3537. || m_camera_offset_changed) {
  3538. runData.update_draw_list_timer = 0;
  3539. client->getEnv().getClientMap().updateDrawList();
  3540. runData.update_draw_list_last_cam_dir = camera_direction;
  3541. }
  3542. updateGui(*stats, dtime, cam);
  3543. /*
  3544. make sure menu is on top
  3545. 1. Delete formspec menu reference if menu was removed
  3546. 2. Else, make sure formspec menu is on top
  3547. */
  3548. if (current_formspec) {
  3549. if (current_formspec->getReferenceCount() == 1) {
  3550. current_formspec->drop();
  3551. current_formspec = NULL;
  3552. } else if (isMenuActive()) {
  3553. guiroot->bringToFront(current_formspec);
  3554. }
  3555. }
  3556. /*
  3557. Drawing begins
  3558. */
  3559. const video::SColor &skycolor = sky->getSkyColor();
  3560. TimeTaker tt_draw("mainloop: draw");
  3561. driver->beginScene(true, true, skycolor);
  3562. RenderingEngine::draw_scene(camera, client, player, hud, mapper,
  3563. guienv, screensize, skycolor, flags.show_hud,
  3564. flags.show_minimap);
  3565. /*
  3566. Profiler graph
  3567. */
  3568. if (flags.show_profiler_graph)
  3569. graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
  3570. /*
  3571. Damage flash
  3572. */
  3573. if (runData.damage_flash > 0.0) {
  3574. video::SColor color(runData.damage_flash, 180, 0, 0);
  3575. driver->draw2DRectangle(color,
  3576. core::rect<s32>(0, 0, screensize.X, screensize.Y),
  3577. NULL);
  3578. runData.damage_flash -= 100.0 * dtime;
  3579. }
  3580. /*
  3581. Damage camera tilt
  3582. */
  3583. if (player->hurt_tilt_timer > 0.0) {
  3584. player->hurt_tilt_timer -= dtime * 5;
  3585. if (player->hurt_tilt_timer < 0)
  3586. player->hurt_tilt_strength = 0;
  3587. }
  3588. /*
  3589. Update minimap pos and rotation
  3590. */
  3591. if (mapper && flags.show_minimap && flags.show_hud) {
  3592. mapper->setPos(floatToInt(player->getPosition(), BS));
  3593. mapper->setAngle(player->getYaw());
  3594. }
  3595. /*
  3596. End scene
  3597. */
  3598. driver->endScene();
  3599. stats->drawtime = tt_draw.stop(true);
  3600. g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
  3601. }
  3602. inline static const char *yawToDirectionString(int yaw)
  3603. {
  3604. static const char *direction[4] = {"North [+Z]", "West [-X]", "South [-Z]", "East [+X]"};
  3605. yaw = wrapDegrees_0_360(yaw);
  3606. yaw = (yaw + 45) % 360 / 90;
  3607. return direction[yaw];
  3608. }
  3609. void Game::updateGui(const RunStats &stats, f32 dtime, const CameraOrientation &cam)
  3610. {
  3611. v2u32 screensize = driver->getScreenSize();
  3612. LocalPlayer *player = client->getEnv().getLocalPlayer();
  3613. v3f player_position = player->getPosition();
  3614. if (flags.show_debug) {
  3615. static float drawtime_avg = 0;
  3616. drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
  3617. u16 fps = 1.0 / stats.dtime_jitter.avg;
  3618. std::ostringstream os(std::ios_base::binary);
  3619. os << std::fixed
  3620. << PROJECT_NAME_C " " << g_version_hash
  3621. << ", FPS = " << fps
  3622. << ", range_all = " << draw_control->range_all
  3623. << std::setprecision(0)
  3624. << ", drawtime = " << drawtime_avg << " ms"
  3625. << std::setprecision(1)
  3626. << ", dtime_jitter = "
  3627. << (stats.dtime_jitter.max_fraction * 100.0) << " %"
  3628. << std::setprecision(1)
  3629. << ", view_range = " << draw_control->wanted_range
  3630. << std::setprecision(3)
  3631. << ", RTT = " << client->getRTT() << " s";
  3632. setStaticText(guitext, utf8_to_wide(os.str()).c_str());
  3633. guitext->setVisible(true);
  3634. } else {
  3635. guitext->setVisible(false);
  3636. }
  3637. if (guitext->isVisible()) {
  3638. core::rect<s32> rect(
  3639. 5, 5,
  3640. screensize.X, 5 + g_fontengine->getTextHeight()
  3641. );
  3642. guitext->setRelativePosition(rect);
  3643. }
  3644. if (flags.show_debug) {
  3645. std::ostringstream os(std::ios_base::binary);
  3646. os << std::setprecision(1) << std::fixed
  3647. << "pos = (" << (player_position.X / BS)
  3648. << ", " << (player_position.Y / BS)
  3649. << ", " << (player_position.Z / BS)
  3650. << "), yaw = " << (wrapDegrees_0_360(cam.camera_yaw)) << "°"
  3651. << " " << yawToDirectionString(cam.camera_yaw)
  3652. << ", seed = " << ((u64)client->getMapSeed());
  3653. setStaticText(guitext2, utf8_to_wide(os.str()).c_str());
  3654. guitext2->setVisible(true);
  3655. } else {
  3656. guitext2->setVisible(false);
  3657. }
  3658. if (guitext2->isVisible()) {
  3659. core::rect<s32> rect(
  3660. 5, 5 + g_fontengine->getTextHeight(),
  3661. screensize.X, 5 + g_fontengine->getTextHeight() * 2
  3662. );
  3663. guitext2->setRelativePosition(rect);
  3664. }
  3665. if (flags.show_debug && runData.pointed_old.type == POINTEDTHING_NODE) {
  3666. ClientMap &map = client->getEnv().getClientMap();
  3667. const INodeDefManager *nodedef = client->getNodeDefManager();
  3668. MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
  3669. if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
  3670. std::ostringstream os(std::ios_base::binary);
  3671. os << "pointing_at = (" << nodedef->get(n).name
  3672. << ", param2 = " << (u64) n.getParam2()
  3673. << ")";
  3674. setStaticText(guitext3, utf8_to_wide(os.str()).c_str());
  3675. guitext3->setVisible(true);
  3676. } else {
  3677. guitext3->setVisible(false);
  3678. }
  3679. } else {
  3680. guitext3->setVisible(false);
  3681. }
  3682. if (guitext3->isVisible()) {
  3683. core::rect<s32> rect(
  3684. 5, 5 + g_fontengine->getTextHeight() * 2,
  3685. screensize.X, 5 + g_fontengine->getTextHeight() * 3
  3686. );
  3687. guitext3->setRelativePosition(rect);
  3688. }
  3689. setStaticText(guitext_info, translate_string(infotext).c_str());
  3690. guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
  3691. float statustext_time_max = 1.5;
  3692. if (!m_statustext.empty()) {
  3693. runData.statustext_time += dtime;
  3694. if (runData.statustext_time >= statustext_time_max) {
  3695. m_statustext = L"";
  3696. runData.statustext_time = 0;
  3697. }
  3698. }
  3699. setStaticText(guitext_status, translate_string(m_statustext).c_str());
  3700. guitext_status->setVisible(!m_statustext.empty());
  3701. if (!m_statustext.empty()) {
  3702. s32 status_width = guitext_status->getTextWidth();
  3703. s32 status_height = guitext_status->getTextHeight();
  3704. s32 status_y = screensize.Y - 150;
  3705. s32 status_x = (screensize.X - status_width) / 2;
  3706. core::rect<s32> rect(
  3707. status_x , status_y - status_height,
  3708. status_x + status_width, status_y
  3709. );
  3710. guitext_status->setRelativePosition(rect);
  3711. // Fade out
  3712. video::SColor initial_color(255, 0, 0, 0);
  3713. if (guienv->getSkin())
  3714. initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
  3715. video::SColor final_color = initial_color;
  3716. final_color.setAlpha(0);
  3717. video::SColor fade_color = initial_color.getInterpolated_quadratic(
  3718. initial_color, final_color,
  3719. pow(runData.statustext_time / statustext_time_max, 2.0f));
  3720. guitext_status->setOverrideColor(fade_color);
  3721. guitext_status->enableOverrideColor(true);
  3722. }
  3723. }
  3724. /* Log times and stuff for visualization */
  3725. inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
  3726. {
  3727. Profiler::GraphValues values;
  3728. g_profiler->graphGet(values);
  3729. graph->put(values);
  3730. }
  3731. /****************************************************************************
  3732. Misc
  3733. ****************************************************************************/
  3734. /* On some computers framerate doesn't seem to be automatically limited
  3735. */
  3736. inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
  3737. {
  3738. // not using getRealTime is necessary for wine
  3739. device->getTimer()->tick(); // Maker sure device time is up-to-date
  3740. u32 time = device->getTimer()->getTime();
  3741. u32 last_time = fps_timings->last_time;
  3742. if (time > last_time) // Make sure time hasn't overflowed
  3743. fps_timings->busy_time = time - last_time;
  3744. else
  3745. fps_timings->busy_time = 0;
  3746. u32 frametime_min = 1000 / (g_menumgr.pausesGame()
  3747. ? g_settings->getFloat("pause_fps_max")
  3748. : g_settings->getFloat("fps_max"));
  3749. if (fps_timings->busy_time < frametime_min) {
  3750. fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
  3751. device->sleep(fps_timings->sleep_time);
  3752. } else {
  3753. fps_timings->sleep_time = 0;
  3754. }
  3755. /* Get the new value of the device timer. Note that device->sleep() may
  3756. * not sleep for the entire requested time as sleep may be interrupted and
  3757. * therefore it is arguably more accurate to get the new time from the
  3758. * device rather than calculating it by adding sleep_time to time.
  3759. */
  3760. device->getTimer()->tick(); // Update device timer
  3761. time = device->getTimer()->getTime();
  3762. if (time > last_time) // Make sure last_time hasn't overflowed
  3763. *dtime = (time - last_time) / 1000.0;
  3764. else
  3765. *dtime = 0;
  3766. fps_timings->last_time = time;
  3767. }
  3768. void Game::showOverlayMessage(const char *msg, float dtime, int percent, bool draw_clouds)
  3769. {
  3770. const wchar_t *wmsg = wgettext(msg);
  3771. RenderingEngine::draw_load_screen(wmsg, guienv, texture_src, dtime, percent,
  3772. draw_clouds);
  3773. delete[] wmsg;
  3774. }
  3775. void Game::settingChangedCallback(const std::string &setting_name, void *data)
  3776. {
  3777. ((Game *)data)->readSettings();
  3778. }
  3779. void Game::readSettings()
  3780. {
  3781. m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
  3782. m_cache_enable_clouds = g_settings->getBool("enable_clouds");
  3783. m_cache_enable_joysticks = g_settings->getBool("enable_joysticks");
  3784. m_cache_enable_particles = g_settings->getBool("enable_particles");
  3785. m_cache_enable_fog = g_settings->getBool("enable_fog");
  3786. m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
  3787. m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
  3788. m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
  3789. m_cache_enable_noclip = g_settings->getBool("noclip");
  3790. m_cache_enable_free_move = g_settings->getBool("free_move");
  3791. m_cache_fog_start = g_settings->getFloat("fog_start");
  3792. m_cache_cam_smoothing = 0;
  3793. if (g_settings->getBool("cinematic"))
  3794. m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
  3795. else
  3796. m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
  3797. m_cache_fog_start = rangelim(m_cache_fog_start, 0.0f, 0.99f);
  3798. m_cache_cam_smoothing = rangelim(m_cache_cam_smoothing, 0.01f, 1.0f);
  3799. m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
  3800. }
  3801. /****************************************************************************/
  3802. /****************************************************************************
  3803. Shutdown / cleanup
  3804. ****************************************************************************/
  3805. /****************************************************************************/
  3806. void Game::extendedResourceCleanup()
  3807. {
  3808. // Extended resource accounting
  3809. infostream << "Irrlicht resources after cleanup:" << std::endl;
  3810. infostream << "\tRemaining meshes : "
  3811. << RenderingEngine::get_mesh_cache()->getMeshCount() << std::endl;
  3812. infostream << "\tRemaining textures : "
  3813. << driver->getTextureCount() << std::endl;
  3814. for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
  3815. irr::video::ITexture *texture = driver->getTextureByIndex(i);
  3816. infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
  3817. << std::endl;
  3818. }
  3819. clearTextureNameCache();
  3820. infostream << "\tRemaining materials: "
  3821. << driver-> getMaterialRendererCount()
  3822. << " (note: irrlicht doesn't support removing renderers)" << std::endl;
  3823. }
  3824. #define GET_KEY_NAME(KEY) gettext(getKeySetting(#KEY).name())
  3825. void Game::showPauseMenu()
  3826. {
  3827. #ifdef __ANDROID__
  3828. static const std::string control_text = strgettext("Default Controls:\n"
  3829. "No menu visible:\n"
  3830. "- single tap: button activate\n"
  3831. "- double tap: place/use\n"
  3832. "- slide finger: look around\n"
  3833. "Menu/Inventory visible:\n"
  3834. "- double tap (outside):\n"
  3835. " -->close\n"
  3836. "- touch stack, touch slot:\n"
  3837. " --> move stack\n"
  3838. "- touch&drag, tap 2nd finger\n"
  3839. " --> place single item to slot\n"
  3840. );
  3841. #else
  3842. static const std::string control_text_template = strgettext("Controls:\n"
  3843. "- %s: move forwards\n"
  3844. "- %s: move backwards\n"
  3845. "- %s: move left\n"
  3846. "- %s: move right\n"
  3847. "- %s: jump/climb\n"
  3848. "- %s: sneak/go down\n"
  3849. "- %s: drop item\n"
  3850. "- %s: inventory\n"
  3851. "- Mouse: turn/look\n"
  3852. "- Mouse left: dig/punch\n"
  3853. "- Mouse right: place/use\n"
  3854. "- Mouse wheel: select item\n"
  3855. "- %s: chat\n"
  3856. );
  3857. char control_text_buf[600];
  3858. snprintf(control_text_buf, ARRLEN(control_text_buf), control_text_template.c_str(),
  3859. GET_KEY_NAME(keymap_forward),
  3860. GET_KEY_NAME(keymap_backward),
  3861. GET_KEY_NAME(keymap_left),
  3862. GET_KEY_NAME(keymap_right),
  3863. GET_KEY_NAME(keymap_jump),
  3864. GET_KEY_NAME(keymap_sneak),
  3865. GET_KEY_NAME(keymap_drop),
  3866. GET_KEY_NAME(keymap_inventory),
  3867. GET_KEY_NAME(keymap_chat)
  3868. );
  3869. std::string control_text = std::string(control_text_buf);
  3870. str_formspec_escape(control_text);
  3871. #endif
  3872. float ypos = simple_singleplayer_mode ? 0.7f : 0.1f;
  3873. std::ostringstream os;
  3874. os << FORMSPEC_VERSION_STRING << SIZE_TAG
  3875. << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
  3876. << strgettext("Continue") << "]";
  3877. if (!simple_singleplayer_mode) {
  3878. os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
  3879. << strgettext("Change Password") << "]";
  3880. } else {
  3881. os << "field[4.95,0;5,1.5;;" << strgettext("Game paused") << ";]";
  3882. }
  3883. #ifndef __ANDROID__
  3884. os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
  3885. << strgettext("Sound Volume") << "]";
  3886. os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
  3887. << strgettext("Change Keys") << "]";
  3888. #endif
  3889. os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
  3890. << strgettext("Exit to Menu") << "]";
  3891. os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
  3892. << strgettext("Exit to OS") << "]"
  3893. << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
  3894. << "textarea[0.4,0.25;3.9,6.25;;" << PROJECT_NAME_C " " VERSION_STRING "\n"
  3895. << "\n"
  3896. << strgettext("Game info:") << "\n";
  3897. const std::string &address = client->getAddressName();
  3898. static const std::string mode = strgettext("- Mode: ");
  3899. if (!simple_singleplayer_mode) {
  3900. Address serverAddress = client->getServerAddress();
  3901. if (!address.empty()) {
  3902. os << mode << strgettext("Remote server") << "\n"
  3903. << strgettext("- Address: ") << address;
  3904. } else {
  3905. os << mode << strgettext("Hosting server");
  3906. }
  3907. os << "\n" << strgettext("- Port: ") << serverAddress.getPort() << "\n";
  3908. } else {
  3909. os << mode << strgettext("Singleplayer") << "\n";
  3910. }
  3911. if (simple_singleplayer_mode || address.empty()) {
  3912. static const std::string on = strgettext("On");
  3913. static const std::string off = strgettext("Off");
  3914. const std::string &damage = g_settings->getBool("enable_damage") ? on : off;
  3915. const std::string &creative = g_settings->getBool("creative_mode") ? on : off;
  3916. const std::string &announced = g_settings->getBool("server_announce") ? on : off;
  3917. os << strgettext("- Damage: ") << damage << "\n"
  3918. << strgettext("- Creative Mode: ") << creative << "\n";
  3919. if (!simple_singleplayer_mode) {
  3920. const std::string &pvp = g_settings->getBool("enable_pvp") ? on : off;
  3921. os << strgettext("- PvP: ") << pvp << "\n"
  3922. << strgettext("- Public: ") << announced << "\n";
  3923. std::string server_name = g_settings->get("server_name");
  3924. str_formspec_escape(server_name);
  3925. if (announced == on && !server_name.empty())
  3926. os << strgettext("- Server Name: ") << server_name;
  3927. }
  3928. }
  3929. os << ";]";
  3930. /* Create menu */
  3931. /* Note: FormspecFormSource and LocalFormspecHandler *
  3932. * are deleted by guiFormSpecMenu */
  3933. FormspecFormSource *fs_src = new FormspecFormSource(os.str());
  3934. LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
  3935. create_formspec_menu(&current_formspec, client, &input->joystick, fs_src, txt_dst);
  3936. current_formspec->setFocus("btn_continue");
  3937. current_formspec->doPause = true;
  3938. }
  3939. /****************************************************************************/
  3940. /****************************************************************************
  3941. extern function for launching the game
  3942. ****************************************************************************/
  3943. /****************************************************************************/
  3944. void the_game(bool *kill,
  3945. bool random_input,
  3946. InputHandler *input,
  3947. const std::string &map_dir,
  3948. const std::string &playername,
  3949. const std::string &password,
  3950. const std::string &address, // If empty local server is created
  3951. u16 port,
  3952. std::string &error_message,
  3953. ChatBackend &chat_backend,
  3954. bool *reconnect_requested,
  3955. const SubgameSpec &gamespec, // Used for local game
  3956. bool simple_singleplayer_mode)
  3957. {
  3958. Game game;
  3959. /* Make a copy of the server address because if a local singleplayer server
  3960. * is created then this is updated and we don't want to change the value
  3961. * passed to us by the calling function
  3962. */
  3963. std::string server_address = address;
  3964. try {
  3965. if (game.startup(kill, random_input, input, map_dir,
  3966. playername, password, &server_address, port, error_message,
  3967. reconnect_requested, &chat_backend, gamespec,
  3968. simple_singleplayer_mode)) {
  3969. game.run();
  3970. game.shutdown();
  3971. }
  3972. } catch (SerializationError &e) {
  3973. error_message = std::string("A serialization error occurred:\n")
  3974. + e.what() + "\n\nThe server is probably "
  3975. " running a different version of " PROJECT_NAME_C ".";
  3976. errorstream << error_message << std::endl;
  3977. } catch (ServerError &e) {
  3978. error_message = e.what();
  3979. errorstream << "ServerError: " << error_message << std::endl;
  3980. } catch (ModError &e) {
  3981. error_message = e.what() + strgettext("\nCheck debug.txt for details.");
  3982. errorstream << "ModError: " << error_message << std::endl;
  3983. }
  3984. }