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"
42 #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"
72 #include "util/pointedthing.h"
78 struct TextDestChat : public TextDest
80 TextDestChat(Client *client)
84 void gotText(std::wstring text)
86 m_client->typeChatMessage(text);
88 void gotText(std::map<std::string, std::string> fields)
90 m_client->typeChatMessage(narrow_to_wide(fields["text"]));
96 struct TextDestNodeMetadata : public TextDest
98 TextDestNodeMetadata(v3s16 p, Client *client)
103 // This is deprecated I guess? -celeron55
104 void gotText(std::wstring text)
106 std::string ntext = wide_to_narrow(text);
107 infostream<<"Submitting 'text' field of node at ("<<m_p.X<<","
108 <<m_p.Y<<","<<m_p.Z<<"): "<<ntext<<std::endl;
109 std::map<std::string, std::string> fields;
110 fields["text"] = ntext;
111 m_client->sendNodemetaFields(m_p, "", fields);
113 void gotText(std::map<std::string, std::string> fields)
115 m_client->sendNodemetaFields(m_p, "", fields);
122 struct TextDestPlayerInventory : public TextDest
124 TextDestPlayerInventory(Client *client)
129 TextDestPlayerInventory(Client *client, std::string formname)
132 m_formname = formname;
134 void gotText(std::map<std::string, std::string> fields)
136 m_client->sendInventoryFields(m_formname, fields);
139 void setFormName(std::string formname) {
140 m_formname = formname;
144 std::string m_formname;
147 /* Respawn menu callback */
149 class MainRespawnInitiator: public IRespawnInitiator
152 MainRespawnInitiator(bool *active, Client *client):
153 m_active(active), m_client(client)
160 m_client->sendRespawn();
167 /* Form update callback */
169 class NodeMetadataFormSource: public IFormSource
172 NodeMetadataFormSource(ClientMap *map, v3s16 p):
177 std::string getForm()
179 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
182 return meta->getString("formspec");
184 std::string resolveText(std::string str)
186 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
189 return meta->resolveString(str);
196 class PlayerInventoryFormSource: public IFormSource
199 PlayerInventoryFormSource(Client *client):
203 std::string getForm()
205 LocalPlayer* player = m_client->getEnv().getLocalPlayer();
206 return player->inventory_formspec;
213 Check if a node is pointable
215 inline bool isPointableNode(const MapNode& n,
216 Client *client, bool liquids_pointable)
218 const ContentFeatures &features = client->getNodeDefManager()->get(n);
219 return features.pointable ||
220 (liquids_pointable && features.isLiquid());
224 Find what the player is pointing at
226 PointedThing getPointedThing(Client *client, v3f player_position,
227 v3f camera_direction, v3f camera_position,
228 core::line3d<f32> shootline, f32 d,
229 bool liquids_pointable,
230 bool look_for_object,
231 std::vector<aabb3f> &hilightboxes,
232 ClientActiveObject *&selected_object)
236 hilightboxes.clear();
237 selected_object = NULL;
239 INodeDefManager *nodedef = client->getNodeDefManager();
240 ClientMap &map = client->getEnv().getClientMap();
242 f32 mindistance = BS * 1001;
244 // First try to find a pointed at active object
247 selected_object = client->getSelectedActiveObject(d*BS,
248 camera_position, shootline);
250 if(selected_object != NULL)
252 if(selected_object->doShowSelectionBox())
254 aabb3f *selection_box = selected_object->getSelectionBox();
255 // Box should exist because object was
256 // returned in the first place
257 assert(selection_box);
259 v3f pos = selected_object->getPosition();
260 hilightboxes.push_back(aabb3f(
261 selection_box->MinEdge + pos,
262 selection_box->MaxEdge + pos));
265 mindistance = (selected_object->getPosition() - camera_position).getLength();
267 result.type = POINTEDTHING_OBJECT;
268 result.object_id = selected_object->getId();
272 // That didn't work, try to find a pointed at node
275 v3s16 pos_i = floatToInt(player_position, BS);
277 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
281 s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
282 s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
283 s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
284 s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
285 s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
286 s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
288 // Prevent signed number overflow
296 for(s16 y = ystart; y <= yend; y++)
297 for(s16 z = zstart; z <= zend; z++)
298 for(s16 x = xstart; x <= xend; x++)
303 n = map.getNode(v3s16(x,y,z));
305 catch(InvalidPositionException &e)
309 if(!isPointableNode(n, client, liquids_pointable))
312 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
315 v3f npf = intToFloat(np, BS);
317 for(std::vector<aabb3f>::const_iterator
319 i != boxes.end(); i++)
325 for(u16 j=0; j<6; j++)
327 v3s16 facedir = g_6dirs[j];
328 aabb3f facebox = box;
332 facebox.MinEdge.X = facebox.MaxEdge.X-d;
333 else if(facedir.X < 0)
334 facebox.MaxEdge.X = facebox.MinEdge.X+d;
335 else if(facedir.Y > 0)
336 facebox.MinEdge.Y = facebox.MaxEdge.Y-d;
337 else if(facedir.Y < 0)
338 facebox.MaxEdge.Y = facebox.MinEdge.Y+d;
339 else if(facedir.Z > 0)
340 facebox.MinEdge.Z = facebox.MaxEdge.Z-d;
341 else if(facedir.Z < 0)
342 facebox.MaxEdge.Z = facebox.MinEdge.Z+d;
344 v3f centerpoint = facebox.getCenter();
345 f32 distance = (centerpoint - camera_position).getLength();
346 if(distance >= mindistance)
348 if(!facebox.intersectsWithLine(shootline))
351 v3s16 np_above = np + facedir;
353 result.type = POINTEDTHING_NODE;
354 result.node_undersurface = np;
355 result.node_abovesurface = np_above;
356 mindistance = distance;
358 hilightboxes.clear();
359 for(std::vector<aabb3f>::const_iterator
361 i2 != boxes.end(); i2++)
364 box.MinEdge += npf + v3f(-d,-d,-d);
365 box.MaxEdge += npf + v3f(d,d,d);
366 hilightboxes.push_back(box);
376 Draws a screen with a single text on it.
377 Text will be removed when the screen is drawn the next time.
378 Additionally, a progressbar can be drawn when percent is set between 0 and 100.
380 /*gui::IGUIStaticText **/
381 void draw_load_screen(const std::wstring &text,
382 IrrlichtDevice* device, gui::IGUIFont* font,
383 float dtime=0 ,int percent=0, bool clouds=true)
385 video::IVideoDriver* driver = device->getVideoDriver();
386 v2u32 screensize = driver->getScreenSize();
387 const wchar_t *loadingtext = text.c_str();
388 core::vector2d<u32> textsize_u = font->getDimension(loadingtext);
389 core::vector2d<s32> textsize(textsize_u.X,textsize_u.Y);
390 core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
391 core::rect<s32> textrect(center - textsize/2, center + textsize/2);
393 gui::IGUIStaticText *guitext = guienv->addStaticText(
394 loadingtext, textrect, false, false);
395 guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
397 bool cloud_menu_background = clouds && g_settings->getBool("menu_clouds");
398 if (cloud_menu_background)
400 g_menuclouds->step(dtime*3);
401 g_menuclouds->render();
402 driver->beginScene(true, true, video::SColor(255,140,186,250));
403 g_menucloudsmgr->drawAll();
406 driver->beginScene(true, true, video::SColor(255,0,0,0));
407 if (percent >= 0 && percent <= 100) // draw progress bar
409 core::vector2d<s32> barsize(256,32);
410 core::rect<s32> barrect(center-barsize/2, center+barsize/2);
411 driver->draw2DRectangle(video::SColor(255,255,255,255),barrect, NULL); // border
412 driver->draw2DRectangle(video::SColor(255,64,64,64), core::rect<s32> (
413 barrect.UpperLeftCorner+1,
414 barrect.LowerRightCorner-1), NULL); // black inside the bar
415 driver->draw2DRectangle(video::SColor(255,128,128,128), core::rect<s32> (
416 barrect.UpperLeftCorner+1,
418 barrect.LowerRightCorner.X-(barsize.X-1)+percent*(barsize.X-2)/100,
419 barrect.LowerRightCorner.Y-1)), NULL); // the actual progress
429 /* Profiler display */
431 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler,
432 gui::IGUIFont *font, u32 text_height,
433 u32 show_profiler, u32 show_profiler_max)
435 if(show_profiler == 0)
437 guitext_profiler->setVisible(false);
442 std::ostringstream os(std::ios_base::binary);
443 g_profiler->printPage(os, show_profiler, show_profiler_max);
444 std::wstring text = narrow_to_wide(os.str());
445 guitext_profiler->setText(text.c_str());
446 guitext_profiler->setVisible(true);
448 s32 w = font->getDimension(text.c_str()).Width;
451 core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
452 8+(text_height+5)*2 +
453 font->getDimension(text.c_str()).Height);
454 guitext_profiler->setRelativePosition(rect);
455 guitext_profiler->setVisible(true);
463 Profiler::GraphValues values;
469 Meta(float initial=0, video::SColor color=
470 video::SColor(255,255,255,255)):
476 std::list<Piece> m_log;
484 void put(const Profiler::GraphValues &values)
487 piece.values = values;
488 m_log.push_back(piece);
489 while(m_log.size() > m_log_max_size)
490 m_log.erase(m_log.begin());
493 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
494 gui::IGUIFont* font) const
496 std::map<std::string, Meta> m_meta;
497 for(std::list<Piece>::const_iterator k = m_log.begin();
498 k != m_log.end(); k++)
500 const Piece &piece = *k;
501 for(Profiler::GraphValues::const_iterator i = piece.values.begin();
502 i != piece.values.end(); i++){
503 const std::string &id = i->first;
504 const float &value = i->second;
505 std::map<std::string, Meta>::iterator j =
507 if(j == m_meta.end()){
508 m_meta[id] = Meta(value);
511 if(value < j->second.min)
512 j->second.min = value;
513 if(value > j->second.max)
514 j->second.max = value;
519 static const video::SColor usable_colors[] = {
520 video::SColor(255,255,100,100),
521 video::SColor(255,90,225,90),
522 video::SColor(255,100,100,255),
523 video::SColor(255,255,150,50),
524 video::SColor(255,220,220,100)
526 static const u32 usable_colors_count =
527 sizeof(usable_colors) / sizeof(*usable_colors);
528 u32 next_color_i = 0;
529 for(std::map<std::string, Meta>::iterator i = m_meta.begin();
530 i != m_meta.end(); i++){
531 Meta &meta = i->second;
532 video::SColor color(255,200,200,200);
533 if(next_color_i < usable_colors_count)
534 color = usable_colors[next_color_i++];
539 s32 textx = x_left + m_log_max_size + 15;
540 s32 textx2 = textx + 200 - 15;
544 u32 num_graphs = m_meta.size();
545 core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
547 video::SColor bgcolor(120,0,0,0);
548 driver->draw2DRectangle(bgcolor, rect, NULL);
552 for(std::map<std::string, Meta>::const_iterator i = m_meta.begin();
553 i != m_meta.end(); i++){
554 const std::string &id = i->first;
555 const Meta &meta = i->second;
557 s32 y = y_bottom - meta_i * 50;
558 float show_min = meta.min;
559 float show_max = meta.max;
560 if(show_min >= -0.0001 && show_max >= -0.0001){
561 if(show_min <= show_max * 0.5)
566 snprintf(buf, 10, "%.3g", show_max);
567 font->draw(narrow_to_wide(buf).c_str(),
568 core::rect<s32>(textx, y - graphh,
569 textx2, y - graphh + texth),
571 snprintf(buf, 10, "%.3g", show_min);
572 font->draw(narrow_to_wide(buf).c_str(),
573 core::rect<s32>(textx, y - texth,
576 font->draw(narrow_to_wide(id).c_str(),
577 core::rect<s32>(textx, y - graphh/2 - texth/2,
578 textx2, y - graphh/2 + texth/2),
581 s32 graph1h = graphh;
582 bool relativegraph = (show_min != 0 && show_min != show_max);
583 float lastscaledvalue = 0.0;
584 bool lastscaledvalue_exists = false;
585 for(std::list<Piece>::const_iterator j = m_log.begin();
586 j != m_log.end(); j++)
588 const Piece &piece = *j;
590 bool value_exists = false;
591 Profiler::GraphValues::const_iterator k =
592 piece.values.find(id);
593 if(k != piece.values.end()){
599 lastscaledvalue_exists = false;
602 float scaledvalue = 1.0;
603 if(show_max != show_min)
604 scaledvalue = (value - show_min) / (show_max - show_min);
605 if(scaledvalue == 1.0 && value == 0){
607 lastscaledvalue_exists = false;
611 if(lastscaledvalue_exists){
612 s32 ivalue1 = lastscaledvalue * graph1h;
613 s32 ivalue2 = scaledvalue * graph1h;
614 driver->draw2DLine(v2s32(x-1, graph1y - ivalue1),
615 v2s32(x, graph1y - ivalue2), meta.color);
617 lastscaledvalue = scaledvalue;
618 lastscaledvalue_exists = true;
620 s32 ivalue = scaledvalue * graph1h;
621 driver->draw2DLine(v2s32(x, graph1y),
622 v2s32(x, graph1y - ivalue), meta.color);
631 class NodeDugEvent: public MtEvent
637 NodeDugEvent(v3s16 p, MapNode n):
641 const char* getType() const
647 ISoundManager *m_sound;
648 INodeDefManager *m_ndef;
650 float m_player_step_timer;
652 SimpleSoundSpec m_player_step_sound;
653 SimpleSoundSpec m_player_leftpunch_sound;
654 SimpleSoundSpec m_player_rightpunch_sound;
656 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
659 m_player_step_timer(0)
663 void playPlayerStep()
665 if(m_player_step_timer <= 0 && m_player_step_sound.exists()){
666 m_player_step_timer = 0.03;
667 m_sound->playSound(m_player_step_sound, false);
671 static void viewBobbingStep(MtEvent *e, void *data)
673 SoundMaker *sm = (SoundMaker*)data;
674 sm->playPlayerStep();
677 static void playerRegainGround(MtEvent *e, void *data)
679 SoundMaker *sm = (SoundMaker*)data;
680 sm->playPlayerStep();
683 static void playerJump(MtEvent *e, void *data)
685 //SoundMaker *sm = (SoundMaker*)data;
688 static void cameraPunchLeft(MtEvent *e, void *data)
690 SoundMaker *sm = (SoundMaker*)data;
691 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
694 static void cameraPunchRight(MtEvent *e, void *data)
696 SoundMaker *sm = (SoundMaker*)data;
697 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
700 static void nodeDug(MtEvent *e, void *data)
702 SoundMaker *sm = (SoundMaker*)data;
703 NodeDugEvent *nde = (NodeDugEvent*)e;
704 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
707 static void playerDamage(MtEvent *e, void *data)
709 SoundMaker *sm = (SoundMaker*)data;
710 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
713 static void playerFallingDamage(MtEvent *e, void *data)
715 SoundMaker *sm = (SoundMaker*)data;
716 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
719 void registerReceiver(MtEventManager *mgr)
721 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
722 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
723 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
724 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
725 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
726 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
727 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
728 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
731 void step(float dtime)
733 m_player_step_timer -= dtime;
737 // Locally stored sounds don't need to be preloaded because of this
738 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
740 std::set<std::string> m_fetched;
743 void fetchSounds(const std::string &name,
744 std::set<std::string> &dst_paths,
745 std::set<std::string> &dst_datas)
747 if(m_fetched.count(name))
749 m_fetched.insert(name);
750 std::string base = porting::path_share + DIR_DELIM + "testsounds";
751 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
752 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
753 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
754 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
755 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
756 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
757 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
758 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
759 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
760 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
761 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
765 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
768 bool *m_force_fog_off;
773 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
774 f32 *fog_range, Client *client):
776 m_force_fog_off(force_fog_off),
777 m_fog_range(fog_range),
780 ~GameGlobalShaderConstantSetter() {}
782 virtual void onSetConstants(video::IMaterialRendererServices *services,
789 video::SColor bgcolor = m_sky->getBgColor();
790 video::SColorf bgcolorf(bgcolor);
791 float bgcolorfa[4] = {
797 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
800 float fog_distance = 10000*BS;
801 if(g_settings->getBool("enable_fog") && !*m_force_fog_off)
802 fog_distance = *m_fog_range;
803 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
806 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
807 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
808 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
810 u32 animation_timer = porting::getTimeMs() % 100000;
811 float animation_timer_f = (float)animation_timer / 100000.0;
812 services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
813 services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
815 LocalPlayer* player = m_client->getEnv().getLocalPlayer();
816 v3f eye_position = player->getEyePosition();
817 services->setPixelShaderConstant("eyePosition", (irr::f32*)&eye_position, 3);
818 services->setVertexShaderConstant("eyePosition", (irr::f32*)&eye_position, 3);
820 // Normal map texture layer
823 // before 1.8 there isn't a "integer interface", only float
824 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
825 services->setPixelShaderConstant("normalTexture" , (irr::f32*)&layer1, 1);
826 services->setPixelShaderConstant("useNormalmap" , (irr::f32*)&layer2, 1);
828 services->setPixelShaderConstant("normalTexture" , (irr::s32*)&layer1, 1);
829 services->setPixelShaderConstant("useNormalmap" , (irr::s32*)&layer2, 1);
834 bool nodePlacementPrediction(Client &client,
835 const ItemDefinition &playeritem_def,
836 v3s16 nodepos, v3s16 neighbourpos)
838 std::string prediction = playeritem_def.node_placement_prediction;
839 INodeDefManager *nodedef = client.ndef();
840 ClientMap &map = client.getEnv().getClientMap();
842 if(prediction != "" && !nodedef->get(map.getNode(nodepos)).rightclickable)
844 verbosestream<<"Node placement prediction for "
845 <<playeritem_def.name<<" is "
846 <<prediction<<std::endl;
847 v3s16 p = neighbourpos;
848 // Place inside node itself if buildable_to
850 MapNode n_under = map.getNode(nodepos);
851 if(nodedef->get(n_under).buildable_to)
853 else if (!nodedef->get(map.getNode(p)).buildable_to)
855 }catch(InvalidPositionException &e){}
856 // Find id of predicted node
858 bool found = nodedef->getId(prediction, id);
860 errorstream<<"Node placement prediction failed for "
861 <<playeritem_def.name<<" (places "
863 <<") - Name not known"<<std::endl;
866 // Predict param2 for facedir and wallmounted nodes
868 if(nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED){
869 v3s16 dir = nodepos - neighbourpos;
870 if(abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))){
871 param2 = dir.Y < 0 ? 1 : 0;
872 } else if(abs(dir.X) > abs(dir.Z)){
873 param2 = dir.X < 0 ? 3 : 2;
875 param2 = dir.Z < 0 ? 5 : 4;
878 if(nodedef->get(id).param_type_2 == CPT2_FACEDIR){
879 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
880 if(abs(dir.X) > abs(dir.Z)){
881 param2 = dir.X < 0 ? 3 : 1;
883 param2 = dir.Z < 0 ? 2 : 0;
886 assert(param2 >= 0 && param2 <= 5);
887 //Check attachment if node is in group attached_node
888 if(((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0){
889 static v3s16 wallmounted_dirs[8] = {
898 if(nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
899 pp = p + wallmounted_dirs[param2];
901 pp = p + v3s16(0,-1,0);
902 if(!nodedef->get(map.getNode(pp)).walkable)
905 // Add node to client map
906 MapNode n(id, 0, param2);
908 // This triggers the required mesh update too
909 client.addNode(p, n);
911 }catch(InvalidPositionException &e){
912 errorstream<<"Node placement prediction failed for "
913 <<playeritem_def.name<<" (places "
915 <<") - Position not loaded"<<std::endl;
926 IrrlichtDevice *device,
929 std::string playername,
930 std::string password,
931 std::string address, // If "", local server is used
933 std::wstring &error_message,
934 ChatBackend &chat_backend,
935 const SubgameSpec &gamespec, // Used for local game,
936 bool simple_singleplayer_mode
939 FormspecFormSource* current_formspec = 0;
940 TextDestPlayerInventory* current_textdest = 0;
941 video::IVideoDriver* driver = device->getVideoDriver();
942 scene::ISceneManager* smgr = device->getSceneManager();
944 // Calculate text height using the font
945 u32 text_height = font->getDimension(L"Random test string").Height;
947 v2u32 last_screensize(0,0);
948 v2u32 screensize = driver->getScreenSize();
951 Draw "Loading" screen
955 wchar_t* text = wgettext("Loading...");
956 draw_load_screen(text, device, font,0,0);
960 // Create texture source
961 IWritableTextureSource *tsrc = createTextureSource(device);
963 // Create shader source
964 IWritableShaderSource *shsrc = createShaderSource(device);
966 // These will be filled by data received from the server
967 // Create item definition manager
968 IWritableItemDefManager *itemdef = createItemDefManager();
969 // Create node definition manager
970 IWritableNodeDefManager *nodedef = createNodeDefManager();
972 // Sound fetcher (useful when testing)
973 GameOnDemandSoundFetcher soundfetcher;
976 ISoundManager *sound = NULL;
977 bool sound_is_dummy = false;
979 if(g_settings->getBool("enable_sound")){
980 infostream<<"Attempting to use OpenAL audio"<<std::endl;
981 sound = createOpenALSoundManager(&soundfetcher);
983 infostream<<"Failed to initialize OpenAL audio"<<std::endl;
985 infostream<<"Sound disabled."<<std::endl;
989 infostream<<"Using dummy audio."<<std::endl;
990 sound = &dummySoundManager;
991 sound_is_dummy = true;
994 Server *server = NULL;
998 EventManager eventmgr;
1001 SoundMaker soundmaker(sound, nodedef);
1002 soundmaker.registerReceiver(&eventmgr);
1004 // Add chat log output for errors to be shown in chat
1005 LogOutputBuffer chat_log_error_buf(LMT_ERROR);
1007 // Create UI for modifying quicktune values
1008 QuicktuneShortcutter quicktune;
1015 wchar_t* text = wgettext("Creating server....");
1016 draw_load_screen(text, device, font,0,25);
1018 infostream<<"Creating server"<<std::endl;
1019 server = new Server(map_dir, gamespec,
1020 simple_singleplayer_mode);
1021 server->start(port);
1024 do{ // Client scope (breakable do-while(0))
1031 wchar_t* text = wgettext("Creating client...");
1032 draw_load_screen(text, device, font,0,50);
1035 infostream<<"Creating client"<<std::endl;
1037 MapDrawControl draw_control;
1040 wchar_t* text = wgettext("Resolving address...");
1041 draw_load_screen(text, device, font,0,75);
1044 Address connect_address(0,0,0,0, port);
1048 //connect_address.Resolve("localhost");
1049 if(g_settings->getBool("enable_ipv6") && g_settings->getBool("ipv6_server"))
1051 IPv6AddressBytes addr_bytes;
1052 addr_bytes.bytes[15] = 1;
1053 connect_address.setAddress(&addr_bytes);
1057 connect_address.setAddress(127,0,0,1);
1061 connect_address.Resolve(address.c_str());
1063 catch(ResolveError &e)
1065 error_message = L"Couldn't resolve address: " + narrow_to_wide(e.what());
1066 errorstream<<wide_to_narrow(error_message)<<std::endl;
1067 // Break out of client scope
1074 Client client(device, playername.c_str(), password, draw_control,
1075 tsrc, shsrc, itemdef, nodedef, sound, &eventmgr,
1076 connect_address.isIPv6());
1078 // Client acts as our GameDef
1079 IGameDef *gamedef = &client;
1082 Attempt to connect to the server
1085 infostream<<"Connecting to server at ";
1086 connect_address.print(&infostream);
1087 infostream<<std::endl;
1088 client.connect(connect_address);
1091 Wait for server to accept connection
1093 bool could_connect = false;
1094 bool connect_aborted = false;
1096 float time_counter = 0.0;
1098 float fps_max = g_settings->getFloat("fps_max");
1099 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1100 u32 lasttime = device->getTimer()->getTime();
1101 while(device->run())
1103 f32 dtime = 0.033; // in seconds
1104 if (cloud_menu_background) {
1105 u32 time = device->getTimer()->getTime();
1107 dtime = (time - lasttime) / 1000.0;
1112 // Update client and server
1115 server->step(dtime);
1118 if(client.connectedAndInitialized()){
1119 could_connect = true;
1123 if(client.accessDenied()){
1124 error_message = L"Access denied. Reason: "
1125 +client.accessDeniedReason();
1126 errorstream<<wide_to_narrow(error_message)<<std::endl;
1129 if(input->wasKeyDown(EscapeKey)){
1130 connect_aborted = true;
1131 infostream<<"Connect aborted [Escape]"<<std::endl;
1137 wchar_t* text = wgettext("Connecting to server...");
1138 draw_load_screen(text, device, font, dtime, 100);
1142 // On some computers framerate doesn't seem to be
1143 // automatically limited
1144 if (cloud_menu_background) {
1145 // Time of frame without fps limit
1148 // not using getRealTime is necessary for wine
1149 u32 time = device->getTimer()->getTime();
1151 busytime_u32 = time - lasttime;
1154 busytime = busytime_u32 / 1000.0;
1157 u32 frametime_min = 1000./fps_max;
1159 if(busytime_u32 < frametime_min) {
1160 u32 sleeptime = frametime_min - busytime_u32;
1161 device->sleep(sleeptime);
1166 time_counter += dtime;
1169 catch(con::PeerNotFoundException &e)
1173 Handle failure to connect
1176 if(error_message == L"" && !connect_aborted){
1177 error_message = L"Connection failed";
1178 errorstream<<wide_to_narrow(error_message)<<std::endl;
1180 // Break out of client scope
1185 Wait until content has been received
1187 bool got_content = false;
1188 bool content_aborted = false;
1190 float time_counter = 0.0;
1192 float fps_max = g_settings->getFloat("fps_max");
1193 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1194 u32 lasttime = device->getTimer()->getTime();
1195 while(device->run())
1197 f32 dtime = 0.033; // in seconds
1198 if (cloud_menu_background) {
1199 u32 time = device->getTimer()->getTime();
1201 dtime = (time - lasttime) / 1000.0;
1206 // Update client and server
1209 server->step(dtime);
1212 if(client.mediaReceived() &&
1213 client.itemdefReceived() &&
1214 client.nodedefReceived()){
1219 if(client.accessDenied()){
1220 error_message = L"Access denied. Reason: "
1221 +client.accessDeniedReason();
1222 errorstream<<wide_to_narrow(error_message)<<std::endl;
1225 if(!client.connectedAndInitialized()){
1226 error_message = L"Client disconnected";
1227 errorstream<<wide_to_narrow(error_message)<<std::endl;
1230 if(input->wasKeyDown(EscapeKey)){
1231 content_aborted = true;
1232 infostream<<"Connect aborted [Escape]"<<std::endl;
1238 if (!client.itemdefReceived())
1240 wchar_t* text = wgettext("Item definitions...");
1242 draw_load_screen(text, device, font, dtime, progress);
1245 else if (!client.nodedefReceived())
1247 wchar_t* text = wgettext("Node definitions...");
1249 draw_load_screen(text, device, font, dtime, progress);
1254 wchar_t* text = wgettext("Media...");
1255 progress = 50+client.mediaReceiveProgress()*50+0.5;
1256 draw_load_screen(text, device, font, dtime, progress);
1260 // On some computers framerate doesn't seem to be
1261 // automatically limited
1262 if (cloud_menu_background) {
1263 // Time of frame without fps limit
1266 // not using getRealTime is necessary for wine
1267 u32 time = device->getTimer()->getTime();
1269 busytime_u32 = time - lasttime;
1272 busytime = busytime_u32 / 1000.0;
1275 u32 frametime_min = 1000./fps_max;
1277 if(busytime_u32 < frametime_min) {
1278 u32 sleeptime = frametime_min - busytime_u32;
1279 device->sleep(sleeptime);
1284 time_counter += dtime;
1289 if(error_message == L"" && !content_aborted){
1290 error_message = L"Something failed";
1291 errorstream<<wide_to_narrow(error_message)<<std::endl;
1293 // Break out of client scope
1298 After all content has been received:
1299 Update cached textures, meshes and materials
1301 client.afterContentReceived(device,font);
1304 Create the camera node
1306 Camera camera(smgr, draw_control, gamedef);
1307 if (!camera.successfullyCreated(error_message))
1310 f32 camera_yaw = 0; // "right/left"
1311 f32 camera_pitch = 0; // "up/down"
1317 Clouds *clouds = NULL;
1318 if(g_settings->getBool("enable_clouds"))
1320 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1328 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, client.getEnv().getLocalPlayer());
1331 A copy of the local inventory
1333 Inventory local_inventory(itemdef);
1336 Find out size of crack animation
1338 int crack_animation_length = 5;
1340 video::ITexture *t = tsrc->getTexture("crack_anylength.png");
1341 v2u32 size = t->getOriginalSize();
1342 crack_animation_length = size.Y / size.X;
1349 // First line of debug text
1350 gui::IGUIStaticText *guitext = guienv->addStaticText(
1352 core::rect<s32>(5, 5, 795, 5+text_height),
1354 // Second line of debug text
1355 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1357 core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
1359 // At the middle of the screen
1360 // Object infos are shown in this
1361 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1363 core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1366 // Status text (displays info when showing and hiding GUI stuff, etc.)
1367 gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1369 core::rect<s32>(0,0,0,0),
1371 guitext_status->setVisible(false);
1373 std::wstring statustext;
1374 float statustext_time = 0;
1377 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1379 core::rect<s32>(0,0,0,0),
1380 //false, false); // Disable word wrap as of now
1382 // Remove stale "recent" chat messages from previous connections
1383 chat_backend.clearRecentChat();
1384 // Chat backend and console
1385 GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1387 // Profiler text (size is updated when text is updated)
1388 gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1390 core::rect<s32>(0,0,0,0),
1392 guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1393 guitext_profiler->setVisible(false);
1394 guitext_profiler->setWordWrap(true);
1397 Some statistics are collected in these
1400 u32 beginscenetime = 0;
1402 u32 endscenetime = 0;
1404 float recent_turn_speed = 0.0;
1406 ProfilerGraph graph;
1407 // Initially clear the profiler
1408 Profiler::GraphValues dummyvalues;
1409 g_profiler->graphGet(dummyvalues);
1411 float nodig_delay_timer = 0.0;
1412 float dig_time = 0.0;
1414 PointedThing pointed_old;
1415 bool digging = false;
1416 bool ldown_for_dig = false;
1418 float damage_flash = 0;
1420 float jump_timer = 0;
1421 bool reset_jump_timer = false;
1423 const float object_hit_delay = 0.2;
1424 float object_hit_delay_timer = 0.0;
1425 float time_from_last_punch = 10;
1427 float update_draw_list_timer = 0.0;
1428 v3f update_draw_list_last_cam_dir;
1430 bool invert_mouse = g_settings->getBool("invert_mouse");
1432 bool respawn_menu_active = false;
1433 bool update_wielded_item_trigger = true;
1435 bool show_hud = true;
1436 bool show_chat = true;
1437 bool force_fog_off = false;
1438 f32 fog_range = 100*BS;
1439 bool disable_camera_update = false;
1440 bool show_debug = g_settings->getBool("show_debug");
1441 bool show_profiler_graph = false;
1442 u32 show_profiler = 0;
1443 u32 show_profiler_max = 3; // Number of pages
1445 float time_of_day = 0;
1446 float time_of_day_smooth = 0;
1448 float repeat_rightclick_timer = 0;
1453 shsrc->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1454 sky, &force_fog_off, &fog_range, &client));
1460 bool first_loop_after_window_activation = true;
1462 // TODO: Convert the static interval timers to these
1463 // Interval limiter for profiler
1464 IntervalLimiter m_profiler_interval;
1466 // Time is in milliseconds
1467 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1468 // NOTE: So we have to use getTime() and call run()s between them
1469 u32 lasttime = device->getTimer()->getTime();
1471 LocalPlayer* player = client.getEnv().getLocalPlayer();
1472 player->hurt_tilt_timer = 0;
1473 player->hurt_tilt_strength = 0;
1478 Hud hud(driver, guienv, font, text_height,
1479 gamedef, player, &local_inventory);
1481 bool use_weather = g_settings->getBool("weather");
1483 core::stringw str = L"Minetest [";
1484 str += driver->getName();
1486 device->setWindowCaption(str.c_str());
1490 if(device->run() == false || kill == true)
1493 // Time of frame without fps limit
1497 // not using getRealTime is necessary for wine
1498 u32 time = device->getTimer()->getTime();
1500 busytime_u32 = time - lasttime;
1503 busytime = busytime_u32 / 1000.0;
1506 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1508 // Necessary for device->getTimer()->getTime()
1516 float fps_max = g_settings->getFloat("fps_max");
1517 u32 frametime_min = 1000./fps_max;
1519 if(busytime_u32 < frametime_min)
1521 u32 sleeptime = frametime_min - busytime_u32;
1522 device->sleep(sleeptime);
1523 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1527 // Necessary for device->getTimer()->getTime()
1531 Time difference calculation
1533 f32 dtime; // in seconds
1535 u32 time = device->getTimer()->getTime();
1537 dtime = (time - lasttime) / 1000.0;
1542 g_profiler->graphAdd("mainloop_dtime", dtime);
1546 if(nodig_delay_timer >= 0)
1547 nodig_delay_timer -= dtime;
1548 if(object_hit_delay_timer >= 0)
1549 object_hit_delay_timer -= dtime;
1550 time_from_last_punch += dtime;
1552 g_profiler->add("Elapsed time", dtime);
1553 g_profiler->avg("FPS", 1./dtime);
1556 Time average and jitter calculation
1559 static f32 dtime_avg1 = 0.0;
1560 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1561 f32 dtime_jitter1 = dtime - dtime_avg1;
1563 static f32 dtime_jitter1_max_sample = 0.0;
1564 static f32 dtime_jitter1_max_fraction = 0.0;
1566 static f32 jitter1_max = 0.0;
1567 static f32 counter = 0.0;
1568 if(dtime_jitter1 > jitter1_max)
1569 jitter1_max = dtime_jitter1;
1574 dtime_jitter1_max_sample = jitter1_max;
1575 dtime_jitter1_max_fraction
1576 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1582 Busytime average and jitter calculation
1585 static f32 busytime_avg1 = 0.0;
1586 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1587 f32 busytime_jitter1 = busytime - busytime_avg1;
1589 static f32 busytime_jitter1_max_sample = 0.0;
1590 static f32 busytime_jitter1_min_sample = 0.0;
1592 static f32 jitter1_max = 0.0;
1593 static f32 jitter1_min = 0.0;
1594 static f32 counter = 0.0;
1595 if(busytime_jitter1 > jitter1_max)
1596 jitter1_max = busytime_jitter1;
1597 if(busytime_jitter1 < jitter1_min)
1598 jitter1_min = busytime_jitter1;
1602 busytime_jitter1_max_sample = jitter1_max;
1603 busytime_jitter1_min_sample = jitter1_min;
1610 Handle miscellaneous stuff
1613 if(client.accessDenied())
1615 error_message = L"Access denied. Reason: "
1616 +client.accessDeniedReason();
1617 errorstream<<wide_to_narrow(error_message)<<std::endl;
1621 if(g_gamecallback->disconnect_requested)
1623 g_gamecallback->disconnect_requested = false;
1627 if(g_gamecallback->changepassword_requested)
1629 (new GUIPasswordChange(guienv, guiroot, -1,
1630 &g_menumgr, &client))->drop();
1631 g_gamecallback->changepassword_requested = false;
1634 if(g_gamecallback->changevolume_requested)
1636 (new GUIVolumeChange(guienv, guiroot, -1,
1637 &g_menumgr, &client))->drop();
1638 g_gamecallback->changevolume_requested = false;
1641 /* Process TextureSource's queue */
1642 tsrc->processQueue();
1644 /* Process ItemDefManager's queue */
1645 itemdef->processQueue(gamedef);
1648 Process ShaderSource's queue
1650 shsrc->processQueue();
1655 last_screensize = screensize;
1656 screensize = driver->getScreenSize();
1657 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1658 //bool screensize_changed = screensize != last_screensize;
1661 // Update HUD values
1662 hud.screensize = screensize;
1663 hud.displaycenter = displaycenter;
1666 // Hilight boxes collected during the loop and displayed
1667 std::vector<aabb3f> hilightboxes;
1670 std::wstring infotext;
1673 Debug info for client
1676 static float counter = 0.0;
1681 client.printDebugInfo(infostream);
1688 float profiler_print_interval =
1689 g_settings->getFloat("profiler_print_interval");
1690 bool print_to_log = true;
1691 if(profiler_print_interval == 0){
1692 print_to_log = false;
1693 profiler_print_interval = 5;
1695 if(m_profiler_interval.step(dtime, profiler_print_interval))
1698 infostream<<"Profiler:"<<std::endl;
1699 g_profiler->print(infostream);
1702 update_profiler_gui(guitext_profiler, font, text_height,
1703 show_profiler, show_profiler_max);
1705 g_profiler->clear();
1709 Direct handling of user input
1712 // Reset input if window not active or some menu is active
1713 if(device->isWindowActive() == false
1714 || noMenuActive() == false
1715 || guienv->hasFocus(gui_chat_console))
1719 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen())
1721 gui_chat_console->closeConsoleAtOnce();
1724 // Input handler step() (used by the random input generator)
1727 // Increase timer for doubleclick of "jump"
1728 if(g_settings->getBool("doubletap_jump") && jump_timer <= 0.2)
1729 jump_timer += dtime;
1732 Launch menus and trigger stuff according to keys
1734 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1736 // drop selected item
1737 IDropAction *a = new IDropAction();
1739 a->from_inv.setCurrentPlayer();
1740 a->from_list = "main";
1741 a->from_i = client.getPlayerItem();
1742 client.inventoryAction(a);
1744 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1746 infostream<<"the_game: "
1747 <<"Launching inventory"<<std::endl;
1749 GUIFormSpecMenu *menu =
1750 new GUIFormSpecMenu(device, guiroot, -1,
1752 &client, gamedef, tsrc);
1754 InventoryLocation inventoryloc;
1755 inventoryloc.setCurrentPlayer();
1757 PlayerInventoryFormSource *src = new PlayerInventoryFormSource(&client);
1759 menu->setFormSpec(src->getForm(), inventoryloc);
1760 menu->setFormSource(src);
1761 menu->setTextDest(new TextDestPlayerInventory(&client));
1764 else if(input->wasKeyDown(EscapeKey))
1766 infostream<<"the_game: "
1767 <<"Launching pause menu"<<std::endl;
1768 // It will delete itself by itself
1769 (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1770 &g_menumgr, simple_singleplayer_mode))->drop();
1772 // Move mouse cursor on top of the disconnect button
1773 if(simple_singleplayer_mode)
1774 input->setMousePos(displaycenter.X, displaycenter.Y+0);
1776 input->setMousePos(displaycenter.X, displaycenter.Y+25);
1778 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1780 TextDest *dest = new TextDestChat(&client);
1782 (new GUITextInputMenu(guienv, guiroot, -1,
1786 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1788 TextDest *dest = new TextDestChat(&client);
1790 (new GUITextInputMenu(guienv, guiroot, -1,
1794 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1796 if (!gui_chat_console->isOpenInhibited())
1798 // Open up to over half of the screen
1799 gui_chat_console->openConsole(0.6);
1800 guienv->setFocus(gui_chat_console);
1803 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1805 if(g_settings->getBool("free_move"))
1807 g_settings->set("free_move","false");
1808 statustext = L"free_move disabled";
1809 statustext_time = 0;
1813 g_settings->set("free_move","true");
1814 statustext = L"free_move enabled";
1815 statustext_time = 0;
1816 if(!client.checkPrivilege("fly"))
1817 statustext += L" (note: no 'fly' privilege)";
1820 else if(input->wasKeyDown(getKeySetting("keymap_jump")))
1822 if(g_settings->getBool("doubletap_jump") && jump_timer < 0.2)
1824 if(g_settings->getBool("free_move"))
1826 g_settings->set("free_move","false");
1827 statustext = L"free_move disabled";
1828 statustext_time = 0;
1832 g_settings->set("free_move","true");
1833 statustext = L"free_move enabled";
1834 statustext_time = 0;
1835 if(!client.checkPrivilege("fly"))
1836 statustext += L" (note: no 'fly' privilege)";
1839 reset_jump_timer = true;
1841 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1843 if(g_settings->getBool("fast_move"))
1845 g_settings->set("fast_move","false");
1846 statustext = L"fast_move disabled";
1847 statustext_time = 0;
1851 g_settings->set("fast_move","true");
1852 statustext = L"fast_move enabled";
1853 statustext_time = 0;
1854 if(!client.checkPrivilege("fast"))
1855 statustext += L" (note: no 'fast' privilege)";
1858 else if(input->wasKeyDown(getKeySetting("keymap_noclip")))
1860 if(g_settings->getBool("noclip"))
1862 g_settings->set("noclip","false");
1863 statustext = L"noclip disabled";
1864 statustext_time = 0;
1868 g_settings->set("noclip","true");
1869 statustext = L"noclip enabled";
1870 statustext_time = 0;
1871 if(!client.checkPrivilege("noclip"))
1872 statustext += L" (note: no 'noclip' privilege)";
1875 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1877 irr::video::IImage* const image = driver->createScreenShot();
1879 irr::c8 filename[256];
1880 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png",
1881 g_settings->get("screenshot_path").c_str(),
1882 device->getTimer()->getRealTime());
1883 if (driver->writeImageToFile(image, filename)) {
1884 std::wstringstream sstr;
1885 sstr<<"Saved screenshot to '"<<filename<<"'";
1886 infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1887 statustext = sstr.str();
1888 statustext_time = 0;
1890 infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1895 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
1897 show_hud = !show_hud;
1899 statustext = L"HUD shown";
1901 statustext = L"HUD hidden";
1902 statustext_time = 0;
1904 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
1906 show_chat = !show_chat;
1908 statustext = L"Chat shown";
1910 statustext = L"Chat hidden";
1911 statustext_time = 0;
1913 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1915 force_fog_off = !force_fog_off;
1917 statustext = L"Fog disabled";
1919 statustext = L"Fog enabled";
1920 statustext_time = 0;
1922 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1924 disable_camera_update = !disable_camera_update;
1925 if(disable_camera_update)
1926 statustext = L"Camera update disabled";
1928 statustext = L"Camera update enabled";
1929 statustext_time = 0;
1931 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
1933 // Initial / 3x toggle: Chat only
1934 // 1x toggle: Debug text with chat
1935 // 2x toggle: Debug text with profiler graph
1939 show_profiler_graph = false;
1940 statustext = L"Debug info shown";
1941 statustext_time = 0;
1943 else if(show_profiler_graph)
1946 show_profiler_graph = false;
1947 statustext = L"Debug info and profiler graph hidden";
1948 statustext_time = 0;
1952 show_profiler_graph = true;
1953 statustext = L"Profiler graph shown";
1954 statustext_time = 0;
1957 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1959 show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
1961 // FIXME: This updates the profiler with incomplete values
1962 update_profiler_gui(guitext_profiler, font, text_height,
1963 show_profiler, show_profiler_max);
1965 if(show_profiler != 0)
1967 std::wstringstream sstr;
1968 sstr<<"Profiler shown (page "<<show_profiler
1969 <<" of "<<show_profiler_max<<")";
1970 statustext = sstr.str();
1971 statustext_time = 0;
1975 statustext = L"Profiler hidden";
1976 statustext_time = 0;
1979 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
1981 s16 range = g_settings->getS16("viewing_range_nodes_min");
1982 s16 range_new = range + 10;
1983 g_settings->set("viewing_range_nodes_min", itos(range_new));
1984 statustext = narrow_to_wide(
1985 "Minimum viewing range changed to "
1987 statustext_time = 0;
1989 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
1991 s16 range = g_settings->getS16("viewing_range_nodes_min");
1992 s16 range_new = range - 10;
1995 g_settings->set("viewing_range_nodes_min",
1997 statustext = narrow_to_wide(
1998 "Minimum viewing range changed to "
2000 statustext_time = 0;
2004 if(!input->isKeyDown(getKeySetting("keymap_jump")) && reset_jump_timer)
2006 reset_jump_timer = false;
2010 // Handle QuicktuneShortcutter
2011 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
2013 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
2015 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
2017 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
2020 std::string msg = quicktune.getMessage();
2022 statustext = narrow_to_wide(msg);
2023 statustext_time = 0;
2027 // Item selection with mouse wheel
2028 u16 new_playeritem = client.getPlayerItem();
2030 s32 wheel = input->getMouseWheel();
2031 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
2032 player->hud_hotbar_itemcount-1);
2036 if(new_playeritem < max_item)
2043 if(new_playeritem > 0)
2046 new_playeritem = max_item;
2051 for(u16 i=0; i<10; i++)
2053 const KeyPress *kp = NumberKey + (i + 1) % 10;
2054 if(input->wasKeyDown(*kp))
2056 if(i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount)
2060 infostream<<"Selected item: "
2061 <<new_playeritem<<std::endl;
2066 // Viewing range selection
2067 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
2069 draw_control.range_all = !draw_control.range_all;
2070 if(draw_control.range_all)
2072 infostream<<"Enabled full viewing range"<<std::endl;
2073 statustext = L"Enabled full viewing range";
2074 statustext_time = 0;
2078 infostream<<"Disabled full viewing range"<<std::endl;
2079 statustext = L"Disabled full viewing range";
2080 statustext_time = 0;
2084 // Print debug stacks
2085 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
2087 dstream<<"-----------------------------------------"
2089 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
2090 dstream<<"-----------------------------------------"
2092 debug_stacks_print();
2096 Mouse and camera control
2097 NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
2100 float turn_amount = 0;
2101 if((device->isWindowActive() && noMenuActive()) || random_input)
2105 // Mac OSX gets upset if this is set every frame
2106 if(device->getCursorControl()->isVisible())
2107 device->getCursorControl()->setVisible(false);
2110 if(first_loop_after_window_activation){
2111 //infostream<<"window active, first loop"<<std::endl;
2112 first_loop_after_window_activation = false;
2115 s32 dx = input->getMousePos().X - displaycenter.X;
2116 s32 dy = input->getMousePos().Y - displaycenter.Y;
2119 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
2121 /*const float keyspeed = 500;
2122 if(input->isKeyDown(irr::KEY_UP))
2123 dy -= dtime * keyspeed;
2124 if(input->isKeyDown(irr::KEY_DOWN))
2125 dy += dtime * keyspeed;
2126 if(input->isKeyDown(irr::KEY_LEFT))
2127 dx -= dtime * keyspeed;
2128 if(input->isKeyDown(irr::KEY_RIGHT))
2129 dx += dtime * keyspeed;*/
2131 float d = g_settings->getFloat("mouse_sensitivity");
2132 d = rangelim(d, 0.01, 100.0);
2134 camera_pitch += dy*d;
2135 if(camera_pitch < -89.5) camera_pitch = -89.5;
2136 if(camera_pitch > 89.5) camera_pitch = 89.5;
2138 turn_amount = v2f(dx, dy).getLength() * d;
2140 input->setMousePos(displaycenter.X, displaycenter.Y);
2143 // Mac OSX gets upset if this is set every frame
2144 if(device->getCursorControl()->isVisible() == false)
2145 device->getCursorControl()->setVisible(true);
2147 //infostream<<"window inactive"<<std::endl;
2148 first_loop_after_window_activation = true;
2150 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
2151 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
2154 Player speed control
2168 PlayerControl control(
2169 input->isKeyDown(getKeySetting("keymap_forward")),
2170 input->isKeyDown(getKeySetting("keymap_backward")),
2171 input->isKeyDown(getKeySetting("keymap_left")),
2172 input->isKeyDown(getKeySetting("keymap_right")),
2173 input->isKeyDown(getKeySetting("keymap_jump")),
2174 input->isKeyDown(getKeySetting("keymap_special1")),
2175 input->isKeyDown(getKeySetting("keymap_sneak")),
2176 input->getLeftState(),
2177 input->getRightState(),
2181 client.setPlayerControl(control);
2183 1*(int)input->isKeyDown(getKeySetting("keymap_forward"))+
2184 2*(int)input->isKeyDown(getKeySetting("keymap_backward"))+
2185 4*(int)input->isKeyDown(getKeySetting("keymap_left"))+
2186 8*(int)input->isKeyDown(getKeySetting("keymap_right"))+
2187 16*(int)input->isKeyDown(getKeySetting("keymap_jump"))+
2188 32*(int)input->isKeyDown(getKeySetting("keymap_special1"))+
2189 64*(int)input->isKeyDown(getKeySetting("keymap_sneak"))+
2190 128*(int)input->getLeftState()+
2191 256*(int)input->getRightState();
2192 LocalPlayer* player = client.getEnv().getLocalPlayer();
2193 player->keyPressed=keyPressed;
2202 //TimeTaker timer("server->step(dtime)");
2203 server->step(dtime);
2211 //TimeTaker timer("client.step(dtime)");
2213 //client.step(dtime_avg1);
2217 // Read client events
2220 ClientEvent event = client.getClientEvent();
2221 if(event.type == CE_NONE)
2225 else if(event.type == CE_PLAYER_DAMAGE &&
2226 client.getHP() != 0)
2228 //u16 damage = event.player_damage.amount;
2229 //infostream<<"Player damage: "<<damage<<std::endl;
2231 damage_flash += 100.0;
2232 damage_flash += 8.0 * event.player_damage.amount;
2234 player->hurt_tilt_timer = 1.5;
2235 player->hurt_tilt_strength = event.player_damage.amount/2;
2236 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 2.0, 10.0);
2238 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
2239 gamedef->event()->put(e);
2241 else if(event.type == CE_PLAYER_FORCE_MOVE)
2243 camera_yaw = event.player_force_move.yaw;
2244 camera_pitch = event.player_force_move.pitch;
2246 else if(event.type == CE_DEATHSCREEN)
2248 if(respawn_menu_active)
2251 /*bool set_camera_point_target =
2252 event.deathscreen.set_camera_point_target;
2253 v3f camera_point_target;
2254 camera_point_target.X = event.deathscreen.camera_point_target_x;
2255 camera_point_target.Y = event.deathscreen.camera_point_target_y;
2256 camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
2257 MainRespawnInitiator *respawner =
2258 new MainRespawnInitiator(
2259 &respawn_menu_active, &client);
2260 GUIDeathScreen *menu =
2261 new GUIDeathScreen(guienv, guiroot, -1,
2262 &g_menumgr, respawner);
2265 chat_backend.addMessage(L"", L"You died.");
2267 /* Handle visualization */
2271 LocalPlayer* player = client.getEnv().getLocalPlayer();
2272 player->hurt_tilt_timer = 0;
2273 player->hurt_tilt_strength = 0;
2275 /*LocalPlayer* player = client.getLocalPlayer();
2276 player->setPosition(player->getPosition() + v3f(0,-BS,0));
2277 camera.update(player, busytime, screensize);*/
2279 else if (event.type == CE_SHOW_FORMSPEC)
2281 if (current_formspec == 0)
2284 /* Note: FormspecFormSource and TextDestPlayerInventory
2285 * are deleted by guiFormSpecMenu */
2286 current_formspec = new FormspecFormSource(*(event.show_formspec.formspec),¤t_formspec);
2287 current_textdest = new TextDestPlayerInventory(&client,*(event.show_formspec.formname));
2288 GUIFormSpecMenu *menu =
2289 new GUIFormSpecMenu(device, guiroot, -1,
2291 &client, gamedef, tsrc);
2292 menu->setFormSource(current_formspec);
2293 menu->setTextDest(current_textdest);
2298 assert(current_textdest != 0);
2300 current_textdest->setFormName(*(event.show_formspec.formname));
2301 current_formspec->setForm(*(event.show_formspec.formspec));
2303 delete(event.show_formspec.formspec);
2304 delete(event.show_formspec.formname);
2306 else if(event.type == CE_SPAWN_PARTICLE)
2308 LocalPlayer* player = client.getEnv().getLocalPlayer();
2309 video::ITexture *texture =
2310 gamedef->tsrc()->getTexture(*(event.spawn_particle.texture));
2312 new Particle(gamedef, smgr, player, client.getEnv(),
2313 *event.spawn_particle.pos,
2314 *event.spawn_particle.vel,
2315 *event.spawn_particle.acc,
2316 event.spawn_particle.expirationtime,
2317 event.spawn_particle.size,
2318 event.spawn_particle.collisiondetection,
2323 else if(event.type == CE_ADD_PARTICLESPAWNER)
2325 LocalPlayer* player = client.getEnv().getLocalPlayer();
2326 video::ITexture *texture =
2327 gamedef->tsrc()->getTexture(*(event.add_particlespawner.texture));
2329 new ParticleSpawner(gamedef, smgr, player,
2330 event.add_particlespawner.amount,
2331 event.add_particlespawner.spawntime,
2332 *event.add_particlespawner.minpos,
2333 *event.add_particlespawner.maxpos,
2334 *event.add_particlespawner.minvel,
2335 *event.add_particlespawner.maxvel,
2336 *event.add_particlespawner.minacc,
2337 *event.add_particlespawner.maxacc,
2338 event.add_particlespawner.minexptime,
2339 event.add_particlespawner.maxexptime,
2340 event.add_particlespawner.minsize,
2341 event.add_particlespawner.maxsize,
2342 event.add_particlespawner.collisiondetection,
2344 event.add_particlespawner.id);
2346 else if(event.type == CE_DELETE_PARTICLESPAWNER)
2348 delete_particlespawner (event.delete_particlespawner.id);
2350 else if (event.type == CE_HUDADD)
2352 u32 id = event.hudadd.id;
2353 size_t nhudelem = player->hud.size();
2354 if (id > nhudelem || (id < nhudelem && player->hud[id])) {
2355 delete event.hudadd.pos;
2356 delete event.hudadd.name;
2357 delete event.hudadd.scale;
2358 delete event.hudadd.text;
2359 delete event.hudadd.align;
2360 delete event.hudadd.offset;
2364 HudElement *e = new HudElement;
2365 e->type = (HudElementType)event.hudadd.type;
2366 e->pos = *event.hudadd.pos;
2367 e->name = *event.hudadd.name;
2368 e->scale = *event.hudadd.scale;
2369 e->text = *event.hudadd.text;
2370 e->number = event.hudadd.number;
2371 e->item = event.hudadd.item;
2372 e->dir = event.hudadd.dir;
2373 e->align = *event.hudadd.align;
2374 e->offset = *event.hudadd.offset;
2377 player->hud.push_back(e);
2379 player->hud[id] = e;
2381 delete event.hudadd.pos;
2382 delete event.hudadd.name;
2383 delete event.hudadd.scale;
2384 delete event.hudadd.text;
2385 delete event.hudadd.align;
2386 delete event.hudadd.offset;
2388 else if (event.type == CE_HUDRM)
2390 u32 id = event.hudrm.id;
2391 if (id < player->hud.size() && player->hud[id]) {
2392 delete player->hud[id];
2393 player->hud[id] = NULL;
2396 else if (event.type == CE_HUDCHANGE)
2398 u32 id = event.hudchange.id;
2399 if (id >= player->hud.size() || !player->hud[id]) {
2400 delete event.hudchange.v2fdata;
2401 delete event.hudchange.sdata;
2405 HudElement* e = player->hud[id];
2406 switch (event.hudchange.stat) {
2408 e->pos = *event.hudchange.v2fdata;
2411 e->name = *event.hudchange.sdata;
2413 case HUD_STAT_SCALE:
2414 e->scale = *event.hudchange.v2fdata;
2417 e->text = *event.hudchange.sdata;
2419 case HUD_STAT_NUMBER:
2420 e->number = event.hudchange.data;
2423 e->item = event.hudchange.data;
2426 e->dir = event.hudchange.data;
2428 case HUD_STAT_ALIGN:
2429 e->align = *event.hudchange.v2fdata;
2431 case HUD_STAT_OFFSET:
2432 e->offset = *event.hudchange.v2fdata;
2436 delete event.hudchange.v2fdata;
2437 delete event.hudchange.sdata;
2442 //TimeTaker //timer2("//timer2");
2445 For interaction purposes, get info about the held item
2447 - Is it a usable item?
2448 - Can it point to liquids?
2450 ItemStack playeritem;
2452 InventoryList *mlist = local_inventory.getList("main");
2455 playeritem = mlist->getItem(client.getPlayerItem());
2458 const ItemDefinition &playeritem_def =
2459 playeritem.getDefinition(itemdef);
2460 ToolCapabilities playeritem_toolcap =
2461 playeritem.getToolCapabilities(itemdef);
2467 LocalPlayer* player = client.getEnv().getLocalPlayer();
2468 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2469 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
2470 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2471 camera.update(player, dtime, busytime, screensize,
2475 v3f player_position = player->getPosition();
2476 v3s16 pos_i = floatToInt(player_position, BS);
2477 v3f camera_position = camera.getPosition();
2478 v3f camera_direction = camera.getDirection();
2479 f32 camera_fov = camera.getFovMax();
2481 if(!disable_camera_update){
2482 client.getEnv().getClientMap().updateCamera(camera_position,
2483 camera_direction, camera_fov);
2486 // Update sound listener
2487 sound->updateListener(camera.getCameraNode()->getPosition(),
2488 v3f(0,0,0), // velocity
2489 camera.getDirection(),
2490 camera.getCameraNode()->getUpVector());
2491 sound->setListenerGain(g_settings->getFloat("sound_volume"));
2497 soundmaker.step(dtime);
2499 ClientMap &map = client.getEnv().getClientMap();
2500 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
2501 soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
2505 Calculate what block is the crosshair pointing to
2508 //u32 t1 = device->getTimer()->getRealTime();
2510 f32 d = playeritem_def.range; // max. distance
2511 f32 d_hand = itemdef->get("").range;
2512 if(d < 0 && d_hand >= 0)
2516 core::line3d<f32> shootline(camera_position,
2517 camera_position + camera_direction * BS * (d+1));
2519 ClientActiveObject *selected_object = NULL;
2521 PointedThing pointed = getPointedThing(
2523 &client, player_position, camera_direction,
2524 camera_position, shootline, d,
2525 playeritem_def.liquids_pointable, !ldown_for_dig,
2530 if(pointed != pointed_old)
2532 infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2533 //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
2538 - releasing left mouse button
2539 - pointing away from node
2543 if(input->getLeftReleased())
2545 infostream<<"Left button released"
2546 <<" (stopped digging)"<<std::endl;
2549 else if(pointed != pointed_old)
2551 if (pointed.type == POINTEDTHING_NODE
2552 && pointed_old.type == POINTEDTHING_NODE
2553 && pointed.node_undersurface == pointed_old.node_undersurface)
2555 // Still pointing to the same node,
2556 // but a different face. Don't reset.
2560 infostream<<"Pointing away from node"
2561 <<" (stopped digging)"<<std::endl;
2567 client.interact(1, pointed_old);
2568 client.setCrack(-1, v3s16(0,0,0));
2572 if(!digging && ldown_for_dig && !input->getLeftState())
2574 ldown_for_dig = false;
2577 bool left_punch = false;
2578 soundmaker.m_player_leftpunch_sound.name = "";
2580 if(input->getRightState())
2581 repeat_rightclick_timer += dtime;
2583 repeat_rightclick_timer = 0;
2585 if(playeritem_def.usable && input->getLeftState())
2587 if(input->getLeftClicked())
2588 client.interact(4, pointed);
2590 else if(pointed.type == POINTEDTHING_NODE)
2592 v3s16 nodepos = pointed.node_undersurface;
2593 v3s16 neighbourpos = pointed.node_abovesurface;
2596 Check information text of node
2599 ClientMap &map = client.getEnv().getClientMap();
2600 NodeMetadata *meta = map.getNodeMetadata(nodepos);
2602 infotext = narrow_to_wide(meta->getString("infotext"));
2604 MapNode n = map.getNode(nodepos);
2605 if(nodedef->get(n).tiledef[0].name == "unknown_node.png"){
2606 infotext = L"Unknown node: ";
2607 infotext += narrow_to_wide(nodedef->get(n).name);
2615 if(nodig_delay_timer <= 0.0 && input->getLeftState()
2616 && client.checkPrivilege("interact"))
2620 infostream<<"Started digging"<<std::endl;
2621 client.interact(0, pointed);
2623 ldown_for_dig = true;
2625 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2627 // NOTE: Similar piece of code exists on the server side for
2629 // Get digging parameters
2630 DigParams params = getDigParams(nodedef->get(n).groups,
2631 &playeritem_toolcap);
2632 // If can't dig, try hand
2633 if(!params.diggable){
2634 const ItemDefinition &hand = itemdef->get("");
2635 const ToolCapabilities *tp = hand.tool_capabilities;
2637 params = getDigParams(nodedef->get(n).groups, tp);
2640 float dig_time_complete = 0.0;
2642 if(params.diggable == false)
2644 // I guess nobody will wait for this long
2645 dig_time_complete = 10000000.0;
2649 dig_time_complete = params.time;
2650 if (g_settings->getBool("enable_particles"))
2652 const ContentFeatures &features =
2653 client.getNodeDefManager()->get(n);
2654 addPunchingParticles
2655 (gamedef, smgr, player, client.getEnv(),
2656 nodepos, features.tiles);
2660 if(dig_time_complete >= 0.001)
2662 dig_index = (u16)((float)crack_animation_length
2663 * dig_time/dig_time_complete);
2665 // This is for torches
2668 dig_index = crack_animation_length;
2671 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2672 if(sound_dig.exists() && params.diggable){
2673 if(sound_dig.name == "__group"){
2674 if(params.main_group != ""){
2675 soundmaker.m_player_leftpunch_sound.gain = 0.5;
2676 soundmaker.m_player_leftpunch_sound.name =
2677 std::string("default_dig_") +
2681 soundmaker.m_player_leftpunch_sound = sound_dig;
2685 // Don't show cracks if not diggable
2686 if(dig_time_complete >= 100000.0)
2689 else if(dig_index < crack_animation_length)
2691 //TimeTaker timer("client.setTempMod");
2692 //infostream<<"dig_index="<<dig_index<<std::endl;
2693 client.setCrack(dig_index, nodepos);
2697 infostream<<"Digging completed"<<std::endl;
2698 client.interact(2, pointed);
2699 client.setCrack(-1, v3s16(0,0,0));
2700 MapNode wasnode = map.getNode(nodepos);
2701 client.removeNode(nodepos);
2703 if (g_settings->getBool("enable_particles"))
2705 const ContentFeatures &features =
2706 client.getNodeDefManager()->get(wasnode);
2708 (gamedef, smgr, player, client.getEnv(),
2709 nodepos, features.tiles);
2715 nodig_delay_timer = dig_time_complete
2716 / (float)crack_animation_length;
2718 // We don't want a corresponding delay to
2719 // very time consuming nodes
2720 if(nodig_delay_timer > 0.3)
2721 nodig_delay_timer = 0.3;
2722 // We want a slight delay to very little
2723 // time consuming nodes
2724 float mindelay = 0.15;
2725 if(nodig_delay_timer < mindelay)
2726 nodig_delay_timer = mindelay;
2728 // Send event to trigger sound
2729 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
2730 gamedef->event()->put(e);
2733 if(dig_time_complete < 100000.0)
2737 client.setCrack(-1, nodepos);
2740 camera.setDigging(0); // left click animation
2743 if((input->getRightClicked() ||
2744 repeat_rightclick_timer >=
2745 g_settings->getFloat("repeat_rightclick_time")) &&
2746 client.checkPrivilege("interact"))
2748 repeat_rightclick_timer = 0;
2749 infostream<<"Ground right-clicked"<<std::endl;
2751 // Sign special case, at least until formspec is properly implemented.
2753 if(meta && meta->getString("formspec") == "hack:sign_text_input"
2755 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2757 infostream<<"Launching metadata text input"<<std::endl;
2759 // Get a new text for it
2761 TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2763 std::wstring wtext = narrow_to_wide(meta->getString("text"));
2765 (new GUITextInputMenu(guienv, guiroot, -1,
2769 // If metadata provides an inventory view, activate it
2770 else if(meta && meta->getString("formspec") != "" && !random_input
2771 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2773 infostream<<"Launching custom inventory view"<<std::endl;
2775 InventoryLocation inventoryloc;
2776 inventoryloc.setNodeMeta(nodepos);
2780 GUIFormSpecMenu *menu =
2781 new GUIFormSpecMenu(device, guiroot, -1,
2783 &client, gamedef, tsrc);
2784 menu->setFormSpec(meta->getString("formspec"),
2786 menu->setFormSource(new NodeMetadataFormSource(
2787 &client.getEnv().getClientMap(), nodepos));
2788 menu->setTextDest(new TextDestNodeMetadata(nodepos, &client));
2791 // Otherwise report right click to server
2795 client.interact(3, pointed);
2796 camera.setDigging(1); // right click animation
2798 // If the wielded item has node placement prediction,
2800 bool placed = nodePlacementPrediction(client,
2802 nodepos, neighbourpos);
2806 soundmaker.m_player_rightpunch_sound =
2807 playeritem_def.sound_place;
2809 soundmaker.m_player_rightpunch_sound =
2814 else if(pointed.type == POINTEDTHING_OBJECT)
2816 infotext = narrow_to_wide(selected_object->infoText());
2818 if(infotext == L"" && show_debug){
2819 infotext = narrow_to_wide(selected_object->debugInfoText());
2822 //if(input->getLeftClicked())
2823 if(input->getLeftState())
2825 bool do_punch = false;
2826 bool do_punch_damage = false;
2827 if(object_hit_delay_timer <= 0.0){
2829 do_punch_damage = true;
2830 object_hit_delay_timer = object_hit_delay;
2832 if(input->getLeftClicked()){
2836 infostream<<"Left-clicked object"<<std::endl;
2839 if(do_punch_damage){
2840 // Report direct punch
2841 v3f objpos = selected_object->getPosition();
2842 v3f dir = (objpos - player_position).normalize();
2844 bool disable_send = selected_object->directReportPunch(
2845 dir, &playeritem, time_from_last_punch);
2846 time_from_last_punch = 0;
2848 client.interact(0, pointed);
2851 else if(input->getRightClicked())
2853 infostream<<"Right-clicked object"<<std::endl;
2854 client.interact(3, pointed); // place
2857 else if(input->getLeftState())
2859 // When button is held down in air, show continuous animation
2863 pointed_old = pointed;
2865 if(left_punch || input->getLeftClicked())
2867 camera.setDigging(0); // left click animation
2870 input->resetLeftClicked();
2871 input->resetRightClicked();
2873 input->resetLeftReleased();
2874 input->resetRightReleased();
2877 Calculate stuff for drawing
2884 if(draw_control.range_all)
2885 fog_range = 100000*BS;
2887 fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
2889 fog_range *= (1.5 - 1.4*(float)client.getEnv().getClientMap().getHumidity(pos_i)/100);
2890 fog_range = MYMIN(fog_range, (draw_control.farthest_drawn+20)*BS);
2895 Calculate general brightness
2897 u32 daynight_ratio = client.getEnv().getDayNightRatio();
2898 float time_brightness = decode_light_f((float)daynight_ratio/1000.0);
2899 float direct_brightness = 0;
2900 bool sunlight_seen = false;
2901 if(g_settings->getBool("free_move")){
2902 direct_brightness = time_brightness;
2903 sunlight_seen = true;
2905 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
2906 float old_brightness = sky->getBrightness();
2907 direct_brightness = (float)client.getEnv().getClientMap()
2908 .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
2909 daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
2913 time_of_day = client.getEnv().getTimeOfDayF();
2915 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
2916 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
2917 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
2918 time_of_day_smooth = time_of_day;
2920 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
2921 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2922 + (time_of_day+1.0) * todsm;
2924 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2925 + time_of_day * todsm;
2927 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
2930 video::SColor bgcolor = sky->getBgColor();
2931 video::SColor skycolor = sky->getSkyColor();
2937 if(sky->getCloudsVisible()){
2938 clouds->setVisible(true);
2939 clouds->step(dtime);
2940 clouds->update(v2f(player_position.X, player_position.Z),
2941 sky->getCloudColor());
2943 clouds->setVisible(false);
2951 allparticles_step(dtime, client.getEnv());
2952 allparticlespawners_step(dtime, client.getEnv());
2958 if(g_settings->getBool("enable_fog") && !force_fog_off)
2962 video::EFT_FOG_LINEAR,
2974 video::EFT_FOG_LINEAR,
2984 Update gui stuff (0ms)
2987 //TimeTaker guiupdatetimer("Gui updating");
2991 static float drawtime_avg = 0;
2992 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2993 /*static float beginscenetime_avg = 0;
2994 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2995 static float scenetime_avg = 0;
2996 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2997 static float endscenetime_avg = 0;
2998 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
3000 u16 fps = (1.0/dtime_avg1);
3002 std::ostringstream os(std::ios_base::binary);
3004 <<"Minetest "<<minetest_version_hash
3006 <<" (R: range_all="<<draw_control.range_all<<")"
3007 <<std::setprecision(0)
3008 <<" drawtime = "<<drawtime_avg
3009 <<std::setprecision(1)
3010 <<", dtime_jitter = "
3011 <<(dtime_jitter1_max_fraction * 100.0)<<" %"
3012 <<std::setprecision(1)
3013 <<", v_range = "<<draw_control.wanted_range
3014 <<std::setprecision(3)
3015 <<", RTT = "<<client.getRTT();
3016 guitext->setText(narrow_to_wide(os.str()).c_str());
3017 guitext->setVisible(true);
3019 else if(show_hud || show_chat)
3021 std::ostringstream os(std::ios_base::binary);
3022 os<<"Minetest "<<minetest_version_hash;
3023 guitext->setText(narrow_to_wide(os.str()).c_str());
3024 guitext->setVisible(true);
3028 guitext->setVisible(false);
3033 std::ostringstream os(std::ios_base::binary);
3034 os<<std::setprecision(1)<<std::fixed
3035 <<"(" <<(player_position.X/BS)
3036 <<", "<<(player_position.Y/BS)
3037 <<", "<<(player_position.Z/BS)
3038 <<") (yaw="<<(wrapDegrees_0_360(camera_yaw))
3039 <<") (t="<<client.getEnv().getClientMap().getHeat(pos_i)
3040 <<"C, h="<<client.getEnv().getClientMap().getHumidity(pos_i)
3041 <<"%) (seed = "<<((unsigned long long)client.getMapSeed())
3043 guitext2->setText(narrow_to_wide(os.str()).c_str());
3044 guitext2->setVisible(true);
3048 guitext2->setVisible(false);
3052 guitext_info->setText(infotext.c_str());
3053 guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
3057 float statustext_time_max = 1.5;
3058 if(!statustext.empty())
3060 statustext_time += dtime;
3061 if(statustext_time >= statustext_time_max)
3064 statustext_time = 0;
3067 guitext_status->setText(statustext.c_str());
3068 guitext_status->setVisible(!statustext.empty());
3070 if(!statustext.empty())
3072 s32 status_y = screensize.Y - 130;
3073 core::rect<s32> rect(
3075 status_y - guitext_status->getTextHeight(),
3079 guitext_status->setRelativePosition(rect);
3082 video::SColor initial_color(255,0,0,0);
3083 if(guienv->getSkin())
3084 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
3085 video::SColor final_color = initial_color;
3086 final_color.setAlpha(0);
3087 video::SColor fade_color =
3088 initial_color.getInterpolated_quadratic(
3091 pow(statustext_time / (float)statustext_time_max, 2.0f));
3092 guitext_status->setOverrideColor(fade_color);
3093 guitext_status->enableOverrideColor(true);
3098 Get chat messages from client
3101 // Get new messages from error log buffer
3102 while(!chat_log_error_buf.empty())
3104 chat_backend.addMessage(L"", narrow_to_wide(
3105 chat_log_error_buf.get()));
3107 // Get new messages from client
3108 std::wstring message;
3109 while(client.getChatMessage(message))
3111 chat_backend.addUnparsedMessage(message);
3113 // Remove old messages
3114 chat_backend.step(dtime);
3116 // Display all messages in a static text element
3117 u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
3118 std::wstring recent_chat = chat_backend.getRecentChat();
3119 guitext_chat->setText(recent_chat.c_str());
3121 // Update gui element size and position
3122 s32 chat_y = 5+(text_height+5);
3124 chat_y += (text_height+5);
3125 core::rect<s32> rect(
3129 chat_y + guitext_chat->getTextHeight()
3131 guitext_chat->setRelativePosition(rect);
3133 // Don't show chat if disabled or empty or profiler is enabled
3134 guitext_chat->setVisible(show_chat && recent_chat_count != 0
3142 if(client.getPlayerItem() != new_playeritem)
3144 client.selectPlayerItem(new_playeritem);
3146 if(client.getLocalInventoryUpdated())
3148 //infostream<<"Updating local inventory"<<std::endl;
3149 client.getLocalInventory(local_inventory);
3151 update_wielded_item_trigger = true;
3153 if(update_wielded_item_trigger)
3155 update_wielded_item_trigger = false;
3156 // Update wielded tool
3157 InventoryList *mlist = local_inventory.getList("main");
3160 item = mlist->getItem(client.getPlayerItem());
3161 camera.wield(item, client.getPlayerItem());
3165 Update block draw list every 200ms or when camera direction has
3168 update_draw_list_timer += dtime;
3169 if(update_draw_list_timer >= 0.2 ||
3170 update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2){
3171 update_draw_list_timer = 0;
3172 client.getEnv().getClientMap().updateDrawList(driver);
3173 update_draw_list_last_cam_dir = camera_direction;
3180 TimeTaker tt_draw("mainloop: draw");
3183 TimeTaker timer("beginScene");
3184 //driver->beginScene(false, true, bgcolor);
3185 //driver->beginScene(true, true, bgcolor);
3186 driver->beginScene(true, true, skycolor);
3187 beginscenetime = timer.stop(true);
3192 //infostream<<"smgr->drawAll()"<<std::endl;
3194 TimeTaker timer("smgr");
3197 if(g_settings->getBool("anaglyph"))
3199 irr::core::vector3df oldPosition = camera.getCameraNode()->getPosition();
3200 irr::core::vector3df oldTarget = camera.getCameraNode()->getTarget();
3202 irr::core::matrix4 startMatrix = camera.getCameraNode()->getAbsoluteTransformation();
3204 irr::core::vector3df focusPoint = (camera.getCameraNode()->getTarget() -
3205 camera.getCameraNode()->getAbsolutePosition()).setLength(1) +
3206 camera.getCameraNode()->getAbsolutePosition() ;
3209 irr::core::vector3df leftEye;
3210 irr::core::matrix4 leftMove;
3212 leftMove.setTranslation( irr::core::vector3df(-g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
3213 leftEye=(startMatrix*leftMove).getTranslation();
3215 //clear the depth buffer, and color
3216 driver->beginScene( true, true, irr::video::SColor(0,200,200,255) );
3218 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_RED;
3219 driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK;
3220 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
3221 irr::scene::ESNRP_SOLID +
3222 irr::scene::ESNRP_TRANSPARENT +
3223 irr::scene::ESNRP_TRANSPARENT_EFFECT +
3224 irr::scene::ESNRP_SHADOW;
3226 camera.getCameraNode()->setPosition( leftEye );
3227 camera.getCameraNode()->setTarget( focusPoint );
3229 smgr->drawAll(); // 'smgr->drawAll();' may go here
3231 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
3234 hud.drawSelectionBoxes(hilightboxes);
3238 irr::core::vector3df rightEye;
3239 irr::core::matrix4 rightMove;
3241 rightMove.setTranslation( irr::core::vector3df(g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
3242 rightEye=(startMatrix*rightMove).getTranslation();
3244 //clear the depth buffer
3245 driver->clearZBuffer();
3247 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_GREEN + irr::video::ECP_BLUE;
3248 driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK;
3249 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
3250 irr::scene::ESNRP_SOLID +
3251 irr::scene::ESNRP_TRANSPARENT +
3252 irr::scene::ESNRP_TRANSPARENT_EFFECT +
3253 irr::scene::ESNRP_SHADOW;
3255 camera.getCameraNode()->setPosition( rightEye );
3256 camera.getCameraNode()->setTarget( focusPoint );
3258 smgr->drawAll(); // 'smgr->drawAll();' may go here
3260 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
3263 hud.drawSelectionBoxes(hilightboxes);
3266 //driver->endScene();
3268 driver->getOverrideMaterial().Material.ColorMask=irr::video::ECP_ALL;
3269 driver->getOverrideMaterial().EnableFlags=0;
3270 driver->getOverrideMaterial().EnablePasses=0;
3272 camera.getCameraNode()->setPosition( oldPosition );
3273 camera.getCameraNode()->setTarget( oldTarget );
3276 scenetime = timer.stop(true);
3280 //TimeTaker timer9("auxiliary drawings");
3284 //TimeTaker //timer10("//timer10");
3290 driver->setMaterial(m);
3292 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
3293 if((!g_settings->getBool("anaglyph")) && (show_hud))
3295 hud.drawSelectionBoxes(hilightboxes);
3301 if(show_hud && (player->hud_flags & HUD_FLAG_WIELDITEM_VISIBLE))
3303 // Warning: This clears the Z buffer.
3304 camera.drawWieldedTool();
3311 client.getEnv().getClientMap().renderPostFx();
3317 if(show_profiler_graph)
3319 graph.draw(10, screensize.Y - 10, driver, font);
3326 hud.drawCrosshair();
3331 //TimeTaker //timer11("//timer11");
3339 hud.drawHotbar(v2s32(displaycenter.X, screensize.Y),
3340 client.getHP(), client.getPlayerItem(), client.getBreath());
3346 if(damage_flash > 0.0)
3348 video::SColor color(std::min(damage_flash, 180.0f),180,0,0);
3349 driver->draw2DRectangle(color,
3350 core::rect<s32>(0,0,screensize.X,screensize.Y),
3353 damage_flash -= 100.0*dtime;
3359 if(player->hurt_tilt_timer > 0.0)
3361 player->hurt_tilt_timer -= dtime*5;
3362 if(player->hurt_tilt_timer < 0)
3363 player->hurt_tilt_strength = 0;
3370 hud.drawLuaElements();
3382 TimeTaker timer("endScene");
3384 endscenetime = timer.stop(true);
3387 drawtime = tt_draw.stop(true);
3388 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
3395 Log times and stuff for visualization
3397 Profiler::GraphValues values;
3398 g_profiler->graphGet(values);
3407 if (gui_chat_console)
3408 gui_chat_console->drop();
3414 Draw a "shutting down" screen, which will be shown while the map
3415 generator and other stuff quits
3418 /*gui::IGUIStaticText *gui_shuttingdowntext = */
3419 wchar_t* text = wgettext("Shutting down stuff...");
3420 draw_load_screen(text, device, font, 0, -1, false);
3422 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
3425 gui_shuttingdowntext->remove();*/
3428 chat_backend.addMessage(L"", L"# Disconnected.");
3429 chat_backend.addMessage(L"", L"");
3431 // Client scope (client is destructed before destructing *def and tsrc)
3434 catch(SerializationError &e)
3436 error_message = L"A serialization error occurred:\n"
3437 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
3438 L" running a different version of Minetest.";
3439 errorstream<<wide_to_narrow(error_message)<<std::endl;
3441 catch(ServerError &e) {
3442 error_message = narrow_to_wide(e.what());
3443 errorstream << "ServerError: " << e.what() << std::endl;
3445 catch(ModError &e) {
3446 errorstream << "ModError: " << e.what() << std::endl;
3447 error_message = narrow_to_wide(e.what()) + wgettext("\nCheck debug.txt for details.");
3455 //has to be deleted first to stop all server threads
3463 //extended resource accounting
3464 infostream << "Irrlicht resources after cleanup:" << std::endl;
3465 infostream << "\tRemaining meshes : "
3466 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
3467 infostream << "\tRemaining textures : "
3468 << driver->getTextureCount() << std::endl;
3469 for (unsigned int i = 0; i < driver->getTextureCount(); i++ ) {
3470 irr::video::ITexture* texture = driver->getTextureByIndex(i);
3471 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
3474 clearTextureNameCache();
3475 infostream << "\tRemaining materials: "
3476 << driver-> getMaterialRendererCount ()
3477 << " (note: irrlicht doesn't support removing renderers)"<< std::endl;