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 // First try to find a pointed at active object
245 selected_object = client->getSelectedActiveObject(d*BS,
246 camera_position, shootline);
248 if(selected_object != NULL)
250 if(selected_object->doShowSelectionBox())
252 aabb3f *selection_box = selected_object->getSelectionBox();
253 // Box should exist because object was
254 // returned in the first place
255 assert(selection_box);
257 v3f pos = selected_object->getPosition();
258 hilightboxes.push_back(aabb3f(
259 selection_box->MinEdge + pos,
260 selection_box->MaxEdge + pos));
264 result.type = POINTEDTHING_OBJECT;
265 result.object_id = selected_object->getId();
270 // That didn't work, try to find a pointed at node
272 f32 mindistance = BS * 1001;
274 v3s16 pos_i = floatToInt(player_position, BS);
276 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
280 s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
281 s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
282 s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
283 s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
284 s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
285 s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
287 // Prevent signed number overflow
295 for(s16 y = ystart; y <= yend; y++)
296 for(s16 z = zstart; z <= zend; z++)
297 for(s16 x = xstart; x <= xend; x++)
302 n = map.getNode(v3s16(x,y,z));
304 catch(InvalidPositionException &e)
308 if(!isPointableNode(n, client, liquids_pointable))
311 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
314 v3f npf = intToFloat(np, BS);
316 for(std::vector<aabb3f>::const_iterator
318 i != boxes.end(); i++)
324 for(u16 j=0; j<6; j++)
326 v3s16 facedir = g_6dirs[j];
327 aabb3f facebox = box;
331 facebox.MinEdge.X = facebox.MaxEdge.X-d;
332 else if(facedir.X < 0)
333 facebox.MaxEdge.X = facebox.MinEdge.X+d;
334 else if(facedir.Y > 0)
335 facebox.MinEdge.Y = facebox.MaxEdge.Y-d;
336 else if(facedir.Y < 0)
337 facebox.MaxEdge.Y = facebox.MinEdge.Y+d;
338 else if(facedir.Z > 0)
339 facebox.MinEdge.Z = facebox.MaxEdge.Z-d;
340 else if(facedir.Z < 0)
341 facebox.MaxEdge.Z = facebox.MinEdge.Z+d;
343 v3f centerpoint = facebox.getCenter();
344 f32 distance = (centerpoint - camera_position).getLength();
345 if(distance >= mindistance)
347 if(!facebox.intersectsWithLine(shootline))
350 v3s16 np_above = np + facedir;
352 result.type = POINTEDTHING_NODE;
353 result.node_undersurface = np;
354 result.node_abovesurface = np_above;
355 mindistance = distance;
357 hilightboxes.clear();
358 for(std::vector<aabb3f>::const_iterator
360 i2 != boxes.end(); i2++)
363 box.MinEdge += npf + v3f(-d,-d,-d);
364 box.MaxEdge += npf + v3f(d,d,d);
365 hilightboxes.push_back(box);
375 Draws a screen with a single text on it.
376 Text will be removed when the screen is drawn the next time.
377 Additionally, a progressbar can be drawn when percent is set between 0 and 100.
379 /*gui::IGUIStaticText **/
380 void draw_load_screen(const std::wstring &text,
381 IrrlichtDevice* device, gui::IGUIFont* font,
382 float dtime=0 ,int percent=0, bool clouds=true)
384 video::IVideoDriver* driver = device->getVideoDriver();
385 v2u32 screensize = driver->getScreenSize();
386 const wchar_t *loadingtext = text.c_str();
387 core::vector2d<u32> textsize_u = font->getDimension(loadingtext);
388 core::vector2d<s32> textsize(textsize_u.X,textsize_u.Y);
389 core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
390 core::rect<s32> textrect(center - textsize/2, center + textsize/2);
392 gui::IGUIStaticText *guitext = guienv->addStaticText(
393 loadingtext, textrect, false, false);
394 guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
396 bool cloud_menu_background = clouds && g_settings->getBool("menu_clouds");
397 if (cloud_menu_background)
399 g_menuclouds->step(dtime*3);
400 g_menuclouds->render();
401 driver->beginScene(true, true, video::SColor(255,140,186,250));
402 g_menucloudsmgr->drawAll();
405 driver->beginScene(true, true, video::SColor(255,0,0,0));
406 if (percent >= 0 && percent <= 100) // draw progress bar
408 core::vector2d<s32> barsize(256,32);
409 core::rect<s32> barrect(center-barsize/2, center+barsize/2);
410 driver->draw2DRectangle(video::SColor(255,255,255,255),barrect, NULL); // border
411 driver->draw2DRectangle(video::SColor(255,64,64,64), core::rect<s32> (
412 barrect.UpperLeftCorner+1,
413 barrect.LowerRightCorner-1), NULL); // black inside the bar
414 driver->draw2DRectangle(video::SColor(255,128,128,128), core::rect<s32> (
415 barrect.UpperLeftCorner+1,
417 barrect.LowerRightCorner.X-(barsize.X-1)+percent*(barsize.X-2)/100,
418 barrect.LowerRightCorner.Y-1)), NULL); // the actual progress
428 /* Profiler display */
430 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler,
431 gui::IGUIFont *font, u32 text_height,
432 u32 show_profiler, u32 show_profiler_max)
434 if(show_profiler == 0)
436 guitext_profiler->setVisible(false);
441 std::ostringstream os(std::ios_base::binary);
442 g_profiler->printPage(os, show_profiler, show_profiler_max);
443 std::wstring text = narrow_to_wide(os.str());
444 guitext_profiler->setText(text.c_str());
445 guitext_profiler->setVisible(true);
447 s32 w = font->getDimension(text.c_str()).Width;
450 core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
451 8+(text_height+5)*2 +
452 font->getDimension(text.c_str()).Height);
453 guitext_profiler->setRelativePosition(rect);
454 guitext_profiler->setVisible(true);
462 Profiler::GraphValues values;
468 Meta(float initial=0, video::SColor color=
469 video::SColor(255,255,255,255)):
475 std::list<Piece> m_log;
483 void put(const Profiler::GraphValues &values)
486 piece.values = values;
487 m_log.push_back(piece);
488 while(m_log.size() > m_log_max_size)
489 m_log.erase(m_log.begin());
492 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
493 gui::IGUIFont* font) const
495 std::map<std::string, Meta> m_meta;
496 for(std::list<Piece>::const_iterator k = m_log.begin();
497 k != m_log.end(); k++)
499 const Piece &piece = *k;
500 for(Profiler::GraphValues::const_iterator i = piece.values.begin();
501 i != piece.values.end(); i++){
502 const std::string &id = i->first;
503 const float &value = i->second;
504 std::map<std::string, Meta>::iterator j =
506 if(j == m_meta.end()){
507 m_meta[id] = Meta(value);
510 if(value < j->second.min)
511 j->second.min = value;
512 if(value > j->second.max)
513 j->second.max = value;
518 static const video::SColor usable_colors[] = {
519 video::SColor(255,255,100,100),
520 video::SColor(255,90,225,90),
521 video::SColor(255,100,100,255),
522 video::SColor(255,255,150,50),
523 video::SColor(255,220,220,100)
525 static const u32 usable_colors_count =
526 sizeof(usable_colors) / sizeof(*usable_colors);
527 u32 next_color_i = 0;
528 for(std::map<std::string, Meta>::iterator i = m_meta.begin();
529 i != m_meta.end(); i++){
530 Meta &meta = i->second;
531 video::SColor color(255,200,200,200);
532 if(next_color_i < usable_colors_count)
533 color = usable_colors[next_color_i++];
538 s32 textx = x_left + m_log_max_size + 15;
539 s32 textx2 = textx + 200 - 15;
543 u32 num_graphs = m_meta.size();
544 core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
546 video::SColor bgcolor(120,0,0,0);
547 driver->draw2DRectangle(bgcolor, rect, NULL);
551 for(std::map<std::string, Meta>::const_iterator i = m_meta.begin();
552 i != m_meta.end(); i++){
553 const std::string &id = i->first;
554 const Meta &meta = i->second;
556 s32 y = y_bottom - meta_i * 50;
557 float show_min = meta.min;
558 float show_max = meta.max;
559 if(show_min >= -0.0001 && show_max >= -0.0001){
560 if(show_min <= show_max * 0.5)
565 snprintf(buf, 10, "%.3g", show_max);
566 font->draw(narrow_to_wide(buf).c_str(),
567 core::rect<s32>(textx, y - graphh,
568 textx2, y - graphh + texth),
570 snprintf(buf, 10, "%.3g", show_min);
571 font->draw(narrow_to_wide(buf).c_str(),
572 core::rect<s32>(textx, y - texth,
575 font->draw(narrow_to_wide(id).c_str(),
576 core::rect<s32>(textx, y - graphh/2 - texth/2,
577 textx2, y - graphh/2 + texth/2),
580 s32 graph1h = graphh;
581 bool relativegraph = (show_min != 0 && show_min != show_max);
582 float lastscaledvalue = 0.0;
583 bool lastscaledvalue_exists = false;
584 for(std::list<Piece>::const_iterator j = m_log.begin();
585 j != m_log.end(); j++)
587 const Piece &piece = *j;
589 bool value_exists = false;
590 Profiler::GraphValues::const_iterator k =
591 piece.values.find(id);
592 if(k != piece.values.end()){
598 lastscaledvalue_exists = false;
601 float scaledvalue = 1.0;
602 if(show_max != show_min)
603 scaledvalue = (value - show_min) / (show_max - show_min);
604 if(scaledvalue == 1.0 && value == 0){
606 lastscaledvalue_exists = false;
610 if(lastscaledvalue_exists){
611 s32 ivalue1 = lastscaledvalue * graph1h;
612 s32 ivalue2 = scaledvalue * graph1h;
613 driver->draw2DLine(v2s32(x-1, graph1y - ivalue1),
614 v2s32(x, graph1y - ivalue2), meta.color);
616 lastscaledvalue = scaledvalue;
617 lastscaledvalue_exists = true;
619 s32 ivalue = scaledvalue * graph1h;
620 driver->draw2DLine(v2s32(x, graph1y),
621 v2s32(x, graph1y - ivalue), meta.color);
630 class NodeDugEvent: public MtEvent
636 NodeDugEvent(v3s16 p, MapNode n):
640 const char* getType() const
646 ISoundManager *m_sound;
647 INodeDefManager *m_ndef;
649 float m_player_step_timer;
651 SimpleSoundSpec m_player_step_sound;
652 SimpleSoundSpec m_player_leftpunch_sound;
653 SimpleSoundSpec m_player_rightpunch_sound;
655 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
658 m_player_step_timer(0)
662 void playPlayerStep()
664 if(m_player_step_timer <= 0 && m_player_step_sound.exists()){
665 m_player_step_timer = 0.03;
666 m_sound->playSound(m_player_step_sound, false);
670 static void viewBobbingStep(MtEvent *e, void *data)
672 SoundMaker *sm = (SoundMaker*)data;
673 sm->playPlayerStep();
676 static void playerRegainGround(MtEvent *e, void *data)
678 SoundMaker *sm = (SoundMaker*)data;
679 sm->playPlayerStep();
682 static void playerJump(MtEvent *e, void *data)
684 //SoundMaker *sm = (SoundMaker*)data;
687 static void cameraPunchLeft(MtEvent *e, void *data)
689 SoundMaker *sm = (SoundMaker*)data;
690 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
693 static void cameraPunchRight(MtEvent *e, void *data)
695 SoundMaker *sm = (SoundMaker*)data;
696 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
699 static void nodeDug(MtEvent *e, void *data)
701 SoundMaker *sm = (SoundMaker*)data;
702 NodeDugEvent *nde = (NodeDugEvent*)e;
703 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
706 static void playerDamage(MtEvent *e, void *data)
708 SoundMaker *sm = (SoundMaker*)data;
709 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
712 static void playerFallingDamage(MtEvent *e, void *data)
714 SoundMaker *sm = (SoundMaker*)data;
715 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
718 void registerReceiver(MtEventManager *mgr)
720 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
721 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
722 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
723 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
724 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
725 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
726 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
727 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
730 void step(float dtime)
732 m_player_step_timer -= dtime;
736 // Locally stored sounds don't need to be preloaded because of this
737 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
739 std::set<std::string> m_fetched;
742 void fetchSounds(const std::string &name,
743 std::set<std::string> &dst_paths,
744 std::set<std::string> &dst_datas)
746 if(m_fetched.count(name))
748 m_fetched.insert(name);
749 std::string base = porting::path_share + DIR_DELIM + "testsounds";
750 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
751 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
752 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
753 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
754 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
755 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
756 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
757 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
758 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
759 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
760 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
764 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
767 bool *m_force_fog_off;
772 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
773 f32 *fog_range, Client *client):
775 m_force_fog_off(force_fog_off),
776 m_fog_range(fog_range),
779 ~GameGlobalShaderConstantSetter() {}
781 virtual void onSetConstants(video::IMaterialRendererServices *services,
788 video::SColor bgcolor = m_sky->getBgColor();
789 video::SColorf bgcolorf(bgcolor);
790 float bgcolorfa[4] = {
796 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
799 float fog_distance = 10000*BS;
800 if(g_settings->getBool("enable_fog") && !*m_force_fog_off)
801 fog_distance = *m_fog_range;
802 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
805 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
806 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
807 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
809 u32 animation_timer = porting::getTimeMs() % 100000;
810 float animation_timer_f = (float)animation_timer / 100000.0;
811 services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
812 services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
814 LocalPlayer* player = m_client->getEnv().getLocalPlayer();
815 v3f eye_position = player->getEyePosition();
816 services->setPixelShaderConstant("eyePosition", (irr::f32*)&eye_position, 3);
817 services->setVertexShaderConstant("eyePosition", (irr::f32*)&eye_position, 3);
819 // Normal map texture layer
822 // before 1.8 there isn't a "integer interface", only float
823 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
824 services->setPixelShaderConstant("normalTexture" , (irr::f32*)&layer1, 1);
825 services->setPixelShaderConstant("useNormalmap" , (irr::f32*)&layer2, 1);
827 services->setPixelShaderConstant("normalTexture" , (irr::s32*)&layer1, 1);
828 services->setPixelShaderConstant("useNormalmap" , (irr::s32*)&layer2, 1);
833 bool nodePlacementPrediction(Client &client,
834 const ItemDefinition &playeritem_def,
835 v3s16 nodepos, v3s16 neighbourpos)
837 std::string prediction = playeritem_def.node_placement_prediction;
838 INodeDefManager *nodedef = client.ndef();
839 ClientMap &map = client.getEnv().getClientMap();
841 if(prediction != "" && !nodedef->get(map.getNode(nodepos)).rightclickable)
843 verbosestream<<"Node placement prediction for "
844 <<playeritem_def.name<<" is "
845 <<prediction<<std::endl;
846 v3s16 p = neighbourpos;
847 // Place inside node itself if buildable_to
849 MapNode n_under = map.getNode(nodepos);
850 if(nodedef->get(n_under).buildable_to)
852 else if (!nodedef->get(map.getNode(p)).buildable_to)
854 }catch(InvalidPositionException &e){}
855 // Find id of predicted node
857 bool found = nodedef->getId(prediction, id);
859 errorstream<<"Node placement prediction failed for "
860 <<playeritem_def.name<<" (places "
862 <<") - Name not known"<<std::endl;
865 // Predict param2 for facedir and wallmounted nodes
867 if(nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED){
868 v3s16 dir = nodepos - neighbourpos;
869 if(abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))){
870 param2 = dir.Y < 0 ? 1 : 0;
871 } else if(abs(dir.X) > abs(dir.Z)){
872 param2 = dir.X < 0 ? 3 : 2;
874 param2 = dir.Z < 0 ? 5 : 4;
877 if(nodedef->get(id).param_type_2 == CPT2_FACEDIR){
878 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
879 if(abs(dir.X) > abs(dir.Z)){
880 param2 = dir.X < 0 ? 3 : 1;
882 param2 = dir.Z < 0 ? 2 : 0;
885 assert(param2 >= 0 && param2 <= 5);
886 //Check attachment if node is in group attached_node
887 if(((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0){
888 static v3s16 wallmounted_dirs[8] = {
897 if(nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
898 pp = p + wallmounted_dirs[param2];
900 pp = p + v3s16(0,-1,0);
901 if(!nodedef->get(map.getNode(pp)).walkable)
904 // Add node to client map
905 MapNode n(id, 0, param2);
907 // This triggers the required mesh update too
908 client.addNode(p, n);
910 }catch(InvalidPositionException &e){
911 errorstream<<"Node placement prediction failed for "
912 <<playeritem_def.name<<" (places "
914 <<") - Position not loaded"<<std::endl;
925 IrrlichtDevice *device,
928 std::string playername,
929 std::string password,
930 std::string address, // If "", local server is used
932 std::wstring &error_message,
933 ChatBackend &chat_backend,
934 const SubgameSpec &gamespec, // Used for local game,
935 bool simple_singleplayer_mode
938 FormspecFormSource* current_formspec = 0;
939 TextDestPlayerInventory* current_textdest = 0;
940 video::IVideoDriver* driver = device->getVideoDriver();
941 scene::ISceneManager* smgr = device->getSceneManager();
943 // Calculate text height using the font
944 u32 text_height = font->getDimension(L"Random test string").Height;
946 v2u32 last_screensize(0,0);
947 v2u32 screensize = driver->getScreenSize();
950 Draw "Loading" screen
954 wchar_t* text = wgettext("Loading...");
955 draw_load_screen(text, device, font,0,0);
959 // Create texture source
960 IWritableTextureSource *tsrc = createTextureSource(device);
962 // Create shader source
963 IWritableShaderSource *shsrc = createShaderSource(device);
965 // These will be filled by data received from the server
966 // Create item definition manager
967 IWritableItemDefManager *itemdef = createItemDefManager();
968 // Create node definition manager
969 IWritableNodeDefManager *nodedef = createNodeDefManager();
971 // Sound fetcher (useful when testing)
972 GameOnDemandSoundFetcher soundfetcher;
975 ISoundManager *sound = NULL;
976 bool sound_is_dummy = false;
978 if(g_settings->getBool("enable_sound")){
979 infostream<<"Attempting to use OpenAL audio"<<std::endl;
980 sound = createOpenALSoundManager(&soundfetcher);
982 infostream<<"Failed to initialize OpenAL audio"<<std::endl;
984 infostream<<"Sound disabled."<<std::endl;
988 infostream<<"Using dummy audio."<<std::endl;
989 sound = &dummySoundManager;
990 sound_is_dummy = true;
993 Server *server = NULL;
997 EventManager eventmgr;
1000 SoundMaker soundmaker(sound, nodedef);
1001 soundmaker.registerReceiver(&eventmgr);
1003 // Add chat log output for errors to be shown in chat
1004 LogOutputBuffer chat_log_error_buf(LMT_ERROR);
1006 // Create UI for modifying quicktune values
1007 QuicktuneShortcutter quicktune;
1014 wchar_t* text = wgettext("Creating server....");
1015 draw_load_screen(text, device, font,0,25);
1017 infostream<<"Creating server"<<std::endl;
1018 server = new Server(map_dir, gamespec,
1019 simple_singleplayer_mode);
1020 server->start(port);
1023 do{ // Client scope (breakable do-while(0))
1030 wchar_t* text = wgettext("Creating client...");
1031 draw_load_screen(text, device, font,0,50);
1034 infostream<<"Creating client"<<std::endl;
1036 MapDrawControl draw_control;
1039 wchar_t* text = wgettext("Resolving address...");
1040 draw_load_screen(text, device, font,0,75);
1043 Address connect_address(0,0,0,0, port);
1047 //connect_address.Resolve("localhost");
1048 if(g_settings->getBool("enable_ipv6") && g_settings->getBool("ipv6_server"))
1050 IPv6AddressBytes addr_bytes;
1051 addr_bytes.bytes[15] = 1;
1052 connect_address.setAddress(&addr_bytes);
1056 connect_address.setAddress(127,0,0,1);
1060 connect_address.Resolve(address.c_str());
1062 catch(ResolveError &e)
1064 error_message = L"Couldn't resolve address: " + narrow_to_wide(e.what());
1065 errorstream<<wide_to_narrow(error_message)<<std::endl;
1066 // Break out of client scope
1073 Client client(device, playername.c_str(), password, draw_control,
1074 tsrc, shsrc, itemdef, nodedef, sound, &eventmgr,
1075 connect_address.isIPv6());
1077 // Client acts as our GameDef
1078 IGameDef *gamedef = &client;
1081 Attempt to connect to the server
1084 infostream<<"Connecting to server at ";
1085 connect_address.print(&infostream);
1086 infostream<<std::endl;
1087 client.connect(connect_address);
1090 Wait for server to accept connection
1092 bool could_connect = false;
1093 bool connect_aborted = false;
1095 float time_counter = 0.0;
1097 float fps_max = g_settings->getFloat("fps_max");
1098 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1099 u32 lasttime = device->getTimer()->getTime();
1100 while(device->run())
1102 f32 dtime = 0.033; // in seconds
1103 if (cloud_menu_background) {
1104 u32 time = device->getTimer()->getTime();
1106 dtime = (time - lasttime) / 1000.0;
1111 // Update client and server
1114 server->step(dtime);
1117 if(client.connectedAndInitialized()){
1118 could_connect = true;
1122 if(client.accessDenied()){
1123 error_message = L"Access denied. Reason: "
1124 +client.accessDeniedReason();
1125 errorstream<<wide_to_narrow(error_message)<<std::endl;
1128 if(input->wasKeyDown(EscapeKey)){
1129 connect_aborted = true;
1130 infostream<<"Connect aborted [Escape]"<<std::endl;
1136 wchar_t* text = wgettext("Connecting to server...");
1137 draw_load_screen(text, device, font, dtime, 100);
1141 // On some computers framerate doesn't seem to be
1142 // automatically limited
1143 if (cloud_menu_background) {
1144 // Time of frame without fps limit
1147 // not using getRealTime is necessary for wine
1148 u32 time = device->getTimer()->getTime();
1150 busytime_u32 = time - lasttime;
1153 busytime = busytime_u32 / 1000.0;
1156 u32 frametime_min = 1000./fps_max;
1158 if(busytime_u32 < frametime_min) {
1159 u32 sleeptime = frametime_min - busytime_u32;
1160 device->sleep(sleeptime);
1165 time_counter += dtime;
1168 catch(con::PeerNotFoundException &e)
1172 Handle failure to connect
1175 if(error_message == L"" && !connect_aborted){
1176 error_message = L"Connection failed";
1177 errorstream<<wide_to_narrow(error_message)<<std::endl;
1179 // Break out of client scope
1184 Wait until content has been received
1186 bool got_content = false;
1187 bool content_aborted = false;
1189 float time_counter = 0.0;
1191 float fps_max = g_settings->getFloat("fps_max");
1192 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1193 u32 lasttime = device->getTimer()->getTime();
1194 while(device->run())
1196 f32 dtime = 0.033; // in seconds
1197 if (cloud_menu_background) {
1198 u32 time = device->getTimer()->getTime();
1200 dtime = (time - lasttime) / 1000.0;
1205 // Update client and server
1208 server->step(dtime);
1211 if(client.mediaReceived() &&
1212 client.itemdefReceived() &&
1213 client.nodedefReceived()){
1218 if(!client.connectedAndInitialized()){
1219 error_message = L"Client disconnected";
1220 errorstream<<wide_to_narrow(error_message)<<std::endl;
1223 if(input->wasKeyDown(EscapeKey)){
1224 content_aborted = true;
1225 infostream<<"Connect aborted [Escape]"<<std::endl;
1231 if (!client.itemdefReceived())
1233 wchar_t* text = wgettext("Item definitions...");
1235 draw_load_screen(text, device, font, dtime, progress);
1238 else if (!client.nodedefReceived())
1240 wchar_t* text = wgettext("Node definitions...");
1242 draw_load_screen(text, device, font, dtime, progress);
1247 wchar_t* text = wgettext("Media...");
1248 progress = 50+client.mediaReceiveProgress()*50+0.5;
1249 draw_load_screen(text, device, font, dtime, progress);
1253 // On some computers framerate doesn't seem to be
1254 // automatically limited
1255 if (cloud_menu_background) {
1256 // Time of frame without fps limit
1259 // not using getRealTime is necessary for wine
1260 u32 time = device->getTimer()->getTime();
1262 busytime_u32 = time - lasttime;
1265 busytime = busytime_u32 / 1000.0;
1268 u32 frametime_min = 1000./fps_max;
1270 if(busytime_u32 < frametime_min) {
1271 u32 sleeptime = frametime_min - busytime_u32;
1272 device->sleep(sleeptime);
1277 time_counter += dtime;
1282 if(error_message == L"" && !content_aborted){
1283 error_message = L"Something failed";
1284 errorstream<<wide_to_narrow(error_message)<<std::endl;
1286 // Break out of client scope
1291 After all content has been received:
1292 Update cached textures, meshes and materials
1294 client.afterContentReceived(device,font);
1297 Create the camera node
1299 Camera camera(smgr, draw_control, gamedef);
1300 if (!camera.successfullyCreated(error_message))
1303 f32 camera_yaw = 0; // "right/left"
1304 f32 camera_pitch = 0; // "up/down"
1310 Clouds *clouds = NULL;
1311 if(g_settings->getBool("enable_clouds"))
1313 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1321 sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1324 A copy of the local inventory
1326 Inventory local_inventory(itemdef);
1329 Find out size of crack animation
1331 int crack_animation_length = 5;
1333 video::ITexture *t = tsrc->getTexture("crack_anylength.png");
1334 v2u32 size = t->getOriginalSize();
1335 crack_animation_length = size.Y / size.X;
1342 // First line of debug text
1343 gui::IGUIStaticText *guitext = guienv->addStaticText(
1345 core::rect<s32>(5, 5, 795, 5+text_height),
1347 // Second line of debug text
1348 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1350 core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
1352 // At the middle of the screen
1353 // Object infos are shown in this
1354 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1356 core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1359 // Status text (displays info when showing and hiding GUI stuff, etc.)
1360 gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1362 core::rect<s32>(0,0,0,0),
1364 guitext_status->setVisible(false);
1366 std::wstring statustext;
1367 float statustext_time = 0;
1370 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1372 core::rect<s32>(0,0,0,0),
1373 //false, false); // Disable word wrap as of now
1375 // Remove stale "recent" chat messages from previous connections
1376 chat_backend.clearRecentChat();
1377 // Chat backend and console
1378 GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1380 // Profiler text (size is updated when text is updated)
1381 gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1383 core::rect<s32>(0,0,0,0),
1385 guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1386 guitext_profiler->setVisible(false);
1387 guitext_profiler->setWordWrap(true);
1390 Some statistics are collected in these
1393 u32 beginscenetime = 0;
1395 u32 endscenetime = 0;
1397 float recent_turn_speed = 0.0;
1399 ProfilerGraph graph;
1400 // Initially clear the profiler
1401 Profiler::GraphValues dummyvalues;
1402 g_profiler->graphGet(dummyvalues);
1404 float nodig_delay_timer = 0.0;
1405 float dig_time = 0.0;
1407 PointedThing pointed_old;
1408 bool digging = false;
1409 bool ldown_for_dig = false;
1411 float damage_flash = 0;
1413 float jump_timer = 0;
1414 bool reset_jump_timer = false;
1416 const float object_hit_delay = 0.2;
1417 float object_hit_delay_timer = 0.0;
1418 float time_from_last_punch = 10;
1420 float update_draw_list_timer = 0.0;
1421 v3f update_draw_list_last_cam_dir;
1423 bool invert_mouse = g_settings->getBool("invert_mouse");
1425 bool respawn_menu_active = false;
1426 bool update_wielded_item_trigger = true;
1428 bool show_hud = true;
1429 bool show_chat = true;
1430 bool force_fog_off = false;
1431 f32 fog_range = 100*BS;
1432 bool disable_camera_update = false;
1433 bool show_debug = g_settings->getBool("show_debug");
1434 bool show_profiler_graph = false;
1435 u32 show_profiler = 0;
1436 u32 show_profiler_max = 3; // Number of pages
1438 float time_of_day = 0;
1439 float time_of_day_smooth = 0;
1441 float repeat_rightclick_timer = 0;
1446 shsrc->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1447 sky, &force_fog_off, &fog_range, &client));
1453 bool first_loop_after_window_activation = true;
1455 // TODO: Convert the static interval timers to these
1456 // Interval limiter for profiler
1457 IntervalLimiter m_profiler_interval;
1459 // Time is in milliseconds
1460 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1461 // NOTE: So we have to use getTime() and call run()s between them
1462 u32 lasttime = device->getTimer()->getTime();
1464 LocalPlayer* player = client.getEnv().getLocalPlayer();
1465 player->hurt_tilt_timer = 0;
1466 player->hurt_tilt_strength = 0;
1471 Hud hud(driver, guienv, font, text_height,
1472 gamedef, player, &local_inventory);
1474 bool use_weather = g_settings->getBool("weather");
1478 if(device->run() == false || kill == true)
1481 // Time of frame without fps limit
1485 // not using getRealTime is necessary for wine
1486 u32 time = device->getTimer()->getTime();
1488 busytime_u32 = time - lasttime;
1491 busytime = busytime_u32 / 1000.0;
1494 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1496 // Necessary for device->getTimer()->getTime()
1504 float fps_max = g_settings->getFloat("fps_max");
1505 u32 frametime_min = 1000./fps_max;
1507 if(busytime_u32 < frametime_min)
1509 u32 sleeptime = frametime_min - busytime_u32;
1510 device->sleep(sleeptime);
1511 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1515 // Necessary for device->getTimer()->getTime()
1519 Time difference calculation
1521 f32 dtime; // in seconds
1523 u32 time = device->getTimer()->getTime();
1525 dtime = (time - lasttime) / 1000.0;
1530 g_profiler->graphAdd("mainloop_dtime", dtime);
1534 if(nodig_delay_timer >= 0)
1535 nodig_delay_timer -= dtime;
1536 if(object_hit_delay_timer >= 0)
1537 object_hit_delay_timer -= dtime;
1538 time_from_last_punch += dtime;
1540 g_profiler->add("Elapsed time", dtime);
1541 g_profiler->avg("FPS", 1./dtime);
1544 Time average and jitter calculation
1547 static f32 dtime_avg1 = 0.0;
1548 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1549 f32 dtime_jitter1 = dtime - dtime_avg1;
1551 static f32 dtime_jitter1_max_sample = 0.0;
1552 static f32 dtime_jitter1_max_fraction = 0.0;
1554 static f32 jitter1_max = 0.0;
1555 static f32 counter = 0.0;
1556 if(dtime_jitter1 > jitter1_max)
1557 jitter1_max = dtime_jitter1;
1562 dtime_jitter1_max_sample = jitter1_max;
1563 dtime_jitter1_max_fraction
1564 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1570 Busytime average and jitter calculation
1573 static f32 busytime_avg1 = 0.0;
1574 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1575 f32 busytime_jitter1 = busytime - busytime_avg1;
1577 static f32 busytime_jitter1_max_sample = 0.0;
1578 static f32 busytime_jitter1_min_sample = 0.0;
1580 static f32 jitter1_max = 0.0;
1581 static f32 jitter1_min = 0.0;
1582 static f32 counter = 0.0;
1583 if(busytime_jitter1 > jitter1_max)
1584 jitter1_max = busytime_jitter1;
1585 if(busytime_jitter1 < jitter1_min)
1586 jitter1_min = busytime_jitter1;
1590 busytime_jitter1_max_sample = jitter1_max;
1591 busytime_jitter1_min_sample = jitter1_min;
1598 Handle miscellaneous stuff
1601 if(client.accessDenied())
1603 error_message = L"Access denied. Reason: "
1604 +client.accessDeniedReason();
1605 errorstream<<wide_to_narrow(error_message)<<std::endl;
1609 if(g_gamecallback->disconnect_requested)
1611 g_gamecallback->disconnect_requested = false;
1615 if(g_gamecallback->changepassword_requested)
1617 (new GUIPasswordChange(guienv, guiroot, -1,
1618 &g_menumgr, &client))->drop();
1619 g_gamecallback->changepassword_requested = false;
1622 if(g_gamecallback->changevolume_requested)
1624 (new GUIVolumeChange(guienv, guiroot, -1,
1625 &g_menumgr, &client))->drop();
1626 g_gamecallback->changevolume_requested = false;
1629 /* Process TextureSource's queue */
1630 tsrc->processQueue();
1632 /* Process ItemDefManager's queue */
1633 itemdef->processQueue(gamedef);
1636 Process ShaderSource's queue
1638 shsrc->processQueue();
1643 last_screensize = screensize;
1644 screensize = driver->getScreenSize();
1645 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1646 //bool screensize_changed = screensize != last_screensize;
1649 // Update HUD values
1650 hud.screensize = screensize;
1651 hud.displaycenter = displaycenter;
1654 // Hilight boxes collected during the loop and displayed
1655 std::vector<aabb3f> hilightboxes;
1658 std::wstring infotext;
1661 Debug info for client
1664 static float counter = 0.0;
1669 client.printDebugInfo(infostream);
1676 float profiler_print_interval =
1677 g_settings->getFloat("profiler_print_interval");
1678 bool print_to_log = true;
1679 if(profiler_print_interval == 0){
1680 print_to_log = false;
1681 profiler_print_interval = 5;
1683 if(m_profiler_interval.step(dtime, profiler_print_interval))
1686 infostream<<"Profiler:"<<std::endl;
1687 g_profiler->print(infostream);
1690 update_profiler_gui(guitext_profiler, font, text_height,
1691 show_profiler, show_profiler_max);
1693 g_profiler->clear();
1697 Direct handling of user input
1700 // Reset input if window not active or some menu is active
1701 if(device->isWindowActive() == false
1702 || noMenuActive() == false
1703 || guienv->hasFocus(gui_chat_console))
1707 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen())
1709 gui_chat_console->closeConsoleAtOnce();
1712 // Input handler step() (used by the random input generator)
1715 // Increase timer for doubleclick of "jump"
1716 if(g_settings->getBool("doubletap_jump") && jump_timer <= 0.2)
1717 jump_timer += dtime;
1720 Launch menus and trigger stuff according to keys
1722 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1724 // drop selected item
1725 IDropAction *a = new IDropAction();
1727 a->from_inv.setCurrentPlayer();
1728 a->from_list = "main";
1729 a->from_i = client.getPlayerItem();
1730 client.inventoryAction(a);
1732 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1734 infostream<<"the_game: "
1735 <<"Launching inventory"<<std::endl;
1737 GUIFormSpecMenu *menu =
1738 new GUIFormSpecMenu(device, guiroot, -1,
1740 &client, gamedef, tsrc);
1742 InventoryLocation inventoryloc;
1743 inventoryloc.setCurrentPlayer();
1745 PlayerInventoryFormSource *src = new PlayerInventoryFormSource(&client);
1747 menu->setFormSpec(src->getForm(), inventoryloc);
1748 menu->setFormSource(src);
1749 menu->setTextDest(new TextDestPlayerInventory(&client));
1752 else if(input->wasKeyDown(EscapeKey))
1754 infostream<<"the_game: "
1755 <<"Launching pause menu"<<std::endl;
1756 // It will delete itself by itself
1757 (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1758 &g_menumgr, simple_singleplayer_mode))->drop();
1760 // Move mouse cursor on top of the disconnect button
1761 if(simple_singleplayer_mode)
1762 input->setMousePos(displaycenter.X, displaycenter.Y+0);
1764 input->setMousePos(displaycenter.X, displaycenter.Y+25);
1766 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1768 TextDest *dest = new TextDestChat(&client);
1770 (new GUITextInputMenu(guienv, guiroot, -1,
1774 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1776 TextDest *dest = new TextDestChat(&client);
1778 (new GUITextInputMenu(guienv, guiroot, -1,
1782 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1784 if (!gui_chat_console->isOpenInhibited())
1786 // Open up to over half of the screen
1787 gui_chat_console->openConsole(0.6);
1788 guienv->setFocus(gui_chat_console);
1791 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1793 if(g_settings->getBool("free_move"))
1795 g_settings->set("free_move","false");
1796 statustext = L"free_move disabled";
1797 statustext_time = 0;
1801 g_settings->set("free_move","true");
1802 statustext = L"free_move enabled";
1803 statustext_time = 0;
1804 if(!client.checkPrivilege("fly"))
1805 statustext += L" (note: no 'fly' privilege)";
1808 else if(input->wasKeyDown(getKeySetting("keymap_jump")))
1810 if(g_settings->getBool("doubletap_jump") && jump_timer < 0.2)
1812 if(g_settings->getBool("free_move"))
1814 g_settings->set("free_move","false");
1815 statustext = L"free_move disabled";
1816 statustext_time = 0;
1820 g_settings->set("free_move","true");
1821 statustext = L"free_move enabled";
1822 statustext_time = 0;
1823 if(!client.checkPrivilege("fly"))
1824 statustext += L" (note: no 'fly' privilege)";
1827 reset_jump_timer = true;
1829 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1831 if(g_settings->getBool("fast_move"))
1833 g_settings->set("fast_move","false");
1834 statustext = L"fast_move disabled";
1835 statustext_time = 0;
1839 g_settings->set("fast_move","true");
1840 statustext = L"fast_move enabled";
1841 statustext_time = 0;
1842 if(!client.checkPrivilege("fast"))
1843 statustext += L" (note: no 'fast' privilege)";
1846 else if(input->wasKeyDown(getKeySetting("keymap_noclip")))
1848 if(g_settings->getBool("noclip"))
1850 g_settings->set("noclip","false");
1851 statustext = L"noclip disabled";
1852 statustext_time = 0;
1856 g_settings->set("noclip","true");
1857 statustext = L"noclip enabled";
1858 statustext_time = 0;
1859 if(!client.checkPrivilege("noclip"))
1860 statustext += L" (note: no 'noclip' privilege)";
1863 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1865 irr::video::IImage* const image = driver->createScreenShot();
1867 irr::c8 filename[256];
1868 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png",
1869 g_settings->get("screenshot_path").c_str(),
1870 device->getTimer()->getRealTime());
1871 if (driver->writeImageToFile(image, filename)) {
1872 std::wstringstream sstr;
1873 sstr<<"Saved screenshot to '"<<filename<<"'";
1874 infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1875 statustext = sstr.str();
1876 statustext_time = 0;
1878 infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1883 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
1885 show_hud = !show_hud;
1887 statustext = L"HUD shown";
1889 statustext = L"HUD hidden";
1890 statustext_time = 0;
1892 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
1894 show_chat = !show_chat;
1896 statustext = L"Chat shown";
1898 statustext = L"Chat hidden";
1899 statustext_time = 0;
1901 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1903 force_fog_off = !force_fog_off;
1905 statustext = L"Fog disabled";
1907 statustext = L"Fog enabled";
1908 statustext_time = 0;
1910 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1912 disable_camera_update = !disable_camera_update;
1913 if(disable_camera_update)
1914 statustext = L"Camera update disabled";
1916 statustext = L"Camera update enabled";
1917 statustext_time = 0;
1919 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
1921 // Initial / 3x toggle: Chat only
1922 // 1x toggle: Debug text with chat
1923 // 2x toggle: Debug text with profiler graph
1927 show_profiler_graph = false;
1928 statustext = L"Debug info shown";
1929 statustext_time = 0;
1931 else if(show_profiler_graph)
1934 show_profiler_graph = false;
1935 statustext = L"Debug info and profiler graph hidden";
1936 statustext_time = 0;
1940 show_profiler_graph = true;
1941 statustext = L"Profiler graph shown";
1942 statustext_time = 0;
1945 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1947 show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
1949 // FIXME: This updates the profiler with incomplete values
1950 update_profiler_gui(guitext_profiler, font, text_height,
1951 show_profiler, show_profiler_max);
1953 if(show_profiler != 0)
1955 std::wstringstream sstr;
1956 sstr<<"Profiler shown (page "<<show_profiler
1957 <<" of "<<show_profiler_max<<")";
1958 statustext = sstr.str();
1959 statustext_time = 0;
1963 statustext = L"Profiler hidden";
1964 statustext_time = 0;
1967 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
1969 s16 range = g_settings->getS16("viewing_range_nodes_min");
1970 s16 range_new = range + 10;
1971 g_settings->set("viewing_range_nodes_min", itos(range_new));
1972 statustext = narrow_to_wide(
1973 "Minimum viewing range changed to "
1975 statustext_time = 0;
1977 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
1979 s16 range = g_settings->getS16("viewing_range_nodes_min");
1980 s16 range_new = range - 10;
1983 g_settings->set("viewing_range_nodes_min",
1985 statustext = narrow_to_wide(
1986 "Minimum viewing range changed to "
1988 statustext_time = 0;
1992 if(!input->isKeyDown(getKeySetting("keymap_jump")) && reset_jump_timer)
1994 reset_jump_timer = false;
1998 // Handle QuicktuneShortcutter
1999 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
2001 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
2003 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
2005 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
2008 std::string msg = quicktune.getMessage();
2010 statustext = narrow_to_wide(msg);
2011 statustext_time = 0;
2015 // Item selection with mouse wheel
2016 u16 new_playeritem = client.getPlayerItem();
2018 s32 wheel = input->getMouseWheel();
2019 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
2020 player->hud_hotbar_itemcount-1);
2024 if(new_playeritem < max_item)
2031 if(new_playeritem > 0)
2034 new_playeritem = max_item;
2039 for(u16 i=0; i<10; i++)
2041 const KeyPress *kp = NumberKey + (i + 1) % 10;
2042 if(input->wasKeyDown(*kp))
2044 if(i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount)
2048 infostream<<"Selected item: "
2049 <<new_playeritem<<std::endl;
2054 // Viewing range selection
2055 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
2057 draw_control.range_all = !draw_control.range_all;
2058 if(draw_control.range_all)
2060 infostream<<"Enabled full viewing range"<<std::endl;
2061 statustext = L"Enabled full viewing range";
2062 statustext_time = 0;
2066 infostream<<"Disabled full viewing range"<<std::endl;
2067 statustext = L"Disabled full viewing range";
2068 statustext_time = 0;
2072 // Print debug stacks
2073 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
2075 dstream<<"-----------------------------------------"
2077 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
2078 dstream<<"-----------------------------------------"
2080 debug_stacks_print();
2084 Mouse and camera control
2085 NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
2088 float turn_amount = 0;
2089 if((device->isWindowActive() && noMenuActive()) || random_input)
2093 // Mac OSX gets upset if this is set every frame
2094 if(device->getCursorControl()->isVisible())
2095 device->getCursorControl()->setVisible(false);
2098 if(first_loop_after_window_activation){
2099 //infostream<<"window active, first loop"<<std::endl;
2100 first_loop_after_window_activation = false;
2103 s32 dx = input->getMousePos().X - displaycenter.X;
2104 s32 dy = input->getMousePos().Y - displaycenter.Y;
2107 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
2109 /*const float keyspeed = 500;
2110 if(input->isKeyDown(irr::KEY_UP))
2111 dy -= dtime * keyspeed;
2112 if(input->isKeyDown(irr::KEY_DOWN))
2113 dy += dtime * keyspeed;
2114 if(input->isKeyDown(irr::KEY_LEFT))
2115 dx -= dtime * keyspeed;
2116 if(input->isKeyDown(irr::KEY_RIGHT))
2117 dx += dtime * keyspeed;*/
2119 float d = g_settings->getFloat("mouse_sensitivity");
2120 d = rangelim(d, 0.01, 100.0);
2122 camera_pitch += dy*d;
2123 if(camera_pitch < -89.5) camera_pitch = -89.5;
2124 if(camera_pitch > 89.5) camera_pitch = 89.5;
2126 turn_amount = v2f(dx, dy).getLength() * d;
2128 input->setMousePos(displaycenter.X, displaycenter.Y);
2131 // Mac OSX gets upset if this is set every frame
2132 if(device->getCursorControl()->isVisible() == false)
2133 device->getCursorControl()->setVisible(true);
2135 //infostream<<"window inactive"<<std::endl;
2136 first_loop_after_window_activation = true;
2138 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
2139 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
2142 Player speed control
2156 PlayerControl control(
2157 input->isKeyDown(getKeySetting("keymap_forward")),
2158 input->isKeyDown(getKeySetting("keymap_backward")),
2159 input->isKeyDown(getKeySetting("keymap_left")),
2160 input->isKeyDown(getKeySetting("keymap_right")),
2161 input->isKeyDown(getKeySetting("keymap_jump")),
2162 input->isKeyDown(getKeySetting("keymap_special1")),
2163 input->isKeyDown(getKeySetting("keymap_sneak")),
2164 input->getLeftState(),
2165 input->getRightState(),
2169 client.setPlayerControl(control);
2171 1*(int)input->isKeyDown(getKeySetting("keymap_forward"))+
2172 2*(int)input->isKeyDown(getKeySetting("keymap_backward"))+
2173 4*(int)input->isKeyDown(getKeySetting("keymap_left"))+
2174 8*(int)input->isKeyDown(getKeySetting("keymap_right"))+
2175 16*(int)input->isKeyDown(getKeySetting("keymap_jump"))+
2176 32*(int)input->isKeyDown(getKeySetting("keymap_special1"))+
2177 64*(int)input->isKeyDown(getKeySetting("keymap_sneak"))+
2178 128*(int)input->getLeftState()+
2179 256*(int)input->getRightState();
2180 LocalPlayer* player = client.getEnv().getLocalPlayer();
2181 player->keyPressed=keyPressed;
2190 //TimeTaker timer("server->step(dtime)");
2191 server->step(dtime);
2199 //TimeTaker timer("client.step(dtime)");
2201 //client.step(dtime_avg1);
2205 // Read client events
2208 ClientEvent event = client.getClientEvent();
2209 if(event.type == CE_NONE)
2213 else if(event.type == CE_PLAYER_DAMAGE &&
2214 client.getHP() != 0)
2216 //u16 damage = event.player_damage.amount;
2217 //infostream<<"Player damage: "<<damage<<std::endl;
2219 damage_flash += 100.0;
2220 damage_flash += 8.0 * event.player_damage.amount;
2222 player->hurt_tilt_timer = 1.5;
2223 player->hurt_tilt_strength = event.player_damage.amount/2;
2224 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 2.0, 10.0);
2226 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
2227 gamedef->event()->put(e);
2229 else if(event.type == CE_PLAYER_FORCE_MOVE)
2231 camera_yaw = event.player_force_move.yaw;
2232 camera_pitch = event.player_force_move.pitch;
2234 else if(event.type == CE_DEATHSCREEN)
2236 if(respawn_menu_active)
2239 /*bool set_camera_point_target =
2240 event.deathscreen.set_camera_point_target;
2241 v3f camera_point_target;
2242 camera_point_target.X = event.deathscreen.camera_point_target_x;
2243 camera_point_target.Y = event.deathscreen.camera_point_target_y;
2244 camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
2245 MainRespawnInitiator *respawner =
2246 new MainRespawnInitiator(
2247 &respawn_menu_active, &client);
2248 GUIDeathScreen *menu =
2249 new GUIDeathScreen(guienv, guiroot, -1,
2250 &g_menumgr, respawner);
2253 chat_backend.addMessage(L"", L"You died.");
2255 /* Handle visualization */
2259 LocalPlayer* player = client.getEnv().getLocalPlayer();
2260 player->hurt_tilt_timer = 0;
2261 player->hurt_tilt_strength = 0;
2263 /*LocalPlayer* player = client.getLocalPlayer();
2264 player->setPosition(player->getPosition() + v3f(0,-BS,0));
2265 camera.update(player, busytime, screensize);*/
2267 else if (event.type == CE_SHOW_FORMSPEC)
2269 if (current_formspec == 0)
2272 /* Note: FormspecFormSource and TextDestPlayerInventory
2273 * are deleted by guiFormSpecMenu */
2274 current_formspec = new FormspecFormSource(*(event.show_formspec.formspec),¤t_formspec);
2275 current_textdest = new TextDestPlayerInventory(&client,*(event.show_formspec.formname));
2276 GUIFormSpecMenu *menu =
2277 new GUIFormSpecMenu(device, guiroot, -1,
2279 &client, gamedef, tsrc);
2280 menu->setFormSource(current_formspec);
2281 menu->setTextDest(current_textdest);
2286 assert(current_textdest != 0);
2288 current_textdest->setFormName(*(event.show_formspec.formname));
2289 current_formspec->setForm(*(event.show_formspec.formspec));
2291 delete(event.show_formspec.formspec);
2292 delete(event.show_formspec.formname);
2294 else if(event.type == CE_SPAWN_PARTICLE)
2296 LocalPlayer* player = client.getEnv().getLocalPlayer();
2297 video::ITexture *texture =
2298 gamedef->tsrc()->getTexture(*(event.spawn_particle.texture));
2300 new Particle(gamedef, smgr, player, client.getEnv(),
2301 *event.spawn_particle.pos,
2302 *event.spawn_particle.vel,
2303 *event.spawn_particle.acc,
2304 event.spawn_particle.expirationtime,
2305 event.spawn_particle.size,
2306 event.spawn_particle.collisiondetection,
2311 else if(event.type == CE_ADD_PARTICLESPAWNER)
2313 LocalPlayer* player = client.getEnv().getLocalPlayer();
2314 video::ITexture *texture =
2315 gamedef->tsrc()->getTexture(*(event.add_particlespawner.texture));
2317 new ParticleSpawner(gamedef, smgr, player,
2318 event.add_particlespawner.amount,
2319 event.add_particlespawner.spawntime,
2320 *event.add_particlespawner.minpos,
2321 *event.add_particlespawner.maxpos,
2322 *event.add_particlespawner.minvel,
2323 *event.add_particlespawner.maxvel,
2324 *event.add_particlespawner.minacc,
2325 *event.add_particlespawner.maxacc,
2326 event.add_particlespawner.minexptime,
2327 event.add_particlespawner.maxexptime,
2328 event.add_particlespawner.minsize,
2329 event.add_particlespawner.maxsize,
2330 event.add_particlespawner.collisiondetection,
2332 event.add_particlespawner.id);
2334 else if(event.type == CE_DELETE_PARTICLESPAWNER)
2336 delete_particlespawner (event.delete_particlespawner.id);
2338 else if (event.type == CE_HUDADD)
2340 u32 id = event.hudadd.id;
2341 size_t nhudelem = player->hud.size();
2342 if (id > nhudelem || (id < nhudelem && player->hud[id])) {
2343 delete event.hudadd.pos;
2344 delete event.hudadd.name;
2345 delete event.hudadd.scale;
2346 delete event.hudadd.text;
2347 delete event.hudadd.align;
2348 delete event.hudadd.offset;
2352 HudElement *e = new HudElement;
2353 e->type = (HudElementType)event.hudadd.type;
2354 e->pos = *event.hudadd.pos;
2355 e->name = *event.hudadd.name;
2356 e->scale = *event.hudadd.scale;
2357 e->text = *event.hudadd.text;
2358 e->number = event.hudadd.number;
2359 e->item = event.hudadd.item;
2360 e->dir = event.hudadd.dir;
2361 e->align = *event.hudadd.align;
2362 e->offset = *event.hudadd.offset;
2365 player->hud.push_back(e);
2367 player->hud[id] = e;
2369 delete event.hudadd.pos;
2370 delete event.hudadd.name;
2371 delete event.hudadd.scale;
2372 delete event.hudadd.text;
2373 delete event.hudadd.align;
2374 delete event.hudadd.offset;
2376 else if (event.type == CE_HUDRM)
2378 u32 id = event.hudrm.id;
2379 if (id < player->hud.size() && player->hud[id]) {
2380 delete player->hud[id];
2381 player->hud[id] = NULL;
2384 else if (event.type == CE_HUDCHANGE)
2386 u32 id = event.hudchange.id;
2387 if (id >= player->hud.size() || !player->hud[id]) {
2388 delete event.hudchange.v2fdata;
2389 delete event.hudchange.sdata;
2393 HudElement* e = player->hud[id];
2394 switch (event.hudchange.stat) {
2396 e->pos = *event.hudchange.v2fdata;
2399 e->name = *event.hudchange.sdata;
2401 case HUD_STAT_SCALE:
2402 e->scale = *event.hudchange.v2fdata;
2405 e->text = *event.hudchange.sdata;
2407 case HUD_STAT_NUMBER:
2408 e->number = event.hudchange.data;
2411 e->item = event.hudchange.data;
2414 e->dir = event.hudchange.data;
2416 case HUD_STAT_ALIGN:
2417 e->align = *event.hudchange.v2fdata;
2419 case HUD_STAT_OFFSET:
2420 e->offset = *event.hudchange.v2fdata;
2424 delete event.hudchange.v2fdata;
2425 delete event.hudchange.sdata;
2430 //TimeTaker //timer2("//timer2");
2433 For interaction purposes, get info about the held item
2435 - Is it a usable item?
2436 - Can it point to liquids?
2438 ItemStack playeritem;
2440 InventoryList *mlist = local_inventory.getList("main");
2443 playeritem = mlist->getItem(client.getPlayerItem());
2446 const ItemDefinition &playeritem_def =
2447 playeritem.getDefinition(itemdef);
2448 ToolCapabilities playeritem_toolcap =
2449 playeritem.getToolCapabilities(itemdef);
2455 LocalPlayer* player = client.getEnv().getLocalPlayer();
2456 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2457 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
2458 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2459 camera.update(player, dtime, busytime, screensize,
2463 v3f player_position = player->getPosition();
2464 v3s16 pos_i = floatToInt(player_position, BS);
2465 v3f camera_position = camera.getPosition();
2466 v3f camera_direction = camera.getDirection();
2467 f32 camera_fov = camera.getFovMax();
2469 if(!disable_camera_update){
2470 client.getEnv().getClientMap().updateCamera(camera_position,
2471 camera_direction, camera_fov);
2474 // Update sound listener
2475 sound->updateListener(camera.getCameraNode()->getPosition(),
2476 v3f(0,0,0), // velocity
2477 camera.getDirection(),
2478 camera.getCameraNode()->getUpVector());
2479 sound->setListenerGain(g_settings->getFloat("sound_volume"));
2485 soundmaker.step(dtime);
2487 ClientMap &map = client.getEnv().getClientMap();
2488 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
2489 soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
2493 Calculate what block is the crosshair pointing to
2496 //u32 t1 = device->getTimer()->getRealTime();
2498 f32 d = playeritem_def.range; // max. distance
2499 f32 d_hand = itemdef->get("").range;
2500 if(d < 0 && d_hand >= 0)
2504 core::line3d<f32> shootline(camera_position,
2505 camera_position + camera_direction * BS * (d+1));
2507 ClientActiveObject *selected_object = NULL;
2509 PointedThing pointed = getPointedThing(
2511 &client, player_position, camera_direction,
2512 camera_position, shootline, d,
2513 playeritem_def.liquids_pointable, !ldown_for_dig,
2518 if(pointed != pointed_old)
2520 infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2521 //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
2526 - releasing left mouse button
2527 - pointing away from node
2531 if(input->getLeftReleased())
2533 infostream<<"Left button released"
2534 <<" (stopped digging)"<<std::endl;
2537 else if(pointed != pointed_old)
2539 if (pointed.type == POINTEDTHING_NODE
2540 && pointed_old.type == POINTEDTHING_NODE
2541 && pointed.node_undersurface == pointed_old.node_undersurface)
2543 // Still pointing to the same node,
2544 // but a different face. Don't reset.
2548 infostream<<"Pointing away from node"
2549 <<" (stopped digging)"<<std::endl;
2555 client.interact(1, pointed_old);
2556 client.setCrack(-1, v3s16(0,0,0));
2560 if(!digging && ldown_for_dig && !input->getLeftState())
2562 ldown_for_dig = false;
2565 bool left_punch = false;
2566 soundmaker.m_player_leftpunch_sound.name = "";
2568 if(input->getRightState())
2569 repeat_rightclick_timer += dtime;
2571 repeat_rightclick_timer = 0;
2573 if(playeritem_def.usable && input->getLeftState())
2575 if(input->getLeftClicked())
2576 client.interact(4, pointed);
2578 else if(pointed.type == POINTEDTHING_NODE)
2580 v3s16 nodepos = pointed.node_undersurface;
2581 v3s16 neighbourpos = pointed.node_abovesurface;
2584 Check information text of node
2587 ClientMap &map = client.getEnv().getClientMap();
2588 NodeMetadata *meta = map.getNodeMetadata(nodepos);
2590 infotext = narrow_to_wide(meta->getString("infotext"));
2592 MapNode n = map.getNode(nodepos);
2593 if(nodedef->get(n).tiledef[0].name == "unknown_node.png"){
2594 infotext = L"Unknown node: ";
2595 infotext += narrow_to_wide(nodedef->get(n).name);
2603 if(nodig_delay_timer <= 0.0 && input->getLeftState()
2604 && client.checkPrivilege("interact"))
2608 infostream<<"Started digging"<<std::endl;
2609 client.interact(0, pointed);
2611 ldown_for_dig = true;
2613 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2615 // NOTE: Similar piece of code exists on the server side for
2617 // Get digging parameters
2618 DigParams params = getDigParams(nodedef->get(n).groups,
2619 &playeritem_toolcap);
2620 // If can't dig, try hand
2621 if(!params.diggable){
2622 const ItemDefinition &hand = itemdef->get("");
2623 const ToolCapabilities *tp = hand.tool_capabilities;
2625 params = getDigParams(nodedef->get(n).groups, tp);
2628 float dig_time_complete = 0.0;
2630 if(params.diggable == false)
2632 // I guess nobody will wait for this long
2633 dig_time_complete = 10000000.0;
2637 dig_time_complete = params.time;
2638 if (g_settings->getBool("enable_particles"))
2640 const ContentFeatures &features =
2641 client.getNodeDefManager()->get(n);
2642 addPunchingParticles
2643 (gamedef, smgr, player, client.getEnv(),
2644 nodepos, features.tiles);
2648 if(dig_time_complete >= 0.001)
2650 dig_index = (u16)((float)crack_animation_length
2651 * dig_time/dig_time_complete);
2653 // This is for torches
2656 dig_index = crack_animation_length;
2659 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2660 if(sound_dig.exists() && params.diggable){
2661 if(sound_dig.name == "__group"){
2662 if(params.main_group != ""){
2663 soundmaker.m_player_leftpunch_sound.gain = 0.5;
2664 soundmaker.m_player_leftpunch_sound.name =
2665 std::string("default_dig_") +
2669 soundmaker.m_player_leftpunch_sound = sound_dig;
2673 // Don't show cracks if not diggable
2674 if(dig_time_complete >= 100000.0)
2677 else if(dig_index < crack_animation_length)
2679 //TimeTaker timer("client.setTempMod");
2680 //infostream<<"dig_index="<<dig_index<<std::endl;
2681 client.setCrack(dig_index, nodepos);
2685 infostream<<"Digging completed"<<std::endl;
2686 client.interact(2, pointed);
2687 client.setCrack(-1, v3s16(0,0,0));
2688 MapNode wasnode = map.getNode(nodepos);
2689 client.removeNode(nodepos);
2691 if (g_settings->getBool("enable_particles"))
2693 const ContentFeatures &features =
2694 client.getNodeDefManager()->get(wasnode);
2696 (gamedef, smgr, player, client.getEnv(),
2697 nodepos, features.tiles);
2703 nodig_delay_timer = dig_time_complete
2704 / (float)crack_animation_length;
2706 // We don't want a corresponding delay to
2707 // very time consuming nodes
2708 if(nodig_delay_timer > 0.3)
2709 nodig_delay_timer = 0.3;
2710 // We want a slight delay to very little
2711 // time consuming nodes
2712 float mindelay = 0.15;
2713 if(nodig_delay_timer < mindelay)
2714 nodig_delay_timer = mindelay;
2716 // Send event to trigger sound
2717 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
2718 gamedef->event()->put(e);
2721 if(dig_time_complete < 100000.0)
2725 client.setCrack(-1, nodepos);
2728 camera.setDigging(0); // left click animation
2731 if((input->getRightClicked() ||
2732 repeat_rightclick_timer >=
2733 g_settings->getFloat("repeat_rightclick_time")) &&
2734 client.checkPrivilege("interact"))
2736 repeat_rightclick_timer = 0;
2737 infostream<<"Ground right-clicked"<<std::endl;
2739 // Sign special case, at least until formspec is properly implemented.
2741 if(meta && meta->getString("formspec") == "hack:sign_text_input"
2743 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2745 infostream<<"Launching metadata text input"<<std::endl;
2747 // Get a new text for it
2749 TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2751 std::wstring wtext = narrow_to_wide(meta->getString("text"));
2753 (new GUITextInputMenu(guienv, guiroot, -1,
2757 // If metadata provides an inventory view, activate it
2758 else if(meta && meta->getString("formspec") != "" && !random_input
2759 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2761 infostream<<"Launching custom inventory view"<<std::endl;
2763 InventoryLocation inventoryloc;
2764 inventoryloc.setNodeMeta(nodepos);
2768 GUIFormSpecMenu *menu =
2769 new GUIFormSpecMenu(device, guiroot, -1,
2771 &client, gamedef, tsrc);
2772 menu->setFormSpec(meta->getString("formspec"),
2774 menu->setFormSource(new NodeMetadataFormSource(
2775 &client.getEnv().getClientMap(), nodepos));
2776 menu->setTextDest(new TextDestNodeMetadata(nodepos, &client));
2779 // Otherwise report right click to server
2783 client.interact(3, pointed);
2784 camera.setDigging(1); // right click animation
2786 // If the wielded item has node placement prediction,
2788 bool placed = nodePlacementPrediction(client,
2790 nodepos, neighbourpos);
2794 soundmaker.m_player_rightpunch_sound =
2795 playeritem_def.sound_place;
2797 soundmaker.m_player_rightpunch_sound =
2802 else if(pointed.type == POINTEDTHING_OBJECT)
2804 infotext = narrow_to_wide(selected_object->infoText());
2806 if(infotext == L"" && show_debug){
2807 infotext = narrow_to_wide(selected_object->debugInfoText());
2810 //if(input->getLeftClicked())
2811 if(input->getLeftState())
2813 bool do_punch = false;
2814 bool do_punch_damage = false;
2815 if(object_hit_delay_timer <= 0.0){
2817 do_punch_damage = true;
2818 object_hit_delay_timer = object_hit_delay;
2820 if(input->getLeftClicked()){
2824 infostream<<"Left-clicked object"<<std::endl;
2827 if(do_punch_damage){
2828 // Report direct punch
2829 v3f objpos = selected_object->getPosition();
2830 v3f dir = (objpos - player_position).normalize();
2832 bool disable_send = selected_object->directReportPunch(
2833 dir, &playeritem, time_from_last_punch);
2834 time_from_last_punch = 0;
2836 client.interact(0, pointed);
2839 else if(input->getRightClicked())
2841 infostream<<"Right-clicked object"<<std::endl;
2842 client.interact(3, pointed); // place
2845 else if(input->getLeftState())
2847 // When button is held down in air, show continuous animation
2851 pointed_old = pointed;
2853 if(left_punch || input->getLeftClicked())
2855 camera.setDigging(0); // left click animation
2858 input->resetLeftClicked();
2859 input->resetRightClicked();
2861 input->resetLeftReleased();
2862 input->resetRightReleased();
2865 Calculate stuff for drawing
2872 if(draw_control.range_all)
2873 fog_range = 100000*BS;
2875 fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
2877 fog_range *= (1.5 - 1.4*(float)client.getEnv().getClientMap().getHumidity(pos_i)/100);
2878 fog_range = MYMIN(fog_range, (draw_control.farthest_drawn+20)*BS);
2883 Calculate general brightness
2885 u32 daynight_ratio = client.getEnv().getDayNightRatio();
2886 float time_brightness = decode_light_f((float)daynight_ratio/1000.0);
2887 float direct_brightness = 0;
2888 bool sunlight_seen = false;
2889 if(g_settings->getBool("free_move")){
2890 direct_brightness = time_brightness;
2891 sunlight_seen = true;
2893 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
2894 float old_brightness = sky->getBrightness();
2895 direct_brightness = (float)client.getEnv().getClientMap()
2896 .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
2897 daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
2901 time_of_day = client.getEnv().getTimeOfDayF();
2903 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
2904 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
2905 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
2906 time_of_day_smooth = time_of_day;
2908 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
2909 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2910 + (time_of_day+1.0) * todsm;
2912 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2913 + time_of_day * todsm;
2915 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
2918 video::SColor bgcolor = sky->getBgColor();
2919 video::SColor skycolor = sky->getSkyColor();
2925 if(sky->getCloudsVisible()){
2926 clouds->setVisible(true);
2927 clouds->step(dtime);
2928 clouds->update(v2f(player_position.X, player_position.Z),
2929 sky->getCloudColor());
2931 clouds->setVisible(false);
2939 allparticles_step(dtime, client.getEnv());
2940 allparticlespawners_step(dtime, client.getEnv());
2946 if(g_settings->getBool("enable_fog") && !force_fog_off)
2950 video::EFT_FOG_LINEAR,
2962 video::EFT_FOG_LINEAR,
2972 Update gui stuff (0ms)
2975 //TimeTaker guiupdatetimer("Gui updating");
2979 static float drawtime_avg = 0;
2980 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2981 /*static float beginscenetime_avg = 0;
2982 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2983 static float scenetime_avg = 0;
2984 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2985 static float endscenetime_avg = 0;
2986 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
2988 std::ostringstream os(std::ios_base::binary);
2990 <<"Minetest "<<minetest_version_hash
2991 <<" (R: range_all="<<draw_control.range_all<<")"
2992 <<std::setprecision(0)
2993 <<" drawtime = "<<drawtime_avg
2994 <<std::setprecision(1)
2995 <<", dtime_jitter = "
2996 <<(dtime_jitter1_max_fraction * 100.0)<<" %"
2997 <<std::setprecision(1)
2998 <<", v_range = "<<draw_control.wanted_range
2999 <<std::setprecision(3)
3000 <<", RTT = "<<client.getRTT();
3001 guitext->setText(narrow_to_wide(os.str()).c_str());
3002 guitext->setVisible(true);
3004 else if(show_hud || show_chat)
3006 std::ostringstream os(std::ios_base::binary);
3007 os<<"Minetest "<<minetest_version_hash;
3008 guitext->setText(narrow_to_wide(os.str()).c_str());
3009 guitext->setVisible(true);
3013 guitext->setVisible(false);
3018 std::ostringstream os(std::ios_base::binary);
3019 os<<std::setprecision(1)<<std::fixed
3020 <<"(" <<(player_position.X/BS)
3021 <<", "<<(player_position.Y/BS)
3022 <<", "<<(player_position.Z/BS)
3023 <<") (yaw="<<(wrapDegrees_0_360(camera_yaw))
3024 <<") (t="<<client.getEnv().getClientMap().getHeat(pos_i)
3025 <<"C, h="<<client.getEnv().getClientMap().getHumidity(pos_i)
3026 <<"%) (seed = "<<((unsigned long long)client.getMapSeed())
3028 guitext2->setText(narrow_to_wide(os.str()).c_str());
3029 guitext2->setVisible(true);
3033 guitext2->setVisible(false);
3037 guitext_info->setText(infotext.c_str());
3038 guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
3042 float statustext_time_max = 1.5;
3043 if(!statustext.empty())
3045 statustext_time += dtime;
3046 if(statustext_time >= statustext_time_max)
3049 statustext_time = 0;
3052 guitext_status->setText(statustext.c_str());
3053 guitext_status->setVisible(!statustext.empty());
3055 if(!statustext.empty())
3057 s32 status_y = screensize.Y - 130;
3058 core::rect<s32> rect(
3060 status_y - guitext_status->getTextHeight(),
3064 guitext_status->setRelativePosition(rect);
3067 video::SColor initial_color(255,0,0,0);
3068 if(guienv->getSkin())
3069 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
3070 video::SColor final_color = initial_color;
3071 final_color.setAlpha(0);
3072 video::SColor fade_color =
3073 initial_color.getInterpolated_quadratic(
3076 pow(statustext_time / (float)statustext_time_max, 2.0f));
3077 guitext_status->setOverrideColor(fade_color);
3078 guitext_status->enableOverrideColor(true);
3083 Get chat messages from client
3086 // Get new messages from error log buffer
3087 while(!chat_log_error_buf.empty())
3089 chat_backend.addMessage(L"", narrow_to_wide(
3090 chat_log_error_buf.get()));
3092 // Get new messages from client
3093 std::wstring message;
3094 while(client.getChatMessage(message))
3096 chat_backend.addUnparsedMessage(message);
3098 // Remove old messages
3099 chat_backend.step(dtime);
3101 // Display all messages in a static text element
3102 u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
3103 std::wstring recent_chat = chat_backend.getRecentChat();
3104 guitext_chat->setText(recent_chat.c_str());
3106 // Update gui element size and position
3107 s32 chat_y = 5+(text_height+5);
3109 chat_y += (text_height+5);
3110 core::rect<s32> rect(
3114 chat_y + guitext_chat->getTextHeight()
3116 guitext_chat->setRelativePosition(rect);
3118 // Don't show chat if disabled or empty or profiler is enabled
3119 guitext_chat->setVisible(show_chat && recent_chat_count != 0
3127 if(client.getPlayerItem() != new_playeritem)
3129 client.selectPlayerItem(new_playeritem);
3131 if(client.getLocalInventoryUpdated())
3133 //infostream<<"Updating local inventory"<<std::endl;
3134 client.getLocalInventory(local_inventory);
3136 update_wielded_item_trigger = true;
3138 if(update_wielded_item_trigger)
3140 update_wielded_item_trigger = false;
3141 // Update wielded tool
3142 InventoryList *mlist = local_inventory.getList("main");
3145 item = mlist->getItem(client.getPlayerItem());
3146 camera.wield(item, client.getPlayerItem());
3150 Update block draw list every 200ms or when camera direction has
3153 update_draw_list_timer += dtime;
3154 if(update_draw_list_timer >= 0.2 ||
3155 update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2){
3156 update_draw_list_timer = 0;
3157 client.getEnv().getClientMap().updateDrawList(driver);
3158 update_draw_list_last_cam_dir = camera_direction;
3165 TimeTaker tt_draw("mainloop: draw");
3168 TimeTaker timer("beginScene");
3169 //driver->beginScene(false, true, bgcolor);
3170 //driver->beginScene(true, true, bgcolor);
3171 driver->beginScene(true, true, skycolor);
3172 beginscenetime = timer.stop(true);
3177 //infostream<<"smgr->drawAll()"<<std::endl;
3179 TimeTaker timer("smgr");
3182 if(g_settings->getBool("anaglyph"))
3184 irr::core::vector3df oldPosition = camera.getCameraNode()->getPosition();
3185 irr::core::vector3df oldTarget = camera.getCameraNode()->getTarget();
3187 irr::core::matrix4 startMatrix = camera.getCameraNode()->getAbsoluteTransformation();
3189 irr::core::vector3df focusPoint = (camera.getCameraNode()->getTarget() -
3190 camera.getCameraNode()->getAbsolutePosition()).setLength(1) +
3191 camera.getCameraNode()->getAbsolutePosition() ;
3194 irr::core::vector3df leftEye;
3195 irr::core::matrix4 leftMove;
3197 leftMove.setTranslation( irr::core::vector3df(-g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
3198 leftEye=(startMatrix*leftMove).getTranslation();
3200 //clear the depth buffer, and color
3201 driver->beginScene( true, true, irr::video::SColor(0,200,200,255) );
3203 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_RED;
3204 driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK;
3205 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
3206 irr::scene::ESNRP_SOLID +
3207 irr::scene::ESNRP_TRANSPARENT +
3208 irr::scene::ESNRP_TRANSPARENT_EFFECT +
3209 irr::scene::ESNRP_SHADOW;
3211 camera.getCameraNode()->setPosition( leftEye );
3212 camera.getCameraNode()->setTarget( focusPoint );
3214 smgr->drawAll(); // 'smgr->drawAll();' may go here
3216 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
3219 hud.drawSelectionBoxes(hilightboxes);
3223 irr::core::vector3df rightEye;
3224 irr::core::matrix4 rightMove;
3226 rightMove.setTranslation( irr::core::vector3df(g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
3227 rightEye=(startMatrix*rightMove).getTranslation();
3229 //clear the depth buffer
3230 driver->clearZBuffer();
3232 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_GREEN + irr::video::ECP_BLUE;
3233 driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK;
3234 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
3235 irr::scene::ESNRP_SOLID +
3236 irr::scene::ESNRP_TRANSPARENT +
3237 irr::scene::ESNRP_TRANSPARENT_EFFECT +
3238 irr::scene::ESNRP_SHADOW;
3240 camera.getCameraNode()->setPosition( rightEye );
3241 camera.getCameraNode()->setTarget( focusPoint );
3243 smgr->drawAll(); // 'smgr->drawAll();' may go here
3245 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
3248 hud.drawSelectionBoxes(hilightboxes);
3251 //driver->endScene();
3253 driver->getOverrideMaterial().Material.ColorMask=irr::video::ECP_ALL;
3254 driver->getOverrideMaterial().EnableFlags=0;
3255 driver->getOverrideMaterial().EnablePasses=0;
3257 camera.getCameraNode()->setPosition( oldPosition );
3258 camera.getCameraNode()->setTarget( oldTarget );
3261 scenetime = timer.stop(true);
3265 //TimeTaker timer9("auxiliary drawings");
3269 //TimeTaker //timer10("//timer10");
3275 driver->setMaterial(m);
3277 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
3278 if((!g_settings->getBool("anaglyph")) && (show_hud))
3280 hud.drawSelectionBoxes(hilightboxes);
3286 if(show_hud && (player->hud_flags & HUD_FLAG_WIELDITEM_VISIBLE))
3288 // Warning: This clears the Z buffer.
3289 camera.drawWieldedTool();
3296 client.getEnv().getClientMap().renderPostFx();
3302 if(show_profiler_graph)
3304 graph.draw(10, screensize.Y - 10, driver, font);
3311 hud.drawCrosshair();
3316 //TimeTaker //timer11("//timer11");
3324 hud.drawHotbar(v2s32(displaycenter.X, screensize.Y),
3325 client.getHP(), client.getPlayerItem(), client.getBreath());
3331 if(damage_flash > 0.0)
3333 video::SColor color(std::min(damage_flash, 180.0f),180,0,0);
3334 driver->draw2DRectangle(color,
3335 core::rect<s32>(0,0,screensize.X,screensize.Y),
3338 damage_flash -= 100.0*dtime;
3344 if(player->hurt_tilt_timer > 0.0)
3346 player->hurt_tilt_timer -= dtime*5;
3347 if(player->hurt_tilt_timer < 0)
3348 player->hurt_tilt_strength = 0;
3355 hud.drawLuaElements();
3367 TimeTaker timer("endScene");
3369 endscenetime = timer.stop(true);
3372 drawtime = tt_draw.stop(true);
3373 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
3379 static s16 lastFPS = 0;
3380 //u16 fps = driver->getFPS();
3381 u16 fps = (1.0/dtime_avg1);
3385 core::stringw str = L"Minetest [";
3386 str += driver->getName();
3390 device->setWindowCaption(str.c_str());
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)
3443 error_message = narrow_to_wide(e.what());
3444 errorstream<<wide_to_narrow(error_message)<<std::endl;
3448 errorstream<<e.what()<<std::endl;
3449 error_message = narrow_to_wide(e.what()) + wgettext("\nCheck debug.txt for details.");
3457 //has to be deleted first to stop all server threads
3465 //extended resource accounting
3466 infostream << "Irrlicht resources after cleanup:" << std::endl;
3467 infostream << "\tRemaining meshes : "
3468 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
3469 infostream << "\tRemaining textures : "
3470 << driver->getTextureCount() << std::endl;
3471 for (unsigned int i = 0; i < driver->getTextureCount(); i++ ) {
3472 irr::video::ITexture* texture = driver->getTextureByIndex(i);
3473 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
3476 clearTextureNameCache();
3477 infostream << "\tRemaining materials: "
3478 << driver-> getMaterialRendererCount ()
3479 << " (note: irrlicht doesn't support removing renderers)"<< std::endl;