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);
810 bool nodePlacementPrediction(Client &client,
811 const ItemDefinition &playeritem_def,
812 v3s16 nodepos, v3s16 neighbourpos)
814 std::string prediction = playeritem_def.node_placement_prediction;
815 INodeDefManager *nodedef = client.ndef();
816 ClientMap &map = client.getEnv().getClientMap();
818 if(prediction != "" && !nodedef->get(map.getNode(nodepos)).rightclickable)
820 verbosestream<<"Node placement prediction for "
821 <<playeritem_def.name<<" is "
822 <<prediction<<std::endl;
823 v3s16 p = neighbourpos;
824 // Place inside node itself if buildable_to
826 MapNode n_under = map.getNode(nodepos);
827 if(nodedef->get(n_under).buildable_to)
829 else if (!nodedef->get(map.getNode(p)).buildable_to)
831 }catch(InvalidPositionException &e){}
832 // Find id of predicted node
834 bool found = nodedef->getId(prediction, id);
836 errorstream<<"Node placement prediction failed for "
837 <<playeritem_def.name<<" (places "
839 <<") - Name not known"<<std::endl;
842 // Predict param2 for facedir and wallmounted nodes
844 if(nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED){
845 v3s16 dir = nodepos - neighbourpos;
846 if(abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))){
847 param2 = dir.Y < 0 ? 1 : 0;
848 } else if(abs(dir.X) > abs(dir.Z)){
849 param2 = dir.X < 0 ? 3 : 2;
851 param2 = dir.Z < 0 ? 5 : 4;
854 if(nodedef->get(id).param_type_2 == CPT2_FACEDIR){
855 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
856 if(abs(dir.X) > abs(dir.Z)){
857 param2 = dir.X < 0 ? 3 : 1;
859 param2 = dir.Z < 0 ? 2 : 0;
862 assert(param2 >= 0 && param2 <= 5);
863 //Check attachment if node is in group attached_node
864 if(((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0){
865 static v3s16 wallmounted_dirs[8] = {
874 if(nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
875 pp = p + wallmounted_dirs[param2];
877 pp = p + v3s16(0,-1,0);
878 if(!nodedef->get(map.getNode(pp)).walkable)
881 // Add node to client map
882 MapNode n(id, 0, param2);
884 // This triggers the required mesh update too
885 client.addNode(p, n);
887 }catch(InvalidPositionException &e){
888 errorstream<<"Node placement prediction failed for "
889 <<playeritem_def.name<<" (places "
891 <<") - Position not loaded"<<std::endl;
902 IrrlichtDevice *device,
905 std::string playername,
906 std::string password,
907 std::string address, // If "", local server is used
909 std::wstring &error_message,
910 std::string configpath,
911 ChatBackend &chat_backend,
912 const SubgameSpec &gamespec, // Used for local game,
913 bool simple_singleplayer_mode
916 FormspecFormSource* current_formspec = 0;
917 TextDestPlayerInventory* current_textdest = 0;
918 video::IVideoDriver* driver = device->getVideoDriver();
919 scene::ISceneManager* smgr = device->getSceneManager();
921 // Calculate text height using the font
922 u32 text_height = font->getDimension(L"Random test string").Height;
924 v2u32 last_screensize(0,0);
925 v2u32 screensize = driver->getScreenSize();
928 Draw "Loading" screen
932 wchar_t* text = wgettext("Loading...");
933 draw_load_screen(text, device, font,0,0);
937 // Create texture source
938 IWritableTextureSource *tsrc = createTextureSource(device);
940 // Create shader source
941 IWritableShaderSource *shsrc = createShaderSource(device);
943 // These will be filled by data received from the server
944 // Create item definition manager
945 IWritableItemDefManager *itemdef = createItemDefManager();
946 // Create node definition manager
947 IWritableNodeDefManager *nodedef = createNodeDefManager();
949 // Sound fetcher (useful when testing)
950 GameOnDemandSoundFetcher soundfetcher;
953 ISoundManager *sound = NULL;
954 bool sound_is_dummy = false;
956 if(g_settings->getBool("enable_sound")){
957 infostream<<"Attempting to use OpenAL audio"<<std::endl;
958 sound = createOpenALSoundManager(&soundfetcher);
960 infostream<<"Failed to initialize OpenAL audio"<<std::endl;
962 infostream<<"Sound disabled."<<std::endl;
966 infostream<<"Using dummy audio."<<std::endl;
967 sound = &dummySoundManager;
968 sound_is_dummy = true;
971 Server *server = NULL;
975 EventManager eventmgr;
978 SoundMaker soundmaker(sound, nodedef);
979 soundmaker.registerReceiver(&eventmgr);
981 // Add chat log output for errors to be shown in chat
982 LogOutputBuffer chat_log_error_buf(LMT_ERROR);
984 // Create UI for modifying quicktune values
985 QuicktuneShortcutter quicktune;
992 wchar_t* text = wgettext("Creating server....");
993 draw_load_screen(text, device, font,0,25);
995 infostream<<"Creating server"<<std::endl;
996 server = new Server(map_dir, configpath, gamespec,
997 simple_singleplayer_mode);
1001 do{ // Client scope (breakable do-while(0))
1008 wchar_t* text = wgettext("Creating client...");
1009 draw_load_screen(text, device, font,0,50);
1012 infostream<<"Creating client"<<std::endl;
1014 MapDrawControl draw_control;
1017 wchar_t* text = wgettext("Resolving address...");
1018 draw_load_screen(text, device, font,0,75);
1021 Address connect_address(0,0,0,0, port);
1025 //connect_address.Resolve("localhost");
1026 if(g_settings->getBool("enable_ipv6") && g_settings->getBool("ipv6_server"))
1028 IPv6AddressBytes addr_bytes;
1029 addr_bytes.bytes[15] = 1;
1030 connect_address.setAddress(&addr_bytes);
1034 connect_address.setAddress(127,0,0,1);
1038 connect_address.Resolve(address.c_str());
1040 catch(ResolveError &e)
1042 error_message = L"Couldn't resolve address: " + narrow_to_wide(e.what());
1043 errorstream<<wide_to_narrow(error_message)<<std::endl;
1044 // Break out of client scope
1051 Client client(device, playername.c_str(), password, draw_control,
1052 tsrc, shsrc, itemdef, nodedef, sound, &eventmgr,
1053 connect_address.isIPv6());
1055 // Client acts as our GameDef
1056 IGameDef *gamedef = &client;
1059 Attempt to connect to the server
1062 infostream<<"Connecting to server at ";
1063 connect_address.print(&infostream);
1064 infostream<<std::endl;
1065 client.connect(connect_address);
1068 Wait for server to accept connection
1070 bool could_connect = false;
1071 bool connect_aborted = false;
1073 float time_counter = 0.0;
1075 float fps_max = g_settings->getFloat("fps_max");
1076 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1077 u32 lasttime = device->getTimer()->getTime();
1078 while(device->run())
1080 f32 dtime = 0.033; // in seconds
1081 if (cloud_menu_background) {
1082 u32 time = device->getTimer()->getTime();
1084 dtime = (time - lasttime) / 1000.0;
1089 // Update client and server
1092 server->step(dtime);
1095 if(client.connectedAndInitialized()){
1096 could_connect = true;
1100 if(client.accessDenied()){
1101 error_message = L"Access denied. Reason: "
1102 +client.accessDeniedReason();
1103 errorstream<<wide_to_narrow(error_message)<<std::endl;
1106 if(input->wasKeyDown(EscapeKey)){
1107 connect_aborted = true;
1108 infostream<<"Connect aborted [Escape]"<<std::endl;
1114 wchar_t* text = wgettext("Connecting to server...");
1115 draw_load_screen(text, device, font, dtime, 100);
1119 // On some computers framerate doesn't seem to be
1120 // automatically limited
1121 if (cloud_menu_background) {
1122 // Time of frame without fps limit
1125 // not using getRealTime is necessary for wine
1126 u32 time = device->getTimer()->getTime();
1128 busytime_u32 = time - lasttime;
1131 busytime = busytime_u32 / 1000.0;
1134 u32 frametime_min = 1000./fps_max;
1136 if(busytime_u32 < frametime_min) {
1137 u32 sleeptime = frametime_min - busytime_u32;
1138 device->sleep(sleeptime);
1143 time_counter += dtime;
1146 catch(con::PeerNotFoundException &e)
1150 Handle failure to connect
1153 if(error_message == L"" && !connect_aborted){
1154 error_message = L"Connection failed";
1155 errorstream<<wide_to_narrow(error_message)<<std::endl;
1157 // Break out of client scope
1162 Wait until content has been received
1164 bool got_content = false;
1165 bool content_aborted = false;
1167 float time_counter = 0.0;
1169 float fps_max = g_settings->getFloat("fps_max");
1170 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1171 u32 lasttime = device->getTimer()->getTime();
1172 while(device->run())
1174 f32 dtime = 0.033; // in seconds
1175 if (cloud_menu_background) {
1176 u32 time = device->getTimer()->getTime();
1178 dtime = (time - lasttime) / 1000.0;
1183 // Update client and server
1186 server->step(dtime);
1189 if(client.texturesReceived() &&
1190 client.itemdefReceived() &&
1191 client.nodedefReceived()){
1196 if(!client.connectedAndInitialized()){
1197 error_message = L"Client disconnected";
1198 errorstream<<wide_to_narrow(error_message)<<std::endl;
1201 if(input->wasKeyDown(EscapeKey)){
1202 content_aborted = true;
1203 infostream<<"Connect aborted [Escape]"<<std::endl;
1209 if (!client.itemdefReceived())
1211 wchar_t* text = wgettext("Item definitions...");
1213 draw_load_screen(text, device, font, dtime, progress);
1216 else if (!client.nodedefReceived())
1218 wchar_t* text = wgettext("Node definitions...");
1220 draw_load_screen(text, device, font, dtime, progress);
1225 wchar_t* text = wgettext("Media...");
1226 progress = 50+client.mediaReceiveProgress()*50+0.5;
1227 draw_load_screen(text, device, font, dtime, progress);
1231 // On some computers framerate doesn't seem to be
1232 // automatically limited
1233 if (cloud_menu_background) {
1234 // Time of frame without fps limit
1237 // not using getRealTime is necessary for wine
1238 u32 time = device->getTimer()->getTime();
1240 busytime_u32 = time - lasttime;
1243 busytime = busytime_u32 / 1000.0;
1246 u32 frametime_min = 1000./fps_max;
1248 if(busytime_u32 < frametime_min) {
1249 u32 sleeptime = frametime_min - busytime_u32;
1250 device->sleep(sleeptime);
1255 time_counter += dtime;
1260 if(error_message == L"" && !content_aborted){
1261 error_message = L"Something failed";
1262 errorstream<<wide_to_narrow(error_message)<<std::endl;
1264 // Break out of client scope
1269 After all content has been received:
1270 Update cached textures, meshes and materials
1272 client.afterContentReceived(device,font);
1275 Create the camera node
1277 Camera camera(smgr, draw_control, gamedef);
1278 if (!camera.successfullyCreated(error_message))
1281 f32 camera_yaw = 0; // "right/left"
1282 f32 camera_pitch = 0; // "up/down"
1288 Clouds *clouds = NULL;
1289 if(g_settings->getBool("enable_clouds"))
1291 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1299 sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1305 FarMesh *farmesh = NULL;
1306 if(g_settings->getBool("enable_farmesh"))
1308 farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
1312 A copy of the local inventory
1314 Inventory local_inventory(itemdef);
1317 Find out size of crack animation
1319 int crack_animation_length = 5;
1321 video::ITexture *t = tsrc->getTexture("crack_anylength.png");
1322 v2u32 size = t->getOriginalSize();
1323 crack_animation_length = size.Y / size.X;
1330 // First line of debug text
1331 gui::IGUIStaticText *guitext = guienv->addStaticText(
1333 core::rect<s32>(5, 5, 795, 5+text_height),
1335 // Second line of debug text
1336 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1338 core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
1340 // At the middle of the screen
1341 // Object infos are shown in this
1342 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1344 core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1347 // Status text (displays info when showing and hiding GUI stuff, etc.)
1348 gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1350 core::rect<s32>(0,0,0,0),
1352 guitext_status->setVisible(false);
1354 std::wstring statustext;
1355 float statustext_time = 0;
1358 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1360 core::rect<s32>(0,0,0,0),
1361 //false, false); // Disable word wrap as of now
1363 // Remove stale "recent" chat messages from previous connections
1364 chat_backend.clearRecentChat();
1365 // Chat backend and console
1366 GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1368 // Profiler text (size is updated when text is updated)
1369 gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1371 core::rect<s32>(0,0,0,0),
1373 guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1374 guitext_profiler->setVisible(false);
1375 guitext_profiler->setWordWrap(true);
1378 Some statistics are collected in these
1381 u32 beginscenetime = 0;
1383 u32 endscenetime = 0;
1385 float recent_turn_speed = 0.0;
1387 ProfilerGraph graph;
1388 // Initially clear the profiler
1389 Profiler::GraphValues dummyvalues;
1390 g_profiler->graphGet(dummyvalues);
1392 float nodig_delay_timer = 0.0;
1393 float dig_time = 0.0;
1395 PointedThing pointed_old;
1396 bool digging = false;
1397 bool ldown_for_dig = false;
1399 float damage_flash = 0;
1400 s16 farmesh_range = 20*MAP_BLOCKSIZE;
1402 float jump_timer = 0;
1403 bool reset_jump_timer = false;
1405 const float object_hit_delay = 0.2;
1406 float object_hit_delay_timer = 0.0;
1407 float time_from_last_punch = 10;
1409 float update_draw_list_timer = 0.0;
1410 v3f update_draw_list_last_cam_dir;
1412 bool invert_mouse = g_settings->getBool("invert_mouse");
1414 bool respawn_menu_active = false;
1415 bool update_wielded_item_trigger = false;
1417 bool show_hud = true;
1418 bool show_chat = true;
1419 bool force_fog_off = false;
1420 f32 fog_range = 100*BS;
1421 bool disable_camera_update = false;
1422 bool show_debug = g_settings->getBool("show_debug");
1423 bool show_profiler_graph = false;
1424 u32 show_profiler = 0;
1425 u32 show_profiler_max = 3; // Number of pages
1427 float time_of_day = 0;
1428 float time_of_day_smooth = 0;
1430 float repeat_rightclick_timer = 0;
1435 shsrc->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1436 sky, &force_fog_off, &fog_range, &client));
1442 bool first_loop_after_window_activation = true;
1444 // TODO: Convert the static interval timers to these
1445 // Interval limiter for profiler
1446 IntervalLimiter m_profiler_interval;
1448 // Time is in milliseconds
1449 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1450 // NOTE: So we have to use getTime() and call run()s between them
1451 u32 lasttime = device->getTimer()->getTime();
1453 LocalPlayer* player = client.getEnv().getLocalPlayer();
1454 player->hurt_tilt_timer = 0;
1455 player->hurt_tilt_strength = 0;
1460 Hud hud(driver, guienv, font, text_height,
1461 gamedef, player, &local_inventory);
1465 if(device->run() == false || kill == true)
1468 // Time of frame without fps limit
1472 // not using getRealTime is necessary for wine
1473 u32 time = device->getTimer()->getTime();
1475 busytime_u32 = time - lasttime;
1478 busytime = busytime_u32 / 1000.0;
1481 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1483 // Necessary for device->getTimer()->getTime()
1491 float fps_max = g_settings->getFloat("fps_max");
1492 u32 frametime_min = 1000./fps_max;
1494 if(busytime_u32 < frametime_min)
1496 u32 sleeptime = frametime_min - busytime_u32;
1497 device->sleep(sleeptime);
1498 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1502 // Necessary for device->getTimer()->getTime()
1506 Time difference calculation
1508 f32 dtime; // in seconds
1510 u32 time = device->getTimer()->getTime();
1512 dtime = (time - lasttime) / 1000.0;
1517 g_profiler->graphAdd("mainloop_dtime", dtime);
1521 if(nodig_delay_timer >= 0)
1522 nodig_delay_timer -= dtime;
1523 if(object_hit_delay_timer >= 0)
1524 object_hit_delay_timer -= dtime;
1525 time_from_last_punch += dtime;
1527 g_profiler->add("Elapsed time", dtime);
1528 g_profiler->avg("FPS", 1./dtime);
1531 Time average and jitter calculation
1534 static f32 dtime_avg1 = 0.0;
1535 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1536 f32 dtime_jitter1 = dtime - dtime_avg1;
1538 static f32 dtime_jitter1_max_sample = 0.0;
1539 static f32 dtime_jitter1_max_fraction = 0.0;
1541 static f32 jitter1_max = 0.0;
1542 static f32 counter = 0.0;
1543 if(dtime_jitter1 > jitter1_max)
1544 jitter1_max = dtime_jitter1;
1549 dtime_jitter1_max_sample = jitter1_max;
1550 dtime_jitter1_max_fraction
1551 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1557 Busytime average and jitter calculation
1560 static f32 busytime_avg1 = 0.0;
1561 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1562 f32 busytime_jitter1 = busytime - busytime_avg1;
1564 static f32 busytime_jitter1_max_sample = 0.0;
1565 static f32 busytime_jitter1_min_sample = 0.0;
1567 static f32 jitter1_max = 0.0;
1568 static f32 jitter1_min = 0.0;
1569 static f32 counter = 0.0;
1570 if(busytime_jitter1 > jitter1_max)
1571 jitter1_max = busytime_jitter1;
1572 if(busytime_jitter1 < jitter1_min)
1573 jitter1_min = busytime_jitter1;
1577 busytime_jitter1_max_sample = jitter1_max;
1578 busytime_jitter1_min_sample = jitter1_min;
1585 Handle miscellaneous stuff
1588 if(client.accessDenied())
1590 error_message = L"Access denied. Reason: "
1591 +client.accessDeniedReason();
1592 errorstream<<wide_to_narrow(error_message)<<std::endl;
1596 if(g_gamecallback->disconnect_requested)
1598 g_gamecallback->disconnect_requested = false;
1602 if(g_gamecallback->changepassword_requested)
1604 (new GUIPasswordChange(guienv, guiroot, -1,
1605 &g_menumgr, &client))->drop();
1606 g_gamecallback->changepassword_requested = false;
1609 if(g_gamecallback->changevolume_requested)
1611 (new GUIVolumeChange(guienv, guiroot, -1,
1612 &g_menumgr, &client))->drop();
1613 g_gamecallback->changevolume_requested = false;
1616 /* Process TextureSource's queue */
1617 tsrc->processQueue();
1619 /* Process ItemDefManager's queue */
1620 itemdef->processQueue(gamedef);
1623 Process ShaderSource's queue
1625 shsrc->processQueue();
1630 last_screensize = screensize;
1631 screensize = driver->getScreenSize();
1632 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1633 //bool screensize_changed = screensize != last_screensize;
1636 // Update HUD values
1637 hud.screensize = screensize;
1638 hud.displaycenter = displaycenter;
1641 // Hilight boxes collected during the loop and displayed
1642 std::vector<aabb3f> hilightboxes;
1645 std::wstring infotext;
1648 Debug info for client
1651 static float counter = 0.0;
1656 client.printDebugInfo(infostream);
1663 float profiler_print_interval =
1664 g_settings->getFloat("profiler_print_interval");
1665 bool print_to_log = true;
1666 if(profiler_print_interval == 0){
1667 print_to_log = false;
1668 profiler_print_interval = 5;
1670 if(m_profiler_interval.step(dtime, profiler_print_interval))
1673 infostream<<"Profiler:"<<std::endl;
1674 g_profiler->print(infostream);
1677 update_profiler_gui(guitext_profiler, font, text_height,
1678 show_profiler, show_profiler_max);
1680 g_profiler->clear();
1684 Direct handling of user input
1687 // Reset input if window not active or some menu is active
1688 if(device->isWindowActive() == false
1689 || noMenuActive() == false
1690 || guienv->hasFocus(gui_chat_console))
1694 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen())
1696 gui_chat_console->closeConsoleAtOnce();
1699 // Input handler step() (used by the random input generator)
1702 // Increase timer for doubleclick of "jump"
1703 if(g_settings->getBool("doubletap_jump") && jump_timer <= 0.2)
1704 jump_timer += dtime;
1707 Launch menus and trigger stuff according to keys
1709 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1711 // drop selected item
1712 IDropAction *a = new IDropAction();
1714 a->from_inv.setCurrentPlayer();
1715 a->from_list = "main";
1716 a->from_i = client.getPlayerItem();
1717 client.inventoryAction(a);
1719 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1721 infostream<<"the_game: "
1722 <<"Launching inventory"<<std::endl;
1724 GUIFormSpecMenu *menu =
1725 new GUIFormSpecMenu(device, guiroot, -1,
1729 InventoryLocation inventoryloc;
1730 inventoryloc.setCurrentPlayer();
1732 PlayerInventoryFormSource *src = new PlayerInventoryFormSource(&client);
1734 menu->setFormSpec(src->getForm(), inventoryloc);
1735 menu->setFormSource(src);
1736 menu->setTextDest(new TextDestPlayerInventory(&client));
1739 else if(input->wasKeyDown(EscapeKey))
1741 infostream<<"the_game: "
1742 <<"Launching pause menu"<<std::endl;
1743 // It will delete itself by itself
1744 (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1745 &g_menumgr, simple_singleplayer_mode))->drop();
1747 // Move mouse cursor on top of the disconnect button
1748 if(simple_singleplayer_mode)
1749 input->setMousePos(displaycenter.X, displaycenter.Y+0);
1751 input->setMousePos(displaycenter.X, displaycenter.Y+25);
1753 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1755 TextDest *dest = new TextDestChat(&client);
1757 (new GUITextInputMenu(guienv, guiroot, -1,
1761 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1763 TextDest *dest = new TextDestChat(&client);
1765 (new GUITextInputMenu(guienv, guiroot, -1,
1769 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1771 if (!gui_chat_console->isOpenInhibited())
1773 // Open up to over half of the screen
1774 gui_chat_console->openConsole(0.6);
1775 guienv->setFocus(gui_chat_console);
1778 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1780 if(g_settings->getBool("free_move"))
1782 g_settings->set("free_move","false");
1783 statustext = L"free_move disabled";
1784 statustext_time = 0;
1788 g_settings->set("free_move","true");
1789 statustext = L"free_move enabled";
1790 statustext_time = 0;
1791 if(!client.checkPrivilege("fly"))
1792 statustext += L" (note: no 'fly' privilege)";
1795 else if(input->wasKeyDown(getKeySetting("keymap_jump")))
1797 if(g_settings->getBool("doubletap_jump") && jump_timer < 0.2)
1799 if(g_settings->getBool("free_move"))
1801 g_settings->set("free_move","false");
1802 statustext = L"free_move disabled";
1803 statustext_time = 0;
1807 g_settings->set("free_move","true");
1808 statustext = L"free_move enabled";
1809 statustext_time = 0;
1810 if(!client.checkPrivilege("fly"))
1811 statustext += L" (note: no 'fly' privilege)";
1814 reset_jump_timer = true;
1816 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1818 if(g_settings->getBool("fast_move"))
1820 g_settings->set("fast_move","false");
1821 statustext = L"fast_move disabled";
1822 statustext_time = 0;
1826 g_settings->set("fast_move","true");
1827 statustext = L"fast_move enabled";
1828 statustext_time = 0;
1829 if(!client.checkPrivilege("fast"))
1830 statustext += L" (note: no 'fast' privilege)";
1833 else if(input->wasKeyDown(getKeySetting("keymap_noclip")))
1835 if(g_settings->getBool("noclip"))
1837 g_settings->set("noclip","false");
1838 statustext = L"noclip disabled";
1839 statustext_time = 0;
1843 g_settings->set("noclip","true");
1844 statustext = L"noclip enabled";
1845 statustext_time = 0;
1846 if(!client.checkPrivilege("noclip"))
1847 statustext += L" (note: no 'noclip' privilege)";
1850 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1852 irr::video::IImage* const image = driver->createScreenShot();
1854 irr::c8 filename[256];
1855 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png",
1856 g_settings->get("screenshot_path").c_str(),
1857 device->getTimer()->getRealTime());
1858 if (driver->writeImageToFile(image, filename)) {
1859 std::wstringstream sstr;
1860 sstr<<"Saved screenshot to '"<<filename<<"'";
1861 infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1862 statustext = sstr.str();
1863 statustext_time = 0;
1865 infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1870 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
1872 show_hud = !show_hud;
1874 statustext = L"HUD shown";
1876 statustext = L"HUD hidden";
1877 statustext_time = 0;
1879 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
1881 show_chat = !show_chat;
1883 statustext = L"Chat shown";
1885 statustext = L"Chat hidden";
1886 statustext_time = 0;
1888 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1890 force_fog_off = !force_fog_off;
1892 statustext = L"Fog disabled";
1894 statustext = L"Fog enabled";
1895 statustext_time = 0;
1897 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1899 disable_camera_update = !disable_camera_update;
1900 if(disable_camera_update)
1901 statustext = L"Camera update disabled";
1903 statustext = L"Camera update enabled";
1904 statustext_time = 0;
1906 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
1908 // Initial / 3x toggle: Chat only
1909 // 1x toggle: Debug text with chat
1910 // 2x toggle: Debug text with profiler graph
1914 show_profiler_graph = false;
1915 statustext = L"Debug info shown";
1916 statustext_time = 0;
1918 else if(show_profiler_graph)
1921 show_profiler_graph = false;
1922 statustext = L"Debug info and profiler graph hidden";
1923 statustext_time = 0;
1927 show_profiler_graph = true;
1928 statustext = L"Profiler graph shown";
1929 statustext_time = 0;
1932 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1934 show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
1936 // FIXME: This updates the profiler with incomplete values
1937 update_profiler_gui(guitext_profiler, font, text_height,
1938 show_profiler, show_profiler_max);
1940 if(show_profiler != 0)
1942 std::wstringstream sstr;
1943 sstr<<"Profiler shown (page "<<show_profiler
1944 <<" of "<<show_profiler_max<<")";
1945 statustext = sstr.str();
1946 statustext_time = 0;
1950 statustext = L"Profiler hidden";
1951 statustext_time = 0;
1954 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
1956 s16 range = g_settings->getS16("viewing_range_nodes_min");
1957 s16 range_new = range + 10;
1958 g_settings->set("viewing_range_nodes_min", itos(range_new));
1959 statustext = narrow_to_wide(
1960 "Minimum viewing range changed to "
1962 statustext_time = 0;
1964 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
1966 s16 range = g_settings->getS16("viewing_range_nodes_min");
1967 s16 range_new = range - 10;
1970 g_settings->set("viewing_range_nodes_min",
1972 statustext = narrow_to_wide(
1973 "Minimum viewing range changed to "
1975 statustext_time = 0;
1979 if(!input->isKeyDown(getKeySetting("keymap_jump")) && reset_jump_timer)
1981 reset_jump_timer = false;
1985 // Handle QuicktuneShortcutter
1986 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
1988 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
1990 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
1992 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
1995 std::string msg = quicktune.getMessage();
1997 statustext = narrow_to_wide(msg);
1998 statustext_time = 0;
2002 // Item selection with mouse wheel
2003 u16 new_playeritem = client.getPlayerItem();
2005 s32 wheel = input->getMouseWheel();
2006 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
2007 player->hud_hotbar_itemcount-1);
2011 if(new_playeritem < max_item)
2018 if(new_playeritem > 0)
2021 new_playeritem = max_item;
2026 for(u16 i=0; i<10; i++)
2028 const KeyPress *kp = NumberKey + (i + 1) % 10;
2029 if(input->wasKeyDown(*kp))
2031 if(i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount)
2035 infostream<<"Selected item: "
2036 <<new_playeritem<<std::endl;
2041 // Viewing range selection
2042 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
2044 draw_control.range_all = !draw_control.range_all;
2045 if(draw_control.range_all)
2047 infostream<<"Enabled full viewing range"<<std::endl;
2048 statustext = L"Enabled full viewing range";
2049 statustext_time = 0;
2053 infostream<<"Disabled full viewing range"<<std::endl;
2054 statustext = L"Disabled full viewing range";
2055 statustext_time = 0;
2059 // Print debug stacks
2060 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
2062 dstream<<"-----------------------------------------"
2064 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
2065 dstream<<"-----------------------------------------"
2067 debug_stacks_print();
2071 Mouse and camera control
2072 NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
2075 float turn_amount = 0;
2076 if((device->isWindowActive() && noMenuActive()) || random_input)
2080 // Mac OSX gets upset if this is set every frame
2081 if(device->getCursorControl()->isVisible())
2082 device->getCursorControl()->setVisible(false);
2085 if(first_loop_after_window_activation){
2086 //infostream<<"window active, first loop"<<std::endl;
2087 first_loop_after_window_activation = false;
2090 s32 dx = input->getMousePos().X - displaycenter.X;
2091 s32 dy = input->getMousePos().Y - displaycenter.Y;
2094 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
2096 /*const float keyspeed = 500;
2097 if(input->isKeyDown(irr::KEY_UP))
2098 dy -= dtime * keyspeed;
2099 if(input->isKeyDown(irr::KEY_DOWN))
2100 dy += dtime * keyspeed;
2101 if(input->isKeyDown(irr::KEY_LEFT))
2102 dx -= dtime * keyspeed;
2103 if(input->isKeyDown(irr::KEY_RIGHT))
2104 dx += dtime * keyspeed;*/
2106 float d = g_settings->getFloat("mouse_sensitivity");
2107 d = rangelim(d, 0.01, 100.0);
2109 camera_pitch += dy*d;
2110 if(camera_pitch < -89.5) camera_pitch = -89.5;
2111 if(camera_pitch > 89.5) camera_pitch = 89.5;
2113 turn_amount = v2f(dx, dy).getLength() * d;
2115 input->setMousePos(displaycenter.X, displaycenter.Y);
2118 // Mac OSX gets upset if this is set every frame
2119 if(device->getCursorControl()->isVisible() == false)
2120 device->getCursorControl()->setVisible(true);
2122 //infostream<<"window inactive"<<std::endl;
2123 first_loop_after_window_activation = true;
2125 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
2126 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
2129 Player speed control
2143 PlayerControl control(
2144 input->isKeyDown(getKeySetting("keymap_forward")),
2145 input->isKeyDown(getKeySetting("keymap_backward")),
2146 input->isKeyDown(getKeySetting("keymap_left")),
2147 input->isKeyDown(getKeySetting("keymap_right")),
2148 input->isKeyDown(getKeySetting("keymap_jump")),
2149 input->isKeyDown(getKeySetting("keymap_special1")),
2150 input->isKeyDown(getKeySetting("keymap_sneak")),
2151 input->getLeftState(),
2152 input->getRightState(),
2156 client.setPlayerControl(control);
2158 1*(int)input->isKeyDown(getKeySetting("keymap_forward"))+
2159 2*(int)input->isKeyDown(getKeySetting("keymap_backward"))+
2160 4*(int)input->isKeyDown(getKeySetting("keymap_left"))+
2161 8*(int)input->isKeyDown(getKeySetting("keymap_right"))+
2162 16*(int)input->isKeyDown(getKeySetting("keymap_jump"))+
2163 32*(int)input->isKeyDown(getKeySetting("keymap_special1"))+
2164 64*(int)input->isKeyDown(getKeySetting("keymap_sneak"))+
2165 128*(int)input->getLeftState()+
2166 256*(int)input->getRightState();
2167 LocalPlayer* player = client.getEnv().getLocalPlayer();
2168 player->keyPressed=keyPressed;
2177 //TimeTaker timer("server->step(dtime)");
2178 server->step(dtime);
2186 //TimeTaker timer("client.step(dtime)");
2188 //client.step(dtime_avg1);
2192 // Read client events
2195 ClientEvent event = client.getClientEvent();
2196 if(event.type == CE_NONE)
2200 else if(event.type == CE_PLAYER_DAMAGE &&
2201 client.getHP() != 0)
2203 //u16 damage = event.player_damage.amount;
2204 //infostream<<"Player damage: "<<damage<<std::endl;
2206 damage_flash += 100.0;
2207 damage_flash += 8.0 * event.player_damage.amount;
2209 player->hurt_tilt_timer = 1.5;
2210 player->hurt_tilt_strength = event.player_damage.amount/2;
2211 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 2.0, 10.0);
2213 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
2214 gamedef->event()->put(e);
2216 else if(event.type == CE_PLAYER_FORCE_MOVE)
2218 camera_yaw = event.player_force_move.yaw;
2219 camera_pitch = event.player_force_move.pitch;
2221 else if(event.type == CE_DEATHSCREEN)
2223 if(respawn_menu_active)
2226 /*bool set_camera_point_target =
2227 event.deathscreen.set_camera_point_target;
2228 v3f camera_point_target;
2229 camera_point_target.X = event.deathscreen.camera_point_target_x;
2230 camera_point_target.Y = event.deathscreen.camera_point_target_y;
2231 camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
2232 MainRespawnInitiator *respawner =
2233 new MainRespawnInitiator(
2234 &respawn_menu_active, &client);
2235 GUIDeathScreen *menu =
2236 new GUIDeathScreen(guienv, guiroot, -1,
2237 &g_menumgr, respawner);
2240 chat_backend.addMessage(L"", L"You died.");
2242 /* Handle visualization */
2246 LocalPlayer* player = client.getEnv().getLocalPlayer();
2247 player->hurt_tilt_timer = 0;
2248 player->hurt_tilt_strength = 0;
2250 /*LocalPlayer* player = client.getLocalPlayer();
2251 player->setPosition(player->getPosition() + v3f(0,-BS,0));
2252 camera.update(player, busytime, screensize);*/
2254 else if (event.type == CE_SHOW_FORMSPEC)
2256 if (current_formspec == 0)
2259 /* Note: FormspecFormSource and TextDestPlayerInventory
2260 * are deleted by guiFormSpecMenu */
2261 current_formspec = new FormspecFormSource(*(event.show_formspec.formspec),¤t_formspec);
2262 current_textdest = new TextDestPlayerInventory(&client,*(event.show_formspec.formname));
2263 GUIFormSpecMenu *menu =
2264 new GUIFormSpecMenu(device, guiroot, -1,
2267 menu->setFormSource(current_formspec);
2268 menu->setTextDest(current_textdest);
2273 assert(current_textdest != 0);
2275 current_textdest->setFormName(*(event.show_formspec.formname));
2276 current_formspec->setForm(*(event.show_formspec.formspec));
2278 delete(event.show_formspec.formspec);
2279 delete(event.show_formspec.formname);
2281 else if(event.type == CE_TEXTURES_UPDATED)
2283 update_wielded_item_trigger = true;
2285 else if(event.type == CE_SPAWN_PARTICLE)
2287 LocalPlayer* player = client.getEnv().getLocalPlayer();
2288 video::ITexture *texture =
2289 gamedef->tsrc()->getTexture(*(event.spawn_particle.texture));
2291 new Particle(gamedef, smgr, player, client.getEnv(),
2292 *event.spawn_particle.pos,
2293 *event.spawn_particle.vel,
2294 *event.spawn_particle.acc,
2295 event.spawn_particle.expirationtime,
2296 event.spawn_particle.size,
2297 event.spawn_particle.collisiondetection,
2302 else if(event.type == CE_ADD_PARTICLESPAWNER)
2304 LocalPlayer* player = client.getEnv().getLocalPlayer();
2305 video::ITexture *texture =
2306 gamedef->tsrc()->getTexture(*(event.add_particlespawner.texture));
2308 new ParticleSpawner(gamedef, smgr, player,
2309 event.add_particlespawner.amount,
2310 event.add_particlespawner.spawntime,
2311 *event.add_particlespawner.minpos,
2312 *event.add_particlespawner.maxpos,
2313 *event.add_particlespawner.minvel,
2314 *event.add_particlespawner.maxvel,
2315 *event.add_particlespawner.minacc,
2316 *event.add_particlespawner.maxacc,
2317 event.add_particlespawner.minexptime,
2318 event.add_particlespawner.maxexptime,
2319 event.add_particlespawner.minsize,
2320 event.add_particlespawner.maxsize,
2321 event.add_particlespawner.collisiondetection,
2323 event.add_particlespawner.id);
2325 else if(event.type == CE_DELETE_PARTICLESPAWNER)
2327 delete_particlespawner (event.delete_particlespawner.id);
2329 else if (event.type == CE_HUDADD)
2331 u32 id = event.hudadd.id;
2332 size_t nhudelem = player->hud.size();
2333 if (id > nhudelem || (id < nhudelem && player->hud[id])) {
2334 delete event.hudadd.pos;
2335 delete event.hudadd.name;
2336 delete event.hudadd.scale;
2337 delete event.hudadd.text;
2338 delete event.hudadd.align;
2339 delete event.hudadd.offset;
2343 HudElement *e = new HudElement;
2344 e->type = (HudElementType)event.hudadd.type;
2345 e->pos = *event.hudadd.pos;
2346 e->name = *event.hudadd.name;
2347 e->scale = *event.hudadd.scale;
2348 e->text = *event.hudadd.text;
2349 e->number = event.hudadd.number;
2350 e->item = event.hudadd.item;
2351 e->dir = event.hudadd.dir;
2352 e->align = *event.hudadd.align;
2353 e->offset = *event.hudadd.offset;
2356 player->hud.push_back(e);
2358 player->hud[id] = e;
2360 delete event.hudadd.pos;
2361 delete event.hudadd.name;
2362 delete event.hudadd.scale;
2363 delete event.hudadd.text;
2364 delete event.hudadd.align;
2365 delete event.hudadd.offset;
2367 else if (event.type == CE_HUDRM)
2369 u32 id = event.hudrm.id;
2370 if (id < player->hud.size() && player->hud[id]) {
2371 delete player->hud[id];
2372 player->hud[id] = NULL;
2375 else if (event.type == CE_HUDCHANGE)
2377 u32 id = event.hudchange.id;
2378 if (id >= player->hud.size() || !player->hud[id]) {
2379 delete event.hudchange.v2fdata;
2380 delete event.hudchange.sdata;
2384 HudElement* e = player->hud[id];
2385 switch (event.hudchange.stat) {
2387 e->pos = *event.hudchange.v2fdata;
2390 e->name = *event.hudchange.sdata;
2392 case HUD_STAT_SCALE:
2393 e->scale = *event.hudchange.v2fdata;
2396 e->text = *event.hudchange.sdata;
2398 case HUD_STAT_NUMBER:
2399 e->number = event.hudchange.data;
2402 e->item = event.hudchange.data;
2405 e->dir = event.hudchange.data;
2407 case HUD_STAT_ALIGN:
2408 e->align = *event.hudchange.v2fdata;
2410 case HUD_STAT_OFFSET:
2411 e->offset = *event.hudchange.v2fdata;
2415 delete event.hudchange.v2fdata;
2416 delete event.hudchange.sdata;
2421 //TimeTaker //timer2("//timer2");
2424 For interaction purposes, get info about the held item
2426 - Is it a usable item?
2427 - Can it point to liquids?
2429 ItemStack playeritem;
2431 InventoryList *mlist = local_inventory.getList("main");
2434 playeritem = mlist->getItem(client.getPlayerItem());
2437 const ItemDefinition &playeritem_def =
2438 playeritem.getDefinition(itemdef);
2439 ToolCapabilities playeritem_toolcap =
2440 playeritem.getToolCapabilities(itemdef);
2446 LocalPlayer* player = client.getEnv().getLocalPlayer();
2447 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2448 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
2449 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2450 camera.update(player, busytime, screensize, tool_reload_ratio);
2453 v3f player_position = player->getPosition();
2454 v3f camera_position = camera.getPosition();
2455 v3f camera_direction = camera.getDirection();
2456 f32 camera_fov = camera.getFovMax();
2458 if(!disable_camera_update){
2459 client.getEnv().getClientMap().updateCamera(camera_position,
2460 camera_direction, camera_fov);
2463 // Update sound listener
2464 sound->updateListener(camera.getCameraNode()->getPosition(),
2465 v3f(0,0,0), // velocity
2466 camera.getDirection(),
2467 camera.getCameraNode()->getUpVector());
2468 sound->setListenerGain(g_settings->getFloat("sound_volume"));
2474 soundmaker.step(dtime);
2476 ClientMap &map = client.getEnv().getClientMap();
2477 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
2478 soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
2482 Calculate what block is the crosshair pointing to
2485 //u32 t1 = device->getTimer()->getRealTime();
2487 f32 d = 4; // max. distance
2488 core::line3d<f32> shootline(camera_position,
2489 camera_position + camera_direction * BS * (d+1));
2491 ClientActiveObject *selected_object = NULL;
2493 PointedThing pointed = getPointedThing(
2495 &client, player_position, camera_direction,
2496 camera_position, shootline, d,
2497 playeritem_def.liquids_pointable, !ldown_for_dig,
2502 if(pointed != pointed_old)
2504 infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2505 //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
2510 - releasing left mouse button
2511 - pointing away from node
2515 if(input->getLeftReleased())
2517 infostream<<"Left button released"
2518 <<" (stopped digging)"<<std::endl;
2521 else if(pointed != pointed_old)
2523 if (pointed.type == POINTEDTHING_NODE
2524 && pointed_old.type == POINTEDTHING_NODE
2525 && pointed.node_undersurface == pointed_old.node_undersurface)
2527 // Still pointing to the same node,
2528 // but a different face. Don't reset.
2532 infostream<<"Pointing away from node"
2533 <<" (stopped digging)"<<std::endl;
2539 client.interact(1, pointed_old);
2540 client.setCrack(-1, v3s16(0,0,0));
2544 if(!digging && ldown_for_dig && !input->getLeftState())
2546 ldown_for_dig = false;
2549 bool left_punch = false;
2550 soundmaker.m_player_leftpunch_sound.name = "";
2552 if(input->getRightState())
2553 repeat_rightclick_timer += dtime;
2555 repeat_rightclick_timer = 0;
2557 if(playeritem_def.usable && input->getLeftState())
2559 if(input->getLeftClicked())
2560 client.interact(4, pointed);
2562 else if(pointed.type == POINTEDTHING_NODE)
2564 v3s16 nodepos = pointed.node_undersurface;
2565 v3s16 neighbourpos = pointed.node_abovesurface;
2568 Check information text of node
2571 ClientMap &map = client.getEnv().getClientMap();
2572 NodeMetadata *meta = map.getNodeMetadata(nodepos);
2574 infotext = narrow_to_wide(meta->getString("infotext"));
2576 MapNode n = map.getNode(nodepos);
2577 if(nodedef->get(n).tiledef[0].name == "unknown_node.png"){
2578 infotext = L"Unknown node: ";
2579 infotext += narrow_to_wide(nodedef->get(n).name);
2587 if(nodig_delay_timer <= 0.0 && input->getLeftState()
2588 && client.checkPrivilege("interact"))
2592 infostream<<"Started digging"<<std::endl;
2593 client.interact(0, pointed);
2595 ldown_for_dig = true;
2597 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2599 // NOTE: Similar piece of code exists on the server side for
2601 // Get digging parameters
2602 DigParams params = getDigParams(nodedef->get(n).groups,
2603 &playeritem_toolcap);
2604 // If can't dig, try hand
2605 if(!params.diggable){
2606 const ItemDefinition &hand = itemdef->get("");
2607 const ToolCapabilities *tp = hand.tool_capabilities;
2609 params = getDigParams(nodedef->get(n).groups, tp);
2612 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2613 if(sound_dig.exists()){
2614 if(sound_dig.name == "__group"){
2615 if(params.main_group != ""){
2616 soundmaker.m_player_leftpunch_sound.gain = 0.5;
2617 soundmaker.m_player_leftpunch_sound.name =
2618 std::string("default_dig_") +
2622 soundmaker.m_player_leftpunch_sound = sound_dig;
2626 float dig_time_complete = 0.0;
2628 if(params.diggable == false)
2630 // I guess nobody will wait for this long
2631 dig_time_complete = 10000000.0;
2635 dig_time_complete = params.time;
2636 if (g_settings->getBool("enable_particles"))
2638 const ContentFeatures &features =
2639 client.getNodeDefManager()->get(n);
2640 addPunchingParticles
2641 (gamedef, smgr, player, client.getEnv(),
2642 nodepos, features.tiles);
2646 if(dig_time_complete >= 0.001)
2648 dig_index = (u16)((float)crack_animation_length
2649 * dig_time/dig_time_complete);
2651 // This is for torches
2654 dig_index = crack_animation_length;
2657 // Don't show cracks if not diggable
2658 if(dig_time_complete >= 100000.0)
2661 else if(dig_index < crack_animation_length)
2663 //TimeTaker timer("client.setTempMod");
2664 //infostream<<"dig_index="<<dig_index<<std::endl;
2665 client.setCrack(dig_index, nodepos);
2669 infostream<<"Digging completed"<<std::endl;
2670 client.interact(2, pointed);
2671 client.setCrack(-1, v3s16(0,0,0));
2672 MapNode wasnode = map.getNode(nodepos);
2673 client.removeNode(nodepos);
2675 if (g_settings->getBool("enable_particles"))
2677 const ContentFeatures &features =
2678 client.getNodeDefManager()->get(wasnode);
2680 (gamedef, smgr, player, client.getEnv(),
2681 nodepos, features.tiles);
2687 nodig_delay_timer = dig_time_complete
2688 / (float)crack_animation_length;
2690 // We don't want a corresponding delay to
2691 // very time consuming nodes
2692 if(nodig_delay_timer > 0.3)
2693 nodig_delay_timer = 0.3;
2694 // We want a slight delay to very little
2695 // time consuming nodes
2696 float mindelay = 0.15;
2697 if(nodig_delay_timer < mindelay)
2698 nodig_delay_timer = mindelay;
2700 // Send event to trigger sound
2701 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
2702 gamedef->event()->put(e);
2705 if(dig_time_complete < 100000.0)
2709 client.setCrack(-1, nodepos);
2712 camera.setDigging(0); // left click animation
2715 if((input->getRightClicked() ||
2716 repeat_rightclick_timer >=
2717 g_settings->getFloat("repeat_rightclick_time")) &&
2718 client.checkPrivilege("interact"))
2720 repeat_rightclick_timer = 0;
2721 infostream<<"Ground right-clicked"<<std::endl;
2723 // Sign special case, at least until formspec is properly implemented.
2725 if(meta && meta->getString("formspec") == "hack:sign_text_input"
2727 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2729 infostream<<"Launching metadata text input"<<std::endl;
2731 // Get a new text for it
2733 TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2735 std::wstring wtext = narrow_to_wide(meta->getString("text"));
2737 (new GUITextInputMenu(guienv, guiroot, -1,
2741 // If metadata provides an inventory view, activate it
2742 else if(meta && meta->getString("formspec") != "" && !random_input
2743 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2745 infostream<<"Launching custom inventory view"<<std::endl;
2747 InventoryLocation inventoryloc;
2748 inventoryloc.setNodeMeta(nodepos);
2752 GUIFormSpecMenu *menu =
2753 new GUIFormSpecMenu(device, guiroot, -1,
2756 menu->setFormSpec(meta->getString("formspec"),
2758 menu->setFormSource(new NodeMetadataFormSource(
2759 &client.getEnv().getClientMap(), nodepos));
2760 menu->setTextDest(new TextDestNodeMetadata(nodepos, &client));
2763 // Otherwise report right click to server
2767 client.interact(3, pointed);
2768 camera.setDigging(1); // right click animation
2770 // If the wielded item has node placement prediction,
2772 bool placed = nodePlacementPrediction(client,
2774 nodepos, neighbourpos);
2778 soundmaker.m_player_rightpunch_sound =
2779 playeritem_def.sound_place;
2781 soundmaker.m_player_rightpunch_sound =
2786 else if(pointed.type == POINTEDTHING_OBJECT)
2788 infotext = narrow_to_wide(selected_object->infoText());
2790 if(infotext == L"" && show_debug){
2791 infotext = narrow_to_wide(selected_object->debugInfoText());
2794 //if(input->getLeftClicked())
2795 if(input->getLeftState())
2797 bool do_punch = false;
2798 bool do_punch_damage = false;
2799 if(object_hit_delay_timer <= 0.0){
2801 do_punch_damage = true;
2802 object_hit_delay_timer = object_hit_delay;
2804 if(input->getLeftClicked()){
2808 infostream<<"Left-clicked object"<<std::endl;
2811 if(do_punch_damage){
2812 // Report direct punch
2813 v3f objpos = selected_object->getPosition();
2814 v3f dir = (objpos - player_position).normalize();
2816 bool disable_send = selected_object->directReportPunch(
2817 dir, &playeritem, time_from_last_punch);
2818 time_from_last_punch = 0;
2820 client.interact(0, pointed);
2823 else if(input->getRightClicked())
2825 infostream<<"Right-clicked object"<<std::endl;
2826 client.interact(3, pointed); // place
2829 else if(input->getLeftState())
2831 // When button is held down in air, show continuous animation
2835 pointed_old = pointed;
2837 if(left_punch || input->getLeftClicked())
2839 camera.setDigging(0); // left click animation
2842 input->resetLeftClicked();
2843 input->resetRightClicked();
2845 input->resetLeftReleased();
2846 input->resetRightReleased();
2849 Calculate stuff for drawing
2858 fog_range = BS*farmesh_range;
2862 fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
2864 if(draw_control.range_all)
2865 fog_range = 100000*BS;
2869 Calculate general brightness
2871 u32 daynight_ratio = client.getEnv().getDayNightRatio();
2872 float time_brightness = decode_light_f((float)daynight_ratio/1000.0);
2873 float direct_brightness = 0;
2874 bool sunlight_seen = false;
2875 if(g_settings->getBool("free_move")){
2876 direct_brightness = time_brightness;
2877 sunlight_seen = true;
2879 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
2880 float old_brightness = sky->getBrightness();
2881 direct_brightness = (float)client.getEnv().getClientMap()
2882 .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
2883 daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
2887 time_of_day = client.getEnv().getTimeOfDayF();
2889 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
2890 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
2891 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
2892 time_of_day_smooth = time_of_day;
2894 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
2895 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2896 + (time_of_day+1.0) * todsm;
2898 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2899 + time_of_day * todsm;
2901 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
2904 float brightness = sky->getBrightness();
2905 video::SColor bgcolor = sky->getBgColor();
2906 video::SColor skycolor = sky->getSkyColor();
2912 if(sky->getCloudsVisible()){
2913 clouds->setVisible(true);
2914 clouds->step(dtime);
2915 clouds->update(v2f(player_position.X, player_position.Z),
2916 sky->getCloudColor());
2918 clouds->setVisible(false);
2927 farmesh_range = draw_control.wanted_range * 10;
2928 if(draw_control.range_all && farmesh_range < 500)
2929 farmesh_range = 500;
2930 if(farmesh_range > 1000)
2931 farmesh_range = 1000;
2933 farmesh->step(dtime);
2934 farmesh->update(v2f(player_position.X, player_position.Z),
2935 brightness, farmesh_range);
2942 allparticles_step(dtime, client.getEnv());
2943 allparticlespawners_step(dtime, client.getEnv());
2949 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2953 video::EFT_FOG_LINEAR,
2965 video::EFT_FOG_LINEAR,
2975 Update gui stuff (0ms)
2978 //TimeTaker guiupdatetimer("Gui updating");
2980 const char program_name_and_version[] =
2981 "Minetest " VERSION_STRING;
2985 static float drawtime_avg = 0;
2986 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2987 /*static float beginscenetime_avg = 0;
2988 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2989 static float scenetime_avg = 0;
2990 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2991 static float endscenetime_avg = 0;
2992 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
2994 std::ostringstream os(std::ios_base::binary);
2996 <<program_name_and_version
2997 <<" (R: range_all="<<draw_control.range_all<<")"
2998 <<std::setprecision(0)
2999 <<" drawtime = "<<drawtime_avg
3000 <<std::setprecision(1)
3001 <<", dtime_jitter = "
3002 <<(dtime_jitter1_max_fraction * 100.0)<<" %"
3003 <<std::setprecision(1)
3004 <<", v_range = "<<draw_control.wanted_range
3005 <<std::setprecision(3)
3006 <<", RTT = "<<client.getRTT();
3007 guitext->setText(narrow_to_wide(os.str()).c_str());
3008 guitext->setVisible(true);
3010 else if(show_hud || show_chat)
3012 guitext->setText(narrow_to_wide(program_name_and_version).c_str());
3013 guitext->setVisible(true);
3017 guitext->setVisible(false);
3022 std::ostringstream os(std::ios_base::binary);
3023 os<<std::setprecision(1)<<std::fixed
3024 <<"(" <<(player_position.X/BS)
3025 <<", "<<(player_position.Y/BS)
3026 <<", "<<(player_position.Z/BS)
3027 <<") (yaw="<<(wrapDegrees_0_360(camera_yaw))
3028 <<") (seed = "<<((unsigned long long)client.getMapSeed())
3030 guitext2->setText(narrow_to_wide(os.str()).c_str());
3031 guitext2->setVisible(true);
3035 guitext2->setVisible(false);
3039 guitext_info->setText(infotext.c_str());
3040 guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
3044 float statustext_time_max = 1.5;
3045 if(!statustext.empty())
3047 statustext_time += dtime;
3048 if(statustext_time >= statustext_time_max)
3051 statustext_time = 0;
3054 guitext_status->setText(statustext.c_str());
3055 guitext_status->setVisible(!statustext.empty());
3057 if(!statustext.empty())
3059 s32 status_y = screensize.Y - 130;
3060 core::rect<s32> rect(
3062 status_y - guitext_status->getTextHeight(),
3066 guitext_status->setRelativePosition(rect);
3069 video::SColor initial_color(255,0,0,0);
3070 if(guienv->getSkin())
3071 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
3072 video::SColor final_color = initial_color;
3073 final_color.setAlpha(0);
3074 video::SColor fade_color =
3075 initial_color.getInterpolated_quadratic(
3078 pow(statustext_time / (float)statustext_time_max, 2.0f));
3079 guitext_status->setOverrideColor(fade_color);
3080 guitext_status->enableOverrideColor(true);
3085 Get chat messages from client
3088 // Get new messages from error log buffer
3089 while(!chat_log_error_buf.empty())
3091 chat_backend.addMessage(L"", narrow_to_wide(
3092 chat_log_error_buf.get()));
3094 // Get new messages from client
3095 std::wstring message;
3096 while(client.getChatMessage(message))
3098 chat_backend.addUnparsedMessage(message);
3100 // Remove old messages
3101 chat_backend.step(dtime);
3103 // Display all messages in a static text element
3104 u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
3105 std::wstring recent_chat = chat_backend.getRecentChat();
3106 guitext_chat->setText(recent_chat.c_str());
3108 // Update gui element size and position
3109 s32 chat_y = 5+(text_height+5);
3111 chat_y += (text_height+5);
3112 core::rect<s32> rect(
3116 chat_y + guitext_chat->getTextHeight()
3118 guitext_chat->setRelativePosition(rect);
3120 // Don't show chat if disabled or empty or profiler is enabled
3121 guitext_chat->setVisible(show_chat && recent_chat_count != 0
3129 if(client.getPlayerItem() != new_playeritem)
3131 client.selectPlayerItem(new_playeritem);
3133 if(client.getLocalInventoryUpdated())
3135 //infostream<<"Updating local inventory"<<std::endl;
3136 client.getLocalInventory(local_inventory);
3138 update_wielded_item_trigger = true;
3140 if(update_wielded_item_trigger)
3142 update_wielded_item_trigger = false;
3143 // Update wielded tool
3144 InventoryList *mlist = local_inventory.getList("main");
3147 item = mlist->getItem(client.getPlayerItem());
3148 camera.wield(item, client.getPlayerItem());
3152 Update block draw list every 200ms or when camera direction has
3155 update_draw_list_timer += dtime;
3156 if(update_draw_list_timer >= 0.2 ||
3157 update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2){
3158 update_draw_list_timer = 0;
3159 client.getEnv().getClientMap().updateDrawList(driver);
3160 update_draw_list_last_cam_dir = camera_direction;
3167 TimeTaker tt_draw("mainloop: draw");
3170 TimeTaker timer("beginScene");
3171 //driver->beginScene(false, true, bgcolor);
3172 //driver->beginScene(true, true, bgcolor);
3173 driver->beginScene(true, true, skycolor);
3174 beginscenetime = timer.stop(true);
3179 //infostream<<"smgr->drawAll()"<<std::endl;
3181 TimeTaker timer("smgr");
3184 if(g_settings->getBool("anaglyph"))
3186 irr::core::vector3df oldPosition = camera.getCameraNode()->getPosition();
3187 irr::core::vector3df oldTarget = camera.getCameraNode()->getTarget();
3189 irr::core::matrix4 startMatrix = camera.getCameraNode()->getAbsoluteTransformation();
3191 irr::core::vector3df focusPoint = (camera.getCameraNode()->getTarget() -
3192 camera.getCameraNode()->getAbsolutePosition()).setLength(1) +
3193 camera.getCameraNode()->getAbsolutePosition() ;
3196 irr::core::vector3df leftEye;
3197 irr::core::matrix4 leftMove;
3199 leftMove.setTranslation( irr::core::vector3df(-g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
3200 leftEye=(startMatrix*leftMove).getTranslation();
3202 //clear the depth buffer, and color
3203 driver->beginScene( true, true, irr::video::SColor(0,200,200,255) );
3205 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_RED;
3206 driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK;
3207 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
3208 irr::scene::ESNRP_SOLID +
3209 irr::scene::ESNRP_TRANSPARENT +
3210 irr::scene::ESNRP_TRANSPARENT_EFFECT +
3211 irr::scene::ESNRP_SHADOW;
3213 camera.getCameraNode()->setPosition( leftEye );
3214 camera.getCameraNode()->setTarget( focusPoint );
3216 smgr->drawAll(); // 'smgr->drawAll();' may go here
3220 irr::core::vector3df rightEye;
3221 irr::core::matrix4 rightMove;
3223 rightMove.setTranslation( irr::core::vector3df(g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
3224 rightEye=(startMatrix*rightMove).getTranslation();
3226 //clear the depth buffer
3227 driver->clearZBuffer();
3229 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_GREEN + irr::video::ECP_BLUE;
3230 driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK;
3231 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
3232 irr::scene::ESNRP_SOLID +
3233 irr::scene::ESNRP_TRANSPARENT +
3234 irr::scene::ESNRP_TRANSPARENT_EFFECT +
3235 irr::scene::ESNRP_SHADOW;
3237 camera.getCameraNode()->setPosition( rightEye );
3238 camera.getCameraNode()->setTarget( focusPoint );
3240 smgr->drawAll(); // 'smgr->drawAll();' may go here
3243 //driver->endScene();
3245 driver->getOverrideMaterial().Material.ColorMask=irr::video::ECP_ALL;
3246 driver->getOverrideMaterial().EnableFlags=0;
3247 driver->getOverrideMaterial().EnablePasses=0;
3249 camera.getCameraNode()->setPosition( oldPosition );
3250 camera.getCameraNode()->setTarget( oldTarget );
3253 scenetime = timer.stop(true);
3257 //TimeTaker timer9("auxiliary drawings");
3261 //TimeTaker //timer10("//timer10");
3267 driver->setMaterial(m);
3269 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
3272 hud.drawSelectionBoxes(hilightboxes);
3276 if(show_hud && (player->hud_flags & HUD_FLAG_WIELDITEM_VISIBLE))
3278 // Warning: This clears the Z buffer.
3279 camera.drawWieldedTool();
3286 client.getEnv().getClientMap().renderPostFx();
3292 if(show_profiler_graph)
3294 graph.draw(10, screensize.Y - 10, driver, font);
3301 hud.drawCrosshair();
3306 //TimeTaker //timer11("//timer11");
3314 hud.drawHotbar(v2s32(displaycenter.X, screensize.Y),
3315 client.getHP(), client.getPlayerItem(), client.getBreath());
3321 if(damage_flash > 0.0)
3323 video::SColor color(std::min(damage_flash, 180.0f),180,0,0);
3324 driver->draw2DRectangle(color,
3325 core::rect<s32>(0,0,screensize.X,screensize.Y),
3328 damage_flash -= 100.0*dtime;
3334 if(player->hurt_tilt_timer > 0.0)
3336 player->hurt_tilt_timer -= dtime*5;
3337 if(player->hurt_tilt_timer < 0)
3338 player->hurt_tilt_strength = 0;
3345 hud.drawLuaElements();
3357 TimeTaker timer("endScene");
3359 endscenetime = timer.stop(true);
3362 drawtime = tt_draw.stop(true);
3363 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
3369 static s16 lastFPS = 0;
3370 //u16 fps = driver->getFPS();
3371 u16 fps = (1.0/dtime_avg1);
3375 core::stringw str = L"Minetest [";
3376 str += driver->getName();
3380 device->setWindowCaption(str.c_str());
3385 Log times and stuff for visualization
3387 Profiler::GraphValues values;
3388 g_profiler->graphGet(values);
3397 if (gui_chat_console)
3398 gui_chat_console->drop();
3404 Draw a "shutting down" screen, which will be shown while the map
3405 generator and other stuff quits
3408 /*gui::IGUIStaticText *gui_shuttingdowntext = */
3409 wchar_t* text = wgettext("Shutting down stuff...");
3410 draw_load_screen(text, device, font, 0, -1, false);
3412 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
3415 gui_shuttingdowntext->remove();*/
3418 chat_backend.addMessage(L"", L"# Disconnected.");
3419 chat_backend.addMessage(L"", L"");
3421 // Client scope (client is destructed before destructing *def and tsrc)
3424 catch(SerializationError &e)
3426 error_message = L"A serialization error occurred:\n"
3427 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
3428 L" running a different version of Minetest.";
3429 errorstream<<wide_to_narrow(error_message)<<std::endl;
3431 catch(ServerError &e)
3433 error_message = narrow_to_wide(e.what());
3434 errorstream<<wide_to_narrow(error_message)<<std::endl;
3438 errorstream<<e.what()<<std::endl;
3439 error_message = narrow_to_wide(e.what()) + wgettext("\nCheck debug.txt for details.");
3447 //has to be deleted first to stop all server threads
3455 //extended resource accounting
3456 infostream << "Irrlicht resources after cleanup:" << std::endl;
3457 infostream << "\tRemaining meshes : "
3458 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
3459 infostream << "\tRemaining textures : "
3460 << driver->getTextureCount() << std::endl;
3461 for (unsigned int i = 0; i < driver->getTextureCount(); i++ ) {
3462 irr::video::ITexture* texture = driver->getTextureByIndex(i);
3463 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
3466 infostream << "\tRemaining materials: "
3467 << driver-> getMaterialRendererCount ()
3468 << " (note: irrlicht doesn't support removing renderers)"<< std::endl;