3 Copyright (C) 2010-2011 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>
30 #include "guiPauseMenu.h"
31 #include "guiPasswordChange.h"
32 #include "guiFormSpecMenu.h"
33 #include "guiTextInputMenu.h"
34 #include "guiDeathScreen.h"
36 #include "guiChatConsole.h"
39 #include "particles.h"
45 #include "mainmenumanager.h"
49 // Needed for determining pointing to nodes
51 #include "nodemetadata.h"
52 #include "main.h" // For g_settings
54 #include "tile.h" // For TextureSource
55 #include "shader.h" // For ShaderSource
56 #include "logoutputbuffer.h"
58 #include "quicktune_shortcutter.h"
59 #include "clientmap.h"
63 #include "sound_openal.h"
65 #include "event_manager.h"
67 #include "util/directiontables.h"
73 struct TextDestChat : public TextDest
75 TextDestChat(Client *client)
79 void gotText(std::wstring text)
81 m_client->typeChatMessage(text);
83 void gotText(std::map<std::string, std::string> fields)
85 m_client->typeChatMessage(narrow_to_wide(fields["text"]));
91 struct TextDestNodeMetadata : public TextDest
93 TextDestNodeMetadata(v3s16 p, Client *client)
98 // This is deprecated I guess? -celeron55
99 void gotText(std::wstring text)
101 std::string ntext = wide_to_narrow(text);
102 infostream<<"Submitting 'text' field of node at ("<<m_p.X<<","
103 <<m_p.Y<<","<<m_p.Z<<"): "<<ntext<<std::endl;
104 std::map<std::string, std::string> fields;
105 fields["text"] = ntext;
106 m_client->sendNodemetaFields(m_p, "", fields);
108 void gotText(std::map<std::string, std::string> fields)
110 m_client->sendNodemetaFields(m_p, "", fields);
117 struct TextDestPlayerInventory : public TextDest
119 TextDestPlayerInventory(Client *client)
124 TextDestPlayerInventory(Client *client, std::string formname)
127 m_formname = formname;
129 void gotText(std::map<std::string, std::string> fields)
131 m_client->sendInventoryFields(m_formname, fields);
135 std::string m_formname;
138 /* Respawn menu callback */
140 class MainRespawnInitiator: public IRespawnInitiator
143 MainRespawnInitiator(bool *active, Client *client):
144 m_active(active), m_client(client)
151 m_client->sendRespawn();
158 /* Form update callback */
160 class NodeMetadataFormSource: public IFormSource
163 NodeMetadataFormSource(ClientMap *map, v3s16 p):
168 std::string getForm()
170 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
173 return meta->getString("formspec");
175 std::string resolveText(std::string str)
177 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
180 return meta->resolveString(str);
187 class PlayerInventoryFormSource: public IFormSource
190 PlayerInventoryFormSource(Client *client):
194 std::string getForm()
196 LocalPlayer* player = m_client->getEnv().getLocalPlayer();
197 return player->inventory_formspec;
203 class FormspecFormSource: public IFormSource
206 FormspecFormSource(std::string formspec,FormspecFormSource** game_formspec)
208 m_formspec = formspec;
209 m_game_formspec = game_formspec;
212 ~FormspecFormSource()
214 *m_game_formspec = 0;
217 void setForm(std::string formspec) {
218 m_formspec = formspec;
221 std::string getForm()
226 std::string m_formspec;
227 FormspecFormSource** m_game_formspec;
232 void draw_hotbar(video::IVideoDriver *driver, gui::IGUIFont *font,
234 v2s32 centerlowerpos, s32 imgsize, s32 itemcount,
235 Inventory *inventory, s32 halfheartcount, u16 playeritem)
237 InventoryList *mainlist = inventory->getList("main");
240 errorstream<<"draw_hotbar(): mainlist == NULL"<<std::endl;
244 s32 padding = imgsize/12;
245 //s32 height = imgsize + padding*2;
246 s32 width = itemcount*(imgsize+padding*2);
248 // Position of upper left corner of bar
249 v2s32 pos = centerlowerpos - v2s32(width/2, imgsize+padding*2);
251 // Draw background color
252 /*core::rect<s32> barrect(0,0,width,height);
254 video::SColor bgcolor(255,128,128,128);
255 driver->draw2DRectangle(bgcolor, barrect, NULL);*/
257 core::rect<s32> imgrect(0,0,imgsize,imgsize);
259 for(s32 i=0; i<itemcount; i++)
261 const ItemStack &item = mainlist->getItem(i);
263 core::rect<s32> rect = imgrect + pos
264 + v2s32(padding+i*(imgsize+padding*2), padding);
268 video::SColor c_outside(255,255,0,0);
269 //video::SColor c_outside(255,0,0,0);
270 //video::SColor c_inside(255,192,192,192);
271 s32 x1 = rect.UpperLeftCorner.X;
272 s32 y1 = rect.UpperLeftCorner.Y;
273 s32 x2 = rect.LowerRightCorner.X;
274 s32 y2 = rect.LowerRightCorner.Y;
275 // Black base borders
276 driver->draw2DRectangle(c_outside,
278 v2s32(x1 - padding, y1 - padding),
279 v2s32(x2 + padding, y1)
281 driver->draw2DRectangle(c_outside,
283 v2s32(x1 - padding, y2),
284 v2s32(x2 + padding, y2 + padding)
286 driver->draw2DRectangle(c_outside,
288 v2s32(x1 - padding, y1),
291 driver->draw2DRectangle(c_outside,
294 v2s32(x2 + padding, y2)
296 /*// Light inside borders
297 driver->draw2DRectangle(c_inside,
299 v2s32(x1 - padding/2, y1 - padding/2),
300 v2s32(x2 + padding/2, y1)
302 driver->draw2DRectangle(c_inside,
304 v2s32(x1 - padding/2, y2),
305 v2s32(x2 + padding/2, y2 + padding/2)
307 driver->draw2DRectangle(c_inside,
309 v2s32(x1 - padding/2, y1),
312 driver->draw2DRectangle(c_inside,
315 v2s32(x2 + padding/2, y2)
320 video::SColor bgcolor2(128,0,0,0);
321 driver->draw2DRectangle(bgcolor2, rect, NULL);
322 drawItemStack(driver, font, item, rect, NULL, gamedef);
328 video::ITexture *heart_texture =
329 gamedef->getTextureSource()->getTextureRaw("heart.png");
332 v2s32 p = pos + v2s32(0, -20);
333 for(s32 i=0; i<halfheartcount/2; i++)
335 const video::SColor color(255,255,255,255);
336 const video::SColor colors[] = {color,color,color,color};
337 core::rect<s32> rect(0,0,16,16);
339 driver->draw2DImage(heart_texture, rect,
340 core::rect<s32>(core::position2d<s32>(0,0),
341 core::dimension2di(heart_texture->getOriginalSize())),
345 if(halfheartcount % 2 == 1)
347 const video::SColor color(255,255,255,255);
348 const video::SColor colors[] = {color,color,color,color};
349 core::rect<s32> rect(0,0,16/2,16);
351 core::dimension2di srcd(heart_texture->getOriginalSize());
353 driver->draw2DImage(heart_texture, rect,
354 core::rect<s32>(core::position2d<s32>(0,0), srcd),
362 Check if a node is pointable
364 inline bool isPointableNode(const MapNode& n,
365 Client *client, bool liquids_pointable)
367 const ContentFeatures &features = client->getNodeDefManager()->get(n);
368 return features.pointable ||
369 (liquids_pointable && features.isLiquid());
373 Find what the player is pointing at
375 PointedThing getPointedThing(Client *client, v3f player_position,
376 v3f camera_direction, v3f camera_position,
377 core::line3d<f32> shootline, f32 d,
378 bool liquids_pointable,
379 bool look_for_object,
380 std::vector<aabb3f> &hilightboxes,
381 ClientActiveObject *&selected_object)
385 hilightboxes.clear();
386 selected_object = NULL;
388 INodeDefManager *nodedef = client->getNodeDefManager();
389 ClientMap &map = client->getEnv().getClientMap();
391 // First try to find a pointed at active object
394 selected_object = client->getSelectedActiveObject(d*BS,
395 camera_position, shootline);
397 if(selected_object != NULL)
399 if(selected_object->doShowSelectionBox())
401 aabb3f *selection_box = selected_object->getSelectionBox();
402 // Box should exist because object was
403 // returned in the first place
404 assert(selection_box);
406 v3f pos = selected_object->getPosition();
407 hilightboxes.push_back(aabb3f(
408 selection_box->MinEdge + pos,
409 selection_box->MaxEdge + pos));
413 result.type = POINTEDTHING_OBJECT;
414 result.object_id = selected_object->getId();
419 // That didn't work, try to find a pointed at node
421 f32 mindistance = BS * 1001;
423 v3s16 pos_i = floatToInt(player_position, BS);
425 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
429 s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
430 s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
431 s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
432 s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
433 s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
434 s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
436 // Prevent signed number overflow
444 for(s16 y = ystart; y <= yend; y++)
445 for(s16 z = zstart; z <= zend; z++)
446 for(s16 x = xstart; x <= xend; x++)
451 n = map.getNode(v3s16(x,y,z));
453 catch(InvalidPositionException &e)
457 if(!isPointableNode(n, client, liquids_pointable))
460 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
463 v3f npf = intToFloat(np, BS);
465 for(std::vector<aabb3f>::const_iterator
467 i != boxes.end(); i++)
473 for(u16 j=0; j<6; j++)
475 v3s16 facedir = g_6dirs[j];
476 aabb3f facebox = box;
480 facebox.MinEdge.X = facebox.MaxEdge.X-d;
481 else if(facedir.X < 0)
482 facebox.MaxEdge.X = facebox.MinEdge.X+d;
483 else if(facedir.Y > 0)
484 facebox.MinEdge.Y = facebox.MaxEdge.Y-d;
485 else if(facedir.Y < 0)
486 facebox.MaxEdge.Y = facebox.MinEdge.Y+d;
487 else if(facedir.Z > 0)
488 facebox.MinEdge.Z = facebox.MaxEdge.Z-d;
489 else if(facedir.Z < 0)
490 facebox.MaxEdge.Z = facebox.MinEdge.Z+d;
492 v3f centerpoint = facebox.getCenter();
493 f32 distance = (centerpoint - camera_position).getLength();
494 if(distance >= mindistance)
496 if(!facebox.intersectsWithLine(shootline))
499 v3s16 np_above = np + facedir;
501 result.type = POINTEDTHING_NODE;
502 result.node_undersurface = np;
503 result.node_abovesurface = np_above;
504 mindistance = distance;
506 hilightboxes.clear();
507 for(std::vector<aabb3f>::const_iterator
509 i2 != boxes.end(); i2++)
512 box.MinEdge += npf + v3f(-d,-d,-d);
513 box.MaxEdge += npf + v3f(d,d,d);
514 hilightboxes.push_back(box);
524 Draws a screen with a single text on it.
525 Text will be removed when the screen is drawn the next time.
527 /*gui::IGUIStaticText **/
528 void draw_load_screen(const std::wstring &text,
529 video::IVideoDriver* driver, gui::IGUIFont* font)
531 v2u32 screensize = driver->getScreenSize();
532 const wchar_t *loadingtext = text.c_str();
533 core::vector2d<u32> textsize_u = font->getDimension(loadingtext);
534 core::vector2d<s32> textsize(textsize_u.X,textsize_u.Y);
535 core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
536 core::rect<s32> textrect(center - textsize/2, center + textsize/2);
538 gui::IGUIStaticText *guitext = guienv->addStaticText(
539 loadingtext, textrect, false, false);
540 guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
542 driver->beginScene(true, true, video::SColor(255,0,0,0));
551 /* Profiler display */
553 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler,
554 gui::IGUIFont *font, u32 text_height,
555 u32 show_profiler, u32 show_profiler_max)
557 if(show_profiler == 0)
559 guitext_profiler->setVisible(false);
564 std::ostringstream os(std::ios_base::binary);
565 g_profiler->printPage(os, show_profiler, show_profiler_max);
566 std::wstring text = narrow_to_wide(os.str());
567 guitext_profiler->setText(text.c_str());
568 guitext_profiler->setVisible(true);
570 s32 w = font->getDimension(text.c_str()).Width;
573 core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
574 8+(text_height+5)*2 +
575 font->getDimension(text.c_str()).Height);
576 guitext_profiler->setRelativePosition(rect);
577 guitext_profiler->setVisible(true);
585 Profiler::GraphValues values;
591 Meta(float initial=0, video::SColor color=
592 video::SColor(255,255,255,255)):
598 std::list<Piece> m_log;
606 void put(const Profiler::GraphValues &values)
609 piece.values = values;
610 m_log.push_back(piece);
611 while(m_log.size() > m_log_max_size)
612 m_log.erase(m_log.begin());
615 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
616 gui::IGUIFont* font) const
618 std::map<std::string, Meta> m_meta;
619 for(std::list<Piece>::const_iterator k = m_log.begin();
620 k != m_log.end(); k++)
622 const Piece &piece = *k;
623 for(Profiler::GraphValues::const_iterator i = piece.values.begin();
624 i != piece.values.end(); i++){
625 const std::string &id = i->first;
626 const float &value = i->second;
627 std::map<std::string, Meta>::iterator j =
629 if(j == m_meta.end()){
630 m_meta[id] = Meta(value);
633 if(value < j->second.min)
634 j->second.min = value;
635 if(value > j->second.max)
636 j->second.max = value;
641 static const video::SColor usable_colors[] = {
642 video::SColor(255,255,100,100),
643 video::SColor(255,90,225,90),
644 video::SColor(255,100,100,255),
645 video::SColor(255,255,150,50),
646 video::SColor(255,220,220,100)
648 static const u32 usable_colors_count =
649 sizeof(usable_colors) / sizeof(*usable_colors);
650 u32 next_color_i = 0;
651 for(std::map<std::string, Meta>::iterator i = m_meta.begin();
652 i != m_meta.end(); i++){
653 Meta &meta = i->second;
654 video::SColor color(255,200,200,200);
655 if(next_color_i < usable_colors_count)
656 color = usable_colors[next_color_i++];
661 s32 textx = x_left + m_log_max_size + 15;
662 s32 textx2 = textx + 200 - 15;
666 u32 num_graphs = m_meta.size();
667 core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
669 video::SColor bgcolor(120,0,0,0);
670 driver->draw2DRectangle(bgcolor, rect, NULL);
674 for(std::map<std::string, Meta>::const_iterator i = m_meta.begin();
675 i != m_meta.end(); i++){
676 const std::string &id = i->first;
677 const Meta &meta = i->second;
679 s32 y = y_bottom - meta_i * 50;
680 float show_min = meta.min;
681 float show_max = meta.max;
682 if(show_min >= -0.0001 && show_max >= -0.0001){
683 if(show_min <= show_max * 0.5)
688 snprintf(buf, 10, "%.3g", show_max);
689 font->draw(narrow_to_wide(buf).c_str(),
690 core::rect<s32>(textx, y - graphh,
691 textx2, y - graphh + texth),
693 snprintf(buf, 10, "%.3g", show_min);
694 font->draw(narrow_to_wide(buf).c_str(),
695 core::rect<s32>(textx, y - texth,
698 font->draw(narrow_to_wide(id).c_str(),
699 core::rect<s32>(textx, y - graphh/2 - texth/2,
700 textx2, y - graphh/2 + texth/2),
703 s32 graph1h = graphh;
704 bool relativegraph = (show_min != 0 && show_min != show_max);
705 float lastscaledvalue = 0.0;
706 bool lastscaledvalue_exists = false;
707 for(std::list<Piece>::const_iterator j = m_log.begin();
708 j != m_log.end(); j++)
710 const Piece &piece = *j;
712 bool value_exists = false;
713 Profiler::GraphValues::const_iterator k =
714 piece.values.find(id);
715 if(k != piece.values.end()){
721 lastscaledvalue_exists = false;
724 float scaledvalue = 1.0;
725 if(show_max != show_min)
726 scaledvalue = (value - show_min) / (show_max - show_min);
727 if(scaledvalue == 1.0 && value == 0){
729 lastscaledvalue_exists = false;
733 if(lastscaledvalue_exists){
734 s32 ivalue1 = lastscaledvalue * graph1h;
735 s32 ivalue2 = scaledvalue * graph1h;
736 driver->draw2DLine(v2s32(x-1, graph1y - ivalue1),
737 v2s32(x, graph1y - ivalue2), meta.color);
739 lastscaledvalue = scaledvalue;
740 lastscaledvalue_exists = true;
742 s32 ivalue = scaledvalue * graph1h;
743 driver->draw2DLine(v2s32(x, graph1y),
744 v2s32(x, graph1y - ivalue), meta.color);
753 class NodeDugEvent: public MtEvent
759 NodeDugEvent(v3s16 p, MapNode n):
763 const char* getType() const
769 ISoundManager *m_sound;
770 INodeDefManager *m_ndef;
772 float m_player_step_timer;
774 SimpleSoundSpec m_player_step_sound;
775 SimpleSoundSpec m_player_leftpunch_sound;
776 SimpleSoundSpec m_player_rightpunch_sound;
778 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
781 m_player_step_timer(0)
785 void playPlayerStep()
787 if(m_player_step_timer <= 0 && m_player_step_sound.exists()){
788 m_player_step_timer = 0.03;
789 m_sound->playSound(m_player_step_sound, false);
793 static void viewBobbingStep(MtEvent *e, void *data)
795 SoundMaker *sm = (SoundMaker*)data;
796 sm->playPlayerStep();
799 static void playerRegainGround(MtEvent *e, void *data)
801 SoundMaker *sm = (SoundMaker*)data;
802 sm->playPlayerStep();
805 static void playerJump(MtEvent *e, void *data)
807 //SoundMaker *sm = (SoundMaker*)data;
810 static void cameraPunchLeft(MtEvent *e, void *data)
812 SoundMaker *sm = (SoundMaker*)data;
813 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
816 static void cameraPunchRight(MtEvent *e, void *data)
818 SoundMaker *sm = (SoundMaker*)data;
819 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
822 static void nodeDug(MtEvent *e, void *data)
824 SoundMaker *sm = (SoundMaker*)data;
825 NodeDugEvent *nde = (NodeDugEvent*)e;
826 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
829 void registerReceiver(MtEventManager *mgr)
831 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
832 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
833 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
834 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
835 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
836 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
839 void step(float dtime)
841 m_player_step_timer -= dtime;
845 // Locally stored sounds don't need to be preloaded because of this
846 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
848 std::set<std::string> m_fetched;
851 void fetchSounds(const std::string &name,
852 std::set<std::string> &dst_paths,
853 std::set<std::string> &dst_datas)
855 if(m_fetched.count(name))
857 m_fetched.insert(name);
858 std::string base = porting::path_share + DIR_DELIM + "testsounds";
859 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
860 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
861 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
862 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
863 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
864 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
865 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
866 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
867 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
868 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
869 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
873 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
876 bool *m_force_fog_off;
881 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
882 f32 *fog_range, Client *client):
884 m_force_fog_off(force_fog_off),
885 m_fog_range(fog_range),
888 ~GameGlobalShaderConstantSetter() {}
890 virtual void onSetConstants(video::IMaterialRendererServices *services,
897 video::SColor bgcolor = m_sky->getBgColor();
898 video::SColorf bgcolorf(bgcolor);
899 float bgcolorfa[4] = {
905 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
908 float fog_distance = *m_fog_range;
910 fog_distance = 10000*BS;
911 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
914 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
915 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
916 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
924 IrrlichtDevice *device,
927 std::string playername,
928 std::string password,
929 std::string address, // If "", local server is used
931 std::wstring &error_message,
932 std::string configpath,
933 ChatBackend &chat_backend,
934 const SubgameSpec &gamespec, // Used for local game,
935 bool simple_singleplayer_mode
938 FormspecFormSource* current_formspec = 0;
939 video::IVideoDriver* driver = device->getVideoDriver();
940 scene::ISceneManager* smgr = device->getSceneManager();
942 // Calculate text height using the font
943 u32 text_height = font->getDimension(L"Random test string").Height;
945 v2u32 screensize(0,0);
946 v2u32 last_screensize(0,0);
947 screensize = driver->getScreenSize();
949 const s32 hotbar_itemcount = 8;
950 //const s32 hotbar_imagesize = 36;
951 //const s32 hotbar_imagesize = 64;
952 s32 hotbar_imagesize = 48;
955 Draw "Loading" screen
958 draw_load_screen(L"Loading...", driver, font);
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;
995 EventManager eventmgr;
998 SoundMaker soundmaker(sound, nodedef);
999 soundmaker.registerReceiver(&eventmgr);
1001 // Add chat log output for errors to be shown in chat
1002 LogOutputBuffer chat_log_error_buf(LMT_ERROR);
1004 // Create UI for modifying quicktune values
1005 QuicktuneShortcutter quicktune;
1009 SharedPtr will delete it when it goes out of scope.
1011 SharedPtr<Server> server;
1013 draw_load_screen(L"Creating server...", driver, font);
1014 infostream<<"Creating server"<<std::endl;
1015 server = new Server(map_dir, configpath, gamespec,
1016 simple_singleplayer_mode);
1017 server->start(port);
1021 do{ // Client scope (breakable do-while(0))
1027 draw_load_screen(L"Creating client...", driver, font);
1028 infostream<<"Creating client"<<std::endl;
1030 MapDrawControl draw_control;
1032 Client client(device, playername.c_str(), password, draw_control,
1033 tsrc, shsrc, itemdef, nodedef, sound, &eventmgr);
1035 // Client acts as our GameDef
1036 IGameDef *gamedef = &client;
1038 draw_load_screen(L"Resolving address...", driver, font);
1039 Address connect_address(0,0,0,0, port);
1042 //connect_address.Resolve("localhost");
1043 connect_address.setAddress(127,0,0,1);
1045 connect_address.Resolve(address.c_str());
1047 catch(ResolveError &e)
1049 error_message = L"Couldn't resolve address";
1050 errorstream<<wide_to_narrow(error_message)<<std::endl;
1051 // Break out of client scope
1056 Attempt to connect to the server
1059 infostream<<"Connecting to server at ";
1060 connect_address.print(&infostream);
1061 infostream<<std::endl;
1062 client.connect(connect_address);
1065 Wait for server to accept connection
1067 bool could_connect = false;
1068 bool connect_aborted = false;
1070 float frametime = 0.033;
1071 float time_counter = 0.0;
1073 while(device->run())
1075 // Update client and server
1076 client.step(frametime);
1078 server->step(frametime);
1081 if(client.connectedAndInitialized()){
1082 could_connect = true;
1086 if(client.accessDenied()){
1087 error_message = L"Access denied. Reason: "
1088 +client.accessDeniedReason();
1089 errorstream<<wide_to_narrow(error_message)<<std::endl;
1092 if(input->wasKeyDown(EscapeKey)){
1093 connect_aborted = true;
1094 infostream<<"Connect aborted [Escape]"<<std::endl;
1099 std::wostringstream ss;
1100 ss<<L"Connecting to server... (press Escape to cancel)\n";
1101 std::wstring animation = L"/-\\|";
1102 ss<<animation[(int)(time_counter/0.2)%4];
1103 draw_load_screen(ss.str(), driver, font);
1106 sleep_ms(1000*frametime);
1107 time_counter += frametime;
1110 catch(con::PeerNotFoundException &e)
1114 Handle failure to connect
1117 if(error_message == L"" && !connect_aborted){
1118 error_message = L"Connection failed";
1119 errorstream<<wide_to_narrow(error_message)<<std::endl;
1121 // Break out of client scope
1126 Wait until content has been received
1128 bool got_content = false;
1129 bool content_aborted = false;
1131 float frametime = 0.033;
1132 float time_counter = 0.0;
1134 while(device->run())
1136 // Update client and server
1137 client.step(frametime);
1139 server->step(frametime);
1142 if(client.texturesReceived() &&
1143 client.itemdefReceived() &&
1144 client.nodedefReceived()){
1149 if(!client.connectedAndInitialized()){
1150 error_message = L"Client disconnected";
1151 errorstream<<wide_to_narrow(error_message)<<std::endl;
1154 if(input->wasKeyDown(EscapeKey)){
1155 content_aborted = true;
1156 infostream<<"Connect aborted [Escape]"<<std::endl;
1161 std::wostringstream ss;
1162 ss<<L"Waiting content... (press Escape to cancel)\n";
1164 ss<<(client.itemdefReceived()?L"[X]":L"[ ]");
1165 ss<<L" Item definitions\n";
1166 ss<<(client.nodedefReceived()?L"[X]":L"[ ]");
1167 ss<<L" Node definitions\n";
1168 ss<<L"["<<(int)(client.mediaReceiveProgress()*100+0.5)<<L"%] ";
1171 draw_load_screen(ss.str(), driver, font);
1174 sleep_ms(1000*frametime);
1175 time_counter += frametime;
1180 if(error_message == L"" && !content_aborted){
1181 error_message = L"Something failed";
1182 errorstream<<wide_to_narrow(error_message)<<std::endl;
1184 // Break out of client scope
1189 After all content has been received:
1190 Update cached textures, meshes and materials
1192 client.afterContentReceived();
1195 Create the camera node
1197 Camera camera(smgr, draw_control, gamedef);
1198 if (!camera.successfullyCreated(error_message))
1201 f32 camera_yaw = 0; // "right/left"
1202 f32 camera_pitch = 0; // "up/down"
1208 Clouds *clouds = NULL;
1209 if(g_settings->getBool("enable_clouds"))
1211 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1219 sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1225 FarMesh *farmesh = NULL;
1226 if(g_settings->getBool("enable_farmesh"))
1228 farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
1232 A copy of the local inventory
1234 Inventory local_inventory(itemdef);
1237 Find out size of crack animation
1239 int crack_animation_length = 5;
1241 video::ITexture *t = tsrc->getTextureRaw("crack_anylength.png");
1242 v2u32 size = t->getOriginalSize();
1243 crack_animation_length = size.Y / size.X;
1250 // First line of debug text
1251 gui::IGUIStaticText *guitext = guienv->addStaticText(
1253 core::rect<s32>(5, 5, 795, 5+text_height),
1255 // Second line of debug text
1256 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1258 core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
1260 // At the middle of the screen
1261 // Object infos are shown in this
1262 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1264 core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1267 // Status text (displays info when showing and hiding GUI stuff, etc.)
1268 gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1270 core::rect<s32>(0,0,0,0),
1272 guitext_status->setVisible(false);
1274 std::wstring statustext;
1275 float statustext_time = 0;
1278 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1280 core::rect<s32>(0,0,0,0),
1281 //false, false); // Disable word wrap as of now
1283 // Remove stale "recent" chat messages from previous connections
1284 chat_backend.clearRecentChat();
1285 // Chat backend and console
1286 GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1288 // Profiler text (size is updated when text is updated)
1289 gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1291 core::rect<s32>(0,0,0,0),
1293 guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1294 guitext_profiler->setVisible(false);
1297 Some statistics are collected in these
1300 u32 beginscenetime = 0;
1302 u32 endscenetime = 0;
1304 float recent_turn_speed = 0.0;
1306 ProfilerGraph graph;
1307 // Initially clear the profiler
1308 Profiler::GraphValues dummyvalues;
1309 g_profiler->graphGet(dummyvalues);
1311 float nodig_delay_timer = 0.0;
1312 float dig_time = 0.0;
1314 PointedThing pointed_old;
1315 bool digging = false;
1316 bool ldown_for_dig = false;
1318 float damage_flash = 0;
1319 s16 farmesh_range = 20*MAP_BLOCKSIZE;
1321 float jump_timer = 0;
1322 bool reset_jump_timer = false;
1324 const float object_hit_delay = 0.2;
1325 float object_hit_delay_timer = 0.0;
1326 float time_from_last_punch = 10;
1328 float update_draw_list_timer = 0.0;
1329 v3f update_draw_list_last_cam_dir;
1331 bool invert_mouse = g_settings->getBool("invert_mouse");
1333 bool respawn_menu_active = false;
1334 bool update_wielded_item_trigger = false;
1336 bool show_hud = true;
1337 bool show_chat = true;
1338 bool force_fog_off = false;
1339 f32 fog_range = 100*BS;
1340 bool disable_camera_update = false;
1341 bool show_debug = g_settings->getBool("show_debug");
1342 bool show_profiler_graph = false;
1343 u32 show_profiler = 0;
1344 u32 show_profiler_max = 3; // Number of pages
1346 float time_of_day = 0;
1347 float time_of_day_smooth = 0;
1349 float repeat_rightclick_timer = 0;
1354 shsrc->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1355 sky, &force_fog_off, &fog_range, &client));
1361 bool first_loop_after_window_activation = true;
1363 // TODO: Convert the static interval timers to these
1364 // Interval limiter for profiler
1365 IntervalLimiter m_profiler_interval;
1367 // Time is in milliseconds
1368 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1369 // NOTE: So we have to use getTime() and call run()s between them
1370 u32 lasttime = device->getTimer()->getTime();
1372 LocalPlayer* player = client.getEnv().getLocalPlayer();
1373 player->hurt_tilt_timer = 0;
1374 player->hurt_tilt_strength = 0;
1378 if(device->run() == false || kill == true)
1381 // Time of frame without fps limit
1385 // not using getRealTime is necessary for wine
1386 u32 time = device->getTimer()->getTime();
1388 busytime_u32 = time - lasttime;
1391 busytime = busytime_u32 / 1000.0;
1394 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1396 // Necessary for device->getTimer()->getTime()
1404 float fps_max = g_settings->getFloat("fps_max");
1405 u32 frametime_min = 1000./fps_max;
1407 if(busytime_u32 < frametime_min)
1409 u32 sleeptime = frametime_min - busytime_u32;
1410 device->sleep(sleeptime);
1411 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1415 // Necessary for device->getTimer()->getTime()
1419 Time difference calculation
1421 f32 dtime; // in seconds
1423 u32 time = device->getTimer()->getTime();
1425 dtime = (time - lasttime) / 1000.0;
1430 g_profiler->graphAdd("mainloop_dtime", dtime);
1434 if(nodig_delay_timer >= 0)
1435 nodig_delay_timer -= dtime;
1436 if(object_hit_delay_timer >= 0)
1437 object_hit_delay_timer -= dtime;
1438 time_from_last_punch += dtime;
1440 g_profiler->add("Elapsed time", dtime);
1441 g_profiler->avg("FPS", 1./dtime);
1444 Time average and jitter calculation
1447 static f32 dtime_avg1 = 0.0;
1448 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1449 f32 dtime_jitter1 = dtime - dtime_avg1;
1451 static f32 dtime_jitter1_max_sample = 0.0;
1452 static f32 dtime_jitter1_max_fraction = 0.0;
1454 static f32 jitter1_max = 0.0;
1455 static f32 counter = 0.0;
1456 if(dtime_jitter1 > jitter1_max)
1457 jitter1_max = dtime_jitter1;
1462 dtime_jitter1_max_sample = jitter1_max;
1463 dtime_jitter1_max_fraction
1464 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1470 Busytime average and jitter calculation
1473 static f32 busytime_avg1 = 0.0;
1474 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1475 f32 busytime_jitter1 = busytime - busytime_avg1;
1477 static f32 busytime_jitter1_max_sample = 0.0;
1478 static f32 busytime_jitter1_min_sample = 0.0;
1480 static f32 jitter1_max = 0.0;
1481 static f32 jitter1_min = 0.0;
1482 static f32 counter = 0.0;
1483 if(busytime_jitter1 > jitter1_max)
1484 jitter1_max = busytime_jitter1;
1485 if(busytime_jitter1 < jitter1_min)
1486 jitter1_min = busytime_jitter1;
1490 busytime_jitter1_max_sample = jitter1_max;
1491 busytime_jitter1_min_sample = jitter1_min;
1498 Handle miscellaneous stuff
1501 if(client.accessDenied())
1503 error_message = L"Access denied. Reason: "
1504 +client.accessDeniedReason();
1505 errorstream<<wide_to_narrow(error_message)<<std::endl;
1509 if(g_gamecallback->disconnect_requested)
1511 g_gamecallback->disconnect_requested = false;
1515 if(g_gamecallback->changepassword_requested)
1517 (new GUIPasswordChange(guienv, guiroot, -1,
1518 &g_menumgr, &client))->drop();
1519 g_gamecallback->changepassword_requested = false;
1522 /* Process TextureSource's queue */
1523 tsrc->processQueue();
1525 /* Process ItemDefManager's queue */
1526 itemdef->processQueue(gamedef);
1529 Process ShaderSource's queue
1531 shsrc->processQueue();
1536 last_screensize = screensize;
1537 screensize = driver->getScreenSize();
1538 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1539 //bool screensize_changed = screensize != last_screensize;
1542 if(screensize.Y <= 800)
1543 hotbar_imagesize = 32;
1544 else if(screensize.Y <= 1280)
1545 hotbar_imagesize = 48;
1547 hotbar_imagesize = 64;
1549 // Hilight boxes collected during the loop and displayed
1550 std::vector<aabb3f> hilightboxes;
1553 std::wstring infotext;
1556 Debug info for client
1559 static float counter = 0.0;
1564 client.printDebugInfo(infostream);
1571 float profiler_print_interval =
1572 g_settings->getFloat("profiler_print_interval");
1573 bool print_to_log = true;
1574 if(profiler_print_interval == 0){
1575 print_to_log = false;
1576 profiler_print_interval = 5;
1578 if(m_profiler_interval.step(dtime, profiler_print_interval))
1581 infostream<<"Profiler:"<<std::endl;
1582 g_profiler->print(infostream);
1585 update_profiler_gui(guitext_profiler, font, text_height,
1586 show_profiler, show_profiler_max);
1588 g_profiler->clear();
1592 Direct handling of user input
1595 // Reset input if window not active or some menu is active
1596 if(device->isWindowActive() == false
1597 || noMenuActive() == false
1598 || guienv->hasFocus(gui_chat_console))
1603 // Input handler step() (used by the random input generator)
1606 // Increase timer for doubleclick of "jump"
1607 if(g_settings->getBool("doubletap_jump") && jump_timer <= 0.2)
1608 jump_timer += dtime;
1611 Launch menus and trigger stuff according to keys
1613 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1615 // drop selected item
1616 IDropAction *a = new IDropAction();
1618 a->from_inv.setCurrentPlayer();
1619 a->from_list = "main";
1620 a->from_i = client.getPlayerItem();
1621 client.inventoryAction(a);
1623 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1625 infostream<<"the_game: "
1626 <<"Launching inventory"<<std::endl;
1628 GUIFormSpecMenu *menu =
1629 new GUIFormSpecMenu(device, guiroot, -1,
1633 InventoryLocation inventoryloc;
1634 inventoryloc.setCurrentPlayer();
1636 PlayerInventoryFormSource *src = new PlayerInventoryFormSource(&client);
1638 menu->setFormSpec(src->getForm(), inventoryloc);
1639 menu->setFormSource(src);
1640 menu->setTextDest(new TextDestPlayerInventory(&client));
1643 else if(input->wasKeyDown(EscapeKey))
1645 infostream<<"the_game: "
1646 <<"Launching pause menu"<<std::endl;
1647 // It will delete itself by itself
1648 (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1649 &g_menumgr, simple_singleplayer_mode))->drop();
1651 // Move mouse cursor on top of the disconnect button
1652 if(simple_singleplayer_mode)
1653 input->setMousePos(displaycenter.X, displaycenter.Y+0);
1655 input->setMousePos(displaycenter.X, displaycenter.Y+25);
1657 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1659 TextDest *dest = new TextDestChat(&client);
1661 (new GUITextInputMenu(guienv, guiroot, -1,
1665 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1667 TextDest *dest = new TextDestChat(&client);
1669 (new GUITextInputMenu(guienv, guiroot, -1,
1673 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1675 if (!gui_chat_console->isOpenInhibited())
1677 // Open up to over half of the screen
1678 gui_chat_console->openConsole(0.6);
1679 guienv->setFocus(gui_chat_console);
1682 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1684 if(g_settings->getBool("free_move"))
1686 g_settings->set("free_move","false");
1687 statustext = L"free_move disabled";
1688 statustext_time = 0;
1692 g_settings->set("free_move","true");
1693 statustext = L"free_move enabled";
1694 statustext_time = 0;
1695 if(!client.checkPrivilege("fly"))
1696 statustext += L" (note: no 'fly' privilege)";
1699 else if(input->wasKeyDown(getKeySetting("keymap_jump")))
1701 if(g_settings->getBool("doubletap_jump") && jump_timer < 0.2)
1703 if(g_settings->getBool("free_move"))
1705 g_settings->set("free_move","false");
1706 statustext = L"free_move disabled";
1707 statustext_time = 0;
1711 g_settings->set("free_move","true");
1712 statustext = L"free_move enabled";
1713 statustext_time = 0;
1714 if(!client.checkPrivilege("fly"))
1715 statustext += L" (note: no 'fly' privilege)";
1718 reset_jump_timer = true;
1720 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1722 if(g_settings->getBool("fast_move"))
1724 g_settings->set("fast_move","false");
1725 statustext = L"fast_move disabled";
1726 statustext_time = 0;
1730 g_settings->set("fast_move","true");
1731 statustext = L"fast_move enabled";
1732 statustext_time = 0;
1733 if(!client.checkPrivilege("fast"))
1734 statustext += L" (note: no 'fast' privilege)";
1737 else if(input->wasKeyDown(getKeySetting("keymap_noclip")))
1739 if(g_settings->getBool("noclip"))
1741 g_settings->set("noclip","false");
1742 statustext = L"noclip disabled";
1743 statustext_time = 0;
1747 g_settings->set("noclip","true");
1748 statustext = L"noclip enabled";
1749 statustext_time = 0;
1750 if(!client.checkPrivilege("noclip"))
1751 statustext += L" (note: no 'noclip' privilege)";
1754 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1756 irr::video::IImage* const image = driver->createScreenShot();
1758 irr::c8 filename[256];
1759 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png",
1760 g_settings->get("screenshot_path").c_str(),
1761 device->getTimer()->getRealTime());
1762 if (driver->writeImageToFile(image, filename)) {
1763 std::wstringstream sstr;
1764 sstr<<"Saved screenshot to '"<<filename<<"'";
1765 infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1766 statustext = sstr.str();
1767 statustext_time = 0;
1769 infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1774 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
1776 show_hud = !show_hud;
1778 statustext = L"HUD shown";
1780 statustext = L"HUD hidden";
1781 statustext_time = 0;
1783 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
1785 show_chat = !show_chat;
1787 statustext = L"Chat shown";
1789 statustext = L"Chat hidden";
1790 statustext_time = 0;
1792 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1794 force_fog_off = !force_fog_off;
1796 statustext = L"Fog disabled";
1798 statustext = L"Fog enabled";
1799 statustext_time = 0;
1801 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1803 disable_camera_update = !disable_camera_update;
1804 if(disable_camera_update)
1805 statustext = L"Camera update disabled";
1807 statustext = L"Camera update enabled";
1808 statustext_time = 0;
1810 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
1812 // Initial / 3x toggle: Chat only
1813 // 1x toggle: Debug text with chat
1814 // 2x toggle: Debug text with profiler graph
1818 show_profiler_graph = false;
1819 statustext = L"Debug info shown";
1820 statustext_time = 0;
1822 else if(show_profiler_graph)
1825 show_profiler_graph = false;
1826 statustext = L"Debug info and profiler graph hidden";
1827 statustext_time = 0;
1831 show_profiler_graph = true;
1832 statustext = L"Profiler graph shown";
1833 statustext_time = 0;
1836 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1838 show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
1840 // FIXME: This updates the profiler with incomplete values
1841 update_profiler_gui(guitext_profiler, font, text_height,
1842 show_profiler, show_profiler_max);
1844 if(show_profiler != 0)
1846 std::wstringstream sstr;
1847 sstr<<"Profiler shown (page "<<show_profiler
1848 <<" of "<<show_profiler_max<<")";
1849 statustext = sstr.str();
1850 statustext_time = 0;
1854 statustext = L"Profiler hidden";
1855 statustext_time = 0;
1858 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
1860 s16 range = g_settings->getS16("viewing_range_nodes_min");
1861 s16 range_new = range + 10;
1862 g_settings->set("viewing_range_nodes_min", itos(range_new));
1863 statustext = narrow_to_wide(
1864 "Minimum viewing range changed to "
1866 statustext_time = 0;
1868 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
1870 s16 range = g_settings->getS16("viewing_range_nodes_min");
1871 s16 range_new = range - 10;
1874 g_settings->set("viewing_range_nodes_min",
1876 statustext = narrow_to_wide(
1877 "Minimum viewing range changed to "
1879 statustext_time = 0;
1883 if(!input->isKeyDown(getKeySetting("keymap_jump")) && reset_jump_timer)
1885 reset_jump_timer = false;
1889 // Handle QuicktuneShortcutter
1890 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
1892 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
1894 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
1896 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
1899 std::string msg = quicktune.getMessage();
1901 statustext = narrow_to_wide(msg);
1902 statustext_time = 0;
1906 // Item selection with mouse wheel
1907 u16 new_playeritem = client.getPlayerItem();
1909 s32 wheel = input->getMouseWheel();
1910 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1911 hotbar_itemcount-1);
1915 if(new_playeritem < max_item)
1922 if(new_playeritem > 0)
1925 new_playeritem = max_item;
1930 for(u16 i=0; i<10; i++)
1932 const KeyPress *kp = NumberKey + (i + 1) % 10;
1933 if(input->wasKeyDown(*kp))
1935 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
1939 infostream<<"Selected item: "
1940 <<new_playeritem<<std::endl;
1945 // Viewing range selection
1946 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
1948 draw_control.range_all = !draw_control.range_all;
1949 if(draw_control.range_all)
1951 infostream<<"Enabled full viewing range"<<std::endl;
1952 statustext = L"Enabled full viewing range";
1953 statustext_time = 0;
1957 infostream<<"Disabled full viewing range"<<std::endl;
1958 statustext = L"Disabled full viewing range";
1959 statustext_time = 0;
1963 // Print debug stacks
1964 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
1966 dstream<<"-----------------------------------------"
1968 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1969 dstream<<"-----------------------------------------"
1971 debug_stacks_print();
1975 Mouse and camera control
1976 NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
1979 float turn_amount = 0;
1980 if((device->isWindowActive() && noMenuActive()) || random_input)
1984 // Mac OSX gets upset if this is set every frame
1985 if(device->getCursorControl()->isVisible())
1986 device->getCursorControl()->setVisible(false);
1989 if(first_loop_after_window_activation){
1990 //infostream<<"window active, first loop"<<std::endl;
1991 first_loop_after_window_activation = false;
1994 s32 dx = input->getMousePos().X - displaycenter.X;
1995 s32 dy = input->getMousePos().Y - displaycenter.Y;
1998 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
2000 /*const float keyspeed = 500;
2001 if(input->isKeyDown(irr::KEY_UP))
2002 dy -= dtime * keyspeed;
2003 if(input->isKeyDown(irr::KEY_DOWN))
2004 dy += dtime * keyspeed;
2005 if(input->isKeyDown(irr::KEY_LEFT))
2006 dx -= dtime * keyspeed;
2007 if(input->isKeyDown(irr::KEY_RIGHT))
2008 dx += dtime * keyspeed;*/
2012 camera_pitch += dy*d;
2013 if(camera_pitch < -89.5) camera_pitch = -89.5;
2014 if(camera_pitch > 89.5) camera_pitch = 89.5;
2016 turn_amount = v2f(dx, dy).getLength() * d;
2018 input->setMousePos(displaycenter.X, displaycenter.Y);
2021 // Mac OSX gets upset if this is set every frame
2022 if(device->getCursorControl()->isVisible() == false)
2023 device->getCursorControl()->setVisible(true);
2025 //infostream<<"window inactive"<<std::endl;
2026 first_loop_after_window_activation = true;
2028 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
2029 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
2032 Player speed control
2046 PlayerControl control(
2047 input->isKeyDown(getKeySetting("keymap_forward")),
2048 input->isKeyDown(getKeySetting("keymap_backward")),
2049 input->isKeyDown(getKeySetting("keymap_left")),
2050 input->isKeyDown(getKeySetting("keymap_right")),
2051 input->isKeyDown(getKeySetting("keymap_jump")),
2052 input->isKeyDown(getKeySetting("keymap_special1")),
2053 input->isKeyDown(getKeySetting("keymap_sneak")),
2054 input->getLeftState(),
2055 input->getRightState(),
2059 client.setPlayerControl(control);
2061 1*(int)input->isKeyDown(getKeySetting("keymap_forward"))+
2062 2*(int)input->isKeyDown(getKeySetting("keymap_backward"))+
2063 4*(int)input->isKeyDown(getKeySetting("keymap_left"))+
2064 8*(int)input->isKeyDown(getKeySetting("keymap_right"))+
2065 16*(int)input->isKeyDown(getKeySetting("keymap_jump"))+
2066 32*(int)input->isKeyDown(getKeySetting("keymap_special1"))+
2067 64*(int)input->isKeyDown(getKeySetting("keymap_sneak"))+
2068 128*(int)input->getLeftState()+
2069 256*(int)input->getRightState();
2070 LocalPlayer* player = client.getEnv().getLocalPlayer();
2071 player->keyPressed=keyPressed;
2080 //TimeTaker timer("server->step(dtime)");
2081 server->step(dtime);
2089 //TimeTaker timer("client.step(dtime)");
2091 //client.step(dtime_avg1);
2095 // Read client events
2098 ClientEvent event = client.getClientEvent();
2099 if(event.type == CE_NONE)
2103 else if(event.type == CE_PLAYER_DAMAGE &&
2104 client.getHP() != 0)
2106 //u16 damage = event.player_damage.amount;
2107 //infostream<<"Player damage: "<<damage<<std::endl;
2109 damage_flash += 100.0;
2110 damage_flash += 8.0 * event.player_damage.amount;
2112 player->hurt_tilt_timer = 1.5;
2113 player->hurt_tilt_strength = event.player_damage.amount/2;
2114 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 2.0, 10.0);
2116 else if(event.type == CE_PLAYER_FORCE_MOVE)
2118 camera_yaw = event.player_force_move.yaw;
2119 camera_pitch = event.player_force_move.pitch;
2121 else if(event.type == CE_DEATHSCREEN)
2123 if(respawn_menu_active)
2126 /*bool set_camera_point_target =
2127 event.deathscreen.set_camera_point_target;
2128 v3f camera_point_target;
2129 camera_point_target.X = event.deathscreen.camera_point_target_x;
2130 camera_point_target.Y = event.deathscreen.camera_point_target_y;
2131 camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
2132 MainRespawnInitiator *respawner =
2133 new MainRespawnInitiator(
2134 &respawn_menu_active, &client);
2135 GUIDeathScreen *menu =
2136 new GUIDeathScreen(guienv, guiroot, -1,
2137 &g_menumgr, respawner);
2140 chat_backend.addMessage(L"", L"You died.");
2142 /* Handle visualization */
2146 LocalPlayer* player = client.getEnv().getLocalPlayer();
2147 player->hurt_tilt_timer = 0;
2148 player->hurt_tilt_strength = 0;
2150 /*LocalPlayer* player = client.getLocalPlayer();
2151 player->setPosition(player->getPosition() + v3f(0,-BS,0));
2152 camera.update(player, busytime, screensize);*/
2154 else if (event.type == CE_SHOW_FORMSPEC)
2156 if (current_formspec == 0)
2159 current_formspec = new FormspecFormSource(*(event.show_formspec.formspec),¤t_formspec);
2161 GUIFormSpecMenu *menu =
2162 new GUIFormSpecMenu(device, guiroot, -1,
2165 menu->setFormSource(current_formspec);
2166 menu->setTextDest(new TextDestPlayerInventory(&client,*(event.show_formspec.formname)));
2172 current_formspec->setForm(*(event.show_formspec.formspec));
2174 delete(event.show_formspec.formspec);
2175 delete(event.show_formspec.formname);
2177 else if(event.type == CE_TEXTURES_UPDATED)
2179 update_wielded_item_trigger = true;
2184 //TimeTaker //timer2("//timer2");
2187 For interaction purposes, get info about the held item
2189 - Is it a usable item?
2190 - Can it point to liquids?
2192 ItemStack playeritem;
2193 bool playeritem_usable = false;
2194 bool playeritem_liquids_pointable = false;
2196 InventoryList *mlist = local_inventory.getList("main");
2199 playeritem = mlist->getItem(client.getPlayerItem());
2200 playeritem_usable = playeritem.getDefinition(itemdef).usable;
2201 playeritem_liquids_pointable = playeritem.getDefinition(itemdef).liquids_pointable;
2204 ToolCapabilities playeritem_toolcap =
2205 playeritem.getToolCapabilities(itemdef);
2211 LocalPlayer* player = client.getEnv().getLocalPlayer();
2212 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2213 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
2214 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2215 camera.update(player, busytime, screensize, tool_reload_ratio);
2218 v3f player_position = player->getPosition();
2219 v3f camera_position = camera.getPosition();
2220 v3f camera_direction = camera.getDirection();
2221 f32 camera_fov = camera.getFovMax();
2223 if(!disable_camera_update){
2224 client.getEnv().getClientMap().updateCamera(camera_position,
2225 camera_direction, camera_fov);
2228 // Update sound listener
2229 sound->updateListener(camera.getCameraNode()->getPosition(),
2230 v3f(0,0,0), // velocity
2231 camera.getDirection(),
2232 camera.getCameraNode()->getUpVector());
2233 sound->setListenerGain(g_settings->getFloat("sound_volume"));
2239 soundmaker.step(dtime);
2241 ClientMap &map = client.getEnv().getClientMap();
2242 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
2243 soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
2247 Calculate what block is the crosshair pointing to
2250 //u32 t1 = device->getTimer()->getRealTime();
2252 f32 d = 4; // max. distance
2253 core::line3d<f32> shootline(camera_position,
2254 camera_position + camera_direction * BS * (d+1));
2256 ClientActiveObject *selected_object = NULL;
2258 PointedThing pointed = getPointedThing(
2260 &client, player_position, camera_direction,
2261 camera_position, shootline, d,
2262 playeritem_liquids_pointable, !ldown_for_dig,
2267 if(pointed != pointed_old)
2269 infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2270 //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
2275 - releasing left mouse button
2276 - pointing away from node
2280 if(input->getLeftReleased())
2282 infostream<<"Left button released"
2283 <<" (stopped digging)"<<std::endl;
2286 else if(pointed != pointed_old)
2288 if (pointed.type == POINTEDTHING_NODE
2289 && pointed_old.type == POINTEDTHING_NODE
2290 && pointed.node_undersurface == pointed_old.node_undersurface)
2292 // Still pointing to the same node,
2293 // but a different face. Don't reset.
2297 infostream<<"Pointing away from node"
2298 <<" (stopped digging)"<<std::endl;
2304 client.interact(1, pointed_old);
2305 client.setCrack(-1, v3s16(0,0,0));
2309 if(!digging && ldown_for_dig && !input->getLeftState())
2311 ldown_for_dig = false;
2314 bool left_punch = false;
2315 soundmaker.m_player_leftpunch_sound.name = "";
2317 if(input->getRightState())
2318 repeat_rightclick_timer += dtime;
2320 repeat_rightclick_timer = 0;
2322 if(playeritem_usable && input->getLeftState())
2324 if(input->getLeftClicked())
2325 client.interact(4, pointed);
2327 else if(pointed.type == POINTEDTHING_NODE)
2329 v3s16 nodepos = pointed.node_undersurface;
2330 v3s16 neighbourpos = pointed.node_abovesurface;
2333 Check information text of node
2336 ClientMap &map = client.getEnv().getClientMap();
2337 NodeMetadata *meta = map.getNodeMetadata(nodepos);
2339 infotext = narrow_to_wide(meta->getString("infotext"));
2341 MapNode n = map.getNode(nodepos);
2342 if(nodedef->get(n).tiledef[0].name == "unknown_block.png"){
2343 infotext = L"Unknown node: ";
2344 infotext += narrow_to_wide(nodedef->get(n).name);
2348 // We can't actually know, but assume the sound of right-clicking
2349 // to be the sound of placing a node
2350 soundmaker.m_player_rightpunch_sound.gain = 0.5;
2351 soundmaker.m_player_rightpunch_sound.name = "default_place_node";
2357 if(nodig_delay_timer <= 0.0 && input->getLeftState())
2361 infostream<<"Started digging"<<std::endl;
2362 client.interact(0, pointed);
2364 ldown_for_dig = true;
2366 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2368 // NOTE: Similar piece of code exists on the server side for
2370 // Get digging parameters
2371 DigParams params = getDigParams(nodedef->get(n).groups,
2372 &playeritem_toolcap);
2373 // If can't dig, try hand
2374 if(!params.diggable){
2375 const ItemDefinition &hand = itemdef->get("");
2376 const ToolCapabilities *tp = hand.tool_capabilities;
2378 params = getDigParams(nodedef->get(n).groups, tp);
2381 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2382 if(sound_dig.exists()){
2383 if(sound_dig.name == "__group"){
2384 if(params.main_group != ""){
2385 soundmaker.m_player_leftpunch_sound.gain = 0.5;
2386 soundmaker.m_player_leftpunch_sound.name =
2387 std::string("default_dig_") +
2391 soundmaker.m_player_leftpunch_sound = sound_dig;
2395 float dig_time_complete = 0.0;
2397 if(params.diggable == false)
2399 // I guess nobody will wait for this long
2400 dig_time_complete = 10000000.0;
2404 dig_time_complete = params.time;
2405 if (g_settings->getBool("enable_particles"))
2407 const ContentFeatures &features =
2408 client.getNodeDefManager()->get(n);
2409 addPunchingParticles
2410 (gamedef, smgr, player, nodepos, features.tiles);
2414 if(dig_time_complete >= 0.001)
2416 dig_index = (u16)((float)crack_animation_length
2417 * dig_time/dig_time_complete);
2419 // This is for torches
2422 dig_index = crack_animation_length;
2425 // Don't show cracks if not diggable
2426 if(dig_time_complete >= 100000.0)
2429 else if(dig_index < crack_animation_length)
2431 //TimeTaker timer("client.setTempMod");
2432 //infostream<<"dig_index="<<dig_index<<std::endl;
2433 client.setCrack(dig_index, nodepos);
2437 infostream<<"Digging completed"<<std::endl;
2438 client.interact(2, pointed);
2439 client.setCrack(-1, v3s16(0,0,0));
2440 MapNode wasnode = map.getNode(nodepos);
2441 client.removeNode(nodepos);
2443 if (g_settings->getBool("enable_particles"))
2445 const ContentFeatures &features =
2446 client.getNodeDefManager()->get(wasnode);
2448 (gamedef, smgr, player, nodepos, features.tiles);
2454 nodig_delay_timer = dig_time_complete
2455 / (float)crack_animation_length;
2457 // We don't want a corresponding delay to
2458 // very time consuming nodes
2459 if(nodig_delay_timer > 0.3)
2460 nodig_delay_timer = 0.3;
2461 // We want a slight delay to very little
2462 // time consuming nodes
2463 float mindelay = 0.15;
2464 if(nodig_delay_timer < mindelay)
2465 nodig_delay_timer = mindelay;
2467 // Send event to trigger sound
2468 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
2469 gamedef->event()->put(e);
2474 camera.setDigging(0); // left click animation
2477 if(input->getRightClicked() ||
2478 repeat_rightclick_timer >= g_settings->getFloat("repeat_rightclick_time"))
2480 repeat_rightclick_timer = 0;
2481 infostream<<"Ground right-clicked"<<std::endl;
2483 // Sign special case, at least until formspec is properly implemented.
2485 if(meta && meta->getString("formspec") == "hack:sign_text_input"
2487 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2489 infostream<<"Launching metadata text input"<<std::endl;
2491 // Get a new text for it
2493 TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2495 std::wstring wtext = narrow_to_wide(meta->getString("text"));
2497 (new GUITextInputMenu(guienv, guiroot, -1,
2501 // If metadata provides an inventory view, activate it
2502 else if(meta && meta->getString("formspec") != "" && !random_input
2503 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2505 infostream<<"Launching custom inventory view"<<std::endl;
2507 InventoryLocation inventoryloc;
2508 inventoryloc.setNodeMeta(nodepos);
2512 GUIFormSpecMenu *menu =
2513 new GUIFormSpecMenu(device, guiroot, -1,
2516 menu->setFormSpec(meta->getString("formspec"),
2518 menu->setFormSource(new NodeMetadataFormSource(
2519 &client.getEnv().getClientMap(), nodepos));
2520 menu->setTextDest(new TextDestNodeMetadata(nodepos, &client));
2523 // Otherwise report right click to server
2527 client.interact(3, pointed);
2528 camera.setDigging(1); // right click animation
2530 // If the wielded item has node placement prediction,
2532 const ItemDefinition &def =
2533 playeritem.getDefinition(itemdef);
2534 if(def.node_placement_prediction != "")
2536 verbosestream<<"Node placement prediction for "
2537 <<playeritem.name<<" is "
2538 <<def.node_placement_prediction<<std::endl;
2539 v3s16 p = neighbourpos;
2540 // Place inside node itself if buildable_to
2542 MapNode n_under = map.getNode(nodepos);
2543 if(nodedef->get(n_under).buildable_to)
2545 }catch(InvalidPositionException &e){}
2546 // Find id of predicted node
2549 nodedef->getId(def.node_placement_prediction, id);
2551 errorstream<<"Node placement prediction failed for "
2552 <<playeritem.name<<" (places "
2553 <<def.node_placement_prediction
2554 <<") - Name not known"<<std::endl;
2559 // This triggers the required mesh update too
2560 client.addNode(p, n);
2561 }catch(InvalidPositionException &e){
2562 errorstream<<"Node placement prediction failed for "
2563 <<playeritem.name<<" (places "
2564 <<def.node_placement_prediction
2565 <<") - Position not loaded"<<std::endl;
2571 else if(pointed.type == POINTEDTHING_OBJECT)
2573 infotext = narrow_to_wide(selected_object->infoText());
2575 if(infotext == L"" && show_debug){
2576 infotext = narrow_to_wide(selected_object->debugInfoText());
2579 //if(input->getLeftClicked())
2580 if(input->getLeftState())
2582 bool do_punch = false;
2583 bool do_punch_damage = false;
2584 if(object_hit_delay_timer <= 0.0){
2586 do_punch_damage = true;
2587 object_hit_delay_timer = object_hit_delay;
2589 if(input->getLeftClicked()){
2593 infostream<<"Left-clicked object"<<std::endl;
2596 if(do_punch_damage){
2597 // Report direct punch
2598 v3f objpos = selected_object->getPosition();
2599 v3f dir = (objpos - player_position).normalize();
2601 bool disable_send = selected_object->directReportPunch(
2602 dir, &playeritem, time_from_last_punch);
2603 time_from_last_punch = 0;
2605 client.interact(0, pointed);
2608 else if(input->getRightClicked())
2610 infostream<<"Right-clicked object"<<std::endl;
2611 client.interact(3, pointed); // place
2614 else if(input->getLeftState())
2616 // When button is held down in air, show continuous animation
2620 pointed_old = pointed;
2622 if(left_punch || input->getLeftClicked())
2624 camera.setDigging(0); // left click animation
2627 input->resetLeftClicked();
2628 input->resetRightClicked();
2630 input->resetLeftReleased();
2631 input->resetRightReleased();
2634 Calculate stuff for drawing
2643 fog_range = BS*farmesh_range;
2647 fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
2649 if(draw_control.range_all)
2650 fog_range = 100000*BS;
2654 Calculate general brightness
2656 u32 daynight_ratio = client.getEnv().getDayNightRatio();
2657 float time_brightness = decode_light_f((float)daynight_ratio/1000.0);
2658 float direct_brightness = 0;
2659 bool sunlight_seen = false;
2660 if(g_settings->getBool("free_move")){
2661 direct_brightness = time_brightness;
2662 sunlight_seen = true;
2664 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
2665 float old_brightness = sky->getBrightness();
2666 direct_brightness = (float)client.getEnv().getClientMap()
2667 .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
2668 daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
2672 time_of_day = client.getEnv().getTimeOfDayF();
2674 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
2675 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
2676 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
2677 time_of_day_smooth = time_of_day;
2679 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
2680 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2681 + (time_of_day+1.0) * todsm;
2683 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2684 + time_of_day * todsm;
2686 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
2689 float brightness = sky->getBrightness();
2690 video::SColor bgcolor = sky->getBgColor();
2691 video::SColor skycolor = sky->getSkyColor();
2697 if(sky->getCloudsVisible()){
2698 clouds->setVisible(true);
2699 clouds->step(dtime);
2700 clouds->update(v2f(player_position.X, player_position.Z),
2701 sky->getCloudColor());
2703 clouds->setVisible(false);
2712 farmesh_range = draw_control.wanted_range * 10;
2713 if(draw_control.range_all && farmesh_range < 500)
2714 farmesh_range = 500;
2715 if(farmesh_range > 1000)
2716 farmesh_range = 1000;
2718 farmesh->step(dtime);
2719 farmesh->update(v2f(player_position.X, player_position.Z),
2720 brightness, farmesh_range);
2727 allparticles_step(dtime, client.getEnv());
2733 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2737 video::EFT_FOG_LINEAR,
2749 video::EFT_FOG_LINEAR,
2759 Update gui stuff (0ms)
2762 //TimeTaker guiupdatetimer("Gui updating");
2764 const char program_name_and_version[] =
2765 "Minetest " VERSION_STRING;
2769 static float drawtime_avg = 0;
2770 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2771 /*static float beginscenetime_avg = 0;
2772 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2773 static float scenetime_avg = 0;
2774 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2775 static float endscenetime_avg = 0;
2776 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
2779 snprintf(temptext, 300, "%s ("
2782 " drawtime=%.0f, dtime_jitter = % .1f %%"
2783 ", v_range = %.1f, RTT = %.3f",
2784 program_name_and_version,
2785 draw_control.range_all,
2787 dtime_jitter1_max_fraction * 100.0,
2788 draw_control.wanted_range,
2792 guitext->setText(narrow_to_wide(temptext).c_str());
2793 guitext->setVisible(true);
2795 else if(show_hud || show_chat)
2797 guitext->setText(narrow_to_wide(program_name_and_version).c_str());
2798 guitext->setVisible(true);
2802 guitext->setVisible(false);
2808 snprintf(temptext, 300,
2809 "(% .1f, % .1f, % .1f)"
2810 " (yaw = %.1f) (seed = %lli)",
2811 player_position.X/BS,
2812 player_position.Y/BS,
2813 player_position.Z/BS,
2814 wrapDegrees_0_360(camera_yaw),
2815 client.getMapSeed());
2817 guitext2->setText(narrow_to_wide(temptext).c_str());
2818 guitext2->setVisible(true);
2822 guitext2->setVisible(false);
2826 guitext_info->setText(infotext.c_str());
2827 guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
2831 float statustext_time_max = 1.5;
2832 if(!statustext.empty())
2834 statustext_time += dtime;
2835 if(statustext_time >= statustext_time_max)
2838 statustext_time = 0;
2841 guitext_status->setText(statustext.c_str());
2842 guitext_status->setVisible(!statustext.empty());
2844 if(!statustext.empty())
2846 s32 status_y = screensize.Y - 130;
2847 core::rect<s32> rect(
2849 status_y - guitext_status->getTextHeight(),
2853 guitext_status->setRelativePosition(rect);
2856 video::SColor initial_color(255,0,0,0);
2857 if(guienv->getSkin())
2858 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
2859 video::SColor final_color = initial_color;
2860 final_color.setAlpha(0);
2861 video::SColor fade_color =
2862 initial_color.getInterpolated_quadratic(
2865 pow(statustext_time / (float)statustext_time_max, 2.0f));
2866 guitext_status->setOverrideColor(fade_color);
2867 guitext_status->enableOverrideColor(true);
2872 Get chat messages from client
2875 // Get new messages from error log buffer
2876 while(!chat_log_error_buf.empty())
2878 chat_backend.addMessage(L"", narrow_to_wide(
2879 chat_log_error_buf.get()));
2881 // Get new messages from client
2882 std::wstring message;
2883 while(client.getChatMessage(message))
2885 chat_backend.addUnparsedMessage(message);
2887 // Remove old messages
2888 chat_backend.step(dtime);
2890 // Display all messages in a static text element
2891 u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
2892 std::wstring recent_chat = chat_backend.getRecentChat();
2893 guitext_chat->setText(recent_chat.c_str());
2895 // Update gui element size and position
2896 s32 chat_y = 5+(text_height+5);
2898 chat_y += (text_height+5);
2899 core::rect<s32> rect(
2903 chat_y + guitext_chat->getTextHeight()
2905 guitext_chat->setRelativePosition(rect);
2907 // Don't show chat if disabled or empty or profiler is enabled
2908 guitext_chat->setVisible(show_chat && recent_chat_count != 0
2916 if(client.getPlayerItem() != new_playeritem)
2918 client.selectPlayerItem(new_playeritem);
2920 if(client.getLocalInventoryUpdated())
2922 //infostream<<"Updating local inventory"<<std::endl;
2923 client.getLocalInventory(local_inventory);
2925 update_wielded_item_trigger = true;
2927 if(update_wielded_item_trigger)
2929 update_wielded_item_trigger = false;
2930 // Update wielded tool
2931 InventoryList *mlist = local_inventory.getList("main");
2934 item = mlist->getItem(client.getPlayerItem());
2939 Update block draw list every 200ms or when camera direction has
2942 update_draw_list_timer += dtime;
2943 if(update_draw_list_timer >= 0.2 ||
2944 update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2){
2945 update_draw_list_timer = 0;
2946 client.getEnv().getClientMap().updateDrawList(driver);
2947 update_draw_list_last_cam_dir = camera_direction;
2954 TimeTaker tt_draw("mainloop: draw");
2958 TimeTaker timer("beginScene");
2959 //driver->beginScene(false, true, bgcolor);
2960 //driver->beginScene(true, true, bgcolor);
2961 driver->beginScene(true, true, skycolor);
2962 beginscenetime = timer.stop(true);
2967 //infostream<<"smgr->drawAll()"<<std::endl;
2969 TimeTaker timer("smgr");
2972 if(g_settings->getBool("anaglyph"))
2974 irr::core::vector3df oldPosition = camera.getCameraNode()->getPosition();
2975 irr::core::vector3df oldTarget = camera.getCameraNode()->getTarget();
2977 irr::core::matrix4 startMatrix = camera.getCameraNode()->getAbsoluteTransformation();
2979 irr::core::vector3df focusPoint = (camera.getCameraNode()->getTarget() -
2980 camera.getCameraNode()->getAbsolutePosition()).setLength(1) +
2981 camera.getCameraNode()->getAbsolutePosition() ;
2984 irr::core::vector3df leftEye;
2985 irr::core::matrix4 leftMove;
2987 leftMove.setTranslation( irr::core::vector3df(-g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
2988 leftEye=(startMatrix*leftMove).getTranslation();
2990 //clear the depth buffer, and color
2991 driver->beginScene( true, true, irr::video::SColor(0,200,200,255) );
2993 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_RED;
2994 driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK;
2995 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
2996 irr::scene::ESNRP_SOLID +
2997 irr::scene::ESNRP_TRANSPARENT +
2998 irr::scene::ESNRP_TRANSPARENT_EFFECT +
2999 irr::scene::ESNRP_SHADOW;
3001 camera.getCameraNode()->setPosition( leftEye );
3002 camera.getCameraNode()->setTarget( focusPoint );
3004 smgr->drawAll(); // 'smgr->drawAll();' may go here
3008 irr::core::vector3df rightEye;
3009 irr::core::matrix4 rightMove;
3011 rightMove.setTranslation( irr::core::vector3df(g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
3012 rightEye=(startMatrix*rightMove).getTranslation();
3014 //clear the depth buffer
3015 driver->clearZBuffer();
3017 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_GREEN + irr::video::ECP_BLUE;
3018 driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK;
3019 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
3020 irr::scene::ESNRP_SOLID +
3021 irr::scene::ESNRP_TRANSPARENT +
3022 irr::scene::ESNRP_TRANSPARENT_EFFECT +
3023 irr::scene::ESNRP_SHADOW;
3025 camera.getCameraNode()->setPosition( rightEye );
3026 camera.getCameraNode()->setTarget( focusPoint );
3028 smgr->drawAll(); // 'smgr->drawAll();' may go here
3031 //driver->endScene();
3033 driver->getOverrideMaterial().Material.ColorMask=irr::video::ECP_ALL;
3034 driver->getOverrideMaterial().EnableFlags=0;
3035 driver->getOverrideMaterial().EnablePasses=0;
3037 camera.getCameraNode()->setPosition( oldPosition );
3038 camera.getCameraNode()->setTarget( oldTarget );
3041 scenetime = timer.stop(true);
3045 //TimeTaker timer9("auxiliary drawings");
3049 //TimeTaker //timer10("//timer10");
3055 driver->setMaterial(m);
3057 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
3061 v3f selectionbox_color = g_settings->getV3F("selectionbox_color");
3062 u32 selectionbox_color_r = rangelim(myround(selectionbox_color.X), 0, 255);
3063 u32 selectionbox_color_g = rangelim(myround(selectionbox_color.Y), 0, 255);
3064 u32 selectionbox_color_b = rangelim(myround(selectionbox_color.Z), 0, 255);
3066 for(std::vector<aabb3f>::const_iterator
3067 i = hilightboxes.begin();
3068 i != hilightboxes.end(); i++)
3070 /*infostream<<"hilightbox min="
3071 <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
3073 <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
3075 driver->draw3DBox(*i, video::SColor(255,selectionbox_color_r,selectionbox_color_g,selectionbox_color_b));
3084 // Warning: This clears the Z buffer.
3085 camera.drawWieldedTool();
3092 client.getEnv().getClientMap().renderPostFx();
3098 if(show_profiler_graph)
3100 graph.draw(10, screensize.Y - 10, driver, font);
3108 v3f crosshair_color = g_settings->getV3F("crosshair_color");
3109 u32 crosshair_color_r = rangelim(myround(crosshair_color.X), 0, 255);
3110 u32 crosshair_color_g = rangelim(myround(crosshair_color.Y), 0, 255);
3111 u32 crosshair_color_b = rangelim(myround(crosshair_color.Z), 0, 255);
3112 u32 crosshair_alpha = rangelim(g_settings->getS32("crosshair_alpha"), 0, 255);
3114 driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),
3115 displaycenter + core::vector2d<s32>(10,0),
3116 video::SColor(crosshair_alpha,crosshair_color_r,crosshair_color_g,crosshair_color_b));
3117 driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),
3118 displaycenter + core::vector2d<s32>(0,10),
3119 video::SColor(crosshair_alpha,crosshair_color_r,crosshair_color_g,crosshair_color_b));
3125 //TimeTaker //timer11("//timer11");
3133 draw_hotbar(driver, font, gamedef,
3134 v2s32(displaycenter.X, screensize.Y),
3135 hotbar_imagesize, hotbar_itemcount, &local_inventory,
3136 client.getHP(), client.getPlayerItem());
3142 if(damage_flash > 0.0)
3144 video::SColor color(std::min(damage_flash, 180.0f),180,0,0);
3145 driver->draw2DRectangle(color,
3146 core::rect<s32>(0,0,screensize.X,screensize.Y),
3149 damage_flash -= 100.0*dtime;
3155 if(player->hurt_tilt_timer > 0.0)
3157 player->hurt_tilt_timer -= dtime*5;
3158 if(player->hurt_tilt_timer < 0)
3159 player->hurt_tilt_strength = 0;
3172 TimeTaker timer("endScene");
3174 endscenetime = timer.stop(true);
3177 drawtime = tt_draw.stop(true);
3178 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
3184 static s16 lastFPS = 0;
3185 //u16 fps = driver->getFPS();
3186 u16 fps = (1.0/dtime_avg1);
3190 core::stringw str = L"Minetest [";
3191 str += driver->getName();
3195 device->setWindowCaption(str.c_str());
3200 Log times and stuff for visualization
3202 Profiler::GraphValues values;
3203 g_profiler->graphGet(values);
3212 if(gui_chat_console)
3213 gui_chat_console->drop();
3216 Draw a "shutting down" screen, which will be shown while the map
3217 generator and other stuff quits
3220 /*gui::IGUIStaticText *gui_shuttingdowntext = */
3221 draw_load_screen(L"Shutting down stuff...", driver, font);
3222 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
3225 gui_shuttingdowntext->remove();*/
3228 chat_backend.addMessage(L"", L"# Disconnected.");
3229 chat_backend.addMessage(L"", L"");
3231 // Client scope (client is destructed before destructing *def and tsrc)
3234 catch(SerializationError &e)
3236 error_message = L"A serialization error occurred:\n"
3237 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
3238 L" running a different version of Minetest.";
3239 errorstream<<wide_to_narrow(error_message)<<std::endl;