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;
212 Check if a node is pointable
214 inline bool isPointableNode(const MapNode& n,
215 Client *client, bool liquids_pointable)
217 const ContentFeatures &features = client->getNodeDefManager()->get(n);
218 return features.pointable ||
219 (liquids_pointable && features.isLiquid());
223 Find what the player is pointing at
225 PointedThing getPointedThing(Client *client, v3f player_position,
226 v3f camera_direction, v3f camera_position,
227 core::line3d<f32> shootline, f32 d,
228 bool liquids_pointable,
229 bool look_for_object,
230 std::vector<aabb3f> &hilightboxes,
231 ClientActiveObject *&selected_object)
235 hilightboxes.clear();
236 selected_object = NULL;
238 INodeDefManager *nodedef = client->getNodeDefManager();
239 ClientMap &map = client->getEnv().getClientMap();
241 // First try to find a pointed at active object
244 selected_object = client->getSelectedActiveObject(d*BS,
245 camera_position, shootline);
247 if(selected_object != NULL)
249 if(selected_object->doShowSelectionBox())
251 aabb3f *selection_box = selected_object->getSelectionBox();
252 // Box should exist because object was
253 // returned in the first place
254 assert(selection_box);
256 v3f pos = selected_object->getPosition();
257 hilightboxes.push_back(aabb3f(
258 selection_box->MinEdge + pos,
259 selection_box->MaxEdge + pos));
263 result.type = POINTEDTHING_OBJECT;
264 result.object_id = selected_object->getId();
269 // That didn't work, try to find a pointed at node
271 f32 mindistance = BS * 1001;
273 v3s16 pos_i = floatToInt(player_position, BS);
275 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
279 s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
280 s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
281 s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
282 s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
283 s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
284 s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
286 // Prevent signed number overflow
294 for(s16 y = ystart; y <= yend; y++)
295 for(s16 z = zstart; z <= zend; z++)
296 for(s16 x = xstart; x <= xend; x++)
301 n = map.getNode(v3s16(x,y,z));
303 catch(InvalidPositionException &e)
307 if(!isPointableNode(n, client, liquids_pointable))
310 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
313 v3f npf = intToFloat(np, BS);
315 for(std::vector<aabb3f>::const_iterator
317 i != boxes.end(); i++)
323 for(u16 j=0; j<6; j++)
325 v3s16 facedir = g_6dirs[j];
326 aabb3f facebox = box;
330 facebox.MinEdge.X = facebox.MaxEdge.X-d;
331 else if(facedir.X < 0)
332 facebox.MaxEdge.X = facebox.MinEdge.X+d;
333 else if(facedir.Y > 0)
334 facebox.MinEdge.Y = facebox.MaxEdge.Y-d;
335 else if(facedir.Y < 0)
336 facebox.MaxEdge.Y = facebox.MinEdge.Y+d;
337 else if(facedir.Z > 0)
338 facebox.MinEdge.Z = facebox.MaxEdge.Z-d;
339 else if(facedir.Z < 0)
340 facebox.MaxEdge.Z = facebox.MinEdge.Z+d;
342 v3f centerpoint = facebox.getCenter();
343 f32 distance = (centerpoint - camera_position).getLength();
344 if(distance >= mindistance)
346 if(!facebox.intersectsWithLine(shootline))
349 v3s16 np_above = np + facedir;
351 result.type = POINTEDTHING_NODE;
352 result.node_undersurface = np;
353 result.node_abovesurface = np_above;
354 mindistance = distance;
356 hilightboxes.clear();
357 for(std::vector<aabb3f>::const_iterator
359 i2 != boxes.end(); i2++)
362 box.MinEdge += npf + v3f(-d,-d,-d);
363 box.MaxEdge += npf + v3f(d,d,d);
364 hilightboxes.push_back(box);
374 Draws a screen with a single text on it.
375 Text will be removed when the screen is drawn the next time.
376 Additionally, a progressbar can be drawn when percent is set between 0 and 100.
378 /*gui::IGUIStaticText **/
379 void draw_load_screen(const std::wstring &text,
380 IrrlichtDevice* device, gui::IGUIFont* font,
381 float dtime=0 ,int percent=0, bool clouds=true)
383 video::IVideoDriver* driver = device->getVideoDriver();
384 v2u32 screensize = driver->getScreenSize();
385 const wchar_t *loadingtext = text.c_str();
386 core::vector2d<u32> textsize_u = font->getDimension(loadingtext);
387 core::vector2d<s32> textsize(textsize_u.X,textsize_u.Y);
388 core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
389 core::rect<s32> textrect(center - textsize/2, center + textsize/2);
391 gui::IGUIStaticText *guitext = guienv->addStaticText(
392 loadingtext, textrect, false, false);
393 guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
395 bool cloud_menu_background = clouds && g_settings->getBool("menu_clouds");
396 if (cloud_menu_background)
398 g_menuclouds->step(dtime*3);
399 g_menuclouds->render();
400 driver->beginScene(true, true, video::SColor(255,140,186,250));
401 g_menucloudsmgr->drawAll();
404 driver->beginScene(true, true, video::SColor(255,0,0,0));
405 if (percent >= 0 && percent <= 100) // draw progress bar
407 core::vector2d<s32> barsize(256,32);
408 core::rect<s32> barrect(center-barsize/2, center+barsize/2);
409 driver->draw2DRectangle(video::SColor(255,255,255,255),barrect, NULL); // border
410 driver->draw2DRectangle(video::SColor(255,64,64,64), core::rect<s32> (
411 barrect.UpperLeftCorner+1,
412 barrect.LowerRightCorner-1), NULL); // black inside the bar
413 driver->draw2DRectangle(video::SColor(255,128,128,128), core::rect<s32> (
414 barrect.UpperLeftCorner+1,
416 barrect.LowerRightCorner.X-(barsize.X-1)+percent*(barsize.X-2)/100,
417 barrect.LowerRightCorner.Y-1)), NULL); // the actual progress
427 /* Profiler display */
429 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler,
430 gui::IGUIFont *font, u32 text_height,
431 u32 show_profiler, u32 show_profiler_max)
433 if(show_profiler == 0)
435 guitext_profiler->setVisible(false);
440 std::ostringstream os(std::ios_base::binary);
441 g_profiler->printPage(os, show_profiler, show_profiler_max);
442 std::wstring text = narrow_to_wide(os.str());
443 guitext_profiler->setText(text.c_str());
444 guitext_profiler->setVisible(true);
446 s32 w = font->getDimension(text.c_str()).Width;
449 core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
450 8+(text_height+5)*2 +
451 font->getDimension(text.c_str()).Height);
452 guitext_profiler->setRelativePosition(rect);
453 guitext_profiler->setVisible(true);
461 Profiler::GraphValues values;
467 Meta(float initial=0, video::SColor color=
468 video::SColor(255,255,255,255)):
474 std::list<Piece> m_log;
482 void put(const Profiler::GraphValues &values)
485 piece.values = values;
486 m_log.push_back(piece);
487 while(m_log.size() > m_log_max_size)
488 m_log.erase(m_log.begin());
491 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
492 gui::IGUIFont* font) const
494 std::map<std::string, Meta> m_meta;
495 for(std::list<Piece>::const_iterator k = m_log.begin();
496 k != m_log.end(); k++)
498 const Piece &piece = *k;
499 for(Profiler::GraphValues::const_iterator i = piece.values.begin();
500 i != piece.values.end(); i++){
501 const std::string &id = i->first;
502 const float &value = i->second;
503 std::map<std::string, Meta>::iterator j =
505 if(j == m_meta.end()){
506 m_meta[id] = Meta(value);
509 if(value < j->second.min)
510 j->second.min = value;
511 if(value > j->second.max)
512 j->second.max = value;
517 static const video::SColor usable_colors[] = {
518 video::SColor(255,255,100,100),
519 video::SColor(255,90,225,90),
520 video::SColor(255,100,100,255),
521 video::SColor(255,255,150,50),
522 video::SColor(255,220,220,100)
524 static const u32 usable_colors_count =
525 sizeof(usable_colors) / sizeof(*usable_colors);
526 u32 next_color_i = 0;
527 for(std::map<std::string, Meta>::iterator i = m_meta.begin();
528 i != m_meta.end(); i++){
529 Meta &meta = i->second;
530 video::SColor color(255,200,200,200);
531 if(next_color_i < usable_colors_count)
532 color = usable_colors[next_color_i++];
537 s32 textx = x_left + m_log_max_size + 15;
538 s32 textx2 = textx + 200 - 15;
542 u32 num_graphs = m_meta.size();
543 core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
545 video::SColor bgcolor(120,0,0,0);
546 driver->draw2DRectangle(bgcolor, rect, NULL);
550 for(std::map<std::string, Meta>::const_iterator i = m_meta.begin();
551 i != m_meta.end(); i++){
552 const std::string &id = i->first;
553 const Meta &meta = i->second;
555 s32 y = y_bottom - meta_i * 50;
556 float show_min = meta.min;
557 float show_max = meta.max;
558 if(show_min >= -0.0001 && show_max >= -0.0001){
559 if(show_min <= show_max * 0.5)
564 snprintf(buf, 10, "%.3g", show_max);
565 font->draw(narrow_to_wide(buf).c_str(),
566 core::rect<s32>(textx, y - graphh,
567 textx2, y - graphh + texth),
569 snprintf(buf, 10, "%.3g", show_min);
570 font->draw(narrow_to_wide(buf).c_str(),
571 core::rect<s32>(textx, y - texth,
574 font->draw(narrow_to_wide(id).c_str(),
575 core::rect<s32>(textx, y - graphh/2 - texth/2,
576 textx2, y - graphh/2 + texth/2),
579 s32 graph1h = graphh;
580 bool relativegraph = (show_min != 0 && show_min != show_max);
581 float lastscaledvalue = 0.0;
582 bool lastscaledvalue_exists = false;
583 for(std::list<Piece>::const_iterator j = m_log.begin();
584 j != m_log.end(); j++)
586 const Piece &piece = *j;
588 bool value_exists = false;
589 Profiler::GraphValues::const_iterator k =
590 piece.values.find(id);
591 if(k != piece.values.end()){
597 lastscaledvalue_exists = false;
600 float scaledvalue = 1.0;
601 if(show_max != show_min)
602 scaledvalue = (value - show_min) / (show_max - show_min);
603 if(scaledvalue == 1.0 && value == 0){
605 lastscaledvalue_exists = false;
609 if(lastscaledvalue_exists){
610 s32 ivalue1 = lastscaledvalue * graph1h;
611 s32 ivalue2 = scaledvalue * graph1h;
612 driver->draw2DLine(v2s32(x-1, graph1y - ivalue1),
613 v2s32(x, graph1y - ivalue2), meta.color);
615 lastscaledvalue = scaledvalue;
616 lastscaledvalue_exists = true;
618 s32 ivalue = scaledvalue * graph1h;
619 driver->draw2DLine(v2s32(x, graph1y),
620 v2s32(x, graph1y - ivalue), meta.color);
629 class NodeDugEvent: public MtEvent
635 NodeDugEvent(v3s16 p, MapNode n):
639 const char* getType() const
645 ISoundManager *m_sound;
646 INodeDefManager *m_ndef;
648 float m_player_step_timer;
650 SimpleSoundSpec m_player_step_sound;
651 SimpleSoundSpec m_player_leftpunch_sound;
652 SimpleSoundSpec m_player_rightpunch_sound;
654 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
657 m_player_step_timer(0)
661 void playPlayerStep()
663 if(m_player_step_timer <= 0 && m_player_step_sound.exists()){
664 m_player_step_timer = 0.03;
665 m_sound->playSound(m_player_step_sound, false);
669 static void viewBobbingStep(MtEvent *e, void *data)
671 SoundMaker *sm = (SoundMaker*)data;
672 sm->playPlayerStep();
675 static void playerRegainGround(MtEvent *e, void *data)
677 SoundMaker *sm = (SoundMaker*)data;
678 sm->playPlayerStep();
681 static void playerJump(MtEvent *e, void *data)
683 //SoundMaker *sm = (SoundMaker*)data;
686 static void cameraPunchLeft(MtEvent *e, void *data)
688 SoundMaker *sm = (SoundMaker*)data;
689 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
692 static void cameraPunchRight(MtEvent *e, void *data)
694 SoundMaker *sm = (SoundMaker*)data;
695 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
698 static void nodeDug(MtEvent *e, void *data)
700 SoundMaker *sm = (SoundMaker*)data;
701 NodeDugEvent *nde = (NodeDugEvent*)e;
702 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
705 static void playerDamage(MtEvent *e, void *data)
707 SoundMaker *sm = (SoundMaker*)data;
708 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
711 static void playerFallingDamage(MtEvent *e, void *data)
713 SoundMaker *sm = (SoundMaker*)data;
714 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
717 void registerReceiver(MtEventManager *mgr)
719 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
720 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
721 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
722 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
723 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
724 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
725 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
726 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
729 void step(float dtime)
731 m_player_step_timer -= dtime;
735 // Locally stored sounds don't need to be preloaded because of this
736 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
738 std::set<std::string> m_fetched;
741 void fetchSounds(const std::string &name,
742 std::set<std::string> &dst_paths,
743 std::set<std::string> &dst_datas)
745 if(m_fetched.count(name))
747 m_fetched.insert(name);
748 std::string base = porting::path_share + DIR_DELIM + "testsounds";
749 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
750 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
751 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
752 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
753 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
754 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
755 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
756 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
757 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
758 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
759 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
763 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
766 bool *m_force_fog_off;
771 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
772 f32 *fog_range, Client *client):
774 m_force_fog_off(force_fog_off),
775 m_fog_range(fog_range),
778 ~GameGlobalShaderConstantSetter() {}
780 virtual void onSetConstants(video::IMaterialRendererServices *services,
787 video::SColor bgcolor = m_sky->getBgColor();
788 video::SColorf bgcolorf(bgcolor);
789 float bgcolorfa[4] = {
795 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
798 float fog_distance = *m_fog_range;
800 fog_distance = 10000*BS;
801 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
804 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
805 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
806 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
808 // Normal map texture layer
810 services->setPixelShaderConstant("normalTexture" , (irr::f32*)&layer, 1);
814 bool nodePlacementPrediction(Client &client,
815 const ItemDefinition &playeritem_def,
816 v3s16 nodepos, v3s16 neighbourpos)
818 std::string prediction = playeritem_def.node_placement_prediction;
819 INodeDefManager *nodedef = client.ndef();
820 ClientMap &map = client.getEnv().getClientMap();
822 if(prediction != "" && !nodedef->get(map.getNode(nodepos)).rightclickable)
824 verbosestream<<"Node placement prediction for "
825 <<playeritem_def.name<<" is "
826 <<prediction<<std::endl;
827 v3s16 p = neighbourpos;
828 // Place inside node itself if buildable_to
830 MapNode n_under = map.getNode(nodepos);
831 if(nodedef->get(n_under).buildable_to)
833 else if (!nodedef->get(map.getNode(p)).buildable_to)
835 }catch(InvalidPositionException &e){}
836 // Find id of predicted node
838 bool found = nodedef->getId(prediction, id);
840 errorstream<<"Node placement prediction failed for "
841 <<playeritem_def.name<<" (places "
843 <<") - Name not known"<<std::endl;
846 // Predict param2 for facedir and wallmounted nodes
848 if(nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED){
849 v3s16 dir = nodepos - neighbourpos;
850 if(abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))){
851 param2 = dir.Y < 0 ? 1 : 0;
852 } else if(abs(dir.X) > abs(dir.Z)){
853 param2 = dir.X < 0 ? 3 : 2;
855 param2 = dir.Z < 0 ? 5 : 4;
858 if(nodedef->get(id).param_type_2 == CPT2_FACEDIR){
859 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
860 if(abs(dir.X) > abs(dir.Z)){
861 param2 = dir.X < 0 ? 3 : 1;
863 param2 = dir.Z < 0 ? 2 : 0;
866 assert(param2 >= 0 && param2 <= 5);
867 //Check attachment if node is in group attached_node
868 if(((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0){
869 static v3s16 wallmounted_dirs[8] = {
878 if(nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
879 pp = p + wallmounted_dirs[param2];
881 pp = p + v3s16(0,-1,0);
882 if(!nodedef->get(map.getNode(pp)).walkable)
885 // Add node to client map
886 MapNode n(id, 0, param2);
888 // This triggers the required mesh update too
889 client.addNode(p, n);
891 }catch(InvalidPositionException &e){
892 errorstream<<"Node placement prediction failed for "
893 <<playeritem_def.name<<" (places "
895 <<") - Position not loaded"<<std::endl;
906 IrrlichtDevice *device,
909 std::string playername,
910 std::string password,
911 std::string address, // If "", local server is used
913 std::wstring &error_message,
914 std::string configpath,
915 ChatBackend &chat_backend,
916 const SubgameSpec &gamespec, // Used for local game,
917 bool simple_singleplayer_mode
920 FormspecFormSource* current_formspec = 0;
921 TextDestPlayerInventory* current_textdest = 0;
922 video::IVideoDriver* driver = device->getVideoDriver();
923 scene::ISceneManager* smgr = device->getSceneManager();
925 // Calculate text height using the font
926 u32 text_height = font->getDimension(L"Random test string").Height;
928 v2u32 last_screensize(0,0);
929 v2u32 screensize = driver->getScreenSize();
932 Draw "Loading" screen
936 wchar_t* text = wgettext("Loading...");
937 draw_load_screen(text, device, font,0,0);
941 // Create texture source
942 IWritableTextureSource *tsrc = createTextureSource(device);
944 // Create shader source
945 IWritableShaderSource *shsrc = createShaderSource(device);
947 // These will be filled by data received from the server
948 // Create item definition manager
949 IWritableItemDefManager *itemdef = createItemDefManager();
950 // Create node definition manager
951 IWritableNodeDefManager *nodedef = createNodeDefManager();
953 // Sound fetcher (useful when testing)
954 GameOnDemandSoundFetcher soundfetcher;
957 ISoundManager *sound = NULL;
958 bool sound_is_dummy = false;
960 if(g_settings->getBool("enable_sound")){
961 infostream<<"Attempting to use OpenAL audio"<<std::endl;
962 sound = createOpenALSoundManager(&soundfetcher);
964 infostream<<"Failed to initialize OpenAL audio"<<std::endl;
966 infostream<<"Sound disabled."<<std::endl;
970 infostream<<"Using dummy audio."<<std::endl;
971 sound = &dummySoundManager;
972 sound_is_dummy = true;
975 Server *server = NULL;
979 EventManager eventmgr;
982 SoundMaker soundmaker(sound, nodedef);
983 soundmaker.registerReceiver(&eventmgr);
985 // Add chat log output for errors to be shown in chat
986 LogOutputBuffer chat_log_error_buf(LMT_ERROR);
988 // Create UI for modifying quicktune values
989 QuicktuneShortcutter quicktune;
996 wchar_t* text = wgettext("Creating server....");
997 draw_load_screen(text, device, font,0,25);
999 infostream<<"Creating server"<<std::endl;
1000 server = new Server(map_dir, configpath, gamespec,
1001 simple_singleplayer_mode);
1002 server->start(port);
1005 do{ // Client scope (breakable do-while(0))
1012 wchar_t* text = wgettext("Creating client...");
1013 draw_load_screen(text, device, font,0,50);
1016 infostream<<"Creating client"<<std::endl;
1018 MapDrawControl draw_control;
1021 wchar_t* text = wgettext("Resolving address...");
1022 draw_load_screen(text, device, font,0,75);
1025 Address connect_address(0,0,0,0, port);
1029 //connect_address.Resolve("localhost");
1030 if(g_settings->getBool("enable_ipv6") && g_settings->getBool("ipv6_server"))
1032 IPv6AddressBytes addr_bytes;
1033 addr_bytes.bytes[15] = 1;
1034 connect_address.setAddress(&addr_bytes);
1038 connect_address.setAddress(127,0,0,1);
1042 connect_address.Resolve(address.c_str());
1044 catch(ResolveError &e)
1046 error_message = L"Couldn't resolve address: " + narrow_to_wide(e.what());
1047 errorstream<<wide_to_narrow(error_message)<<std::endl;
1048 // Break out of client scope
1055 Client client(device, playername.c_str(), password, draw_control,
1056 tsrc, shsrc, itemdef, nodedef, sound, &eventmgr,
1057 connect_address.isIPv6());
1059 // Client acts as our GameDef
1060 IGameDef *gamedef = &client;
1063 Attempt to connect to the server
1066 infostream<<"Connecting to server at ";
1067 connect_address.print(&infostream);
1068 infostream<<std::endl;
1069 client.connect(connect_address);
1072 Wait for server to accept connection
1074 bool could_connect = false;
1075 bool connect_aborted = false;
1077 float time_counter = 0.0;
1079 float fps_max = g_settings->getFloat("fps_max");
1080 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1081 u32 lasttime = device->getTimer()->getTime();
1082 while(device->run())
1084 f32 dtime = 0.033; // in seconds
1085 if (cloud_menu_background) {
1086 u32 time = device->getTimer()->getTime();
1088 dtime = (time - lasttime) / 1000.0;
1093 // Update client and server
1096 server->step(dtime);
1099 if(client.connectedAndInitialized()){
1100 could_connect = true;
1104 if(client.accessDenied()){
1105 error_message = L"Access denied. Reason: "
1106 +client.accessDeniedReason();
1107 errorstream<<wide_to_narrow(error_message)<<std::endl;
1110 if(input->wasKeyDown(EscapeKey)){
1111 connect_aborted = true;
1112 infostream<<"Connect aborted [Escape]"<<std::endl;
1118 wchar_t* text = wgettext("Connecting to server...");
1119 draw_load_screen(text, device, font, dtime, 100);
1123 // On some computers framerate doesn't seem to be
1124 // automatically limited
1125 if (cloud_menu_background) {
1126 // Time of frame without fps limit
1129 // not using getRealTime is necessary for wine
1130 u32 time = device->getTimer()->getTime();
1132 busytime_u32 = time - lasttime;
1135 busytime = busytime_u32 / 1000.0;
1138 u32 frametime_min = 1000./fps_max;
1140 if(busytime_u32 < frametime_min) {
1141 u32 sleeptime = frametime_min - busytime_u32;
1142 device->sleep(sleeptime);
1147 time_counter += dtime;
1150 catch(con::PeerNotFoundException &e)
1154 Handle failure to connect
1157 if(error_message == L"" && !connect_aborted){
1158 error_message = L"Connection failed";
1159 errorstream<<wide_to_narrow(error_message)<<std::endl;
1161 // Break out of client scope
1166 Wait until content has been received
1168 bool got_content = false;
1169 bool content_aborted = false;
1171 float time_counter = 0.0;
1173 float fps_max = g_settings->getFloat("fps_max");
1174 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1175 u32 lasttime = device->getTimer()->getTime();
1176 while(device->run())
1178 f32 dtime = 0.033; // in seconds
1179 if (cloud_menu_background) {
1180 u32 time = device->getTimer()->getTime();
1182 dtime = (time - lasttime) / 1000.0;
1187 // Update client and server
1190 server->step(dtime);
1193 if(client.texturesReceived() &&
1194 client.itemdefReceived() &&
1195 client.nodedefReceived()){
1200 if(!client.connectedAndInitialized()){
1201 error_message = L"Client disconnected";
1202 errorstream<<wide_to_narrow(error_message)<<std::endl;
1205 if(input->wasKeyDown(EscapeKey)){
1206 content_aborted = true;
1207 infostream<<"Connect aborted [Escape]"<<std::endl;
1213 if (!client.itemdefReceived())
1215 wchar_t* text = wgettext("Item definitions...");
1217 draw_load_screen(text, device, font, dtime, progress);
1220 else if (!client.nodedefReceived())
1222 wchar_t* text = wgettext("Node definitions...");
1224 draw_load_screen(text, device, font, dtime, progress);
1229 wchar_t* text = wgettext("Media...");
1230 progress = 50+client.mediaReceiveProgress()*50+0.5;
1231 draw_load_screen(text, device, font, dtime, progress);
1235 // On some computers framerate doesn't seem to be
1236 // automatically limited
1237 if (cloud_menu_background) {
1238 // Time of frame without fps limit
1241 // not using getRealTime is necessary for wine
1242 u32 time = device->getTimer()->getTime();
1244 busytime_u32 = time - lasttime;
1247 busytime = busytime_u32 / 1000.0;
1250 u32 frametime_min = 1000./fps_max;
1252 if(busytime_u32 < frametime_min) {
1253 u32 sleeptime = frametime_min - busytime_u32;
1254 device->sleep(sleeptime);
1259 time_counter += dtime;
1264 if(error_message == L"" && !content_aborted){
1265 error_message = L"Something failed";
1266 errorstream<<wide_to_narrow(error_message)<<std::endl;
1268 // Break out of client scope
1273 After all content has been received:
1274 Update cached textures, meshes and materials
1276 client.afterContentReceived(device,font);
1279 Create the camera node
1281 Camera camera(smgr, draw_control, gamedef);
1282 if (!camera.successfullyCreated(error_message))
1285 f32 camera_yaw = 0; // "right/left"
1286 f32 camera_pitch = 0; // "up/down"
1292 Clouds *clouds = NULL;
1293 if(g_settings->getBool("enable_clouds"))
1295 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1303 sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1309 FarMesh *farmesh = NULL;
1310 if(g_settings->getBool("enable_farmesh"))
1312 farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
1316 A copy of the local inventory
1318 Inventory local_inventory(itemdef);
1321 Find out size of crack animation
1323 int crack_animation_length = 5;
1325 video::ITexture *t = tsrc->getTexture("crack_anylength.png");
1326 v2u32 size = t->getOriginalSize();
1327 crack_animation_length = size.Y / size.X;
1334 // First line of debug text
1335 gui::IGUIStaticText *guitext = guienv->addStaticText(
1337 core::rect<s32>(5, 5, 795, 5+text_height),
1339 // Second line of debug text
1340 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1342 core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
1344 // At the middle of the screen
1345 // Object infos are shown in this
1346 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1348 core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1351 // Status text (displays info when showing and hiding GUI stuff, etc.)
1352 gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1354 core::rect<s32>(0,0,0,0),
1356 guitext_status->setVisible(false);
1358 std::wstring statustext;
1359 float statustext_time = 0;
1362 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1364 core::rect<s32>(0,0,0,0),
1365 //false, false); // Disable word wrap as of now
1367 // Remove stale "recent" chat messages from previous connections
1368 chat_backend.clearRecentChat();
1369 // Chat backend and console
1370 GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1372 // Profiler text (size is updated when text is updated)
1373 gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1375 core::rect<s32>(0,0,0,0),
1377 guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1378 guitext_profiler->setVisible(false);
1379 guitext_profiler->setWordWrap(true);
1382 Some statistics are collected in these
1385 u32 beginscenetime = 0;
1387 u32 endscenetime = 0;
1389 float recent_turn_speed = 0.0;
1391 ProfilerGraph graph;
1392 // Initially clear the profiler
1393 Profiler::GraphValues dummyvalues;
1394 g_profiler->graphGet(dummyvalues);
1396 float nodig_delay_timer = 0.0;
1397 float dig_time = 0.0;
1399 PointedThing pointed_old;
1400 bool digging = false;
1401 bool ldown_for_dig = false;
1403 float damage_flash = 0;
1404 s16 farmesh_range = 20*MAP_BLOCKSIZE;
1406 float jump_timer = 0;
1407 bool reset_jump_timer = false;
1409 const float object_hit_delay = 0.2;
1410 float object_hit_delay_timer = 0.0;
1411 float time_from_last_punch = 10;
1413 float update_draw_list_timer = 0.0;
1414 v3f update_draw_list_last_cam_dir;
1416 bool invert_mouse = g_settings->getBool("invert_mouse");
1418 bool respawn_menu_active = false;
1419 bool update_wielded_item_trigger = false;
1421 bool show_hud = true;
1422 bool show_chat = true;
1423 bool force_fog_off = false;
1424 f32 fog_range = 100*BS;
1425 bool disable_camera_update = false;
1426 bool show_debug = g_settings->getBool("show_debug");
1427 bool show_profiler_graph = false;
1428 u32 show_profiler = 0;
1429 u32 show_profiler_max = 3; // Number of pages
1431 float time_of_day = 0;
1432 float time_of_day_smooth = 0;
1434 float repeat_rightclick_timer = 0;
1439 shsrc->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1440 sky, &force_fog_off, &fog_range, &client));
1446 bool first_loop_after_window_activation = true;
1448 // TODO: Convert the static interval timers to these
1449 // Interval limiter for profiler
1450 IntervalLimiter m_profiler_interval;
1452 // Time is in milliseconds
1453 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1454 // NOTE: So we have to use getTime() and call run()s between them
1455 u32 lasttime = device->getTimer()->getTime();
1457 LocalPlayer* player = client.getEnv().getLocalPlayer();
1458 player->hurt_tilt_timer = 0;
1459 player->hurt_tilt_strength = 0;
1464 Hud hud(driver, guienv, font, text_height,
1465 gamedef, player, &local_inventory);
1469 if(device->run() == false || kill == true)
1472 // Time of frame without fps limit
1476 // not using getRealTime is necessary for wine
1477 u32 time = device->getTimer()->getTime();
1479 busytime_u32 = time - lasttime;
1482 busytime = busytime_u32 / 1000.0;
1485 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1487 // Necessary for device->getTimer()->getTime()
1495 float fps_max = g_settings->getFloat("fps_max");
1496 u32 frametime_min = 1000./fps_max;
1498 if(busytime_u32 < frametime_min)
1500 u32 sleeptime = frametime_min - busytime_u32;
1501 device->sleep(sleeptime);
1502 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1506 // Necessary for device->getTimer()->getTime()
1510 Time difference calculation
1512 f32 dtime; // in seconds
1514 u32 time = device->getTimer()->getTime();
1516 dtime = (time - lasttime) / 1000.0;
1521 g_profiler->graphAdd("mainloop_dtime", dtime);
1525 if(nodig_delay_timer >= 0)
1526 nodig_delay_timer -= dtime;
1527 if(object_hit_delay_timer >= 0)
1528 object_hit_delay_timer -= dtime;
1529 time_from_last_punch += dtime;
1531 g_profiler->add("Elapsed time", dtime);
1532 g_profiler->avg("FPS", 1./dtime);
1535 Time average and jitter calculation
1538 static f32 dtime_avg1 = 0.0;
1539 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1540 f32 dtime_jitter1 = dtime - dtime_avg1;
1542 static f32 dtime_jitter1_max_sample = 0.0;
1543 static f32 dtime_jitter1_max_fraction = 0.0;
1545 static f32 jitter1_max = 0.0;
1546 static f32 counter = 0.0;
1547 if(dtime_jitter1 > jitter1_max)
1548 jitter1_max = dtime_jitter1;
1553 dtime_jitter1_max_sample = jitter1_max;
1554 dtime_jitter1_max_fraction
1555 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1561 Busytime average and jitter calculation
1564 static f32 busytime_avg1 = 0.0;
1565 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1566 f32 busytime_jitter1 = busytime - busytime_avg1;
1568 static f32 busytime_jitter1_max_sample = 0.0;
1569 static f32 busytime_jitter1_min_sample = 0.0;
1571 static f32 jitter1_max = 0.0;
1572 static f32 jitter1_min = 0.0;
1573 static f32 counter = 0.0;
1574 if(busytime_jitter1 > jitter1_max)
1575 jitter1_max = busytime_jitter1;
1576 if(busytime_jitter1 < jitter1_min)
1577 jitter1_min = busytime_jitter1;
1581 busytime_jitter1_max_sample = jitter1_max;
1582 busytime_jitter1_min_sample = jitter1_min;
1589 Handle miscellaneous stuff
1592 if(client.accessDenied())
1594 error_message = L"Access denied. Reason: "
1595 +client.accessDeniedReason();
1596 errorstream<<wide_to_narrow(error_message)<<std::endl;
1600 if(g_gamecallback->disconnect_requested)
1602 g_gamecallback->disconnect_requested = false;
1606 if(g_gamecallback->changepassword_requested)
1608 (new GUIPasswordChange(guienv, guiroot, -1,
1609 &g_menumgr, &client))->drop();
1610 g_gamecallback->changepassword_requested = false;
1613 if(g_gamecallback->changevolume_requested)
1615 (new GUIVolumeChange(guienv, guiroot, -1,
1616 &g_menumgr, &client))->drop();
1617 g_gamecallback->changevolume_requested = false;
1620 /* Process TextureSource's queue */
1621 tsrc->processQueue();
1623 /* Process ItemDefManager's queue */
1624 itemdef->processQueue(gamedef);
1627 Process ShaderSource's queue
1629 shsrc->processQueue();
1634 last_screensize = screensize;
1635 screensize = driver->getScreenSize();
1636 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1637 //bool screensize_changed = screensize != last_screensize;
1640 // Update HUD values
1641 hud.screensize = screensize;
1642 hud.displaycenter = displaycenter;
1645 // Hilight boxes collected during the loop and displayed
1646 std::vector<aabb3f> hilightboxes;
1649 std::wstring infotext;
1652 Debug info for client
1655 static float counter = 0.0;
1660 client.printDebugInfo(infostream);
1667 float profiler_print_interval =
1668 g_settings->getFloat("profiler_print_interval");
1669 bool print_to_log = true;
1670 if(profiler_print_interval == 0){
1671 print_to_log = false;
1672 profiler_print_interval = 5;
1674 if(m_profiler_interval.step(dtime, profiler_print_interval))
1677 infostream<<"Profiler:"<<std::endl;
1678 g_profiler->print(infostream);
1681 update_profiler_gui(guitext_profiler, font, text_height,
1682 show_profiler, show_profiler_max);
1684 g_profiler->clear();
1688 Direct handling of user input
1691 // Reset input if window not active or some menu is active
1692 if(device->isWindowActive() == false
1693 || noMenuActive() == false
1694 || guienv->hasFocus(gui_chat_console))
1698 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen())
1700 gui_chat_console->closeConsoleAtOnce();
1703 // Input handler step() (used by the random input generator)
1706 // Increase timer for doubleclick of "jump"
1707 if(g_settings->getBool("doubletap_jump") && jump_timer <= 0.2)
1708 jump_timer += dtime;
1711 Launch menus and trigger stuff according to keys
1713 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1715 // drop selected item
1716 IDropAction *a = new IDropAction();
1718 a->from_inv.setCurrentPlayer();
1719 a->from_list = "main";
1720 a->from_i = client.getPlayerItem();
1721 client.inventoryAction(a);
1723 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1725 infostream<<"the_game: "
1726 <<"Launching inventory"<<std::endl;
1728 GUIFormSpecMenu *menu =
1729 new GUIFormSpecMenu(device, guiroot, -1,
1733 InventoryLocation inventoryloc;
1734 inventoryloc.setCurrentPlayer();
1736 PlayerInventoryFormSource *src = new PlayerInventoryFormSource(&client);
1738 menu->setFormSpec(src->getForm(), inventoryloc);
1739 menu->setFormSource(src);
1740 menu->setTextDest(new TextDestPlayerInventory(&client));
1743 else if(input->wasKeyDown(EscapeKey))
1745 infostream<<"the_game: "
1746 <<"Launching pause menu"<<std::endl;
1747 // It will delete itself by itself
1748 (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1749 &g_menumgr, simple_singleplayer_mode))->drop();
1751 // Move mouse cursor on top of the disconnect button
1752 if(simple_singleplayer_mode)
1753 input->setMousePos(displaycenter.X, displaycenter.Y+0);
1755 input->setMousePos(displaycenter.X, displaycenter.Y+25);
1757 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1759 TextDest *dest = new TextDestChat(&client);
1761 (new GUITextInputMenu(guienv, guiroot, -1,
1765 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1767 TextDest *dest = new TextDestChat(&client);
1769 (new GUITextInputMenu(guienv, guiroot, -1,
1773 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1775 if (!gui_chat_console->isOpenInhibited())
1777 // Open up to over half of the screen
1778 gui_chat_console->openConsole(0.6);
1779 guienv->setFocus(gui_chat_console);
1782 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1784 if(g_settings->getBool("free_move"))
1786 g_settings->set("free_move","false");
1787 statustext = L"free_move disabled";
1788 statustext_time = 0;
1792 g_settings->set("free_move","true");
1793 statustext = L"free_move enabled";
1794 statustext_time = 0;
1795 if(!client.checkPrivilege("fly"))
1796 statustext += L" (note: no 'fly' privilege)";
1799 else if(input->wasKeyDown(getKeySetting("keymap_jump")))
1801 if(g_settings->getBool("doubletap_jump") && jump_timer < 0.2)
1803 if(g_settings->getBool("free_move"))
1805 g_settings->set("free_move","false");
1806 statustext = L"free_move disabled";
1807 statustext_time = 0;
1811 g_settings->set("free_move","true");
1812 statustext = L"free_move enabled";
1813 statustext_time = 0;
1814 if(!client.checkPrivilege("fly"))
1815 statustext += L" (note: no 'fly' privilege)";
1818 reset_jump_timer = true;
1820 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1822 if(g_settings->getBool("fast_move"))
1824 g_settings->set("fast_move","false");
1825 statustext = L"fast_move disabled";
1826 statustext_time = 0;
1830 g_settings->set("fast_move","true");
1831 statustext = L"fast_move enabled";
1832 statustext_time = 0;
1833 if(!client.checkPrivilege("fast"))
1834 statustext += L" (note: no 'fast' privilege)";
1837 else if(input->wasKeyDown(getKeySetting("keymap_noclip")))
1839 if(g_settings->getBool("noclip"))
1841 g_settings->set("noclip","false");
1842 statustext = L"noclip disabled";
1843 statustext_time = 0;
1847 g_settings->set("noclip","true");
1848 statustext = L"noclip enabled";
1849 statustext_time = 0;
1850 if(!client.checkPrivilege("noclip"))
1851 statustext += L" (note: no 'noclip' privilege)";
1854 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1856 irr::video::IImage* const image = driver->createScreenShot();
1858 irr::c8 filename[256];
1859 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png",
1860 g_settings->get("screenshot_path").c_str(),
1861 device->getTimer()->getRealTime());
1862 if (driver->writeImageToFile(image, filename)) {
1863 std::wstringstream sstr;
1864 sstr<<"Saved screenshot to '"<<filename<<"'";
1865 infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1866 statustext = sstr.str();
1867 statustext_time = 0;
1869 infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1874 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
1876 show_hud = !show_hud;
1878 statustext = L"HUD shown";
1880 statustext = L"HUD hidden";
1881 statustext_time = 0;
1883 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
1885 show_chat = !show_chat;
1887 statustext = L"Chat shown";
1889 statustext = L"Chat hidden";
1890 statustext_time = 0;
1892 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1894 force_fog_off = !force_fog_off;
1896 statustext = L"Fog disabled";
1898 statustext = L"Fog enabled";
1899 statustext_time = 0;
1901 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1903 disable_camera_update = !disable_camera_update;
1904 if(disable_camera_update)
1905 statustext = L"Camera update disabled";
1907 statustext = L"Camera update enabled";
1908 statustext_time = 0;
1910 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
1912 // Initial / 3x toggle: Chat only
1913 // 1x toggle: Debug text with chat
1914 // 2x toggle: Debug text with profiler graph
1918 show_profiler_graph = false;
1919 statustext = L"Debug info shown";
1920 statustext_time = 0;
1922 else if(show_profiler_graph)
1925 show_profiler_graph = false;
1926 statustext = L"Debug info and profiler graph hidden";
1927 statustext_time = 0;
1931 show_profiler_graph = true;
1932 statustext = L"Profiler graph shown";
1933 statustext_time = 0;
1936 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1938 show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
1940 // FIXME: This updates the profiler with incomplete values
1941 update_profiler_gui(guitext_profiler, font, text_height,
1942 show_profiler, show_profiler_max);
1944 if(show_profiler != 0)
1946 std::wstringstream sstr;
1947 sstr<<"Profiler shown (page "<<show_profiler
1948 <<" of "<<show_profiler_max<<")";
1949 statustext = sstr.str();
1950 statustext_time = 0;
1954 statustext = L"Profiler hidden";
1955 statustext_time = 0;
1958 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
1960 s16 range = g_settings->getS16("viewing_range_nodes_min");
1961 s16 range_new = range + 10;
1962 g_settings->set("viewing_range_nodes_min", itos(range_new));
1963 statustext = narrow_to_wide(
1964 "Minimum viewing range changed to "
1966 statustext_time = 0;
1968 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
1970 s16 range = g_settings->getS16("viewing_range_nodes_min");
1971 s16 range_new = range - 10;
1974 g_settings->set("viewing_range_nodes_min",
1976 statustext = narrow_to_wide(
1977 "Minimum viewing range changed to "
1979 statustext_time = 0;
1983 if(!input->isKeyDown(getKeySetting("keymap_jump")) && reset_jump_timer)
1985 reset_jump_timer = false;
1989 // Handle QuicktuneShortcutter
1990 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
1992 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
1994 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
1996 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
1999 std::string msg = quicktune.getMessage();
2001 statustext = narrow_to_wide(msg);
2002 statustext_time = 0;
2006 // Item selection with mouse wheel
2007 u16 new_playeritem = client.getPlayerItem();
2009 s32 wheel = input->getMouseWheel();
2010 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
2011 player->hud_hotbar_itemcount-1);
2015 if(new_playeritem < max_item)
2022 if(new_playeritem > 0)
2025 new_playeritem = max_item;
2030 for(u16 i=0; i<10; i++)
2032 const KeyPress *kp = NumberKey + (i + 1) % 10;
2033 if(input->wasKeyDown(*kp))
2035 if(i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount)
2039 infostream<<"Selected item: "
2040 <<new_playeritem<<std::endl;
2045 // Viewing range selection
2046 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
2048 draw_control.range_all = !draw_control.range_all;
2049 if(draw_control.range_all)
2051 infostream<<"Enabled full viewing range"<<std::endl;
2052 statustext = L"Enabled full viewing range";
2053 statustext_time = 0;
2057 infostream<<"Disabled full viewing range"<<std::endl;
2058 statustext = L"Disabled full viewing range";
2059 statustext_time = 0;
2063 // Print debug stacks
2064 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
2066 dstream<<"-----------------------------------------"
2068 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
2069 dstream<<"-----------------------------------------"
2071 debug_stacks_print();
2075 Mouse and camera control
2076 NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
2079 float turn_amount = 0;
2080 if((device->isWindowActive() && noMenuActive()) || random_input)
2084 // Mac OSX gets upset if this is set every frame
2085 if(device->getCursorControl()->isVisible())
2086 device->getCursorControl()->setVisible(false);
2089 if(first_loop_after_window_activation){
2090 //infostream<<"window active, first loop"<<std::endl;
2091 first_loop_after_window_activation = false;
2094 s32 dx = input->getMousePos().X - displaycenter.X;
2095 s32 dy = input->getMousePos().Y - displaycenter.Y;
2098 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
2100 /*const float keyspeed = 500;
2101 if(input->isKeyDown(irr::KEY_UP))
2102 dy -= dtime * keyspeed;
2103 if(input->isKeyDown(irr::KEY_DOWN))
2104 dy += dtime * keyspeed;
2105 if(input->isKeyDown(irr::KEY_LEFT))
2106 dx -= dtime * keyspeed;
2107 if(input->isKeyDown(irr::KEY_RIGHT))
2108 dx += dtime * keyspeed;*/
2110 float d = g_settings->getFloat("mouse_sensitivity");
2111 d = rangelim(d, 0.01, 100.0);
2113 camera_pitch += dy*d;
2114 if(camera_pitch < -89.5) camera_pitch = -89.5;
2115 if(camera_pitch > 89.5) camera_pitch = 89.5;
2117 turn_amount = v2f(dx, dy).getLength() * d;
2119 input->setMousePos(displaycenter.X, displaycenter.Y);
2122 // Mac OSX gets upset if this is set every frame
2123 if(device->getCursorControl()->isVisible() == false)
2124 device->getCursorControl()->setVisible(true);
2126 //infostream<<"window inactive"<<std::endl;
2127 first_loop_after_window_activation = true;
2129 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
2130 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
2133 Player speed control
2147 PlayerControl control(
2148 input->isKeyDown(getKeySetting("keymap_forward")),
2149 input->isKeyDown(getKeySetting("keymap_backward")),
2150 input->isKeyDown(getKeySetting("keymap_left")),
2151 input->isKeyDown(getKeySetting("keymap_right")),
2152 input->isKeyDown(getKeySetting("keymap_jump")),
2153 input->isKeyDown(getKeySetting("keymap_special1")),
2154 input->isKeyDown(getKeySetting("keymap_sneak")),
2155 input->getLeftState(),
2156 input->getRightState(),
2160 client.setPlayerControl(control);
2162 1*(int)input->isKeyDown(getKeySetting("keymap_forward"))+
2163 2*(int)input->isKeyDown(getKeySetting("keymap_backward"))+
2164 4*(int)input->isKeyDown(getKeySetting("keymap_left"))+
2165 8*(int)input->isKeyDown(getKeySetting("keymap_right"))+
2166 16*(int)input->isKeyDown(getKeySetting("keymap_jump"))+
2167 32*(int)input->isKeyDown(getKeySetting("keymap_special1"))+
2168 64*(int)input->isKeyDown(getKeySetting("keymap_sneak"))+
2169 128*(int)input->getLeftState()+
2170 256*(int)input->getRightState();
2171 LocalPlayer* player = client.getEnv().getLocalPlayer();
2172 player->keyPressed=keyPressed;
2181 //TimeTaker timer("server->step(dtime)");
2182 server->step(dtime);
2190 //TimeTaker timer("client.step(dtime)");
2192 //client.step(dtime_avg1);
2196 // Read client events
2199 ClientEvent event = client.getClientEvent();
2200 if(event.type == CE_NONE)
2204 else if(event.type == CE_PLAYER_DAMAGE &&
2205 client.getHP() != 0)
2207 //u16 damage = event.player_damage.amount;
2208 //infostream<<"Player damage: "<<damage<<std::endl;
2210 damage_flash += 100.0;
2211 damage_flash += 8.0 * event.player_damage.amount;
2213 player->hurt_tilt_timer = 1.5;
2214 player->hurt_tilt_strength = event.player_damage.amount/2;
2215 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 2.0, 10.0);
2217 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
2218 gamedef->event()->put(e);
2220 else if(event.type == CE_PLAYER_FORCE_MOVE)
2222 camera_yaw = event.player_force_move.yaw;
2223 camera_pitch = event.player_force_move.pitch;
2225 else if(event.type == CE_DEATHSCREEN)
2227 if(respawn_menu_active)
2230 /*bool set_camera_point_target =
2231 event.deathscreen.set_camera_point_target;
2232 v3f camera_point_target;
2233 camera_point_target.X = event.deathscreen.camera_point_target_x;
2234 camera_point_target.Y = event.deathscreen.camera_point_target_y;
2235 camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
2236 MainRespawnInitiator *respawner =
2237 new MainRespawnInitiator(
2238 &respawn_menu_active, &client);
2239 GUIDeathScreen *menu =
2240 new GUIDeathScreen(guienv, guiroot, -1,
2241 &g_menumgr, respawner);
2244 chat_backend.addMessage(L"", L"You died.");
2246 /* Handle visualization */
2250 LocalPlayer* player = client.getEnv().getLocalPlayer();
2251 player->hurt_tilt_timer = 0;
2252 player->hurt_tilt_strength = 0;
2254 /*LocalPlayer* player = client.getLocalPlayer();
2255 player->setPosition(player->getPosition() + v3f(0,-BS,0));
2256 camera.update(player, busytime, screensize);*/
2258 else if (event.type == CE_SHOW_FORMSPEC)
2260 if (current_formspec == 0)
2263 /* Note: FormspecFormSource and TextDestPlayerInventory
2264 * are deleted by guiFormSpecMenu */
2265 current_formspec = new FormspecFormSource(*(event.show_formspec.formspec),¤t_formspec);
2266 current_textdest = new TextDestPlayerInventory(&client,*(event.show_formspec.formname));
2267 GUIFormSpecMenu *menu =
2268 new GUIFormSpecMenu(device, guiroot, -1,
2271 menu->setFormSource(current_formspec);
2272 menu->setTextDest(current_textdest);
2277 assert(current_textdest != 0);
2279 current_textdest->setFormName(*(event.show_formspec.formname));
2280 current_formspec->setForm(*(event.show_formspec.formspec));
2282 delete(event.show_formspec.formspec);
2283 delete(event.show_formspec.formname);
2285 else if(event.type == CE_TEXTURES_UPDATED)
2287 update_wielded_item_trigger = true;
2289 else if(event.type == CE_SPAWN_PARTICLE)
2291 LocalPlayer* player = client.getEnv().getLocalPlayer();
2292 video::ITexture *texture =
2293 gamedef->tsrc()->getTexture(*(event.spawn_particle.texture));
2295 new Particle(gamedef, smgr, player, client.getEnv(),
2296 *event.spawn_particle.pos,
2297 *event.spawn_particle.vel,
2298 *event.spawn_particle.acc,
2299 event.spawn_particle.expirationtime,
2300 event.spawn_particle.size,
2301 event.spawn_particle.collisiondetection,
2306 else if(event.type == CE_ADD_PARTICLESPAWNER)
2308 LocalPlayer* player = client.getEnv().getLocalPlayer();
2309 video::ITexture *texture =
2310 gamedef->tsrc()->getTexture(*(event.add_particlespawner.texture));
2312 new ParticleSpawner(gamedef, smgr, player,
2313 event.add_particlespawner.amount,
2314 event.add_particlespawner.spawntime,
2315 *event.add_particlespawner.minpos,
2316 *event.add_particlespawner.maxpos,
2317 *event.add_particlespawner.minvel,
2318 *event.add_particlespawner.maxvel,
2319 *event.add_particlespawner.minacc,
2320 *event.add_particlespawner.maxacc,
2321 event.add_particlespawner.minexptime,
2322 event.add_particlespawner.maxexptime,
2323 event.add_particlespawner.minsize,
2324 event.add_particlespawner.maxsize,
2325 event.add_particlespawner.collisiondetection,
2327 event.add_particlespawner.id);
2329 else if(event.type == CE_DELETE_PARTICLESPAWNER)
2331 delete_particlespawner (event.delete_particlespawner.id);
2333 else if (event.type == CE_HUDADD)
2335 u32 id = event.hudadd.id;
2336 size_t nhudelem = player->hud.size();
2337 if (id > nhudelem || (id < nhudelem && player->hud[id])) {
2338 delete event.hudadd.pos;
2339 delete event.hudadd.name;
2340 delete event.hudadd.scale;
2341 delete event.hudadd.text;
2342 delete event.hudadd.align;
2343 delete event.hudadd.offset;
2347 HudElement *e = new HudElement;
2348 e->type = (HudElementType)event.hudadd.type;
2349 e->pos = *event.hudadd.pos;
2350 e->name = *event.hudadd.name;
2351 e->scale = *event.hudadd.scale;
2352 e->text = *event.hudadd.text;
2353 e->number = event.hudadd.number;
2354 e->item = event.hudadd.item;
2355 e->dir = event.hudadd.dir;
2356 e->align = *event.hudadd.align;
2357 e->offset = *event.hudadd.offset;
2360 player->hud.push_back(e);
2362 player->hud[id] = e;
2364 delete event.hudadd.pos;
2365 delete event.hudadd.name;
2366 delete event.hudadd.scale;
2367 delete event.hudadd.text;
2368 delete event.hudadd.align;
2369 delete event.hudadd.offset;
2371 else if (event.type == CE_HUDRM)
2373 u32 id = event.hudrm.id;
2374 if (id < player->hud.size() && player->hud[id]) {
2375 delete player->hud[id];
2376 player->hud[id] = NULL;
2379 else if (event.type == CE_HUDCHANGE)
2381 u32 id = event.hudchange.id;
2382 if (id >= player->hud.size() || !player->hud[id]) {
2383 delete event.hudchange.v2fdata;
2384 delete event.hudchange.sdata;
2388 HudElement* e = player->hud[id];
2389 switch (event.hudchange.stat) {
2391 e->pos = *event.hudchange.v2fdata;
2394 e->name = *event.hudchange.sdata;
2396 case HUD_STAT_SCALE:
2397 e->scale = *event.hudchange.v2fdata;
2400 e->text = *event.hudchange.sdata;
2402 case HUD_STAT_NUMBER:
2403 e->number = event.hudchange.data;
2406 e->item = event.hudchange.data;
2409 e->dir = event.hudchange.data;
2411 case HUD_STAT_ALIGN:
2412 e->align = *event.hudchange.v2fdata;
2414 case HUD_STAT_OFFSET:
2415 e->offset = *event.hudchange.v2fdata;
2419 delete event.hudchange.v2fdata;
2420 delete event.hudchange.sdata;
2425 //TimeTaker //timer2("//timer2");
2428 For interaction purposes, get info about the held item
2430 - Is it a usable item?
2431 - Can it point to liquids?
2433 ItemStack playeritem;
2435 InventoryList *mlist = local_inventory.getList("main");
2438 playeritem = mlist->getItem(client.getPlayerItem());
2441 const ItemDefinition &playeritem_def =
2442 playeritem.getDefinition(itemdef);
2443 ToolCapabilities playeritem_toolcap =
2444 playeritem.getToolCapabilities(itemdef);
2450 LocalPlayer* player = client.getEnv().getLocalPlayer();
2451 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2452 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
2453 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2454 camera.update(player, busytime, screensize, tool_reload_ratio);
2457 v3f player_position = player->getPosition();
2458 v3f camera_position = camera.getPosition();
2459 v3f camera_direction = camera.getDirection();
2460 f32 camera_fov = camera.getFovMax();
2462 if(!disable_camera_update){
2463 client.getEnv().getClientMap().updateCamera(camera_position,
2464 camera_direction, camera_fov);
2467 // Update sound listener
2468 sound->updateListener(camera.getCameraNode()->getPosition(),
2469 v3f(0,0,0), // velocity
2470 camera.getDirection(),
2471 camera.getCameraNode()->getUpVector());
2472 sound->setListenerGain(g_settings->getFloat("sound_volume"));
2478 soundmaker.step(dtime);
2480 ClientMap &map = client.getEnv().getClientMap();
2481 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
2482 soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
2486 Calculate what block is the crosshair pointing to
2489 //u32 t1 = device->getTimer()->getRealTime();
2491 f32 d = 4; // max. distance
2492 core::line3d<f32> shootline(camera_position,
2493 camera_position + camera_direction * BS * (d+1));
2495 ClientActiveObject *selected_object = NULL;
2497 PointedThing pointed = getPointedThing(
2499 &client, player_position, camera_direction,
2500 camera_position, shootline, d,
2501 playeritem_def.liquids_pointable, !ldown_for_dig,
2506 if(pointed != pointed_old)
2508 infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2509 //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
2514 - releasing left mouse button
2515 - pointing away from node
2519 if(input->getLeftReleased())
2521 infostream<<"Left button released"
2522 <<" (stopped digging)"<<std::endl;
2525 else if(pointed != pointed_old)
2527 if (pointed.type == POINTEDTHING_NODE
2528 && pointed_old.type == POINTEDTHING_NODE
2529 && pointed.node_undersurface == pointed_old.node_undersurface)
2531 // Still pointing to the same node,
2532 // but a different face. Don't reset.
2536 infostream<<"Pointing away from node"
2537 <<" (stopped digging)"<<std::endl;
2543 client.interact(1, pointed_old);
2544 client.setCrack(-1, v3s16(0,0,0));
2548 if(!digging && ldown_for_dig && !input->getLeftState())
2550 ldown_for_dig = false;
2553 bool left_punch = false;
2554 soundmaker.m_player_leftpunch_sound.name = "";
2556 if(input->getRightState())
2557 repeat_rightclick_timer += dtime;
2559 repeat_rightclick_timer = 0;
2561 if(playeritem_def.usable && input->getLeftState())
2563 if(input->getLeftClicked())
2564 client.interact(4, pointed);
2566 else if(pointed.type == POINTEDTHING_NODE)
2568 v3s16 nodepos = pointed.node_undersurface;
2569 v3s16 neighbourpos = pointed.node_abovesurface;
2572 Check information text of node
2575 ClientMap &map = client.getEnv().getClientMap();
2576 NodeMetadata *meta = map.getNodeMetadata(nodepos);
2578 infotext = narrow_to_wide(meta->getString("infotext"));
2580 MapNode n = map.getNode(nodepos);
2581 if(nodedef->get(n).tiledef[0].name == "unknown_node.png"){
2582 infotext = L"Unknown node: ";
2583 infotext += narrow_to_wide(nodedef->get(n).name);
2591 if(nodig_delay_timer <= 0.0 && input->getLeftState()
2592 && client.checkPrivilege("interact"))
2596 infostream<<"Started digging"<<std::endl;
2597 client.interact(0, pointed);
2599 ldown_for_dig = true;
2601 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2603 // NOTE: Similar piece of code exists on the server side for
2605 // Get digging parameters
2606 DigParams params = getDigParams(nodedef->get(n).groups,
2607 &playeritem_toolcap);
2608 // If can't dig, try hand
2609 if(!params.diggable){
2610 const ItemDefinition &hand = itemdef->get("");
2611 const ToolCapabilities *tp = hand.tool_capabilities;
2613 params = getDigParams(nodedef->get(n).groups, tp);
2616 float dig_time_complete = 0.0;
2618 if(params.diggable == false)
2620 // I guess nobody will wait for this long
2621 dig_time_complete = 10000000.0;
2625 dig_time_complete = params.time;
2626 if (g_settings->getBool("enable_particles"))
2628 const ContentFeatures &features =
2629 client.getNodeDefManager()->get(n);
2630 addPunchingParticles
2631 (gamedef, smgr, player, client.getEnv(),
2632 nodepos, features.tiles);
2636 if(dig_time_complete >= 0.001)
2638 dig_index = (u16)((float)crack_animation_length
2639 * dig_time/dig_time_complete);
2641 // This is for torches
2644 dig_index = crack_animation_length;
2647 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2648 if(sound_dig.exists() && params.diggable){
2649 if(sound_dig.name == "__group"){
2650 if(params.main_group != ""){
2651 soundmaker.m_player_leftpunch_sound.gain = 0.5;
2652 soundmaker.m_player_leftpunch_sound.name =
2653 std::string("default_dig_") +
2657 soundmaker.m_player_leftpunch_sound = sound_dig;
2661 // Don't show cracks if not diggable
2662 if(dig_time_complete >= 100000.0)
2665 else if(dig_index < crack_animation_length)
2667 //TimeTaker timer("client.setTempMod");
2668 //infostream<<"dig_index="<<dig_index<<std::endl;
2669 client.setCrack(dig_index, nodepos);
2673 infostream<<"Digging completed"<<std::endl;
2674 client.interact(2, pointed);
2675 client.setCrack(-1, v3s16(0,0,0));
2676 MapNode wasnode = map.getNode(nodepos);
2677 client.removeNode(nodepos);
2679 if (g_settings->getBool("enable_particles"))
2681 const ContentFeatures &features =
2682 client.getNodeDefManager()->get(wasnode);
2684 (gamedef, smgr, player, client.getEnv(),
2685 nodepos, features.tiles);
2691 nodig_delay_timer = dig_time_complete
2692 / (float)crack_animation_length;
2694 // We don't want a corresponding delay to
2695 // very time consuming nodes
2696 if(nodig_delay_timer > 0.3)
2697 nodig_delay_timer = 0.3;
2698 // We want a slight delay to very little
2699 // time consuming nodes
2700 float mindelay = 0.15;
2701 if(nodig_delay_timer < mindelay)
2702 nodig_delay_timer = mindelay;
2704 // Send event to trigger sound
2705 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
2706 gamedef->event()->put(e);
2709 if(dig_time_complete < 100000.0)
2713 client.setCrack(-1, nodepos);
2716 camera.setDigging(0); // left click animation
2719 if((input->getRightClicked() ||
2720 repeat_rightclick_timer >=
2721 g_settings->getFloat("repeat_rightclick_time")) &&
2722 client.checkPrivilege("interact"))
2724 repeat_rightclick_timer = 0;
2725 infostream<<"Ground right-clicked"<<std::endl;
2727 // Sign special case, at least until formspec is properly implemented.
2729 if(meta && meta->getString("formspec") == "hack:sign_text_input"
2731 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2733 infostream<<"Launching metadata text input"<<std::endl;
2735 // Get a new text for it
2737 TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2739 std::wstring wtext = narrow_to_wide(meta->getString("text"));
2741 (new GUITextInputMenu(guienv, guiroot, -1,
2745 // If metadata provides an inventory view, activate it
2746 else if(meta && meta->getString("formspec") != "" && !random_input
2747 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2749 infostream<<"Launching custom inventory view"<<std::endl;
2751 InventoryLocation inventoryloc;
2752 inventoryloc.setNodeMeta(nodepos);
2756 GUIFormSpecMenu *menu =
2757 new GUIFormSpecMenu(device, guiroot, -1,
2760 menu->setFormSpec(meta->getString("formspec"),
2762 menu->setFormSource(new NodeMetadataFormSource(
2763 &client.getEnv().getClientMap(), nodepos));
2764 menu->setTextDest(new TextDestNodeMetadata(nodepos, &client));
2767 // Otherwise report right click to server
2771 client.interact(3, pointed);
2772 camera.setDigging(1); // right click animation
2774 // If the wielded item has node placement prediction,
2776 bool placed = nodePlacementPrediction(client,
2778 nodepos, neighbourpos);
2782 soundmaker.m_player_rightpunch_sound =
2783 playeritem_def.sound_place;
2785 soundmaker.m_player_rightpunch_sound =
2790 else if(pointed.type == POINTEDTHING_OBJECT)
2792 infotext = narrow_to_wide(selected_object->infoText());
2794 if(infotext == L"" && show_debug){
2795 infotext = narrow_to_wide(selected_object->debugInfoText());
2798 //if(input->getLeftClicked())
2799 if(input->getLeftState())
2801 bool do_punch = false;
2802 bool do_punch_damage = false;
2803 if(object_hit_delay_timer <= 0.0){
2805 do_punch_damage = true;
2806 object_hit_delay_timer = object_hit_delay;
2808 if(input->getLeftClicked()){
2812 infostream<<"Left-clicked object"<<std::endl;
2815 if(do_punch_damage){
2816 // Report direct punch
2817 v3f objpos = selected_object->getPosition();
2818 v3f dir = (objpos - player_position).normalize();
2820 bool disable_send = selected_object->directReportPunch(
2821 dir, &playeritem, time_from_last_punch);
2822 time_from_last_punch = 0;
2824 client.interact(0, pointed);
2827 else if(input->getRightClicked())
2829 infostream<<"Right-clicked object"<<std::endl;
2830 client.interact(3, pointed); // place
2833 else if(input->getLeftState())
2835 // When button is held down in air, show continuous animation
2839 pointed_old = pointed;
2841 if(left_punch || input->getLeftClicked())
2843 camera.setDigging(0); // left click animation
2846 input->resetLeftClicked();
2847 input->resetRightClicked();
2849 input->resetLeftReleased();
2850 input->resetRightReleased();
2853 Calculate stuff for drawing
2862 fog_range = BS*farmesh_range;
2866 fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
2868 if(draw_control.range_all)
2869 fog_range = 100000*BS;
2873 Calculate general brightness
2875 u32 daynight_ratio = client.getEnv().getDayNightRatio();
2876 float time_brightness = decode_light_f((float)daynight_ratio/1000.0);
2877 float direct_brightness = 0;
2878 bool sunlight_seen = false;
2879 if(g_settings->getBool("free_move")){
2880 direct_brightness = time_brightness;
2881 sunlight_seen = true;
2883 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
2884 float old_brightness = sky->getBrightness();
2885 direct_brightness = (float)client.getEnv().getClientMap()
2886 .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
2887 daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
2891 time_of_day = client.getEnv().getTimeOfDayF();
2893 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
2894 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
2895 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
2896 time_of_day_smooth = time_of_day;
2898 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
2899 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2900 + (time_of_day+1.0) * todsm;
2902 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2903 + time_of_day * todsm;
2905 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
2908 float brightness = sky->getBrightness();
2909 video::SColor bgcolor = sky->getBgColor();
2910 video::SColor skycolor = sky->getSkyColor();
2916 if(sky->getCloudsVisible()){
2917 clouds->setVisible(true);
2918 clouds->step(dtime);
2919 clouds->update(v2f(player_position.X, player_position.Z),
2920 sky->getCloudColor());
2922 clouds->setVisible(false);
2931 farmesh_range = draw_control.wanted_range * 10;
2932 if(draw_control.range_all && farmesh_range < 500)
2933 farmesh_range = 500;
2934 if(farmesh_range > 1000)
2935 farmesh_range = 1000;
2937 farmesh->step(dtime);
2938 farmesh->update(v2f(player_position.X, player_position.Z),
2939 brightness, farmesh_range);
2946 allparticles_step(dtime, client.getEnv());
2947 allparticlespawners_step(dtime, client.getEnv());
2953 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2957 video::EFT_FOG_LINEAR,
2969 video::EFT_FOG_LINEAR,
2979 Update gui stuff (0ms)
2982 //TimeTaker guiupdatetimer("Gui updating");
2984 const char program_name_and_version[] =
2985 "Minetest " VERSION_STRING;
2989 static float drawtime_avg = 0;
2990 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2991 /*static float beginscenetime_avg = 0;
2992 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2993 static float scenetime_avg = 0;
2994 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2995 static float endscenetime_avg = 0;
2996 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
2998 std::ostringstream os(std::ios_base::binary);
3000 <<program_name_and_version
3001 <<" (R: range_all="<<draw_control.range_all<<")"
3002 <<std::setprecision(0)
3003 <<" drawtime = "<<drawtime_avg
3004 <<std::setprecision(1)
3005 <<", dtime_jitter = "
3006 <<(dtime_jitter1_max_fraction * 100.0)<<" %"
3007 <<std::setprecision(1)
3008 <<", v_range = "<<draw_control.wanted_range
3009 <<std::setprecision(3)
3010 <<", RTT = "<<client.getRTT();
3011 guitext->setText(narrow_to_wide(os.str()).c_str());
3012 guitext->setVisible(true);
3014 else if(show_hud || show_chat)
3016 guitext->setText(narrow_to_wide(program_name_and_version).c_str());
3017 guitext->setVisible(true);
3021 guitext->setVisible(false);
3026 std::ostringstream os(std::ios_base::binary);
3027 os<<std::setprecision(1)<<std::fixed
3028 <<"(" <<(player_position.X/BS)
3029 <<", "<<(player_position.Y/BS)
3030 <<", "<<(player_position.Z/BS)
3031 <<") (yaw="<<(wrapDegrees_0_360(camera_yaw))
3032 <<") (seed = "<<((unsigned long long)client.getMapSeed())
3034 guitext2->setText(narrow_to_wide(os.str()).c_str());
3035 guitext2->setVisible(true);
3039 guitext2->setVisible(false);
3043 guitext_info->setText(infotext.c_str());
3044 guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
3048 float statustext_time_max = 1.5;
3049 if(!statustext.empty())
3051 statustext_time += dtime;
3052 if(statustext_time >= statustext_time_max)
3055 statustext_time = 0;
3058 guitext_status->setText(statustext.c_str());
3059 guitext_status->setVisible(!statustext.empty());
3061 if(!statustext.empty())
3063 s32 status_y = screensize.Y - 130;
3064 core::rect<s32> rect(
3066 status_y - guitext_status->getTextHeight(),
3070 guitext_status->setRelativePosition(rect);
3073 video::SColor initial_color(255,0,0,0);
3074 if(guienv->getSkin())
3075 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
3076 video::SColor final_color = initial_color;
3077 final_color.setAlpha(0);
3078 video::SColor fade_color =
3079 initial_color.getInterpolated_quadratic(
3082 pow(statustext_time / (float)statustext_time_max, 2.0f));
3083 guitext_status->setOverrideColor(fade_color);
3084 guitext_status->enableOverrideColor(true);
3089 Get chat messages from client
3092 // Get new messages from error log buffer
3093 while(!chat_log_error_buf.empty())
3095 chat_backend.addMessage(L"", narrow_to_wide(
3096 chat_log_error_buf.get()));
3098 // Get new messages from client
3099 std::wstring message;
3100 while(client.getChatMessage(message))
3102 chat_backend.addUnparsedMessage(message);
3104 // Remove old messages
3105 chat_backend.step(dtime);
3107 // Display all messages in a static text element
3108 u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
3109 std::wstring recent_chat = chat_backend.getRecentChat();
3110 guitext_chat->setText(recent_chat.c_str());
3112 // Update gui element size and position
3113 s32 chat_y = 5+(text_height+5);
3115 chat_y += (text_height+5);
3116 core::rect<s32> rect(
3120 chat_y + guitext_chat->getTextHeight()
3122 guitext_chat->setRelativePosition(rect);
3124 // Don't show chat if disabled or empty or profiler is enabled
3125 guitext_chat->setVisible(show_chat && recent_chat_count != 0
3133 if(client.getPlayerItem() != new_playeritem)
3135 client.selectPlayerItem(new_playeritem);
3137 if(client.getLocalInventoryUpdated())
3139 //infostream<<"Updating local inventory"<<std::endl;
3140 client.getLocalInventory(local_inventory);
3142 update_wielded_item_trigger = true;
3144 if(update_wielded_item_trigger)
3146 update_wielded_item_trigger = false;
3147 // Update wielded tool
3148 InventoryList *mlist = local_inventory.getList("main");
3151 item = mlist->getItem(client.getPlayerItem());
3152 camera.wield(item, client.getPlayerItem());
3156 Update block draw list every 200ms or when camera direction has
3159 update_draw_list_timer += dtime;
3160 if(update_draw_list_timer >= 0.2 ||
3161 update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2){
3162 update_draw_list_timer = 0;
3163 client.getEnv().getClientMap().updateDrawList(driver);
3164 update_draw_list_last_cam_dir = camera_direction;
3171 TimeTaker tt_draw("mainloop: draw");
3174 TimeTaker timer("beginScene");
3175 //driver->beginScene(false, true, bgcolor);
3176 //driver->beginScene(true, true, bgcolor);
3177 driver->beginScene(true, true, skycolor);
3178 beginscenetime = timer.stop(true);
3183 //infostream<<"smgr->drawAll()"<<std::endl;
3185 TimeTaker timer("smgr");
3188 if(g_settings->getBool("anaglyph"))
3190 irr::core::vector3df oldPosition = camera.getCameraNode()->getPosition();
3191 irr::core::vector3df oldTarget = camera.getCameraNode()->getTarget();
3193 irr::core::matrix4 startMatrix = camera.getCameraNode()->getAbsoluteTransformation();
3195 irr::core::vector3df focusPoint = (camera.getCameraNode()->getTarget() -
3196 camera.getCameraNode()->getAbsolutePosition()).setLength(1) +
3197 camera.getCameraNode()->getAbsolutePosition() ;
3200 irr::core::vector3df leftEye;
3201 irr::core::matrix4 leftMove;
3203 leftMove.setTranslation( irr::core::vector3df(-g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
3204 leftEye=(startMatrix*leftMove).getTranslation();
3206 //clear the depth buffer, and color
3207 driver->beginScene( true, true, irr::video::SColor(0,200,200,255) );
3209 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_RED;
3210 driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK;
3211 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
3212 irr::scene::ESNRP_SOLID +
3213 irr::scene::ESNRP_TRANSPARENT +
3214 irr::scene::ESNRP_TRANSPARENT_EFFECT +
3215 irr::scene::ESNRP_SHADOW;
3217 camera.getCameraNode()->setPosition( leftEye );
3218 camera.getCameraNode()->setTarget( focusPoint );
3220 smgr->drawAll(); // 'smgr->drawAll();' may go here
3224 irr::core::vector3df rightEye;
3225 irr::core::matrix4 rightMove;
3227 rightMove.setTranslation( irr::core::vector3df(g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
3228 rightEye=(startMatrix*rightMove).getTranslation();
3230 //clear the depth buffer
3231 driver->clearZBuffer();
3233 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_GREEN + irr::video::ECP_BLUE;
3234 driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK;
3235 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
3236 irr::scene::ESNRP_SOLID +
3237 irr::scene::ESNRP_TRANSPARENT +
3238 irr::scene::ESNRP_TRANSPARENT_EFFECT +
3239 irr::scene::ESNRP_SHADOW;
3241 camera.getCameraNode()->setPosition( rightEye );
3242 camera.getCameraNode()->setTarget( focusPoint );
3244 smgr->drawAll(); // 'smgr->drawAll();' may go here
3247 //driver->endScene();
3249 driver->getOverrideMaterial().Material.ColorMask=irr::video::ECP_ALL;
3250 driver->getOverrideMaterial().EnableFlags=0;
3251 driver->getOverrideMaterial().EnablePasses=0;
3253 camera.getCameraNode()->setPosition( oldPosition );
3254 camera.getCameraNode()->setTarget( oldTarget );
3257 scenetime = timer.stop(true);
3261 //TimeTaker timer9("auxiliary drawings");
3265 //TimeTaker //timer10("//timer10");
3271 driver->setMaterial(m);
3273 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
3276 hud.drawSelectionBoxes(hilightboxes);
3280 if(show_hud && (player->hud_flags & HUD_FLAG_WIELDITEM_VISIBLE))
3282 // Warning: This clears the Z buffer.
3283 camera.drawWieldedTool();
3290 client.getEnv().getClientMap().renderPostFx();
3296 if(show_profiler_graph)
3298 graph.draw(10, screensize.Y - 10, driver, font);
3305 hud.drawCrosshair();
3310 //TimeTaker //timer11("//timer11");
3318 hud.drawHotbar(v2s32(displaycenter.X, screensize.Y),
3319 client.getHP(), client.getPlayerItem(), client.getBreath());
3325 if(damage_flash > 0.0)
3327 video::SColor color(std::min(damage_flash, 180.0f),180,0,0);
3328 driver->draw2DRectangle(color,
3329 core::rect<s32>(0,0,screensize.X,screensize.Y),
3332 damage_flash -= 100.0*dtime;
3338 if(player->hurt_tilt_timer > 0.0)
3340 player->hurt_tilt_timer -= dtime*5;
3341 if(player->hurt_tilt_timer < 0)
3342 player->hurt_tilt_strength = 0;
3349 hud.drawLuaElements();
3361 TimeTaker timer("endScene");
3363 endscenetime = timer.stop(true);
3366 drawtime = tt_draw.stop(true);
3367 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
3373 static s16 lastFPS = 0;
3374 //u16 fps = driver->getFPS();
3375 u16 fps = (1.0/dtime_avg1);
3379 core::stringw str = L"Minetest [";
3380 str += driver->getName();
3384 device->setWindowCaption(str.c_str());
3389 Log times and stuff for visualization
3391 Profiler::GraphValues values;
3392 g_profiler->graphGet(values);
3401 if (gui_chat_console)
3402 gui_chat_console->drop();
3408 Draw a "shutting down" screen, which will be shown while the map
3409 generator and other stuff quits
3412 /*gui::IGUIStaticText *gui_shuttingdowntext = */
3413 wchar_t* text = wgettext("Shutting down stuff...");
3414 draw_load_screen(text, device, font, 0, -1, false);
3416 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
3419 gui_shuttingdowntext->remove();*/
3422 chat_backend.addMessage(L"", L"# Disconnected.");
3423 chat_backend.addMessage(L"", L"");
3425 // Client scope (client is destructed before destructing *def and tsrc)
3428 catch(SerializationError &e)
3430 error_message = L"A serialization error occurred:\n"
3431 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
3432 L" running a different version of Minetest.";
3433 errorstream<<wide_to_narrow(error_message)<<std::endl;
3435 catch(ServerError &e)
3437 error_message = narrow_to_wide(e.what());
3438 errorstream<<wide_to_narrow(error_message)<<std::endl;
3442 errorstream<<e.what()<<std::endl;
3443 error_message = narrow_to_wide(e.what()) + wgettext("\nCheck debug.txt for details.");
3451 //has to be deleted first to stop all server threads
3459 //extended resource accounting
3460 infostream << "Irrlicht resources after cleanup:" << std::endl;
3461 infostream << "\tRemaining meshes : "
3462 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
3463 infostream << "\tRemaining textures : "
3464 << driver->getTextureCount() << std::endl;
3465 for (unsigned int i = 0; i < driver->getTextureCount(); i++ ) {
3466 irr::video::ITexture* texture = driver->getTextureByIndex(i);
3467 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
3470 infostream << "\tRemaining materials: "
3471 << driver-> getMaterialRendererCount ()
3472 << " (note: irrlicht doesn't support removing renderers)"<< std::endl;