3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 #include "irrlichttypes_extrabloated.h"
22 #include <IGUICheckBox.h>
23 #include <IGUIEditBox.h>
24 #include <IGUIButton.h>
25 #include <IGUIStaticText.h>
27 #include <IMaterialRendererServices.h>
28 #include "IMeshCache.h"
31 #include "guiPauseMenu.h"
32 #include "guiPasswordChange.h"
33 #include "guiVolumeChange.h"
34 #include "guiFormSpecMenu.h"
35 #include "guiTextInputMenu.h"
36 #include "guiDeathScreen.h"
38 #include "guiChatConsole.h"
41 #include "particles.h"
47 #include "mainmenumanager.h"
51 // Needed for determining pointing to nodes
53 #include "nodemetadata.h"
54 #include "main.h" // For g_settings
56 #include "tile.h" // For TextureSource
57 #include "shader.h" // For ShaderSource
58 #include "logoutputbuffer.h"
60 #include "quicktune_shortcutter.h"
61 #include "clientmap.h"
66 #include "sound_openal.h"
68 #include "event_manager.h"
71 #include "util/directiontables.h"
77 struct TextDestChat : public TextDest
79 TextDestChat(Client *client)
83 void gotText(std::wstring text)
85 m_client->typeChatMessage(text);
87 void gotText(std::map<std::string, std::string> fields)
89 m_client->typeChatMessage(narrow_to_wide(fields["text"]));
95 struct TextDestNodeMetadata : public TextDest
97 TextDestNodeMetadata(v3s16 p, Client *client)
102 // This is deprecated I guess? -celeron55
103 void gotText(std::wstring text)
105 std::string ntext = wide_to_narrow(text);
106 infostream<<"Submitting 'text' field of node at ("<<m_p.X<<","
107 <<m_p.Y<<","<<m_p.Z<<"): "<<ntext<<std::endl;
108 std::map<std::string, std::string> fields;
109 fields["text"] = ntext;
110 m_client->sendNodemetaFields(m_p, "", fields);
112 void gotText(std::map<std::string, std::string> fields)
114 m_client->sendNodemetaFields(m_p, "", fields);
121 struct TextDestPlayerInventory : public TextDest
123 TextDestPlayerInventory(Client *client)
128 TextDestPlayerInventory(Client *client, std::string formname)
131 m_formname = formname;
133 void gotText(std::map<std::string, std::string> fields)
135 m_client->sendInventoryFields(m_formname, fields);
138 void setFormName(std::string formname) {
139 m_formname = formname;
143 std::string m_formname;
146 /* Respawn menu callback */
148 class MainRespawnInitiator: public IRespawnInitiator
151 MainRespawnInitiator(bool *active, Client *client):
152 m_active(active), m_client(client)
159 m_client->sendRespawn();
166 /* Form update callback */
168 class NodeMetadataFormSource: public IFormSource
171 NodeMetadataFormSource(ClientMap *map, v3s16 p):
176 std::string getForm()
178 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
181 return meta->getString("formspec");
183 std::string resolveText(std::string str)
185 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
188 return meta->resolveString(str);
195 class PlayerInventoryFormSource: public IFormSource
198 PlayerInventoryFormSource(Client *client):
202 std::string getForm()
204 LocalPlayer* player = m_client->getEnv().getLocalPlayer();
205 return player->inventory_formspec;
211 class FormspecFormSource: public IFormSource
214 FormspecFormSource(std::string formspec,FormspecFormSource** game_formspec)
216 m_formspec = formspec;
217 m_game_formspec = game_formspec;
220 ~FormspecFormSource()
222 *m_game_formspec = 0;
225 void setForm(std::string formspec) {
226 m_formspec = formspec;
229 std::string getForm()
234 std::string m_formspec;
235 FormspecFormSource** m_game_formspec;
239 Check if a node is pointable
241 inline bool isPointableNode(const MapNode& n,
242 Client *client, bool liquids_pointable)
244 const ContentFeatures &features = client->getNodeDefManager()->get(n);
245 return features.pointable ||
246 (liquids_pointable && features.isLiquid());
250 Find what the player is pointing at
252 PointedThing getPointedThing(Client *client, v3f player_position,
253 v3f camera_direction, v3f camera_position,
254 core::line3d<f32> shootline, f32 d,
255 bool liquids_pointable,
256 bool look_for_object,
257 std::vector<aabb3f> &hilightboxes,
258 ClientActiveObject *&selected_object)
262 hilightboxes.clear();
263 selected_object = NULL;
265 INodeDefManager *nodedef = client->getNodeDefManager();
266 ClientMap &map = client->getEnv().getClientMap();
268 // First try to find a pointed at active object
271 selected_object = client->getSelectedActiveObject(d*BS,
272 camera_position, shootline);
274 if(selected_object != NULL)
276 if(selected_object->doShowSelectionBox())
278 aabb3f *selection_box = selected_object->getSelectionBox();
279 // Box should exist because object was
280 // returned in the first place
281 assert(selection_box);
283 v3f pos = selected_object->getPosition();
284 hilightboxes.push_back(aabb3f(
285 selection_box->MinEdge + pos,
286 selection_box->MaxEdge + pos));
290 result.type = POINTEDTHING_OBJECT;
291 result.object_id = selected_object->getId();
296 // That didn't work, try to find a pointed at node
298 f32 mindistance = BS * 1001;
300 v3s16 pos_i = floatToInt(player_position, BS);
302 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
306 s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
307 s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
308 s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
309 s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
310 s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
311 s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
313 // Prevent signed number overflow
321 for(s16 y = ystart; y <= yend; y++)
322 for(s16 z = zstart; z <= zend; z++)
323 for(s16 x = xstart; x <= xend; x++)
328 n = map.getNode(v3s16(x,y,z));
330 catch(InvalidPositionException &e)
334 if(!isPointableNode(n, client, liquids_pointable))
337 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
340 v3f npf = intToFloat(np, BS);
342 for(std::vector<aabb3f>::const_iterator
344 i != boxes.end(); i++)
350 for(u16 j=0; j<6; j++)
352 v3s16 facedir = g_6dirs[j];
353 aabb3f facebox = box;
357 facebox.MinEdge.X = facebox.MaxEdge.X-d;
358 else if(facedir.X < 0)
359 facebox.MaxEdge.X = facebox.MinEdge.X+d;
360 else if(facedir.Y > 0)
361 facebox.MinEdge.Y = facebox.MaxEdge.Y-d;
362 else if(facedir.Y < 0)
363 facebox.MaxEdge.Y = facebox.MinEdge.Y+d;
364 else if(facedir.Z > 0)
365 facebox.MinEdge.Z = facebox.MaxEdge.Z-d;
366 else if(facedir.Z < 0)
367 facebox.MaxEdge.Z = facebox.MinEdge.Z+d;
369 v3f centerpoint = facebox.getCenter();
370 f32 distance = (centerpoint - camera_position).getLength();
371 if(distance >= mindistance)
373 if(!facebox.intersectsWithLine(shootline))
376 v3s16 np_above = np + facedir;
378 result.type = POINTEDTHING_NODE;
379 result.node_undersurface = np;
380 result.node_abovesurface = np_above;
381 mindistance = distance;
383 hilightboxes.clear();
384 for(std::vector<aabb3f>::const_iterator
386 i2 != boxes.end(); i2++)
389 box.MinEdge += npf + v3f(-d,-d,-d);
390 box.MaxEdge += npf + v3f(d,d,d);
391 hilightboxes.push_back(box);
401 Draws a screen with a single text on it.
402 Text will be removed when the screen is drawn the next time.
403 Additionally, a progressbar can be drawn when percent is set between 0 and 100.
405 /*gui::IGUIStaticText **/
406 void draw_load_screen(const std::wstring &text,
407 IrrlichtDevice* device, gui::IGUIFont* font,
408 float dtime=0 ,int percent=0, bool clouds=true)
410 video::IVideoDriver* driver = device->getVideoDriver();
411 v2u32 screensize = driver->getScreenSize();
412 const wchar_t *loadingtext = text.c_str();
413 core::vector2d<u32> textsize_u = font->getDimension(loadingtext);
414 core::vector2d<s32> textsize(textsize_u.X,textsize_u.Y);
415 core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
416 core::rect<s32> textrect(center - textsize/2, center + textsize/2);
418 gui::IGUIStaticText *guitext = guienv->addStaticText(
419 loadingtext, textrect, false, false);
420 guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
422 bool cloud_menu_background = clouds && g_settings->getBool("menu_clouds");
423 if (cloud_menu_background)
425 g_menuclouds->step(dtime*3);
426 g_menuclouds->render();
427 driver->beginScene(true, true, video::SColor(255,140,186,250));
428 g_menucloudsmgr->drawAll();
431 driver->beginScene(true, true, video::SColor(255,0,0,0));
432 if (percent >= 0 && percent <= 100) // draw progress bar
434 core::vector2d<s32> barsize(256,32);
435 core::rect<s32> barrect(center-barsize/2, center+barsize/2);
436 driver->draw2DRectangle(video::SColor(255,255,255,255),barrect, NULL); // border
437 driver->draw2DRectangle(video::SColor(255,64,64,64), core::rect<s32> (
438 barrect.UpperLeftCorner+1,
439 barrect.LowerRightCorner-1), NULL); // black inside the bar
440 driver->draw2DRectangle(video::SColor(255,128,128,128), core::rect<s32> (
441 barrect.UpperLeftCorner+1,
443 barrect.LowerRightCorner.X-(barsize.X-1)+percent*(barsize.X-2)/100,
444 barrect.LowerRightCorner.Y-1)), NULL); // the actual progress
454 /* Profiler display */
456 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler,
457 gui::IGUIFont *font, u32 text_height,
458 u32 show_profiler, u32 show_profiler_max)
460 if(show_profiler == 0)
462 guitext_profiler->setVisible(false);
467 std::ostringstream os(std::ios_base::binary);
468 g_profiler->printPage(os, show_profiler, show_profiler_max);
469 std::wstring text = narrow_to_wide(os.str());
470 guitext_profiler->setText(text.c_str());
471 guitext_profiler->setVisible(true);
473 s32 w = font->getDimension(text.c_str()).Width;
476 core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
477 8+(text_height+5)*2 +
478 font->getDimension(text.c_str()).Height);
479 guitext_profiler->setRelativePosition(rect);
480 guitext_profiler->setVisible(true);
488 Profiler::GraphValues values;
494 Meta(float initial=0, video::SColor color=
495 video::SColor(255,255,255,255)):
501 std::list<Piece> m_log;
509 void put(const Profiler::GraphValues &values)
512 piece.values = values;
513 m_log.push_back(piece);
514 while(m_log.size() > m_log_max_size)
515 m_log.erase(m_log.begin());
518 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
519 gui::IGUIFont* font) const
521 std::map<std::string, Meta> m_meta;
522 for(std::list<Piece>::const_iterator k = m_log.begin();
523 k != m_log.end(); k++)
525 const Piece &piece = *k;
526 for(Profiler::GraphValues::const_iterator i = piece.values.begin();
527 i != piece.values.end(); i++){
528 const std::string &id = i->first;
529 const float &value = i->second;
530 std::map<std::string, Meta>::iterator j =
532 if(j == m_meta.end()){
533 m_meta[id] = Meta(value);
536 if(value < j->second.min)
537 j->second.min = value;
538 if(value > j->second.max)
539 j->second.max = value;
544 static const video::SColor usable_colors[] = {
545 video::SColor(255,255,100,100),
546 video::SColor(255,90,225,90),
547 video::SColor(255,100,100,255),
548 video::SColor(255,255,150,50),
549 video::SColor(255,220,220,100)
551 static const u32 usable_colors_count =
552 sizeof(usable_colors) / sizeof(*usable_colors);
553 u32 next_color_i = 0;
554 for(std::map<std::string, Meta>::iterator i = m_meta.begin();
555 i != m_meta.end(); i++){
556 Meta &meta = i->second;
557 video::SColor color(255,200,200,200);
558 if(next_color_i < usable_colors_count)
559 color = usable_colors[next_color_i++];
564 s32 textx = x_left + m_log_max_size + 15;
565 s32 textx2 = textx + 200 - 15;
569 u32 num_graphs = m_meta.size();
570 core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
572 video::SColor bgcolor(120,0,0,0);
573 driver->draw2DRectangle(bgcolor, rect, NULL);
577 for(std::map<std::string, Meta>::const_iterator i = m_meta.begin();
578 i != m_meta.end(); i++){
579 const std::string &id = i->first;
580 const Meta &meta = i->second;
582 s32 y = y_bottom - meta_i * 50;
583 float show_min = meta.min;
584 float show_max = meta.max;
585 if(show_min >= -0.0001 && show_max >= -0.0001){
586 if(show_min <= show_max * 0.5)
591 snprintf(buf, 10, "%.3g", show_max);
592 font->draw(narrow_to_wide(buf).c_str(),
593 core::rect<s32>(textx, y - graphh,
594 textx2, y - graphh + texth),
596 snprintf(buf, 10, "%.3g", show_min);
597 font->draw(narrow_to_wide(buf).c_str(),
598 core::rect<s32>(textx, y - texth,
601 font->draw(narrow_to_wide(id).c_str(),
602 core::rect<s32>(textx, y - graphh/2 - texth/2,
603 textx2, y - graphh/2 + texth/2),
606 s32 graph1h = graphh;
607 bool relativegraph = (show_min != 0 && show_min != show_max);
608 float lastscaledvalue = 0.0;
609 bool lastscaledvalue_exists = false;
610 for(std::list<Piece>::const_iterator j = m_log.begin();
611 j != m_log.end(); j++)
613 const Piece &piece = *j;
615 bool value_exists = false;
616 Profiler::GraphValues::const_iterator k =
617 piece.values.find(id);
618 if(k != piece.values.end()){
624 lastscaledvalue_exists = false;
627 float scaledvalue = 1.0;
628 if(show_max != show_min)
629 scaledvalue = (value - show_min) / (show_max - show_min);
630 if(scaledvalue == 1.0 && value == 0){
632 lastscaledvalue_exists = false;
636 if(lastscaledvalue_exists){
637 s32 ivalue1 = lastscaledvalue * graph1h;
638 s32 ivalue2 = scaledvalue * graph1h;
639 driver->draw2DLine(v2s32(x-1, graph1y - ivalue1),
640 v2s32(x, graph1y - ivalue2), meta.color);
642 lastscaledvalue = scaledvalue;
643 lastscaledvalue_exists = true;
645 s32 ivalue = scaledvalue * graph1h;
646 driver->draw2DLine(v2s32(x, graph1y),
647 v2s32(x, graph1y - ivalue), meta.color);
656 class NodeDugEvent: public MtEvent
662 NodeDugEvent(v3s16 p, MapNode n):
666 const char* getType() const
672 ISoundManager *m_sound;
673 INodeDefManager *m_ndef;
675 float m_player_step_timer;
677 SimpleSoundSpec m_player_step_sound;
678 SimpleSoundSpec m_player_leftpunch_sound;
679 SimpleSoundSpec m_player_rightpunch_sound;
681 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
684 m_player_step_timer(0)
688 void playPlayerStep()
690 if(m_player_step_timer <= 0 && m_player_step_sound.exists()){
691 m_player_step_timer = 0.03;
692 m_sound->playSound(m_player_step_sound, false);
696 static void viewBobbingStep(MtEvent *e, void *data)
698 SoundMaker *sm = (SoundMaker*)data;
699 sm->playPlayerStep();
702 static void playerRegainGround(MtEvent *e, void *data)
704 SoundMaker *sm = (SoundMaker*)data;
705 sm->playPlayerStep();
708 static void playerJump(MtEvent *e, void *data)
710 //SoundMaker *sm = (SoundMaker*)data;
713 static void cameraPunchLeft(MtEvent *e, void *data)
715 SoundMaker *sm = (SoundMaker*)data;
716 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
719 static void cameraPunchRight(MtEvent *e, void *data)
721 SoundMaker *sm = (SoundMaker*)data;
722 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
725 static void nodeDug(MtEvent *e, void *data)
727 SoundMaker *sm = (SoundMaker*)data;
728 NodeDugEvent *nde = (NodeDugEvent*)e;
729 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
732 static void playerDamage(MtEvent *e, void *data)
734 SoundMaker *sm = (SoundMaker*)data;
735 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
738 static void playerFallingDamage(MtEvent *e, void *data)
740 SoundMaker *sm = (SoundMaker*)data;
741 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
744 void registerReceiver(MtEventManager *mgr)
746 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
747 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
748 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
749 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
750 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
751 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
752 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
753 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
756 void step(float dtime)
758 m_player_step_timer -= dtime;
762 // Locally stored sounds don't need to be preloaded because of this
763 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
765 std::set<std::string> m_fetched;
768 void fetchSounds(const std::string &name,
769 std::set<std::string> &dst_paths,
770 std::set<std::string> &dst_datas)
772 if(m_fetched.count(name))
774 m_fetched.insert(name);
775 std::string base = porting::path_share + DIR_DELIM + "testsounds";
776 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
777 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
778 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
779 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
780 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
781 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
782 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
783 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
784 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
785 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
786 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
790 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
793 bool *m_force_fog_off;
798 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
799 f32 *fog_range, Client *client):
801 m_force_fog_off(force_fog_off),
802 m_fog_range(fog_range),
805 ~GameGlobalShaderConstantSetter() {}
807 virtual void onSetConstants(video::IMaterialRendererServices *services,
814 video::SColor bgcolor = m_sky->getBgColor();
815 video::SColorf bgcolorf(bgcolor);
816 float bgcolorfa[4] = {
822 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
825 float fog_distance = *m_fog_range;
827 fog_distance = 10000*BS;
828 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
831 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
832 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
833 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
837 bool nodePlacementPrediction(Client &client,
838 const ItemDefinition &playeritem_def,
839 v3s16 nodepos, v3s16 neighbourpos)
841 std::string prediction = playeritem_def.node_placement_prediction;
842 INodeDefManager *nodedef = client.ndef();
843 ClientMap &map = client.getEnv().getClientMap();
845 if(prediction != "" && !nodedef->get(map.getNode(nodepos)).rightclickable)
847 verbosestream<<"Node placement prediction for "
848 <<playeritem_def.name<<" is "
849 <<prediction<<std::endl;
850 v3s16 p = neighbourpos;
851 // Place inside node itself if buildable_to
853 MapNode n_under = map.getNode(nodepos);
854 if(nodedef->get(n_under).buildable_to)
856 else if (!nodedef->get(map.getNode(p)).buildable_to)
858 }catch(InvalidPositionException &e){}
859 // Find id of predicted node
861 bool found = nodedef->getId(prediction, id);
863 errorstream<<"Node placement prediction failed for "
864 <<playeritem_def.name<<" (places "
866 <<") - Name not known"<<std::endl;
869 // Predict param2 for facedir and wallmounted nodes
871 if(nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED){
872 v3s16 dir = nodepos - neighbourpos;
873 if(abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))){
874 param2 = dir.Y < 0 ? 1 : 0;
875 } else if(abs(dir.X) > abs(dir.Z)){
876 param2 = dir.X < 0 ? 3 : 2;
878 param2 = dir.Z < 0 ? 5 : 4;
881 if(nodedef->get(id).param_type_2 == CPT2_FACEDIR){
882 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
883 if(abs(dir.X) > abs(dir.Z)){
884 param2 = dir.X < 0 ? 3 : 1;
886 param2 = dir.Z < 0 ? 2 : 0;
889 assert(param2 >= 0 && param2 <= 5);
890 //Check attachment if node is in group attached_node
891 if(((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0){
892 static v3s16 wallmounted_dirs[8] = {
901 if(nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
902 pp = p + wallmounted_dirs[param2];
904 pp = p + v3s16(0,-1,0);
905 if(!nodedef->get(map.getNode(pp)).walkable)
908 // Add node to client map
909 MapNode n(id, 0, param2);
911 // This triggers the required mesh update too
912 client.addNode(p, n);
914 }catch(InvalidPositionException &e){
915 errorstream<<"Node placement prediction failed for "
916 <<playeritem_def.name<<" (places "
918 <<") - Position not loaded"<<std::endl;
929 IrrlichtDevice *device,
932 std::string playername,
933 std::string password,
934 std::string address, // If "", local server is used
936 std::wstring &error_message,
937 std::string configpath,
938 ChatBackend &chat_backend,
939 const SubgameSpec &gamespec, // Used for local game,
940 bool simple_singleplayer_mode
943 FormspecFormSource* current_formspec = 0;
944 TextDestPlayerInventory* current_textdest = 0;
945 video::IVideoDriver* driver = device->getVideoDriver();
946 scene::ISceneManager* smgr = device->getSceneManager();
948 // Calculate text height using the font
949 u32 text_height = font->getDimension(L"Random test string").Height;
951 v2u32 last_screensize(0,0);
952 v2u32 screensize = driver->getScreenSize();
955 Draw "Loading" screen
959 wchar_t* text = wgettext("Loading...");
960 draw_load_screen(text, device, font,0,0);
964 // Create texture source
965 IWritableTextureSource *tsrc = createTextureSource(device);
967 // Create shader source
968 IWritableShaderSource *shsrc = createShaderSource(device);
970 // These will be filled by data received from the server
971 // Create item definition manager
972 IWritableItemDefManager *itemdef = createItemDefManager();
973 // Create node definition manager
974 IWritableNodeDefManager *nodedef = createNodeDefManager();
976 // Sound fetcher (useful when testing)
977 GameOnDemandSoundFetcher soundfetcher;
980 ISoundManager *sound = NULL;
981 bool sound_is_dummy = false;
983 if(g_settings->getBool("enable_sound")){
984 infostream<<"Attempting to use OpenAL audio"<<std::endl;
985 sound = createOpenALSoundManager(&soundfetcher);
987 infostream<<"Failed to initialize OpenAL audio"<<std::endl;
989 infostream<<"Sound disabled."<<std::endl;
993 infostream<<"Using dummy audio."<<std::endl;
994 sound = &dummySoundManager;
995 sound_is_dummy = true;
998 Server *server = NULL;
1002 EventManager eventmgr;
1005 SoundMaker soundmaker(sound, nodedef);
1006 soundmaker.registerReceiver(&eventmgr);
1008 // Add chat log output for errors to be shown in chat
1009 LogOutputBuffer chat_log_error_buf(LMT_ERROR);
1011 // Create UI for modifying quicktune values
1012 QuicktuneShortcutter quicktune;
1019 wchar_t* text = wgettext("Creating server....");
1020 draw_load_screen(text, device, font,0,25);
1022 infostream<<"Creating server"<<std::endl;
1023 server = new Server(map_dir, configpath, gamespec,
1024 simple_singleplayer_mode);
1025 server->start(port);
1028 do{ // Client scope (breakable do-while(0))
1035 wchar_t* text = wgettext("Creating client...");
1036 draw_load_screen(text, device, font,0,50);
1039 infostream<<"Creating client"<<std::endl;
1041 MapDrawControl draw_control;
1044 wchar_t* text = wgettext("Resolving address...");
1045 draw_load_screen(text, device, font,0,75);
1048 Address connect_address(0,0,0,0, port);
1052 //connect_address.Resolve("localhost");
1053 if(g_settings->getBool("enable_ipv6") && g_settings->getBool("ipv6_server"))
1055 IPv6AddressBytes addr_bytes;
1056 addr_bytes.bytes[15] = 1;
1057 connect_address.setAddress(&addr_bytes);
1061 connect_address.setAddress(127,0,0,1);
1065 connect_address.Resolve(address.c_str());
1067 catch(ResolveError &e)
1069 error_message = L"Couldn't resolve address: " + narrow_to_wide(e.what());
1070 errorstream<<wide_to_narrow(error_message)<<std::endl;
1071 // Break out of client scope
1078 Client client(device, playername.c_str(), password, draw_control,
1079 tsrc, shsrc, itemdef, nodedef, sound, &eventmgr,
1080 connect_address.isIPv6());
1082 // Client acts as our GameDef
1083 IGameDef *gamedef = &client;
1086 Attempt to connect to the server
1089 infostream<<"Connecting to server at ";
1090 connect_address.print(&infostream);
1091 infostream<<std::endl;
1092 client.connect(connect_address);
1095 Wait for server to accept connection
1097 bool could_connect = false;
1098 bool connect_aborted = false;
1100 float time_counter = 0.0;
1102 float fps_max = g_settings->getFloat("fps_max");
1103 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1104 u32 lasttime = device->getTimer()->getTime();
1105 while(device->run())
1107 f32 dtime = 0.033; // in seconds
1108 if (cloud_menu_background) {
1109 u32 time = device->getTimer()->getTime();
1111 dtime = (time - lasttime) / 1000.0;
1116 // Update client and server
1119 server->step(dtime);
1122 if(client.connectedAndInitialized()){
1123 could_connect = true;
1127 if(client.accessDenied()){
1128 error_message = L"Access denied. Reason: "
1129 +client.accessDeniedReason();
1130 errorstream<<wide_to_narrow(error_message)<<std::endl;
1133 if(input->wasKeyDown(EscapeKey)){
1134 connect_aborted = true;
1135 infostream<<"Connect aborted [Escape]"<<std::endl;
1141 wchar_t* text = wgettext("Connecting to server...");
1142 draw_load_screen(text, device, font, dtime, 100);
1146 // On some computers framerate doesn't seem to be
1147 // automatically limited
1148 if (cloud_menu_background) {
1149 // Time of frame without fps limit
1152 // not using getRealTime is necessary for wine
1153 u32 time = device->getTimer()->getTime();
1155 busytime_u32 = time - lasttime;
1158 busytime = busytime_u32 / 1000.0;
1161 u32 frametime_min = 1000./fps_max;
1163 if(busytime_u32 < frametime_min) {
1164 u32 sleeptime = frametime_min - busytime_u32;
1165 device->sleep(sleeptime);
1170 time_counter += dtime;
1173 catch(con::PeerNotFoundException &e)
1177 Handle failure to connect
1180 if(error_message == L"" && !connect_aborted){
1181 error_message = L"Connection failed";
1182 errorstream<<wide_to_narrow(error_message)<<std::endl;
1184 // Break out of client scope
1189 Wait until content has been received
1191 bool got_content = false;
1192 bool content_aborted = false;
1194 float time_counter = 0.0;
1196 float fps_max = g_settings->getFloat("fps_max");
1197 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1198 u32 lasttime = device->getTimer()->getTime();
1199 while(device->run())
1201 f32 dtime = 0.033; // in seconds
1202 if (cloud_menu_background) {
1203 u32 time = device->getTimer()->getTime();
1205 dtime = (time - lasttime) / 1000.0;
1210 // Update client and server
1213 server->step(dtime);
1216 if(client.texturesReceived() &&
1217 client.itemdefReceived() &&
1218 client.nodedefReceived()){
1223 if(!client.connectedAndInitialized()){
1224 error_message = L"Client disconnected";
1225 errorstream<<wide_to_narrow(error_message)<<std::endl;
1228 if(input->wasKeyDown(EscapeKey)){
1229 content_aborted = true;
1230 infostream<<"Connect aborted [Escape]"<<std::endl;
1235 std::ostringstream ss;
1237 if (!client.itemdefReceived())
1239 ss << "Item definitions...";
1242 else if (!client.nodedefReceived())
1244 ss << "Node definitions...";
1250 progress = 50+client.mediaReceiveProgress()*50+0.5;
1252 wchar_t* text = wgettext(ss.str().c_str());
1253 draw_load_screen(text, device, font, dtime, progress);
1256 // On some computers framerate doesn't seem to be
1257 // automatically limited
1258 if (cloud_menu_background) {
1259 // Time of frame without fps limit
1262 // not using getRealTime is necessary for wine
1263 u32 time = device->getTimer()->getTime();
1265 busytime_u32 = time - lasttime;
1268 busytime = busytime_u32 / 1000.0;
1271 u32 frametime_min = 1000./fps_max;
1273 if(busytime_u32 < frametime_min) {
1274 u32 sleeptime = frametime_min - busytime_u32;
1275 device->sleep(sleeptime);
1280 time_counter += dtime;
1285 if(error_message == L"" && !content_aborted){
1286 error_message = L"Something failed";
1287 errorstream<<wide_to_narrow(error_message)<<std::endl;
1289 // Break out of client scope
1294 After all content has been received:
1295 Update cached textures, meshes and materials
1297 client.afterContentReceived(device,font);
1300 Create the camera node
1302 Camera camera(smgr, draw_control, gamedef);
1303 if (!camera.successfullyCreated(error_message))
1306 f32 camera_yaw = 0; // "right/left"
1307 f32 camera_pitch = 0; // "up/down"
1313 Clouds *clouds = NULL;
1314 if(g_settings->getBool("enable_clouds"))
1316 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1324 sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1330 FarMesh *farmesh = NULL;
1331 if(g_settings->getBool("enable_farmesh"))
1333 farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
1337 A copy of the local inventory
1339 Inventory local_inventory(itemdef);
1342 Find out size of crack animation
1344 int crack_animation_length = 5;
1346 video::ITexture *t = tsrc->getTextureRaw("crack_anylength.png");
1347 v2u32 size = t->getOriginalSize();
1348 crack_animation_length = size.Y / size.X;
1355 // First line of debug text
1356 gui::IGUIStaticText *guitext = guienv->addStaticText(
1358 core::rect<s32>(5, 5, 795, 5+text_height),
1360 // Second line of debug text
1361 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1363 core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
1365 // At the middle of the screen
1366 // Object infos are shown in this
1367 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1369 core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1372 // Status text (displays info when showing and hiding GUI stuff, etc.)
1373 gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1375 core::rect<s32>(0,0,0,0),
1377 guitext_status->setVisible(false);
1379 std::wstring statustext;
1380 float statustext_time = 0;
1383 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1385 core::rect<s32>(0,0,0,0),
1386 //false, false); // Disable word wrap as of now
1388 // Remove stale "recent" chat messages from previous connections
1389 chat_backend.clearRecentChat();
1390 // Chat backend and console
1391 GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1393 // Profiler text (size is updated when text is updated)
1394 gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1396 core::rect<s32>(0,0,0,0),
1398 guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1399 guitext_profiler->setVisible(false);
1400 guitext_profiler->setWordWrap(true);
1403 Some statistics are collected in these
1406 u32 beginscenetime = 0;
1408 u32 endscenetime = 0;
1410 float recent_turn_speed = 0.0;
1412 ProfilerGraph graph;
1413 // Initially clear the profiler
1414 Profiler::GraphValues dummyvalues;
1415 g_profiler->graphGet(dummyvalues);
1417 float nodig_delay_timer = 0.0;
1418 float dig_time = 0.0;
1420 PointedThing pointed_old;
1421 bool digging = false;
1422 bool ldown_for_dig = false;
1424 float damage_flash = 0;
1425 s16 farmesh_range = 20*MAP_BLOCKSIZE;
1427 float jump_timer = 0;
1428 bool reset_jump_timer = false;
1430 const float object_hit_delay = 0.2;
1431 float object_hit_delay_timer = 0.0;
1432 float time_from_last_punch = 10;
1434 float update_draw_list_timer = 0.0;
1435 v3f update_draw_list_last_cam_dir;
1437 bool invert_mouse = g_settings->getBool("invert_mouse");
1439 bool respawn_menu_active = false;
1440 bool update_wielded_item_trigger = false;
1442 bool show_hud = true;
1443 bool show_chat = true;
1444 bool force_fog_off = false;
1445 f32 fog_range = 100*BS;
1446 bool disable_camera_update = false;
1447 bool show_debug = g_settings->getBool("show_debug");
1448 bool show_profiler_graph = false;
1449 u32 show_profiler = 0;
1450 u32 show_profiler_max = 3; // Number of pages
1452 float time_of_day = 0;
1453 float time_of_day_smooth = 0;
1455 float repeat_rightclick_timer = 0;
1460 shsrc->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1461 sky, &force_fog_off, &fog_range, &client));
1467 bool first_loop_after_window_activation = true;
1469 // TODO: Convert the static interval timers to these
1470 // Interval limiter for profiler
1471 IntervalLimiter m_profiler_interval;
1473 // Time is in milliseconds
1474 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1475 // NOTE: So we have to use getTime() and call run()s between them
1476 u32 lasttime = device->getTimer()->getTime();
1478 LocalPlayer* player = client.getEnv().getLocalPlayer();
1479 player->hurt_tilt_timer = 0;
1480 player->hurt_tilt_strength = 0;
1485 Hud hud(driver, guienv, font, text_height,
1486 gamedef, player, &local_inventory);
1490 if(device->run() == false || kill == true)
1493 // Time of frame without fps limit
1497 // not using getRealTime is necessary for wine
1498 u32 time = device->getTimer()->getTime();
1500 busytime_u32 = time - lasttime;
1503 busytime = busytime_u32 / 1000.0;
1506 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1508 // Necessary for device->getTimer()->getTime()
1516 float fps_max = g_settings->getFloat("fps_max");
1517 u32 frametime_min = 1000./fps_max;
1519 if(busytime_u32 < frametime_min)
1521 u32 sleeptime = frametime_min - busytime_u32;
1522 device->sleep(sleeptime);
1523 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1527 // Necessary for device->getTimer()->getTime()
1531 Time difference calculation
1533 f32 dtime; // in seconds
1535 u32 time = device->getTimer()->getTime();
1537 dtime = (time - lasttime) / 1000.0;
1542 g_profiler->graphAdd("mainloop_dtime", dtime);
1546 if(nodig_delay_timer >= 0)
1547 nodig_delay_timer -= dtime;
1548 if(object_hit_delay_timer >= 0)
1549 object_hit_delay_timer -= dtime;
1550 time_from_last_punch += dtime;
1552 g_profiler->add("Elapsed time", dtime);
1553 g_profiler->avg("FPS", 1./dtime);
1556 Time average and jitter calculation
1559 static f32 dtime_avg1 = 0.0;
1560 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1561 f32 dtime_jitter1 = dtime - dtime_avg1;
1563 static f32 dtime_jitter1_max_sample = 0.0;
1564 static f32 dtime_jitter1_max_fraction = 0.0;
1566 static f32 jitter1_max = 0.0;
1567 static f32 counter = 0.0;
1568 if(dtime_jitter1 > jitter1_max)
1569 jitter1_max = dtime_jitter1;
1574 dtime_jitter1_max_sample = jitter1_max;
1575 dtime_jitter1_max_fraction
1576 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1582 Busytime average and jitter calculation
1585 static f32 busytime_avg1 = 0.0;
1586 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1587 f32 busytime_jitter1 = busytime - busytime_avg1;
1589 static f32 busytime_jitter1_max_sample = 0.0;
1590 static f32 busytime_jitter1_min_sample = 0.0;
1592 static f32 jitter1_max = 0.0;
1593 static f32 jitter1_min = 0.0;
1594 static f32 counter = 0.0;
1595 if(busytime_jitter1 > jitter1_max)
1596 jitter1_max = busytime_jitter1;
1597 if(busytime_jitter1 < jitter1_min)
1598 jitter1_min = busytime_jitter1;
1602 busytime_jitter1_max_sample = jitter1_max;
1603 busytime_jitter1_min_sample = jitter1_min;
1610 Handle miscellaneous stuff
1613 if(client.accessDenied())
1615 error_message = L"Access denied. Reason: "
1616 +client.accessDeniedReason();
1617 errorstream<<wide_to_narrow(error_message)<<std::endl;
1621 if(g_gamecallback->disconnect_requested)
1623 g_gamecallback->disconnect_requested = false;
1627 if(g_gamecallback->changepassword_requested)
1629 (new GUIPasswordChange(guienv, guiroot, -1,
1630 &g_menumgr, &client))->drop();
1631 g_gamecallback->changepassword_requested = false;
1634 if(g_gamecallback->changevolume_requested)
1636 (new GUIVolumeChange(guienv, guiroot, -1,
1637 &g_menumgr, &client))->drop();
1638 g_gamecallback->changevolume_requested = false;
1641 /* Process TextureSource's queue */
1642 tsrc->processQueue();
1644 /* Process ItemDefManager's queue */
1645 itemdef->processQueue(gamedef);
1648 Process ShaderSource's queue
1650 shsrc->processQueue();
1655 last_screensize = screensize;
1656 screensize = driver->getScreenSize();
1657 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1658 //bool screensize_changed = screensize != last_screensize;
1661 // Update HUD values
1662 hud.screensize = screensize;
1663 hud.displaycenter = displaycenter;
1666 // Hilight boxes collected during the loop and displayed
1667 std::vector<aabb3f> hilightboxes;
1670 std::wstring infotext;
1673 Debug info for client
1676 static float counter = 0.0;
1681 client.printDebugInfo(infostream);
1688 float profiler_print_interval =
1689 g_settings->getFloat("profiler_print_interval");
1690 bool print_to_log = true;
1691 if(profiler_print_interval == 0){
1692 print_to_log = false;
1693 profiler_print_interval = 5;
1695 if(m_profiler_interval.step(dtime, profiler_print_interval))
1698 infostream<<"Profiler:"<<std::endl;
1699 g_profiler->print(infostream);
1702 update_profiler_gui(guitext_profiler, font, text_height,
1703 show_profiler, show_profiler_max);
1705 g_profiler->clear();
1709 Direct handling of user input
1712 // Reset input if window not active or some menu is active
1713 if(device->isWindowActive() == false
1714 || noMenuActive() == false
1715 || guienv->hasFocus(gui_chat_console))
1719 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen())
1721 gui_chat_console->closeConsoleAtOnce();
1724 // Input handler step() (used by the random input generator)
1727 // Increase timer for doubleclick of "jump"
1728 if(g_settings->getBool("doubletap_jump") && jump_timer <= 0.2)
1729 jump_timer += dtime;
1732 Launch menus and trigger stuff according to keys
1734 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1736 // drop selected item
1737 IDropAction *a = new IDropAction();
1739 a->from_inv.setCurrentPlayer();
1740 a->from_list = "main";
1741 a->from_i = client.getPlayerItem();
1742 client.inventoryAction(a);
1744 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1746 infostream<<"the_game: "
1747 <<"Launching inventory"<<std::endl;
1749 GUIFormSpecMenu *menu =
1750 new GUIFormSpecMenu(device, guiroot, -1,
1754 InventoryLocation inventoryloc;
1755 inventoryloc.setCurrentPlayer();
1757 PlayerInventoryFormSource *src = new PlayerInventoryFormSource(&client);
1759 menu->setFormSpec(src->getForm(), inventoryloc);
1760 menu->setFormSource(src);
1761 menu->setTextDest(new TextDestPlayerInventory(&client));
1764 else if(input->wasKeyDown(EscapeKey))
1766 infostream<<"the_game: "
1767 <<"Launching pause menu"<<std::endl;
1768 // It will delete itself by itself
1769 (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1770 &g_menumgr, simple_singleplayer_mode))->drop();
1772 // Move mouse cursor on top of the disconnect button
1773 if(simple_singleplayer_mode)
1774 input->setMousePos(displaycenter.X, displaycenter.Y+0);
1776 input->setMousePos(displaycenter.X, displaycenter.Y+25);
1778 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1780 TextDest *dest = new TextDestChat(&client);
1782 (new GUITextInputMenu(guienv, guiroot, -1,
1786 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1788 TextDest *dest = new TextDestChat(&client);
1790 (new GUITextInputMenu(guienv, guiroot, -1,
1794 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1796 if (!gui_chat_console->isOpenInhibited())
1798 // Open up to over half of the screen
1799 gui_chat_console->openConsole(0.6);
1800 guienv->setFocus(gui_chat_console);
1803 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1805 if(g_settings->getBool("free_move"))
1807 g_settings->set("free_move","false");
1808 statustext = L"free_move disabled";
1809 statustext_time = 0;
1813 g_settings->set("free_move","true");
1814 statustext = L"free_move enabled";
1815 statustext_time = 0;
1816 if(!client.checkPrivilege("fly"))
1817 statustext += L" (note: no 'fly' privilege)";
1820 else if(input->wasKeyDown(getKeySetting("keymap_jump")))
1822 if(g_settings->getBool("doubletap_jump") && jump_timer < 0.2)
1824 if(g_settings->getBool("free_move"))
1826 g_settings->set("free_move","false");
1827 statustext = L"free_move disabled";
1828 statustext_time = 0;
1832 g_settings->set("free_move","true");
1833 statustext = L"free_move enabled";
1834 statustext_time = 0;
1835 if(!client.checkPrivilege("fly"))
1836 statustext += L" (note: no 'fly' privilege)";
1839 reset_jump_timer = true;
1841 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1843 if(g_settings->getBool("fast_move"))
1845 g_settings->set("fast_move","false");
1846 statustext = L"fast_move disabled";
1847 statustext_time = 0;
1851 g_settings->set("fast_move","true");
1852 statustext = L"fast_move enabled";
1853 statustext_time = 0;
1854 if(!client.checkPrivilege("fast"))
1855 statustext += L" (note: no 'fast' privilege)";
1858 else if(input->wasKeyDown(getKeySetting("keymap_noclip")))
1860 if(g_settings->getBool("noclip"))
1862 g_settings->set("noclip","false");
1863 statustext = L"noclip disabled";
1864 statustext_time = 0;
1868 g_settings->set("noclip","true");
1869 statustext = L"noclip enabled";
1870 statustext_time = 0;
1871 if(!client.checkPrivilege("noclip"))
1872 statustext += L" (note: no 'noclip' privilege)";
1875 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1877 irr::video::IImage* const image = driver->createScreenShot();
1879 irr::c8 filename[256];
1880 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png",
1881 g_settings->get("screenshot_path").c_str(),
1882 device->getTimer()->getRealTime());
1883 if (driver->writeImageToFile(image, filename)) {
1884 std::wstringstream sstr;
1885 sstr<<"Saved screenshot to '"<<filename<<"'";
1886 infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1887 statustext = sstr.str();
1888 statustext_time = 0;
1890 infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1895 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
1897 show_hud = !show_hud;
1899 statustext = L"HUD shown";
1901 statustext = L"HUD hidden";
1902 statustext_time = 0;
1904 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
1906 show_chat = !show_chat;
1908 statustext = L"Chat shown";
1910 statustext = L"Chat hidden";
1911 statustext_time = 0;
1913 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1915 force_fog_off = !force_fog_off;
1917 statustext = L"Fog disabled";
1919 statustext = L"Fog enabled";
1920 statustext_time = 0;
1922 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1924 disable_camera_update = !disable_camera_update;
1925 if(disable_camera_update)
1926 statustext = L"Camera update disabled";
1928 statustext = L"Camera update enabled";
1929 statustext_time = 0;
1931 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
1933 // Initial / 3x toggle: Chat only
1934 // 1x toggle: Debug text with chat
1935 // 2x toggle: Debug text with profiler graph
1939 show_profiler_graph = false;
1940 statustext = L"Debug info shown";
1941 statustext_time = 0;
1943 else if(show_profiler_graph)
1946 show_profiler_graph = false;
1947 statustext = L"Debug info and profiler graph hidden";
1948 statustext_time = 0;
1952 show_profiler_graph = true;
1953 statustext = L"Profiler graph shown";
1954 statustext_time = 0;
1957 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1959 show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
1961 // FIXME: This updates the profiler with incomplete values
1962 update_profiler_gui(guitext_profiler, font, text_height,
1963 show_profiler, show_profiler_max);
1965 if(show_profiler != 0)
1967 std::wstringstream sstr;
1968 sstr<<"Profiler shown (page "<<show_profiler
1969 <<" of "<<show_profiler_max<<")";
1970 statustext = sstr.str();
1971 statustext_time = 0;
1975 statustext = L"Profiler hidden";
1976 statustext_time = 0;
1979 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
1981 s16 range = g_settings->getS16("viewing_range_nodes_min");
1982 s16 range_new = range + 10;
1983 g_settings->set("viewing_range_nodes_min", itos(range_new));
1984 statustext = narrow_to_wide(
1985 "Minimum viewing range changed to "
1987 statustext_time = 0;
1989 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
1991 s16 range = g_settings->getS16("viewing_range_nodes_min");
1992 s16 range_new = range - 10;
1995 g_settings->set("viewing_range_nodes_min",
1997 statustext = narrow_to_wide(
1998 "Minimum viewing range changed to "
2000 statustext_time = 0;
2004 if(!input->isKeyDown(getKeySetting("keymap_jump")) && reset_jump_timer)
2006 reset_jump_timer = false;
2010 // Handle QuicktuneShortcutter
2011 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
2013 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
2015 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
2017 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
2020 std::string msg = quicktune.getMessage();
2022 statustext = narrow_to_wide(msg);
2023 statustext_time = 0;
2027 // Item selection with mouse wheel
2028 u16 new_playeritem = client.getPlayerItem();
2030 s32 wheel = input->getMouseWheel();
2031 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
2032 player->hud_hotbar_itemcount-1);
2036 if(new_playeritem < max_item)
2043 if(new_playeritem > 0)
2046 new_playeritem = max_item;
2051 for(u16 i=0; i<10; i++)
2053 const KeyPress *kp = NumberKey + (i + 1) % 10;
2054 if(input->wasKeyDown(*kp))
2056 if(i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount)
2060 infostream<<"Selected item: "
2061 <<new_playeritem<<std::endl;
2066 // Viewing range selection
2067 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
2069 draw_control.range_all = !draw_control.range_all;
2070 if(draw_control.range_all)
2072 infostream<<"Enabled full viewing range"<<std::endl;
2073 statustext = L"Enabled full viewing range";
2074 statustext_time = 0;
2078 infostream<<"Disabled full viewing range"<<std::endl;
2079 statustext = L"Disabled full viewing range";
2080 statustext_time = 0;
2084 // Print debug stacks
2085 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
2087 dstream<<"-----------------------------------------"
2089 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
2090 dstream<<"-----------------------------------------"
2092 debug_stacks_print();
2096 Mouse and camera control
2097 NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
2100 float turn_amount = 0;
2101 if((device->isWindowActive() && noMenuActive()) || random_input)
2105 // Mac OSX gets upset if this is set every frame
2106 if(device->getCursorControl()->isVisible())
2107 device->getCursorControl()->setVisible(false);
2110 if(first_loop_after_window_activation){
2111 //infostream<<"window active, first loop"<<std::endl;
2112 first_loop_after_window_activation = false;
2115 s32 dx = input->getMousePos().X - displaycenter.X;
2116 s32 dy = input->getMousePos().Y - displaycenter.Y;
2119 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
2121 /*const float keyspeed = 500;
2122 if(input->isKeyDown(irr::KEY_UP))
2123 dy -= dtime * keyspeed;
2124 if(input->isKeyDown(irr::KEY_DOWN))
2125 dy += dtime * keyspeed;
2126 if(input->isKeyDown(irr::KEY_LEFT))
2127 dx -= dtime * keyspeed;
2128 if(input->isKeyDown(irr::KEY_RIGHT))
2129 dx += dtime * keyspeed;*/
2131 float d = g_settings->getFloat("mouse_sensitivity");
2132 d = rangelim(d, 0.01, 100.0);
2134 camera_pitch += dy*d;
2135 if(camera_pitch < -89.5) camera_pitch = -89.5;
2136 if(camera_pitch > 89.5) camera_pitch = 89.5;
2138 turn_amount = v2f(dx, dy).getLength() * d;
2140 input->setMousePos(displaycenter.X, displaycenter.Y);
2143 // Mac OSX gets upset if this is set every frame
2144 if(device->getCursorControl()->isVisible() == false)
2145 device->getCursorControl()->setVisible(true);
2147 //infostream<<"window inactive"<<std::endl;
2148 first_loop_after_window_activation = true;
2150 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
2151 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
2154 Player speed control
2168 PlayerControl control(
2169 input->isKeyDown(getKeySetting("keymap_forward")),
2170 input->isKeyDown(getKeySetting("keymap_backward")),
2171 input->isKeyDown(getKeySetting("keymap_left")),
2172 input->isKeyDown(getKeySetting("keymap_right")),
2173 input->isKeyDown(getKeySetting("keymap_jump")),
2174 input->isKeyDown(getKeySetting("keymap_special1")),
2175 input->isKeyDown(getKeySetting("keymap_sneak")),
2176 input->getLeftState(),
2177 input->getRightState(),
2181 client.setPlayerControl(control);
2183 1*(int)input->isKeyDown(getKeySetting("keymap_forward"))+
2184 2*(int)input->isKeyDown(getKeySetting("keymap_backward"))+
2185 4*(int)input->isKeyDown(getKeySetting("keymap_left"))+
2186 8*(int)input->isKeyDown(getKeySetting("keymap_right"))+
2187 16*(int)input->isKeyDown(getKeySetting("keymap_jump"))+
2188 32*(int)input->isKeyDown(getKeySetting("keymap_special1"))+
2189 64*(int)input->isKeyDown(getKeySetting("keymap_sneak"))+
2190 128*(int)input->getLeftState()+
2191 256*(int)input->getRightState();
2192 LocalPlayer* player = client.getEnv().getLocalPlayer();
2193 player->keyPressed=keyPressed;
2202 //TimeTaker timer("server->step(dtime)");
2203 server->step(dtime);
2211 //TimeTaker timer("client.step(dtime)");
2213 //client.step(dtime_avg1);
2217 // Read client events
2220 ClientEvent event = client.getClientEvent();
2221 if(event.type == CE_NONE)
2225 else if(event.type == CE_PLAYER_DAMAGE &&
2226 client.getHP() != 0)
2228 //u16 damage = event.player_damage.amount;
2229 //infostream<<"Player damage: "<<damage<<std::endl;
2231 damage_flash += 100.0;
2232 damage_flash += 8.0 * event.player_damage.amount;
2234 player->hurt_tilt_timer = 1.5;
2235 player->hurt_tilt_strength = event.player_damage.amount/2;
2236 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 2.0, 10.0);
2238 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
2239 gamedef->event()->put(e);
2241 else if(event.type == CE_PLAYER_FORCE_MOVE)
2243 camera_yaw = event.player_force_move.yaw;
2244 camera_pitch = event.player_force_move.pitch;
2246 else if(event.type == CE_DEATHSCREEN)
2248 if(respawn_menu_active)
2251 /*bool set_camera_point_target =
2252 event.deathscreen.set_camera_point_target;
2253 v3f camera_point_target;
2254 camera_point_target.X = event.deathscreen.camera_point_target_x;
2255 camera_point_target.Y = event.deathscreen.camera_point_target_y;
2256 camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
2257 MainRespawnInitiator *respawner =
2258 new MainRespawnInitiator(
2259 &respawn_menu_active, &client);
2260 GUIDeathScreen *menu =
2261 new GUIDeathScreen(guienv, guiroot, -1,
2262 &g_menumgr, respawner);
2265 chat_backend.addMessage(L"", L"You died.");
2267 /* Handle visualization */
2271 LocalPlayer* player = client.getEnv().getLocalPlayer();
2272 player->hurt_tilt_timer = 0;
2273 player->hurt_tilt_strength = 0;
2275 /*LocalPlayer* player = client.getLocalPlayer();
2276 player->setPosition(player->getPosition() + v3f(0,-BS,0));
2277 camera.update(player, busytime, screensize);*/
2279 else if (event.type == CE_SHOW_FORMSPEC)
2281 if (current_formspec == 0)
2284 /* Note: FormspecFormSource and TextDestPlayerInventory
2285 * are deleted by guiFormSpecMenu */
2286 current_formspec = new FormspecFormSource(*(event.show_formspec.formspec),¤t_formspec);
2287 current_textdest = new TextDestPlayerInventory(&client,*(event.show_formspec.formname));
2288 GUIFormSpecMenu *menu =
2289 new GUIFormSpecMenu(device, guiroot, -1,
2292 menu->setFormSource(current_formspec);
2293 menu->setTextDest(current_textdest);
2298 assert(current_textdest != 0);
2300 current_textdest->setFormName(*(event.show_formspec.formname));
2301 current_formspec->setForm(*(event.show_formspec.formspec));
2303 delete(event.show_formspec.formspec);
2304 delete(event.show_formspec.formname);
2306 else if(event.type == CE_TEXTURES_UPDATED)
2308 update_wielded_item_trigger = true;
2310 else if(event.type == CE_SPAWN_PARTICLE)
2312 LocalPlayer* player = client.getEnv().getLocalPlayer();
2314 gamedef->tsrc()->getTexture(*(event.spawn_particle.texture));
2316 new Particle(gamedef, smgr, player, client.getEnv(),
2317 *event.spawn_particle.pos,
2318 *event.spawn_particle.vel,
2319 *event.spawn_particle.acc,
2320 event.spawn_particle.expirationtime,
2321 event.spawn_particle.size,
2322 event.spawn_particle.collisiondetection, ap);
2324 else if(event.type == CE_ADD_PARTICLESPAWNER)
2326 LocalPlayer* player = client.getEnv().getLocalPlayer();
2328 gamedef->tsrc()->getTexture(*(event.add_particlespawner.texture));
2330 new ParticleSpawner(gamedef, smgr, player,
2331 event.add_particlespawner.amount,
2332 event.add_particlespawner.spawntime,
2333 *event.add_particlespawner.minpos,
2334 *event.add_particlespawner.maxpos,
2335 *event.add_particlespawner.minvel,
2336 *event.add_particlespawner.maxvel,
2337 *event.add_particlespawner.minacc,
2338 *event.add_particlespawner.maxacc,
2339 event.add_particlespawner.minexptime,
2340 event.add_particlespawner.maxexptime,
2341 event.add_particlespawner.minsize,
2342 event.add_particlespawner.maxsize,
2343 event.add_particlespawner.collisiondetection,
2345 event.add_particlespawner.id);
2347 else if(event.type == CE_DELETE_PARTICLESPAWNER)
2349 delete_particlespawner (event.delete_particlespawner.id);
2351 else if (event.type == CE_HUDADD)
2353 u32 id = event.hudadd.id;
2354 size_t nhudelem = player->hud.size();
2355 if (id > nhudelem || (id < nhudelem && player->hud[id])) {
2356 delete event.hudadd.pos;
2357 delete event.hudadd.name;
2358 delete event.hudadd.scale;
2359 delete event.hudadd.text;
2360 delete event.hudadd.align;
2361 delete event.hudadd.offset;
2365 HudElement *e = new HudElement;
2366 e->type = (HudElementType)event.hudadd.type;
2367 e->pos = *event.hudadd.pos;
2368 e->name = *event.hudadd.name;
2369 e->scale = *event.hudadd.scale;
2370 e->text = *event.hudadd.text;
2371 e->number = event.hudadd.number;
2372 e->item = event.hudadd.item;
2373 e->dir = event.hudadd.dir;
2374 e->align = *event.hudadd.align;
2375 e->offset = *event.hudadd.offset;
2378 player->hud.push_back(e);
2380 player->hud[id] = e;
2382 delete event.hudadd.pos;
2383 delete event.hudadd.name;
2384 delete event.hudadd.scale;
2385 delete event.hudadd.text;
2386 delete event.hudadd.align;
2387 delete event.hudadd.offset;
2389 else if (event.type == CE_HUDRM)
2391 u32 id = event.hudrm.id;
2392 if (id < player->hud.size() && player->hud[id]) {
2393 delete player->hud[id];
2394 player->hud[id] = NULL;
2397 else if (event.type == CE_HUDCHANGE)
2399 u32 id = event.hudchange.id;
2400 if (id >= player->hud.size() || !player->hud[id]) {
2401 delete event.hudchange.v2fdata;
2402 delete event.hudchange.sdata;
2406 HudElement* e = player->hud[id];
2407 switch (event.hudchange.stat) {
2409 e->pos = *event.hudchange.v2fdata;
2412 e->name = *event.hudchange.sdata;
2414 case HUD_STAT_SCALE:
2415 e->scale = *event.hudchange.v2fdata;
2418 e->text = *event.hudchange.sdata;
2420 case HUD_STAT_NUMBER:
2421 e->number = event.hudchange.data;
2424 e->item = event.hudchange.data;
2427 e->dir = event.hudchange.data;
2429 case HUD_STAT_ALIGN:
2430 e->align = *event.hudchange.v2fdata;
2432 case HUD_STAT_OFFSET:
2433 e->offset = *event.hudchange.v2fdata;
2437 delete event.hudchange.v2fdata;
2438 delete event.hudchange.sdata;
2443 //TimeTaker //timer2("//timer2");
2446 For interaction purposes, get info about the held item
2448 - Is it a usable item?
2449 - Can it point to liquids?
2451 ItemStack playeritem;
2453 InventoryList *mlist = local_inventory.getList("main");
2456 playeritem = mlist->getItem(client.getPlayerItem());
2459 const ItemDefinition &playeritem_def =
2460 playeritem.getDefinition(itemdef);
2461 ToolCapabilities playeritem_toolcap =
2462 playeritem.getToolCapabilities(itemdef);
2468 LocalPlayer* player = client.getEnv().getLocalPlayer();
2469 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2470 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
2471 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2472 camera.update(player, busytime, screensize, tool_reload_ratio);
2475 v3f player_position = player->getPosition();
2476 v3f camera_position = camera.getPosition();
2477 v3f camera_direction = camera.getDirection();
2478 f32 camera_fov = camera.getFovMax();
2480 if(!disable_camera_update){
2481 client.getEnv().getClientMap().updateCamera(camera_position,
2482 camera_direction, camera_fov);
2485 // Update sound listener
2486 sound->updateListener(camera.getCameraNode()->getPosition(),
2487 v3f(0,0,0), // velocity
2488 camera.getDirection(),
2489 camera.getCameraNode()->getUpVector());
2490 sound->setListenerGain(g_settings->getFloat("sound_volume"));
2496 soundmaker.step(dtime);
2498 ClientMap &map = client.getEnv().getClientMap();
2499 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
2500 soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
2504 Calculate what block is the crosshair pointing to
2507 //u32 t1 = device->getTimer()->getRealTime();
2509 f32 d = 4; // max. distance
2510 core::line3d<f32> shootline(camera_position,
2511 camera_position + camera_direction * BS * (d+1));
2513 ClientActiveObject *selected_object = NULL;
2515 PointedThing pointed = getPointedThing(
2517 &client, player_position, camera_direction,
2518 camera_position, shootline, d,
2519 playeritem_def.liquids_pointable, !ldown_for_dig,
2524 if(pointed != pointed_old)
2526 infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2527 //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
2532 - releasing left mouse button
2533 - pointing away from node
2537 if(input->getLeftReleased())
2539 infostream<<"Left button released"
2540 <<" (stopped digging)"<<std::endl;
2543 else if(pointed != pointed_old)
2545 if (pointed.type == POINTEDTHING_NODE
2546 && pointed_old.type == POINTEDTHING_NODE
2547 && pointed.node_undersurface == pointed_old.node_undersurface)
2549 // Still pointing to the same node,
2550 // but a different face. Don't reset.
2554 infostream<<"Pointing away from node"
2555 <<" (stopped digging)"<<std::endl;
2561 client.interact(1, pointed_old);
2562 client.setCrack(-1, v3s16(0,0,0));
2566 if(!digging && ldown_for_dig && !input->getLeftState())
2568 ldown_for_dig = false;
2571 bool left_punch = false;
2572 soundmaker.m_player_leftpunch_sound.name = "";
2574 if(input->getRightState())
2575 repeat_rightclick_timer += dtime;
2577 repeat_rightclick_timer = 0;
2579 if(playeritem_def.usable && input->getLeftState())
2581 if(input->getLeftClicked())
2582 client.interact(4, pointed);
2584 else if(pointed.type == POINTEDTHING_NODE)
2586 v3s16 nodepos = pointed.node_undersurface;
2587 v3s16 neighbourpos = pointed.node_abovesurface;
2590 Check information text of node
2593 ClientMap &map = client.getEnv().getClientMap();
2594 NodeMetadata *meta = map.getNodeMetadata(nodepos);
2596 infotext = narrow_to_wide(meta->getString("infotext"));
2598 MapNode n = map.getNode(nodepos);
2599 if(nodedef->get(n).tiledef[0].name == "unknown_node.png"){
2600 infotext = L"Unknown node: ";
2601 infotext += narrow_to_wide(nodedef->get(n).name);
2609 if(nodig_delay_timer <= 0.0 && input->getLeftState()
2610 && client.checkPrivilege("interact"))
2614 infostream<<"Started digging"<<std::endl;
2615 client.interact(0, pointed);
2617 ldown_for_dig = true;
2619 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2621 // NOTE: Similar piece of code exists on the server side for
2623 // Get digging parameters
2624 DigParams params = getDigParams(nodedef->get(n).groups,
2625 &playeritem_toolcap);
2626 // If can't dig, try hand
2627 if(!params.diggable){
2628 const ItemDefinition &hand = itemdef->get("");
2629 const ToolCapabilities *tp = hand.tool_capabilities;
2631 params = getDigParams(nodedef->get(n).groups, tp);
2634 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2635 if(sound_dig.exists()){
2636 if(sound_dig.name == "__group"){
2637 if(params.main_group != ""){
2638 soundmaker.m_player_leftpunch_sound.gain = 0.5;
2639 soundmaker.m_player_leftpunch_sound.name =
2640 std::string("default_dig_") +
2644 soundmaker.m_player_leftpunch_sound = sound_dig;
2648 float dig_time_complete = 0.0;
2650 if(params.diggable == false)
2652 // I guess nobody will wait for this long
2653 dig_time_complete = 10000000.0;
2657 dig_time_complete = params.time;
2658 if (g_settings->getBool("enable_particles"))
2660 const ContentFeatures &features =
2661 client.getNodeDefManager()->get(n);
2662 addPunchingParticles
2663 (gamedef, smgr, player, client.getEnv(),
2664 nodepos, features.tiles);
2668 if(dig_time_complete >= 0.001)
2670 dig_index = (u16)((float)crack_animation_length
2671 * dig_time/dig_time_complete);
2673 // This is for torches
2676 dig_index = crack_animation_length;
2679 // Don't show cracks if not diggable
2680 if(dig_time_complete >= 100000.0)
2683 else if(dig_index < crack_animation_length)
2685 //TimeTaker timer("client.setTempMod");
2686 //infostream<<"dig_index="<<dig_index<<std::endl;
2687 client.setCrack(dig_index, nodepos);
2691 infostream<<"Digging completed"<<std::endl;
2692 client.interact(2, pointed);
2693 client.setCrack(-1, v3s16(0,0,0));
2694 MapNode wasnode = map.getNode(nodepos);
2695 client.removeNode(nodepos);
2697 if (g_settings->getBool("enable_particles"))
2699 const ContentFeatures &features =
2700 client.getNodeDefManager()->get(wasnode);
2702 (gamedef, smgr, player, client.getEnv(),
2703 nodepos, features.tiles);
2709 nodig_delay_timer = dig_time_complete
2710 / (float)crack_animation_length;
2712 // We don't want a corresponding delay to
2713 // very time consuming nodes
2714 if(nodig_delay_timer > 0.3)
2715 nodig_delay_timer = 0.3;
2716 // We want a slight delay to very little
2717 // time consuming nodes
2718 float mindelay = 0.15;
2719 if(nodig_delay_timer < mindelay)
2720 nodig_delay_timer = mindelay;
2722 // Send event to trigger sound
2723 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
2724 gamedef->event()->put(e);
2727 if(dig_time_complete < 100000.0)
2731 client.setCrack(-1, nodepos);
2734 camera.setDigging(0); // left click animation
2737 if((input->getRightClicked() ||
2738 repeat_rightclick_timer >=
2739 g_settings->getFloat("repeat_rightclick_time")) &&
2740 client.checkPrivilege("interact"))
2742 repeat_rightclick_timer = 0;
2743 infostream<<"Ground right-clicked"<<std::endl;
2745 // Sign special case, at least until formspec is properly implemented.
2747 if(meta && meta->getString("formspec") == "hack:sign_text_input"
2749 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2751 infostream<<"Launching metadata text input"<<std::endl;
2753 // Get a new text for it
2755 TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2757 std::wstring wtext = narrow_to_wide(meta->getString("text"));
2759 (new GUITextInputMenu(guienv, guiroot, -1,
2763 // If metadata provides an inventory view, activate it
2764 else if(meta && meta->getString("formspec") != "" && !random_input
2765 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2767 infostream<<"Launching custom inventory view"<<std::endl;
2769 InventoryLocation inventoryloc;
2770 inventoryloc.setNodeMeta(nodepos);
2774 GUIFormSpecMenu *menu =
2775 new GUIFormSpecMenu(device, guiroot, -1,
2778 menu->setFormSpec(meta->getString("formspec"),
2780 menu->setFormSource(new NodeMetadataFormSource(
2781 &client.getEnv().getClientMap(), nodepos));
2782 menu->setTextDest(new TextDestNodeMetadata(nodepos, &client));
2785 // Otherwise report right click to server
2789 client.interact(3, pointed);
2790 camera.setDigging(1); // right click animation
2792 // If the wielded item has node placement prediction,
2794 bool placed = nodePlacementPrediction(client,
2796 nodepos, neighbourpos);
2800 soundmaker.m_player_rightpunch_sound =
2801 playeritem_def.sound_place;
2803 soundmaker.m_player_rightpunch_sound =
2808 else if(pointed.type == POINTEDTHING_OBJECT)
2810 infotext = narrow_to_wide(selected_object->infoText());
2812 if(infotext == L"" && show_debug){
2813 infotext = narrow_to_wide(selected_object->debugInfoText());
2816 //if(input->getLeftClicked())
2817 if(input->getLeftState())
2819 bool do_punch = false;
2820 bool do_punch_damage = false;
2821 if(object_hit_delay_timer <= 0.0){
2823 do_punch_damage = true;
2824 object_hit_delay_timer = object_hit_delay;
2826 if(input->getLeftClicked()){
2830 infostream<<"Left-clicked object"<<std::endl;
2833 if(do_punch_damage){
2834 // Report direct punch
2835 v3f objpos = selected_object->getPosition();
2836 v3f dir = (objpos - player_position).normalize();
2838 bool disable_send = selected_object->directReportPunch(
2839 dir, &playeritem, time_from_last_punch);
2840 time_from_last_punch = 0;
2842 client.interact(0, pointed);
2845 else if(input->getRightClicked())
2847 infostream<<"Right-clicked object"<<std::endl;
2848 client.interact(3, pointed); // place
2851 else if(input->getLeftState())
2853 // When button is held down in air, show continuous animation
2857 pointed_old = pointed;
2859 if(left_punch || input->getLeftClicked())
2861 camera.setDigging(0); // left click animation
2864 input->resetLeftClicked();
2865 input->resetRightClicked();
2867 input->resetLeftReleased();
2868 input->resetRightReleased();
2871 Calculate stuff for drawing
2880 fog_range = BS*farmesh_range;
2884 fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
2886 if(draw_control.range_all)
2887 fog_range = 100000*BS;
2891 Calculate general brightness
2893 u32 daynight_ratio = client.getEnv().getDayNightRatio();
2894 float time_brightness = decode_light_f((float)daynight_ratio/1000.0);
2895 float direct_brightness = 0;
2896 bool sunlight_seen = false;
2897 if(g_settings->getBool("free_move")){
2898 direct_brightness = time_brightness;
2899 sunlight_seen = true;
2901 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
2902 float old_brightness = sky->getBrightness();
2903 direct_brightness = (float)client.getEnv().getClientMap()
2904 .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
2905 daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
2909 time_of_day = client.getEnv().getTimeOfDayF();
2911 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
2912 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
2913 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
2914 time_of_day_smooth = time_of_day;
2916 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
2917 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2918 + (time_of_day+1.0) * todsm;
2920 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2921 + time_of_day * todsm;
2923 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
2926 float brightness = sky->getBrightness();
2927 video::SColor bgcolor = sky->getBgColor();
2928 video::SColor skycolor = sky->getSkyColor();
2934 if(sky->getCloudsVisible()){
2935 clouds->setVisible(true);
2936 clouds->step(dtime);
2937 clouds->update(v2f(player_position.X, player_position.Z),
2938 sky->getCloudColor());
2940 clouds->setVisible(false);
2949 farmesh_range = draw_control.wanted_range * 10;
2950 if(draw_control.range_all && farmesh_range < 500)
2951 farmesh_range = 500;
2952 if(farmesh_range > 1000)
2953 farmesh_range = 1000;
2955 farmesh->step(dtime);
2956 farmesh->update(v2f(player_position.X, player_position.Z),
2957 brightness, farmesh_range);
2964 allparticles_step(dtime, client.getEnv());
2965 allparticlespawners_step(dtime, client.getEnv());
2971 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2975 video::EFT_FOG_LINEAR,
2987 video::EFT_FOG_LINEAR,
2997 Update gui stuff (0ms)
3000 //TimeTaker guiupdatetimer("Gui updating");
3002 const char program_name_and_version[] =
3003 "Minetest " VERSION_STRING;
3007 static float drawtime_avg = 0;
3008 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
3009 /*static float beginscenetime_avg = 0;
3010 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
3011 static float scenetime_avg = 0;
3012 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
3013 static float endscenetime_avg = 0;
3014 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
3016 std::ostringstream os(std::ios_base::binary);
3018 <<program_name_and_version
3019 <<" (R: range_all="<<draw_control.range_all<<")"
3020 <<std::setprecision(0)
3021 <<" drawtime = "<<drawtime_avg
3022 <<std::setprecision(1)
3023 <<", dtime_jitter = "
3024 <<(dtime_jitter1_max_fraction * 100.0)<<" %"
3025 <<std::setprecision(1)
3026 <<", v_range = "<<draw_control.wanted_range
3027 <<std::setprecision(3)
3028 <<", RTT = "<<client.getRTT();
3029 guitext->setText(narrow_to_wide(os.str()).c_str());
3030 guitext->setVisible(true);
3032 else if(show_hud || show_chat)
3034 guitext->setText(narrow_to_wide(program_name_and_version).c_str());
3035 guitext->setVisible(true);
3039 guitext->setVisible(false);
3044 std::ostringstream os(std::ios_base::binary);
3045 os<<std::setprecision(1)<<std::fixed
3046 <<"(" <<(player_position.X/BS)
3047 <<", "<<(player_position.Y/BS)
3048 <<", "<<(player_position.Z/BS)
3049 <<") (yaw="<<(wrapDegrees_0_360(camera_yaw))
3050 <<") (seed = "<<((unsigned long long)client.getMapSeed())
3052 guitext2->setText(narrow_to_wide(os.str()).c_str());
3053 guitext2->setVisible(true);
3057 guitext2->setVisible(false);
3061 guitext_info->setText(infotext.c_str());
3062 guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
3066 float statustext_time_max = 1.5;
3067 if(!statustext.empty())
3069 statustext_time += dtime;
3070 if(statustext_time >= statustext_time_max)
3073 statustext_time = 0;
3076 guitext_status->setText(statustext.c_str());
3077 guitext_status->setVisible(!statustext.empty());
3079 if(!statustext.empty())
3081 s32 status_y = screensize.Y - 130;
3082 core::rect<s32> rect(
3084 status_y - guitext_status->getTextHeight(),
3088 guitext_status->setRelativePosition(rect);
3091 video::SColor initial_color(255,0,0,0);
3092 if(guienv->getSkin())
3093 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
3094 video::SColor final_color = initial_color;
3095 final_color.setAlpha(0);
3096 video::SColor fade_color =
3097 initial_color.getInterpolated_quadratic(
3100 pow(statustext_time / (float)statustext_time_max, 2.0f));
3101 guitext_status->setOverrideColor(fade_color);
3102 guitext_status->enableOverrideColor(true);
3107 Get chat messages from client
3110 // Get new messages from error log buffer
3111 while(!chat_log_error_buf.empty())
3113 chat_backend.addMessage(L"", narrow_to_wide(
3114 chat_log_error_buf.get()));
3116 // Get new messages from client
3117 std::wstring message;
3118 while(client.getChatMessage(message))
3120 chat_backend.addUnparsedMessage(message);
3122 // Remove old messages
3123 chat_backend.step(dtime);
3125 // Display all messages in a static text element
3126 u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
3127 std::wstring recent_chat = chat_backend.getRecentChat();
3128 guitext_chat->setText(recent_chat.c_str());
3130 // Update gui element size and position
3131 s32 chat_y = 5+(text_height+5);
3133 chat_y += (text_height+5);
3134 core::rect<s32> rect(
3138 chat_y + guitext_chat->getTextHeight()
3140 guitext_chat->setRelativePosition(rect);
3142 // Don't show chat if disabled or empty or profiler is enabled
3143 guitext_chat->setVisible(show_chat && recent_chat_count != 0
3151 if(client.getPlayerItem() != new_playeritem)
3153 client.selectPlayerItem(new_playeritem);
3155 if(client.getLocalInventoryUpdated())
3157 //infostream<<"Updating local inventory"<<std::endl;
3158 client.getLocalInventory(local_inventory);
3160 update_wielded_item_trigger = true;
3162 if(update_wielded_item_trigger)
3164 update_wielded_item_trigger = false;
3165 // Update wielded tool
3166 InventoryList *mlist = local_inventory.getList("main");
3169 item = mlist->getItem(client.getPlayerItem());
3170 camera.wield(item, client.getPlayerItem());
3174 Update block draw list every 200ms or when camera direction has
3177 update_draw_list_timer += dtime;
3178 if(update_draw_list_timer >= 0.2 ||
3179 update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2){
3180 update_draw_list_timer = 0;
3181 client.getEnv().getClientMap().updateDrawList(driver);
3182 update_draw_list_last_cam_dir = camera_direction;
3189 TimeTaker tt_draw("mainloop: draw");
3192 TimeTaker timer("beginScene");
3193 //driver->beginScene(false, true, bgcolor);
3194 //driver->beginScene(true, true, bgcolor);
3195 driver->beginScene(true, true, skycolor);
3196 beginscenetime = timer.stop(true);
3201 //infostream<<"smgr->drawAll()"<<std::endl;
3203 TimeTaker timer("smgr");
3206 if(g_settings->getBool("anaglyph"))
3208 irr::core::vector3df oldPosition = camera.getCameraNode()->getPosition();
3209 irr::core::vector3df oldTarget = camera.getCameraNode()->getTarget();
3211 irr::core::matrix4 startMatrix = camera.getCameraNode()->getAbsoluteTransformation();
3213 irr::core::vector3df focusPoint = (camera.getCameraNode()->getTarget() -
3214 camera.getCameraNode()->getAbsolutePosition()).setLength(1) +
3215 camera.getCameraNode()->getAbsolutePosition() ;
3218 irr::core::vector3df leftEye;
3219 irr::core::matrix4 leftMove;
3221 leftMove.setTranslation( irr::core::vector3df(-g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
3222 leftEye=(startMatrix*leftMove).getTranslation();
3224 //clear the depth buffer, and color
3225 driver->beginScene( true, true, irr::video::SColor(0,200,200,255) );
3227 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_RED;
3228 driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK;
3229 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
3230 irr::scene::ESNRP_SOLID +
3231 irr::scene::ESNRP_TRANSPARENT +
3232 irr::scene::ESNRP_TRANSPARENT_EFFECT +
3233 irr::scene::ESNRP_SHADOW;
3235 camera.getCameraNode()->setPosition( leftEye );
3236 camera.getCameraNode()->setTarget( focusPoint );
3238 smgr->drawAll(); // 'smgr->drawAll();' may go here
3242 irr::core::vector3df rightEye;
3243 irr::core::matrix4 rightMove;
3245 rightMove.setTranslation( irr::core::vector3df(g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
3246 rightEye=(startMatrix*rightMove).getTranslation();
3248 //clear the depth buffer
3249 driver->clearZBuffer();
3251 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_GREEN + irr::video::ECP_BLUE;
3252 driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK;
3253 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
3254 irr::scene::ESNRP_SOLID +
3255 irr::scene::ESNRP_TRANSPARENT +
3256 irr::scene::ESNRP_TRANSPARENT_EFFECT +
3257 irr::scene::ESNRP_SHADOW;
3259 camera.getCameraNode()->setPosition( rightEye );
3260 camera.getCameraNode()->setTarget( focusPoint );
3262 smgr->drawAll(); // 'smgr->drawAll();' may go here
3265 //driver->endScene();
3267 driver->getOverrideMaterial().Material.ColorMask=irr::video::ECP_ALL;
3268 driver->getOverrideMaterial().EnableFlags=0;
3269 driver->getOverrideMaterial().EnablePasses=0;
3271 camera.getCameraNode()->setPosition( oldPosition );
3272 camera.getCameraNode()->setTarget( oldTarget );
3275 scenetime = timer.stop(true);
3279 //TimeTaker timer9("auxiliary drawings");
3283 //TimeTaker //timer10("//timer10");
3289 driver->setMaterial(m);
3291 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
3294 hud.drawSelectionBoxes(hilightboxes);
3298 if(show_hud && (player->hud_flags & HUD_FLAG_WIELDITEM_VISIBLE))
3300 // Warning: This clears the Z buffer.
3301 camera.drawWieldedTool();
3308 client.getEnv().getClientMap().renderPostFx();
3314 if(show_profiler_graph)
3316 graph.draw(10, screensize.Y - 10, driver, font);
3323 hud.drawCrosshair();
3328 //TimeTaker //timer11("//timer11");
3336 hud.drawHotbar(v2s32(displaycenter.X, screensize.Y),
3337 client.getHP(), client.getPlayerItem(), client.getBreath());
3343 if(damage_flash > 0.0)
3345 video::SColor color(std::min(damage_flash, 180.0f),180,0,0);
3346 driver->draw2DRectangle(color,
3347 core::rect<s32>(0,0,screensize.X,screensize.Y),
3350 damage_flash -= 100.0*dtime;
3356 if(player->hurt_tilt_timer > 0.0)
3358 player->hurt_tilt_timer -= dtime*5;
3359 if(player->hurt_tilt_timer < 0)
3360 player->hurt_tilt_strength = 0;
3367 hud.drawLuaElements();
3379 TimeTaker timer("endScene");
3381 endscenetime = timer.stop(true);
3384 drawtime = tt_draw.stop(true);
3385 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
3391 static s16 lastFPS = 0;
3392 //u16 fps = driver->getFPS();
3393 u16 fps = (1.0/dtime_avg1);
3397 core::stringw str = L"Minetest [";
3398 str += driver->getName();
3402 device->setWindowCaption(str.c_str());
3407 Log times and stuff for visualization
3409 Profiler::GraphValues values;
3410 g_profiler->graphGet(values);
3419 if (gui_chat_console)
3420 gui_chat_console->drop();
3426 Draw a "shutting down" screen, which will be shown while the map
3427 generator and other stuff quits
3430 /*gui::IGUIStaticText *gui_shuttingdowntext = */
3431 wchar_t* text = wgettext("Shutting down stuff...");
3432 draw_load_screen(text, device, font, 0, -1, false);
3434 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
3437 gui_shuttingdowntext->remove();*/
3440 chat_backend.addMessage(L"", L"# Disconnected.");
3441 chat_backend.addMessage(L"", L"");
3443 // Client scope (client is destructed before destructing *def and tsrc)
3446 catch(SerializationError &e)
3448 error_message = L"A serialization error occurred:\n"
3449 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
3450 L" running a different version of Minetest.";
3451 errorstream<<wide_to_narrow(error_message)<<std::endl;
3453 catch(ServerError &e)
3455 error_message = narrow_to_wide(e.what());
3456 errorstream<<wide_to_narrow(error_message)<<std::endl;
3460 errorstream<<e.what()<<std::endl;
3461 error_message = narrow_to_wide(e.what()) + wgettext("\nCheck debug.txt for details.");
3469 //has to be deleted first to stop all server threads
3477 //extended resource accounting
3478 infostream << "Irrlicht resources after cleanup:" << std::endl;
3479 infostream << "\tRemaining meshes : "
3480 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
3481 infostream << "\tRemaining textures : "
3482 << driver->getTextureCount() << std::endl;
3483 for (unsigned int i = 0; i < driver->getTextureCount(); i++ ) {
3484 irr::video::ITexture* texture = driver->getTextureByIndex(i);
3485 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
3488 infostream << "\tRemaining materials: "
3489 << driver-> getMaterialRendererCount ()
3490 << " (note: irrlicht doesn't support removing renderers)"<< std::endl;