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 "guiPasswordChange.h"
32 #include "guiVolumeChange.h"
33 #include "guiFormSpecMenu.h"
34 #include "guiTextInputMenu.h"
36 #include "guiChatConsole.h"
40 #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"
64 #include "sound_openal.h"
66 #include "event_manager.h"
69 #include "util/directiontables.h"
70 #include "util/pointedthing.h"
76 struct TextDestNodeMetadata : public TextDest
78 TextDestNodeMetadata(v3s16 p, Client *client)
83 // This is deprecated I guess? -celeron55
84 void gotText(std::wstring text)
86 std::string ntext = wide_to_narrow(text);
87 infostream<<"Submitting 'text' field of node at ("<<m_p.X<<","
88 <<m_p.Y<<","<<m_p.Z<<"): "<<ntext<<std::endl;
89 std::map<std::string, std::string> fields;
90 fields["text"] = ntext;
91 m_client->sendNodemetaFields(m_p, "", fields);
93 void gotText(std::map<std::string, std::string> fields)
95 m_client->sendNodemetaFields(m_p, "", fields);
102 struct TextDestPlayerInventory : public TextDest
104 TextDestPlayerInventory(Client *client)
109 TextDestPlayerInventory(Client *client, std::string formname)
112 m_formname = formname;
114 void gotText(std::map<std::string, std::string> fields)
116 m_client->sendInventoryFields(m_formname, fields);
122 struct LocalFormspecHandler : public TextDest
124 LocalFormspecHandler();
125 LocalFormspecHandler(std::string formname) {
126 m_formname = formname;
129 LocalFormspecHandler(std::string formname,Client *client) {
130 m_formname = formname;
134 void gotText(std::wstring message) {
135 errorstream << "LocalFormspecHandler::gotText old style message received" << std::endl;
138 void gotText(std::map<std::string, std::string> fields)
140 if (m_formname == "MT_PAUSE_MENU") {
141 if (fields.find("btn_sound") != fields.end()) {
142 g_gamecallback->changeVolume();
146 if (fields.find("btn_exit_menu") != fields.end()) {
147 g_gamecallback->disconnect();
151 if (fields.find("btn_exit_os") != fields.end()) {
152 g_gamecallback->exitToOS();
156 if (fields.find("btn_change_password") != fields.end()) {
157 g_gamecallback->changePassword();
161 if (fields.find("quit") != fields.end()) {
165 if (fields.find("btn_continue") != fields.end()) {
169 if (m_formname == "MT_CHAT_MENU") {
170 if ((fields.find("btn_send") != fields.end()) ||
171 (fields.find("quit") != fields.end())) {
172 if (fields.find("f_text") != fields.end()) {
174 m_client->typeChatMessage(narrow_to_wide(fields["f_text"]));
177 errorstream << "LocalFormspecHandler::gotText received chat message but m_client is NULL" << std::endl;
184 if (m_formname == "MT_DEATH_SCREEN") {
185 if ((fields.find("btn_respawn") != fields.end())) {
186 m_client->sendRespawn();
191 errorstream << "LocalFormspecHandler::gotText unhandled >" << m_formname << "< event" << std::endl;
193 for (std::map<std::string,std::string>::iterator iter = fields.begin();
194 iter != fields.end(); iter++) {
195 errorstream << "\t"<< i << ": " << iter->first << "=" << iter->second << std::endl;
203 /* Form update callback */
205 class NodeMetadataFormSource: public IFormSource
208 NodeMetadataFormSource(ClientMap *map, v3s16 p):
213 std::string getForm()
215 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
218 return meta->getString("formspec");
220 std::string resolveText(std::string str)
222 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
225 return meta->resolveString(str);
232 class PlayerInventoryFormSource: public IFormSource
235 PlayerInventoryFormSource(Client *client):
239 std::string getForm()
241 LocalPlayer* player = m_client->getEnv().getLocalPlayer();
242 return player->inventory_formspec;
249 Check if a node is pointable
251 inline bool isPointableNode(const MapNode& n,
252 Client *client, bool liquids_pointable)
254 const ContentFeatures &features = client->getNodeDefManager()->get(n);
255 return features.pointable ||
256 (liquids_pointable && features.isLiquid());
260 Find what the player is pointing at
262 PointedThing getPointedThing(Client *client, v3f player_position,
263 v3f camera_direction, v3f camera_position, core::line3d<f32> shootline,
264 f32 d, bool liquids_pointable, bool look_for_object, v3s16 camera_offset,
265 std::vector<aabb3f> &hilightboxes, ClientActiveObject *&selected_object)
269 hilightboxes.clear();
270 selected_object = NULL;
272 INodeDefManager *nodedef = client->getNodeDefManager();
273 ClientMap &map = client->getEnv().getClientMap();
275 f32 mindistance = BS * 1001;
277 // First try to find a pointed at active object
280 selected_object = client->getSelectedActiveObject(d*BS,
281 camera_position, shootline);
283 if(selected_object != NULL)
285 if(selected_object->doShowSelectionBox())
287 aabb3f *selection_box = selected_object->getSelectionBox();
288 // Box should exist because object was
289 // returned in the first place
290 assert(selection_box);
292 v3f pos = selected_object->getPosition();
293 hilightboxes.push_back(aabb3f(
294 selection_box->MinEdge + pos - intToFloat(camera_offset, BS),
295 selection_box->MaxEdge + pos - intToFloat(camera_offset, BS)));
298 mindistance = (selected_object->getPosition() - camera_position).getLength();
300 result.type = POINTEDTHING_OBJECT;
301 result.object_id = selected_object->getId();
305 // That didn't work, try to find a pointed at node
308 v3s16 pos_i = floatToInt(player_position, BS);
310 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
314 s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
315 s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
316 s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
317 s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
318 s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
319 s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
321 // Prevent signed number overflow
329 for(s16 y = ystart; y <= yend; y++)
330 for(s16 z = zstart; z <= zend; z++)
331 for(s16 x = xstart; x <= xend; x++)
336 n = map.getNode(v3s16(x,y,z));
338 catch(InvalidPositionException &e)
342 if(!isPointableNode(n, client, liquids_pointable))
345 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
348 v3f npf = intToFloat(np, BS);
350 for(std::vector<aabb3f>::const_iterator
352 i != boxes.end(); i++)
358 for(u16 j=0; j<6; j++)
360 v3s16 facedir = g_6dirs[j];
361 aabb3f facebox = box;
365 facebox.MinEdge.X = facebox.MaxEdge.X-d;
366 else if(facedir.X < 0)
367 facebox.MaxEdge.X = facebox.MinEdge.X+d;
368 else if(facedir.Y > 0)
369 facebox.MinEdge.Y = facebox.MaxEdge.Y-d;
370 else if(facedir.Y < 0)
371 facebox.MaxEdge.Y = facebox.MinEdge.Y+d;
372 else if(facedir.Z > 0)
373 facebox.MinEdge.Z = facebox.MaxEdge.Z-d;
374 else if(facedir.Z < 0)
375 facebox.MaxEdge.Z = facebox.MinEdge.Z+d;
377 v3f centerpoint = facebox.getCenter();
378 f32 distance = (centerpoint - camera_position).getLength();
379 if(distance >= mindistance)
381 if(!facebox.intersectsWithLine(shootline))
384 v3s16 np_above = np + facedir;
386 result.type = POINTEDTHING_NODE;
387 result.node_undersurface = np;
388 result.node_abovesurface = np_above;
389 mindistance = distance;
391 hilightboxes.clear();
392 for(std::vector<aabb3f>::const_iterator
394 i2 != boxes.end(); i2++)
397 box.MinEdge += npf + v3f(-d,-d,-d) - intToFloat(camera_offset, BS);
398 box.MaxEdge += npf + v3f(d,d,d) - intToFloat(camera_offset, BS);
399 hilightboxes.push_back(box);
409 Draws a screen with a single text on it.
410 Text will be removed when the screen is drawn the next time.
411 Additionally, a progressbar can be drawn when percent is set between 0 and 100.
413 /*gui::IGUIStaticText **/
414 void draw_load_screen(const std::wstring &text, IrrlichtDevice* device,
415 gui::IGUIFont* font, float dtime=0 ,int percent=0, bool clouds=true)
417 video::IVideoDriver* driver = device->getVideoDriver();
418 v2u32 screensize = driver->getScreenSize();
419 const wchar_t *loadingtext = text.c_str();
420 core::vector2d<u32> textsize_u = font->getDimension(loadingtext);
421 core::vector2d<s32> textsize(textsize_u.X,textsize_u.Y);
422 core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
423 core::rect<s32> textrect(center - textsize/2, center + textsize/2);
425 gui::IGUIStaticText *guitext = guienv->addStaticText(
426 loadingtext, textrect, false, false);
427 guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
429 bool cloud_menu_background = clouds && g_settings->getBool("menu_clouds");
430 if (cloud_menu_background)
432 g_menuclouds->step(dtime*3);
433 g_menuclouds->render();
434 driver->beginScene(true, true, video::SColor(255,140,186,250));
435 g_menucloudsmgr->drawAll();
438 driver->beginScene(true, true, video::SColor(255,0,0,0));
439 if (percent >= 0 && percent <= 100) // draw progress bar
441 core::vector2d<s32> barsize(256,32);
442 core::rect<s32> barrect(center-barsize/2, center+barsize/2);
443 driver->draw2DRectangle(video::SColor(255,255,255,255),barrect, NULL); // border
444 driver->draw2DRectangle(video::SColor(255,64,64,64), core::rect<s32> (
445 barrect.UpperLeftCorner+1,
446 barrect.LowerRightCorner-1), NULL); // black inside the bar
447 driver->draw2DRectangle(video::SColor(255,128,128,128), core::rect<s32> (
448 barrect.UpperLeftCorner+1,
450 barrect.LowerRightCorner.X-(barsize.X-1)+percent*(barsize.X-2)/100,
451 barrect.LowerRightCorner.Y-1)), NULL); // the actual progress
461 /* Profiler display */
463 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler,
464 gui::IGUIFont *font, u32 text_height, u32 show_profiler,
465 u32 show_profiler_max)
467 if(show_profiler == 0)
469 guitext_profiler->setVisible(false);
474 std::ostringstream os(std::ios_base::binary);
475 g_profiler->printPage(os, show_profiler, show_profiler_max);
476 std::wstring text = narrow_to_wide(os.str());
477 guitext_profiler->setText(text.c_str());
478 guitext_profiler->setVisible(true);
480 s32 w = font->getDimension(text.c_str()).Width;
483 core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
484 8+(text_height+5)*2 +
485 font->getDimension(text.c_str()).Height);
486 guitext_profiler->setRelativePosition(rect);
487 guitext_profiler->setVisible(true);
495 Profiler::GraphValues values;
501 Meta(float initial=0, video::SColor color=
502 video::SColor(255,255,255,255)):
508 std::list<Piece> m_log;
516 void put(const Profiler::GraphValues &values)
519 piece.values = values;
520 m_log.push_back(piece);
521 while(m_log.size() > m_log_max_size)
522 m_log.erase(m_log.begin());
525 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
526 gui::IGUIFont* font) const
528 std::map<std::string, Meta> m_meta;
529 for(std::list<Piece>::const_iterator k = m_log.begin();
530 k != m_log.end(); k++)
532 const Piece &piece = *k;
533 for(Profiler::GraphValues::const_iterator i = piece.values.begin();
534 i != piece.values.end(); i++){
535 const std::string &id = i->first;
536 const float &value = i->second;
537 std::map<std::string, Meta>::iterator j =
539 if(j == m_meta.end()){
540 m_meta[id] = Meta(value);
543 if(value < j->second.min)
544 j->second.min = value;
545 if(value > j->second.max)
546 j->second.max = value;
551 static const video::SColor usable_colors[] = {
552 video::SColor(255,255,100,100),
553 video::SColor(255,90,225,90),
554 video::SColor(255,100,100,255),
555 video::SColor(255,255,150,50),
556 video::SColor(255,220,220,100)
558 static const u32 usable_colors_count =
559 sizeof(usable_colors) / sizeof(*usable_colors);
560 u32 next_color_i = 0;
561 for(std::map<std::string, Meta>::iterator i = m_meta.begin();
562 i != m_meta.end(); i++){
563 Meta &meta = i->second;
564 video::SColor color(255,200,200,200);
565 if(next_color_i < usable_colors_count)
566 color = usable_colors[next_color_i++];
571 s32 textx = x_left + m_log_max_size + 15;
572 s32 textx2 = textx + 200 - 15;
576 u32 num_graphs = m_meta.size();
577 core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
579 video::SColor bgcolor(120,0,0,0);
580 driver->draw2DRectangle(bgcolor, rect, NULL);
584 for(std::map<std::string, Meta>::const_iterator i = m_meta.begin();
585 i != m_meta.end(); i++){
586 const std::string &id = i->first;
587 const Meta &meta = i->second;
589 s32 y = y_bottom - meta_i * 50;
590 float show_min = meta.min;
591 float show_max = meta.max;
592 if(show_min >= -0.0001 && show_max >= -0.0001){
593 if(show_min <= show_max * 0.5)
598 snprintf(buf, 10, "%.3g", show_max);
599 font->draw(narrow_to_wide(buf).c_str(),
600 core::rect<s32>(textx, y - graphh,
601 textx2, y - graphh + texth),
603 snprintf(buf, 10, "%.3g", show_min);
604 font->draw(narrow_to_wide(buf).c_str(),
605 core::rect<s32>(textx, y - texth,
608 font->draw(narrow_to_wide(id).c_str(),
609 core::rect<s32>(textx, y - graphh/2 - texth/2,
610 textx2, y - graphh/2 + texth/2),
613 s32 graph1h = graphh;
614 bool relativegraph = (show_min != 0 && show_min != show_max);
615 float lastscaledvalue = 0.0;
616 bool lastscaledvalue_exists = false;
617 for(std::list<Piece>::const_iterator j = m_log.begin();
618 j != m_log.end(); j++)
620 const Piece &piece = *j;
622 bool value_exists = false;
623 Profiler::GraphValues::const_iterator k =
624 piece.values.find(id);
625 if(k != piece.values.end()){
631 lastscaledvalue_exists = false;
634 float scaledvalue = 1.0;
635 if(show_max != show_min)
636 scaledvalue = (value - show_min) / (show_max - show_min);
637 if(scaledvalue == 1.0 && value == 0){
639 lastscaledvalue_exists = false;
643 if(lastscaledvalue_exists){
644 s32 ivalue1 = lastscaledvalue * graph1h;
645 s32 ivalue2 = scaledvalue * graph1h;
646 driver->draw2DLine(v2s32(x-1, graph1y - ivalue1),
647 v2s32(x, graph1y - ivalue2), meta.color);
649 lastscaledvalue = scaledvalue;
650 lastscaledvalue_exists = true;
652 s32 ivalue = scaledvalue * graph1h;
653 driver->draw2DLine(v2s32(x, graph1y),
654 v2s32(x, graph1y - ivalue), meta.color);
663 class NodeDugEvent: public MtEvent
669 NodeDugEvent(v3s16 p, MapNode n):
673 const char* getType() const
679 ISoundManager *m_sound;
680 INodeDefManager *m_ndef;
682 float m_player_step_timer;
684 SimpleSoundSpec m_player_step_sound;
685 SimpleSoundSpec m_player_leftpunch_sound;
686 SimpleSoundSpec m_player_rightpunch_sound;
688 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
691 m_player_step_timer(0)
695 void playPlayerStep()
697 if(m_player_step_timer <= 0 && m_player_step_sound.exists()){
698 m_player_step_timer = 0.03;
699 m_sound->playSound(m_player_step_sound, false);
703 static void viewBobbingStep(MtEvent *e, void *data)
705 SoundMaker *sm = (SoundMaker*)data;
706 sm->playPlayerStep();
709 static void playerRegainGround(MtEvent *e, void *data)
711 SoundMaker *sm = (SoundMaker*)data;
712 sm->playPlayerStep();
715 static void playerJump(MtEvent *e, void *data)
717 //SoundMaker *sm = (SoundMaker*)data;
720 static void cameraPunchLeft(MtEvent *e, void *data)
722 SoundMaker *sm = (SoundMaker*)data;
723 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
726 static void cameraPunchRight(MtEvent *e, void *data)
728 SoundMaker *sm = (SoundMaker*)data;
729 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
732 static void nodeDug(MtEvent *e, void *data)
734 SoundMaker *sm = (SoundMaker*)data;
735 NodeDugEvent *nde = (NodeDugEvent*)e;
736 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
739 static void playerDamage(MtEvent *e, void *data)
741 SoundMaker *sm = (SoundMaker*)data;
742 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
745 static void playerFallingDamage(MtEvent *e, void *data)
747 SoundMaker *sm = (SoundMaker*)data;
748 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
751 void registerReceiver(MtEventManager *mgr)
753 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
754 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
755 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
756 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
757 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
758 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
759 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
760 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
763 void step(float dtime)
765 m_player_step_timer -= dtime;
769 // Locally stored sounds don't need to be preloaded because of this
770 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
772 std::set<std::string> m_fetched;
775 void fetchSounds(const std::string &name,
776 std::set<std::string> &dst_paths,
777 std::set<std::string> &dst_datas)
779 if(m_fetched.count(name))
781 m_fetched.insert(name);
782 std::string base = porting::path_share + DIR_DELIM + "testsounds";
783 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
784 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
785 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
786 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
787 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
788 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
789 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
790 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
791 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
792 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
793 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
797 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
800 bool *m_force_fog_off;
805 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
806 f32 *fog_range, Client *client):
808 m_force_fog_off(force_fog_off),
809 m_fog_range(fog_range),
812 ~GameGlobalShaderConstantSetter() {}
814 virtual void onSetConstants(video::IMaterialRendererServices *services,
821 video::SColor bgcolor = m_sky->getBgColor();
822 video::SColorf bgcolorf(bgcolor);
823 float bgcolorfa[4] = {
829 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
832 float fog_distance = 10000*BS;
833 if(g_settings->getBool("enable_fog") && !*m_force_fog_off)
834 fog_distance = *m_fog_range;
835 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
838 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
839 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
840 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
842 u32 animation_timer = porting::getTimeMs() % 100000;
843 float animation_timer_f = (float)animation_timer / 100000.0;
844 services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
845 services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
847 LocalPlayer* player = m_client->getEnv().getLocalPlayer();
848 v3f eye_position = player->getEyePosition();
849 services->setPixelShaderConstant("eyePosition", (irr::f32*)&eye_position, 3);
850 services->setVertexShaderConstant("eyePosition", (irr::f32*)&eye_position, 3);
852 // Uniform sampler layers
856 // before 1.8 there isn't a "integer interface", only float
857 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
858 services->setPixelShaderConstant("baseTexture" , (irr::f32*)&layer0, 1);
859 services->setPixelShaderConstant("normalTexture" , (irr::f32*)&layer1, 1);
860 services->setPixelShaderConstant("useNormalmap" , (irr::f32*)&layer2, 1);
862 services->setPixelShaderConstant("baseTexture" , (irr::s32*)&layer0, 1);
863 services->setPixelShaderConstant("normalTexture" , (irr::s32*)&layer1, 1);
864 services->setPixelShaderConstant("useNormalmap" , (irr::s32*)&layer2, 1);
869 bool nodePlacementPrediction(Client &client,
870 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
872 std::string prediction = playeritem_def.node_placement_prediction;
873 INodeDefManager *nodedef = client.ndef();
874 ClientMap &map = client.getEnv().getClientMap();
876 if(prediction != "" && !nodedef->get(map.getNode(nodepos)).rightclickable)
878 verbosestream<<"Node placement prediction for "
879 <<playeritem_def.name<<" is "
880 <<prediction<<std::endl;
881 v3s16 p = neighbourpos;
882 // Place inside node itself if buildable_to
884 MapNode n_under = map.getNode(nodepos);
885 if(nodedef->get(n_under).buildable_to)
887 else if (!nodedef->get(map.getNode(p)).buildable_to)
889 }catch(InvalidPositionException &e){}
890 // Find id of predicted node
892 bool found = nodedef->getId(prediction, id);
894 errorstream<<"Node placement prediction failed for "
895 <<playeritem_def.name<<" (places "
897 <<") - Name not known"<<std::endl;
900 // Predict param2 for facedir and wallmounted nodes
902 if(nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED){
903 v3s16 dir = nodepos - neighbourpos;
904 if(abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))){
905 param2 = dir.Y < 0 ? 1 : 0;
906 } else if(abs(dir.X) > abs(dir.Z)){
907 param2 = dir.X < 0 ? 3 : 2;
909 param2 = dir.Z < 0 ? 5 : 4;
912 if(nodedef->get(id).param_type_2 == CPT2_FACEDIR){
913 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
914 if(abs(dir.X) > abs(dir.Z)){
915 param2 = dir.X < 0 ? 3 : 1;
917 param2 = dir.Z < 0 ? 2 : 0;
920 assert(param2 >= 0 && param2 <= 5);
921 //Check attachment if node is in group attached_node
922 if(((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0){
923 static v3s16 wallmounted_dirs[8] = {
932 if(nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
933 pp = p + wallmounted_dirs[param2];
935 pp = p + v3s16(0,-1,0);
936 if(!nodedef->get(map.getNode(pp)).walkable)
939 // Add node to client map
940 MapNode n(id, 0, param2);
942 LocalPlayer* player = client.getEnv().getLocalPlayer();
944 // Dont place node when player would be inside new node
945 // NOTE: This is to be eventually implemented by a mod as client-side Lua
946 if (!nodedef->get(n).walkable ||
947 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
948 (nodedef->get(n).walkable &&
949 neighbourpos != player->getStandingNodePos() + v3s16(0,1,0) &&
950 neighbourpos != player->getStandingNodePos() + v3s16(0,2,0))) {
952 // This triggers the required mesh update too
953 client.addNode(p, n);
956 }catch(InvalidPositionException &e){
957 errorstream<<"Node placement prediction failed for "
958 <<playeritem_def.name<<" (places "
960 <<") - Position not loaded"<<std::endl;
966 static void show_chat_menu(FormspecFormSource* current_formspec,
967 TextDest* current_textdest, IWritableTextureSource* tsrc,
968 IrrlichtDevice * device, Client* client, std::string text)
970 std::string formspec =
972 "field[3,2.35;6,0.5;f_text;;" + text + "]"
973 "button_exit[4,3;3,0.5;btn_send;" + wide_to_narrow(wstrgettext("Proceed")) + "]"
977 /* Note: FormspecFormSource and LocalFormspecHandler
978 * are deleted by guiFormSpecMenu */
979 current_formspec = new FormspecFormSource(formspec,¤t_formspec);
980 current_textdest = new LocalFormspecHandler("MT_CHAT_MENU",client);
981 GUIFormSpecMenu *menu =
982 new GUIFormSpecMenu(device, guiroot, -1,
985 menu->doPause = false;
986 menu->setFormSource(current_formspec);
987 menu->setTextDest(current_textdest);
991 static void show_deathscreen(FormspecFormSource* current_formspec,
992 TextDest* current_textdest, IWritableTextureSource* tsrc,
993 IrrlichtDevice * device, Client* client)
995 std::string formspec =
998 "label[4.85,1.35;You died.]"
999 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
1003 /* Note: FormspecFormSource and LocalFormspecHandler
1004 * are deleted by guiFormSpecMenu */
1005 current_formspec = new FormspecFormSource(formspec,¤t_formspec);
1006 current_textdest = new LocalFormspecHandler("MT_DEATH_SCREEN",client);
1007 GUIFormSpecMenu *menu =
1008 new GUIFormSpecMenu(device, guiroot, -1,
1011 menu->doPause = false;
1012 menu->setFormSource(current_formspec);
1013 menu->setTextDest(current_textdest);
1017 /******************************************************************************/
1018 static void show_pause_menu(FormspecFormSource* current_formspec,
1019 TextDest* current_textdest, IWritableTextureSource* tsrc,
1020 IrrlichtDevice * device, bool singleplayermode)
1023 std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1025 "- Space: jump/climb\n"
1026 "- Shift: sneak/go down\n"
1029 "- Mouse: turn/look\n"
1030 "- Mouse left: dig/punch\n"
1031 "- Mouse right: place/use\n"
1032 "- Mouse wheel: select item\n"
1036 float ypos = singleplayermode ? 1.0 : 0.5;
1037 std::ostringstream os;
1039 os << "size[11,5.5,true]"
1040 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1041 << wide_to_narrow(wstrgettext("Continue")) << "]";
1043 if (!singleplayermode) {
1044 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1045 << wide_to_narrow(wstrgettext("Change Password")) << "]";
1048 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1049 << wide_to_narrow(wstrgettext("Sound Volume")) << "]";
1050 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1051 << wide_to_narrow(wstrgettext("Exit to Menu")) << "]";
1052 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1053 << wide_to_narrow(wstrgettext("Exit to OS")) << "]"
1054 << "textarea[7.5,0.25;3.75,6;;" << control_text << ";]"
1055 << "textarea[0.4,0.25;3.5,6;;" << "Minetest\n"
1056 << minetest_build_info << "\n"
1057 << "path_user = " << wrap_rows(porting::path_user, 20)
1061 /* Note: FormspecFormSource and LocalFormspecHandler *
1062 * are deleted by guiFormSpecMenu */
1063 current_formspec = new FormspecFormSource(os.str(),¤t_formspec);
1064 current_textdest = new LocalFormspecHandler("MT_PAUSE_MENU");
1065 GUIFormSpecMenu *menu =
1066 new GUIFormSpecMenu(device, guiroot, -1, &g_menumgr, NULL, NULL, tsrc);
1067 menu->doPause = true;
1068 menu->setFormSource(current_formspec);
1069 menu->setTextDest(current_textdest);
1073 /******************************************************************************/
1074 void the_game(bool &kill, bool random_input, InputHandler *input,
1075 IrrlichtDevice *device, gui::IGUIFont* font, std::string map_dir,
1076 std::string playername, std::string password,
1077 std::string address /* If "", local server is used */,
1078 u16 port, std::wstring &error_message, ChatBackend &chat_backend,
1079 const SubgameSpec &gamespec /* Used for local game */,
1080 bool simple_singleplayer_mode)
1082 FormspecFormSource* current_formspec = 0;
1083 TextDest* current_textdest = 0;
1084 video::IVideoDriver* driver = device->getVideoDriver();
1085 scene::ISceneManager* smgr = device->getSceneManager();
1087 // Calculate text height using the font
1088 u32 text_height = font->getDimension(L"Random test string").Height;
1090 v2u32 last_screensize(0,0);
1091 v2u32 screensize = driver->getScreenSize();
1094 Draw "Loading" screen
1098 wchar_t* text = wgettext("Loading...");
1099 draw_load_screen(text, device, font,0,0);
1103 // Create texture source
1104 IWritableTextureSource *tsrc = createTextureSource(device);
1106 // Create shader source
1107 IWritableShaderSource *shsrc = createShaderSource(device);
1109 // These will be filled by data received from the server
1110 // Create item definition manager
1111 IWritableItemDefManager *itemdef = createItemDefManager();
1112 // Create node definition manager
1113 IWritableNodeDefManager *nodedef = createNodeDefManager();
1115 // Sound fetcher (useful when testing)
1116 GameOnDemandSoundFetcher soundfetcher;
1119 ISoundManager *sound = NULL;
1120 bool sound_is_dummy = false;
1122 if(g_settings->getBool("enable_sound")){
1123 infostream<<"Attempting to use OpenAL audio"<<std::endl;
1124 sound = createOpenALSoundManager(&soundfetcher);
1126 infostream<<"Failed to initialize OpenAL audio"<<std::endl;
1128 infostream<<"Sound disabled."<<std::endl;
1132 infostream<<"Using dummy audio."<<std::endl;
1133 sound = &dummySoundManager;
1134 sound_is_dummy = true;
1137 Server *server = NULL;
1141 EventManager eventmgr;
1144 SoundMaker soundmaker(sound, nodedef);
1145 soundmaker.registerReceiver(&eventmgr);
1147 // Add chat log output for errors to be shown in chat
1148 LogOutputBuffer chat_log_error_buf(LMT_ERROR);
1150 // Create UI for modifying quicktune values
1151 QuicktuneShortcutter quicktune;
1158 wchar_t* text = wgettext("Creating server....");
1159 draw_load_screen(text, device, font,0,25);
1161 infostream<<"Creating server"<<std::endl;
1163 std::string bind_str = g_settings->get("bind_address");
1164 Address bind_addr(0,0,0,0, port);
1166 if (g_settings->getBool("ipv6_server")) {
1167 bind_addr.setAddress((IPv6AddressBytes*) NULL);
1170 bind_addr.Resolve(bind_str.c_str());
1172 } catch (ResolveError &e) {
1173 infostream << "Resolving bind address \"" << bind_str
1174 << "\" failed: " << e.what()
1175 << " -- Listening on all addresses." << std::endl;
1178 if(bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1179 error_message = L"Unable to listen on " +
1180 narrow_to_wide(bind_addr.serializeString()) +
1181 L" because IPv6 is disabled";
1182 errorstream<<wide_to_narrow(error_message)<<std::endl;
1183 // Break out of client scope
1187 server = new Server(map_dir, gamespec,
1188 simple_singleplayer_mode,
1189 bind_addr.isIPv6());
1191 server->start(bind_addr);
1194 do{ // Client scope (breakable do-while(0))
1201 wchar_t* text = wgettext("Creating client...");
1202 draw_load_screen(text, device, font,0,50);
1205 infostream<<"Creating client"<<std::endl;
1207 MapDrawControl draw_control;
1210 wchar_t* text = wgettext("Resolving address...");
1211 draw_load_screen(text, device, font,0,75);
1214 Address connect_address(0,0,0,0, port);
1216 connect_address.Resolve(address.c_str());
1217 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
1218 //connect_address.Resolve("localhost");
1219 if (connect_address.isIPv6()) {
1220 IPv6AddressBytes addr_bytes;
1221 addr_bytes.bytes[15] = 1;
1222 connect_address.setAddress(&addr_bytes);
1224 connect_address.setAddress(127,0,0,1);
1228 catch(ResolveError &e) {
1229 error_message = L"Couldn't resolve address: " + narrow_to_wide(e.what());
1230 errorstream<<wide_to_narrow(error_message)<<std::endl;
1231 // Break out of client scope
1234 if(connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1235 error_message = L"Unable to connect to " +
1236 narrow_to_wide(connect_address.serializeString()) +
1237 L" because IPv6 is disabled";
1238 errorstream<<wide_to_narrow(error_message)<<std::endl;
1239 // Break out of client scope
1246 Client client(device, playername.c_str(), password, draw_control,
1247 tsrc, shsrc, itemdef, nodedef, sound, &eventmgr,
1248 connect_address.isIPv6());
1250 // Client acts as our GameDef
1251 IGameDef *gamedef = &client;
1254 Attempt to connect to the server
1257 infostream<<"Connecting to server at ";
1258 connect_address.print(&infostream);
1259 infostream<<std::endl;
1260 client.connect(connect_address);
1263 Wait for server to accept connection
1265 bool could_connect = false;
1266 bool connect_aborted = false;
1268 float time_counter = 0.0;
1270 float fps_max = g_settings->getFloat("fps_max");
1271 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1272 u32 lasttime = device->getTimer()->getTime();
1273 while(device->run())
1275 f32 dtime = 0.033; // in seconds
1276 if (cloud_menu_background) {
1277 u32 time = device->getTimer()->getTime();
1279 dtime = (time - lasttime) / 1000.0;
1284 // Update client and server
1287 server->step(dtime);
1290 if(client.getState() == LC_Init){
1291 could_connect = true;
1295 if(client.accessDenied()){
1296 error_message = L"Access denied. Reason: "
1297 +client.accessDeniedReason();
1298 errorstream<<wide_to_narrow(error_message)<<std::endl;
1301 if(input->wasKeyDown(EscapeKey)){
1302 connect_aborted = true;
1303 infostream<<"Connect aborted [Escape]"<<std::endl;
1309 wchar_t* text = wgettext("Connecting to server...");
1310 draw_load_screen(text, device, font, dtime, 100);
1314 // On some computers framerate doesn't seem to be
1315 // automatically limited
1316 if (cloud_menu_background) {
1317 // Time of frame without fps limit
1320 // not using getRealTime is necessary for wine
1321 u32 time = device->getTimer()->getTime();
1323 busytime_u32 = time - lasttime;
1326 busytime = busytime_u32 / 1000.0;
1329 u32 frametime_min = 1000./fps_max;
1331 if(busytime_u32 < frametime_min) {
1332 u32 sleeptime = frametime_min - busytime_u32;
1333 device->sleep(sleeptime);
1338 time_counter += dtime;
1341 catch(con::PeerNotFoundException &e)
1345 Handle failure to connect
1348 if(error_message == L"" && !connect_aborted){
1349 error_message = L"Connection failed";
1350 errorstream<<wide_to_narrow(error_message)<<std::endl;
1352 // Break out of client scope
1357 Wait until content has been received
1359 bool got_content = false;
1360 bool content_aborted = false;
1362 float time_counter = 0.0;
1364 float fps_max = g_settings->getFloat("fps_max");
1365 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1366 u32 lasttime = device->getTimer()->getTime();
1367 while(device->run())
1369 f32 dtime = 0.033; // in seconds
1370 if (cloud_menu_background) {
1371 u32 time = device->getTimer()->getTime();
1373 dtime = (time - lasttime) / 1000.0;
1378 // Update client and server
1381 server->step(dtime);
1384 if(client.mediaReceived() &&
1385 client.itemdefReceived() &&
1386 client.nodedefReceived()){
1391 if(client.accessDenied()){
1392 error_message = L"Access denied. Reason: "
1393 +client.accessDeniedReason();
1394 errorstream<<wide_to_narrow(error_message)<<std::endl;
1397 if(client.getState() < LC_Init){
1398 error_message = L"Client disconnected";
1399 errorstream<<wide_to_narrow(error_message)<<std::endl;
1402 if(input->wasKeyDown(EscapeKey)){
1403 content_aborted = true;
1404 infostream<<"Connect aborted [Escape]"<<std::endl;
1410 if (!client.itemdefReceived())
1412 wchar_t* text = wgettext("Item definitions...");
1414 draw_load_screen(text, device, font, dtime, progress);
1417 else if (!client.nodedefReceived())
1419 wchar_t* text = wgettext("Node definitions...");
1421 draw_load_screen(text, device, font, dtime, progress);
1426 wchar_t* text = wgettext("Media...");
1427 progress = 50+client.mediaReceiveProgress()*50+0.5;
1428 draw_load_screen(text, device, font, dtime, progress);
1432 // On some computers framerate doesn't seem to be
1433 // automatically limited
1434 if (cloud_menu_background) {
1435 // Time of frame without fps limit
1438 // not using getRealTime is necessary for wine
1439 u32 time = device->getTimer()->getTime();
1441 busytime_u32 = time - lasttime;
1444 busytime = busytime_u32 / 1000.0;
1447 u32 frametime_min = 1000./fps_max;
1449 if(busytime_u32 < frametime_min) {
1450 u32 sleeptime = frametime_min - busytime_u32;
1451 device->sleep(sleeptime);
1456 time_counter += dtime;
1461 if(error_message == L"" && !content_aborted){
1462 error_message = L"Something failed";
1463 errorstream<<wide_to_narrow(error_message)<<std::endl;
1465 // Break out of client scope
1470 After all content has been received:
1471 Update cached textures, meshes and materials
1473 client.afterContentReceived(device,font);
1476 Create the camera node
1478 Camera camera(smgr, draw_control, gamedef);
1479 if (!camera.successfullyCreated(error_message))
1482 f32 camera_yaw = 0; // "right/left"
1483 f32 camera_pitch = 0; // "up/down"
1485 int current_camera_mode = CAMERA_MODE_FIRST; // start in first-person view
1491 Clouds *clouds = NULL;
1492 if(g_settings->getBool("enable_clouds"))
1494 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1502 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, client.getEnv().getLocalPlayer());
1504 scene::ISceneNode* skybox = NULL;
1507 A copy of the local inventory
1509 Inventory local_inventory(itemdef);
1512 Find out size of crack animation
1514 int crack_animation_length = 5;
1516 video::ITexture *t = tsrc->getTexture("crack_anylength.png");
1517 v2u32 size = t->getOriginalSize();
1518 crack_animation_length = size.Y / size.X;
1525 // First line of debug text
1526 gui::IGUIStaticText *guitext = guienv->addStaticText(
1528 core::rect<s32>(5, 5, 795, 5+text_height),
1530 // Second line of debug text
1531 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1533 core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
1535 // At the middle of the screen
1536 // Object infos are shown in this
1537 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1539 core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1542 // Status text (displays info when showing and hiding GUI stuff, etc.)
1543 gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1545 core::rect<s32>(0,0,0,0),
1547 guitext_status->setVisible(false);
1549 std::wstring statustext;
1550 float statustext_time = 0;
1553 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1555 core::rect<s32>(0,0,0,0),
1556 //false, false); // Disable word wrap as of now
1558 // Remove stale "recent" chat messages from previous connections
1559 chat_backend.clearRecentChat();
1560 // Chat backend and console
1561 GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1563 // Profiler text (size is updated when text is updated)
1564 gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1566 core::rect<s32>(0,0,0,0),
1568 guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1569 guitext_profiler->setVisible(false);
1570 guitext_profiler->setWordWrap(true);
1573 Some statistics are collected in these
1576 u32 beginscenetime = 0;
1578 u32 endscenetime = 0;
1580 float recent_turn_speed = 0.0;
1582 ProfilerGraph graph;
1583 // Initially clear the profiler
1584 Profiler::GraphValues dummyvalues;
1585 g_profiler->graphGet(dummyvalues);
1587 float nodig_delay_timer = 0.0;
1588 float dig_time = 0.0;
1590 PointedThing pointed_old;
1591 bool digging = false;
1592 bool ldown_for_dig = false;
1594 float damage_flash = 0;
1596 float jump_timer = 0;
1597 bool reset_jump_timer = false;
1599 const float object_hit_delay = 0.2;
1600 float object_hit_delay_timer = 0.0;
1601 float time_from_last_punch = 10;
1603 float update_draw_list_timer = 0.0;
1604 v3f update_draw_list_last_cam_dir;
1606 bool invert_mouse = g_settings->getBool("invert_mouse");
1608 bool update_wielded_item_trigger = true;
1610 bool show_hud = true;
1611 bool show_chat = true;
1612 bool force_fog_off = false;
1613 f32 fog_range = 100*BS;
1614 bool disable_camera_update = false;
1615 bool show_debug = g_settings->getBool("show_debug");
1616 bool show_profiler_graph = false;
1617 u32 show_profiler = 0;
1618 u32 show_profiler_max = 3; // Number of pages
1620 float time_of_day = 0;
1621 float time_of_day_smooth = 0;
1623 float repeat_rightclick_timer = 0;
1628 shsrc->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1629 sky, &force_fog_off, &fog_range, &client));
1635 bool first_loop_after_window_activation = true;
1637 // TODO: Convert the static interval timers to these
1638 // Interval limiter for profiler
1639 IntervalLimiter m_profiler_interval;
1641 // Time is in milliseconds
1642 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1643 // NOTE: So we have to use getTime() and call run()s between them
1644 u32 lasttime = device->getTimer()->getTime();
1646 LocalPlayer* player = client.getEnv().getLocalPlayer();
1647 player->hurt_tilt_timer = 0;
1648 player->hurt_tilt_strength = 0;
1653 Hud hud(driver, smgr, guienv, font, text_height,
1654 gamedef, player, &local_inventory);
1656 core::stringw str = L"Minetest [";
1657 str += driver->getName();
1659 device->setWindowCaption(str.c_str());
1662 std::wstring infotext;
1666 if(device->run() == false || kill == true)
1669 // Time of frame without fps limit
1673 // not using getRealTime is necessary for wine
1674 u32 time = device->getTimer()->getTime();
1676 busytime_u32 = time - lasttime;
1679 busytime = busytime_u32 / 1000.0;
1682 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1684 // Necessary for device->getTimer()->getTime()
1692 float fps_max = g_menumgr.pausesGame() ?
1693 g_settings->getFloat("pause_fps_max") :
1694 g_settings->getFloat("fps_max");
1695 u32 frametime_min = 1000./fps_max;
1697 if(busytime_u32 < frametime_min)
1699 u32 sleeptime = frametime_min - busytime_u32;
1700 device->sleep(sleeptime);
1701 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1705 // Necessary for device->getTimer()->getTime()
1709 Time difference calculation
1711 f32 dtime; // in seconds
1713 u32 time = device->getTimer()->getTime();
1715 dtime = (time - lasttime) / 1000.0;
1720 g_profiler->graphAdd("mainloop_dtime", dtime);
1724 if(nodig_delay_timer >= 0)
1725 nodig_delay_timer -= dtime;
1726 if(object_hit_delay_timer >= 0)
1727 object_hit_delay_timer -= dtime;
1728 time_from_last_punch += dtime;
1730 g_profiler->add("Elapsed time", dtime);
1731 g_profiler->avg("FPS", 1./dtime);
1734 Time average and jitter calculation
1737 static f32 dtime_avg1 = 0.0;
1738 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1739 f32 dtime_jitter1 = dtime - dtime_avg1;
1741 static f32 dtime_jitter1_max_sample = 0.0;
1742 static f32 dtime_jitter1_max_fraction = 0.0;
1744 static f32 jitter1_max = 0.0;
1745 static f32 counter = 0.0;
1746 if(dtime_jitter1 > jitter1_max)
1747 jitter1_max = dtime_jitter1;
1752 dtime_jitter1_max_sample = jitter1_max;
1753 dtime_jitter1_max_fraction
1754 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1760 Busytime average and jitter calculation
1763 static f32 busytime_avg1 = 0.0;
1764 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1765 f32 busytime_jitter1 = busytime - busytime_avg1;
1767 static f32 busytime_jitter1_max_sample = 0.0;
1768 static f32 busytime_jitter1_min_sample = 0.0;
1770 static f32 jitter1_max = 0.0;
1771 static f32 jitter1_min = 0.0;
1772 static f32 counter = 0.0;
1773 if(busytime_jitter1 > jitter1_max)
1774 jitter1_max = busytime_jitter1;
1775 if(busytime_jitter1 < jitter1_min)
1776 jitter1_min = busytime_jitter1;
1780 busytime_jitter1_max_sample = jitter1_max;
1781 busytime_jitter1_min_sample = jitter1_min;
1788 Handle miscellaneous stuff
1791 if(client.accessDenied())
1793 error_message = L"Access denied. Reason: "
1794 +client.accessDeniedReason();
1795 errorstream<<wide_to_narrow(error_message)<<std::endl;
1799 if(g_gamecallback->disconnect_requested)
1801 g_gamecallback->disconnect_requested = false;
1805 if(g_gamecallback->changepassword_requested)
1807 (new GUIPasswordChange(guienv, guiroot, -1,
1808 &g_menumgr, &client))->drop();
1809 g_gamecallback->changepassword_requested = false;
1812 if(g_gamecallback->changevolume_requested)
1814 (new GUIVolumeChange(guienv, guiroot, -1,
1815 &g_menumgr, &client))->drop();
1816 g_gamecallback->changevolume_requested = false;
1819 /* Process TextureSource's queue */
1820 tsrc->processQueue();
1822 /* Process ItemDefManager's queue */
1823 itemdef->processQueue(gamedef);
1826 Process ShaderSource's queue
1828 shsrc->processQueue();
1833 last_screensize = screensize;
1834 screensize = driver->getScreenSize();
1835 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1836 //bool screensize_changed = screensize != last_screensize;
1839 // Update HUD values
1840 hud.screensize = screensize;
1841 hud.displaycenter = displaycenter;
1844 // Hilight boxes collected during the loop and displayed
1845 std::vector<aabb3f> hilightboxes;
1847 /* reset infotext */
1852 float profiler_print_interval =
1853 g_settings->getFloat("profiler_print_interval");
1854 bool print_to_log = true;
1855 if(profiler_print_interval == 0){
1856 print_to_log = false;
1857 profiler_print_interval = 5;
1859 if(m_profiler_interval.step(dtime, profiler_print_interval))
1862 infostream<<"Profiler:"<<std::endl;
1863 g_profiler->print(infostream);
1866 update_profiler_gui(guitext_profiler, font, text_height,
1867 show_profiler, show_profiler_max);
1869 g_profiler->clear();
1873 Direct handling of user input
1876 // Reset input if window not active or some menu is active
1877 if(device->isWindowActive() == false
1878 || noMenuActive() == false
1879 || guienv->hasFocus(gui_chat_console))
1883 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen())
1885 gui_chat_console->closeConsoleAtOnce();
1888 // Input handler step() (used by the random input generator)
1891 // Increase timer for doubleclick of "jump"
1892 if(g_settings->getBool("doubletap_jump") && jump_timer <= 0.2)
1893 jump_timer += dtime;
1896 Launch menus and trigger stuff according to keys
1898 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1900 // drop selected item
1901 IDropAction *a = new IDropAction();
1903 a->from_inv.setCurrentPlayer();
1904 a->from_list = "main";
1905 a->from_i = client.getPlayerItem();
1906 client.inventoryAction(a);
1908 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1910 infostream<<"the_game: "
1911 <<"Launching inventory"<<std::endl;
1913 GUIFormSpecMenu *menu =
1914 new GUIFormSpecMenu(device, guiroot, -1,
1916 &client, gamedef, tsrc);
1918 InventoryLocation inventoryloc;
1919 inventoryloc.setCurrentPlayer();
1921 PlayerInventoryFormSource *src = new PlayerInventoryFormSource(&client);
1923 menu->doPause = false;
1924 menu->setFormSpec(src->getForm(), inventoryloc);
1925 menu->setFormSource(src);
1926 menu->setTextDest(new TextDestPlayerInventory(&client));
1929 else if(input->wasKeyDown(EscapeKey))
1931 show_pause_menu(current_formspec, current_textdest, tsrc, device,
1932 simple_singleplayer_mode);
1934 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1936 show_chat_menu(current_formspec, current_textdest, tsrc, device, &client,"");
1938 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1940 show_chat_menu(current_formspec, current_textdest, tsrc, device, &client,"/");
1942 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1944 if (!gui_chat_console->isOpenInhibited())
1946 // Open up to over half of the screen
1947 gui_chat_console->openConsole(0.6);
1948 guienv->setFocus(gui_chat_console);
1951 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1953 if(g_settings->getBool("free_move"))
1955 g_settings->set("free_move","false");
1956 statustext = L"free_move disabled";
1957 statustext_time = 0;
1961 g_settings->set("free_move","true");
1962 statustext = L"free_move enabled";
1963 statustext_time = 0;
1964 if(!client.checkPrivilege("fly"))
1965 statustext += L" (note: no 'fly' privilege)";
1968 else if(input->wasKeyDown(getKeySetting("keymap_jump")))
1970 if(g_settings->getBool("doubletap_jump") && jump_timer < 0.2)
1972 if(g_settings->getBool("free_move"))
1974 g_settings->set("free_move","false");
1975 statustext = L"free_move disabled";
1976 statustext_time = 0;
1980 g_settings->set("free_move","true");
1981 statustext = L"free_move enabled";
1982 statustext_time = 0;
1983 if(!client.checkPrivilege("fly"))
1984 statustext += L" (note: no 'fly' privilege)";
1987 reset_jump_timer = true;
1989 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1991 if(g_settings->getBool("fast_move"))
1993 g_settings->set("fast_move","false");
1994 statustext = L"fast_move disabled";
1995 statustext_time = 0;
1999 g_settings->set("fast_move","true");
2000 statustext = L"fast_move enabled";
2001 statustext_time = 0;
2002 if(!client.checkPrivilege("fast"))
2003 statustext += L" (note: no 'fast' privilege)";
2006 else if(input->wasKeyDown(getKeySetting("keymap_noclip")))
2008 if(g_settings->getBool("noclip"))
2010 g_settings->set("noclip","false");
2011 statustext = L"noclip disabled";
2012 statustext_time = 0;
2016 g_settings->set("noclip","true");
2017 statustext = L"noclip enabled";
2018 statustext_time = 0;
2019 if(!client.checkPrivilege("noclip"))
2020 statustext += L" (note: no 'noclip' privilege)";
2023 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
2025 irr::video::IImage* const image = driver->createScreenShot();
2027 irr::c8 filename[256];
2028 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png",
2029 g_settings->get("screenshot_path").c_str(),
2030 device->getTimer()->getRealTime());
2031 if (driver->writeImageToFile(image, filename)) {
2032 std::wstringstream sstr;
2033 sstr<<"Saved screenshot to '"<<filename<<"'";
2034 infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
2035 statustext = sstr.str();
2036 statustext_time = 0;
2038 infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
2043 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
2045 show_hud = !show_hud;
2047 statustext = L"HUD shown";
2049 statustext = L"HUD hidden";
2050 statustext_time = 0;
2052 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
2054 show_chat = !show_chat;
2056 statustext = L"Chat shown";
2058 statustext = L"Chat hidden";
2059 statustext_time = 0;
2061 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
2063 force_fog_off = !force_fog_off;
2065 statustext = L"Fog disabled";
2067 statustext = L"Fog enabled";
2068 statustext_time = 0;
2070 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
2072 disable_camera_update = !disable_camera_update;
2073 if(disable_camera_update)
2074 statustext = L"Camera update disabled";
2076 statustext = L"Camera update enabled";
2077 statustext_time = 0;
2079 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
2081 // Initial / 3x toggle: Chat only
2082 // 1x toggle: Debug text with chat
2083 // 2x toggle: Debug text with profiler graph
2087 show_profiler_graph = false;
2088 statustext = L"Debug info shown";
2089 statustext_time = 0;
2091 else if(show_profiler_graph)
2094 show_profiler_graph = false;
2095 statustext = L"Debug info and profiler graph hidden";
2096 statustext_time = 0;
2100 show_profiler_graph = true;
2101 statustext = L"Profiler graph shown";
2102 statustext_time = 0;
2105 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
2107 show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
2109 // FIXME: This updates the profiler with incomplete values
2110 update_profiler_gui(guitext_profiler, font, text_height,
2111 show_profiler, show_profiler_max);
2113 if(show_profiler != 0)
2115 std::wstringstream sstr;
2116 sstr<<"Profiler shown (page "<<show_profiler
2117 <<" of "<<show_profiler_max<<")";
2118 statustext = sstr.str();
2119 statustext_time = 0;
2123 statustext = L"Profiler hidden";
2124 statustext_time = 0;
2127 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
2129 s16 range = g_settings->getS16("viewing_range_nodes_min");
2130 s16 range_new = range + 10;
2131 g_settings->set("viewing_range_nodes_min", itos(range_new));
2132 statustext = narrow_to_wide(
2133 "Minimum viewing range changed to "
2135 statustext_time = 0;
2137 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
2139 s16 range = g_settings->getS16("viewing_range_nodes_min");
2140 s16 range_new = range - 10;
2143 g_settings->set("viewing_range_nodes_min",
2145 statustext = narrow_to_wide(
2146 "Minimum viewing range changed to "
2148 statustext_time = 0;
2152 if(!input->isKeyDown(getKeySetting("keymap_jump")) && reset_jump_timer)
2154 reset_jump_timer = false;
2158 // Handle QuicktuneShortcutter
2159 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
2161 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
2163 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
2165 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
2168 std::string msg = quicktune.getMessage();
2170 statustext = narrow_to_wide(msg);
2171 statustext_time = 0;
2175 // Item selection with mouse wheel
2176 u16 new_playeritem = client.getPlayerItem();
2178 s32 wheel = input->getMouseWheel();
2179 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
2180 player->hud_hotbar_itemcount-1);
2184 if(new_playeritem < max_item)
2191 if(new_playeritem > 0)
2194 new_playeritem = max_item;
2199 for(u16 i=0; i<10; i++)
2201 const KeyPress *kp = NumberKey + (i + 1) % 10;
2202 if(input->wasKeyDown(*kp))
2204 if(i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount)
2208 infostream<<"Selected item: "
2209 <<new_playeritem<<std::endl;
2214 // Viewing range selection
2215 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
2217 draw_control.range_all = !draw_control.range_all;
2218 if(draw_control.range_all)
2220 infostream<<"Enabled full viewing range"<<std::endl;
2221 statustext = L"Enabled full viewing range";
2222 statustext_time = 0;
2226 infostream<<"Disabled full viewing range"<<std::endl;
2227 statustext = L"Disabled full viewing range";
2228 statustext_time = 0;
2232 // Print debug stacks
2233 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
2235 dstream<<"-----------------------------------------"
2237 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
2238 dstream<<"-----------------------------------------"
2240 debug_stacks_print();
2244 Mouse and camera control
2245 NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
2248 float turn_amount = 0;
2249 if((device->isWindowActive() && noMenuActive()) || random_input)
2253 // Mac OSX gets upset if this is set every frame
2254 if(device->getCursorControl()->isVisible())
2255 device->getCursorControl()->setVisible(false);
2258 if(first_loop_after_window_activation){
2259 //infostream<<"window active, first loop"<<std::endl;
2260 first_loop_after_window_activation = false;
2263 s32 dx = input->getMousePos().X - displaycenter.X;
2264 s32 dy = input->getMousePos().Y - displaycenter.Y;
2265 if(invert_mouse || player->camera_mode == CAMERA_MODE_THIRD_FRONT)
2267 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
2269 /*const float keyspeed = 500;
2270 if(input->isKeyDown(irr::KEY_UP))
2271 dy -= dtime * keyspeed;
2272 if(input->isKeyDown(irr::KEY_DOWN))
2273 dy += dtime * keyspeed;
2274 if(input->isKeyDown(irr::KEY_LEFT))
2275 dx -= dtime * keyspeed;
2276 if(input->isKeyDown(irr::KEY_RIGHT))
2277 dx += dtime * keyspeed;*/
2279 float d = g_settings->getFloat("mouse_sensitivity");
2280 d = rangelim(d, 0.01, 100.0);
2282 camera_pitch += dy*d;
2283 if(camera_pitch < -89.5) camera_pitch = -89.5;
2284 if(camera_pitch > 89.5) camera_pitch = 89.5;
2286 turn_amount = v2f(dx, dy).getLength() * d;
2288 input->setMousePos(displaycenter.X, displaycenter.Y);
2291 // Mac OSX gets upset if this is set every frame
2292 if(device->getCursorControl()->isVisible() == false)
2293 device->getCursorControl()->setVisible(true);
2295 //infostream<<"window inactive"<<std::endl;
2296 first_loop_after_window_activation = true;
2298 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
2299 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
2302 Player speed control
2316 PlayerControl control(
2317 input->isKeyDown(getKeySetting("keymap_forward")),
2318 input->isKeyDown(getKeySetting("keymap_backward")),
2319 input->isKeyDown(getKeySetting("keymap_left")),
2320 input->isKeyDown(getKeySetting("keymap_right")),
2321 input->isKeyDown(getKeySetting("keymap_jump")),
2322 input->isKeyDown(getKeySetting("keymap_special1")),
2323 input->isKeyDown(getKeySetting("keymap_sneak")),
2324 input->getLeftState(),
2325 input->getRightState(),
2329 client.setPlayerControl(control);
2330 LocalPlayer* player = client.getEnv().getLocalPlayer();
2332 (((int)input->isKeyDown(getKeySetting("keymap_forward")) & 0x1) << 0) |
2333 (((int)input->isKeyDown(getKeySetting("keymap_backward")) & 0x1) << 1) |
2334 (((int)input->isKeyDown(getKeySetting("keymap_left")) & 0x1) << 2) |
2335 (((int)input->isKeyDown(getKeySetting("keymap_right")) & 0x1) << 3) |
2336 (((int)input->isKeyDown(getKeySetting("keymap_jump")) & 0x1) << 4) |
2337 (((int)input->isKeyDown(getKeySetting("keymap_special1")) & 0x1) << 5) |
2338 (((int)input->isKeyDown(getKeySetting("keymap_sneak")) & 0x1) << 6) |
2339 (((int)input->getLeftState() & 0x1) << 7) |
2340 (((int)input->getRightState() & 0x1) << 8);
2344 Run server, client (and process environments)
2346 bool can_be_and_is_paused =
2347 (simple_singleplayer_mode && g_menumgr.pausesGame());
2348 if(can_be_and_is_paused)
2357 //TimeTaker timer("server->step(dtime)");
2358 server->step(dtime);
2361 //TimeTaker timer("client.step(dtime)");
2367 // Read client events
2370 ClientEvent event = client.getClientEvent();
2371 if(event.type == CE_NONE)
2375 else if(event.type == CE_PLAYER_DAMAGE &&
2376 client.getHP() != 0)
2378 //u16 damage = event.player_damage.amount;
2379 //infostream<<"Player damage: "<<damage<<std::endl;
2381 damage_flash += 100.0;
2382 damage_flash += 8.0 * event.player_damage.amount;
2384 player->hurt_tilt_timer = 1.5;
2385 player->hurt_tilt_strength = event.player_damage.amount/2;
2386 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 2.0, 10.0);
2388 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
2389 gamedef->event()->put(e);
2391 else if(event.type == CE_PLAYER_FORCE_MOVE)
2393 camera_yaw = event.player_force_move.yaw;
2394 camera_pitch = event.player_force_move.pitch;
2396 else if(event.type == CE_DEATHSCREEN)
2398 show_deathscreen(current_formspec, current_textdest,
2399 tsrc, device, &client);
2401 chat_backend.addMessage(L"", L"You died.");
2403 /* Handle visualization */
2406 LocalPlayer* player = client.getEnv().getLocalPlayer();
2407 player->hurt_tilt_timer = 0;
2408 player->hurt_tilt_strength = 0;
2411 else if (event.type == CE_SHOW_FORMSPEC)
2413 if (current_formspec == 0)
2416 /* Note: FormspecFormSource and TextDestPlayerInventory
2417 * are deleted by guiFormSpecMenu */
2418 current_formspec = new FormspecFormSource(*(event.show_formspec.formspec),¤t_formspec);
2419 current_textdest = new TextDestPlayerInventory(&client,*(event.show_formspec.formname));
2420 GUIFormSpecMenu *menu =
2421 new GUIFormSpecMenu(device, guiroot, -1,
2423 &client, gamedef, tsrc);
2424 menu->doPause = false;
2425 menu->setFormSource(current_formspec);
2426 menu->setTextDest(current_textdest);
2431 assert(current_textdest != 0);
2433 current_textdest->setFormName(*(event.show_formspec.formname));
2434 current_formspec->setForm(*(event.show_formspec.formspec));
2436 delete(event.show_formspec.formspec);
2437 delete(event.show_formspec.formname);
2439 else if(event.type == CE_SPAWN_PARTICLE)
2441 LocalPlayer* player = client.getEnv().getLocalPlayer();
2442 video::ITexture *texture =
2443 gamedef->tsrc()->getTexture(*(event.spawn_particle.texture));
2445 new Particle(gamedef, smgr, player, client.getEnv(),
2446 *event.spawn_particle.pos,
2447 *event.spawn_particle.vel,
2448 *event.spawn_particle.acc,
2449 event.spawn_particle.expirationtime,
2450 event.spawn_particle.size,
2451 event.spawn_particle.collisiondetection,
2452 event.spawn_particle.vertical,
2457 else if(event.type == CE_ADD_PARTICLESPAWNER)
2459 LocalPlayer* player = client.getEnv().getLocalPlayer();
2460 video::ITexture *texture =
2461 gamedef->tsrc()->getTexture(*(event.add_particlespawner.texture));
2463 new ParticleSpawner(gamedef, smgr, player,
2464 event.add_particlespawner.amount,
2465 event.add_particlespawner.spawntime,
2466 *event.add_particlespawner.minpos,
2467 *event.add_particlespawner.maxpos,
2468 *event.add_particlespawner.minvel,
2469 *event.add_particlespawner.maxvel,
2470 *event.add_particlespawner.minacc,
2471 *event.add_particlespawner.maxacc,
2472 event.add_particlespawner.minexptime,
2473 event.add_particlespawner.maxexptime,
2474 event.add_particlespawner.minsize,
2475 event.add_particlespawner.maxsize,
2476 event.add_particlespawner.collisiondetection,
2477 event.add_particlespawner.vertical,
2479 event.add_particlespawner.id);
2481 else if(event.type == CE_DELETE_PARTICLESPAWNER)
2483 delete_particlespawner (event.delete_particlespawner.id);
2485 else if (event.type == CE_HUDADD)
2487 u32 id = event.hudadd.id;
2488 size_t nhudelem = player->hud.size();
2489 if (id > nhudelem || (id < nhudelem && player->hud[id])) {
2490 delete event.hudadd.pos;
2491 delete event.hudadd.name;
2492 delete event.hudadd.scale;
2493 delete event.hudadd.text;
2494 delete event.hudadd.align;
2495 delete event.hudadd.offset;
2496 delete event.hudadd.world_pos;
2500 HudElement *e = new HudElement;
2501 e->type = (HudElementType)event.hudadd.type;
2502 e->pos = *event.hudadd.pos;
2503 e->name = *event.hudadd.name;
2504 e->scale = *event.hudadd.scale;
2505 e->text = *event.hudadd.text;
2506 e->number = event.hudadd.number;
2507 e->item = event.hudadd.item;
2508 e->dir = event.hudadd.dir;
2509 e->align = *event.hudadd.align;
2510 e->offset = *event.hudadd.offset;
2511 e->world_pos = *event.hudadd.world_pos;
2514 player->hud.push_back(e);
2516 player->hud[id] = e;
2518 delete event.hudadd.pos;
2519 delete event.hudadd.name;
2520 delete event.hudadd.scale;
2521 delete event.hudadd.text;
2522 delete event.hudadd.align;
2523 delete event.hudadd.offset;
2524 delete event.hudadd.world_pos;
2526 else if (event.type == CE_HUDRM)
2528 u32 id = event.hudrm.id;
2529 if (id < player->hud.size() && player->hud[id]) {
2530 delete player->hud[id];
2531 player->hud[id] = NULL;
2534 else if (event.type == CE_HUDCHANGE)
2536 u32 id = event.hudchange.id;
2537 if (id >= player->hud.size() || !player->hud[id]) {
2538 delete event.hudchange.v3fdata;
2539 delete event.hudchange.v2fdata;
2540 delete event.hudchange.sdata;
2544 HudElement* e = player->hud[id];
2545 switch (event.hudchange.stat) {
2547 e->pos = *event.hudchange.v2fdata;
2550 e->name = *event.hudchange.sdata;
2552 case HUD_STAT_SCALE:
2553 e->scale = *event.hudchange.v2fdata;
2556 e->text = *event.hudchange.sdata;
2558 case HUD_STAT_NUMBER:
2559 e->number = event.hudchange.data;
2562 e->item = event.hudchange.data;
2565 e->dir = event.hudchange.data;
2567 case HUD_STAT_ALIGN:
2568 e->align = *event.hudchange.v2fdata;
2570 case HUD_STAT_OFFSET:
2571 e->offset = *event.hudchange.v2fdata;
2573 case HUD_STAT_WORLD_POS:
2574 e->world_pos = *event.hudchange.v3fdata;
2578 delete event.hudchange.v3fdata;
2579 delete event.hudchange.v2fdata;
2580 delete event.hudchange.sdata;
2582 else if (event.type == CE_SET_SKY)
2584 sky->setVisible(false);
2589 // Handle according to type
2590 if(*event.set_sky.type == "regular"){
2591 sky->setVisible(true);
2593 else if(*event.set_sky.type == "skybox" &&
2594 event.set_sky.params->size() == 6){
2595 sky->setFallbackBgColor(*event.set_sky.bgcolor);
2596 skybox = smgr->addSkyBoxSceneNode(
2597 tsrc->getTexture((*event.set_sky.params)[0]),
2598 tsrc->getTexture((*event.set_sky.params)[1]),
2599 tsrc->getTexture((*event.set_sky.params)[2]),
2600 tsrc->getTexture((*event.set_sky.params)[3]),
2601 tsrc->getTexture((*event.set_sky.params)[4]),
2602 tsrc->getTexture((*event.set_sky.params)[5]));
2604 // Handle everything else as plain color
2606 if(*event.set_sky.type != "plain")
2607 infostream<<"Unknown sky type: "
2608 <<(*event.set_sky.type)<<std::endl;
2609 sky->setFallbackBgColor(*event.set_sky.bgcolor);
2612 delete event.set_sky.bgcolor;
2613 delete event.set_sky.type;
2614 delete event.set_sky.params;
2616 else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO)
2618 bool enable = event.override_day_night_ratio.do_override;
2619 u32 value = event.override_day_night_ratio.ratio_f * 1000;
2620 client.getEnv().setDayNightRatioOverride(enable, value);
2625 //TimeTaker //timer2("//timer2");
2628 For interaction purposes, get info about the held item
2630 - Is it a usable item?
2631 - Can it point to liquids?
2633 ItemStack playeritem;
2635 InventoryList *mlist = local_inventory.getList("main");
2638 playeritem = mlist->getItem(client.getPlayerItem());
2641 const ItemDefinition &playeritem_def =
2642 playeritem.getDefinition(itemdef);
2643 ToolCapabilities playeritem_toolcap =
2644 playeritem.getToolCapabilities(itemdef);
2650 v3s16 old_camera_offset = camera.getOffset();
2652 LocalPlayer* player = client.getEnv().getLocalPlayer();
2653 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2654 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
2656 if(input->wasKeyDown(getKeySetting("keymap_camera_mode"))) {
2658 if (current_camera_mode == CAMERA_MODE_FIRST)
2659 current_camera_mode = CAMERA_MODE_THIRD;
2660 else if (current_camera_mode == CAMERA_MODE_THIRD)
2661 current_camera_mode = CAMERA_MODE_THIRD_FRONT;
2663 current_camera_mode = CAMERA_MODE_FIRST;
2666 player->camera_mode = current_camera_mode;
2667 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2668 camera.update(player, dtime, busytime, screensize, tool_reload_ratio,
2669 current_camera_mode, client.getEnv());
2672 v3f player_position = player->getPosition();
2673 v3f camera_position = camera.getPosition();
2674 v3f camera_direction = camera.getDirection();
2675 f32 camera_fov = camera.getFovMax();
2676 v3s16 camera_offset = camera.getOffset();
2678 bool camera_offset_changed = (camera_offset != old_camera_offset);
2680 if(!disable_camera_update){
2681 client.getEnv().getClientMap().updateCamera(camera_position,
2682 camera_direction, camera_fov, camera_offset);
2683 if (camera_offset_changed){
2684 client.updateCameraOffset(camera_offset);
2685 client.getEnv().updateCameraOffset(camera_offset);
2687 clouds->updateCameraOffset(camera_offset);
2691 // Update sound listener
2692 sound->updateListener(camera.getCameraNode()->getPosition()+intToFloat(camera_offset, BS),
2693 v3f(0,0,0), // velocity
2694 camera.getDirection(),
2695 camera.getCameraNode()->getUpVector());
2696 sound->setListenerGain(g_settings->getFloat("sound_volume"));
2702 soundmaker.step(dtime);
2704 ClientMap &map = client.getEnv().getClientMap();
2705 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
2706 soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
2710 Calculate what block is the crosshair pointing to
2713 //u32 t1 = device->getTimer()->getRealTime();
2715 f32 d = playeritem_def.range; // max. distance
2716 f32 d_hand = itemdef->get("").range;
2717 if(d < 0 && d_hand >= 0)
2721 core::line3d<f32> shootline(camera_position,
2722 camera_position + camera_direction * BS * (d+1));
2724 // prevent player pointing anything in front-view
2725 if (current_camera_mode == CAMERA_MODE_THIRD_FRONT)
2726 shootline = core::line3d<f32>(0,0,0,0,0,0);
2728 ClientActiveObject *selected_object = NULL;
2730 PointedThing pointed = getPointedThing(
2732 &client, player_position, camera_direction,
2733 camera_position, shootline, d,
2734 playeritem_def.liquids_pointable, !ldown_for_dig,
2740 if(pointed != pointed_old)
2742 infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2743 //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
2748 - releasing left mouse button
2749 - pointing away from node
2753 if(input->getLeftReleased())
2755 infostream<<"Left button released"
2756 <<" (stopped digging)"<<std::endl;
2759 else if(pointed != pointed_old)
2761 if (pointed.type == POINTEDTHING_NODE
2762 && pointed_old.type == POINTEDTHING_NODE
2763 && pointed.node_undersurface == pointed_old.node_undersurface)
2765 // Still pointing to the same node,
2766 // but a different face. Don't reset.
2770 infostream<<"Pointing away from node"
2771 <<" (stopped digging)"<<std::endl;
2777 client.interact(1, pointed_old);
2778 client.setCrack(-1, v3s16(0,0,0));
2782 if(!digging && ldown_for_dig && !input->getLeftState())
2784 ldown_for_dig = false;
2787 bool left_punch = false;
2788 soundmaker.m_player_leftpunch_sound.name = "";
2790 if(input->getRightState())
2791 repeat_rightclick_timer += dtime;
2793 repeat_rightclick_timer = 0;
2795 if(playeritem_def.usable && input->getLeftState())
2797 if(input->getLeftClicked())
2798 client.interact(4, pointed);
2800 else if(pointed.type == POINTEDTHING_NODE)
2802 v3s16 nodepos = pointed.node_undersurface;
2803 v3s16 neighbourpos = pointed.node_abovesurface;
2806 Check information text of node
2809 ClientMap &map = client.getEnv().getClientMap();
2810 NodeMetadata *meta = map.getNodeMetadata(nodepos);
2812 infotext = narrow_to_wide(meta->getString("infotext"));
2814 MapNode n = map.getNode(nodepos);
2815 if(nodedef->get(n).tiledef[0].name == "unknown_node.png"){
2816 infotext = L"Unknown node: ";
2817 infotext += narrow_to_wide(nodedef->get(n).name);
2825 if(nodig_delay_timer <= 0.0 && input->getLeftState()
2826 && client.checkPrivilege("interact"))
2830 infostream<<"Started digging"<<std::endl;
2831 client.interact(0, pointed);
2833 ldown_for_dig = true;
2835 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2837 // NOTE: Similar piece of code exists on the server side for
2839 // Get digging parameters
2840 DigParams params = getDigParams(nodedef->get(n).groups,
2841 &playeritem_toolcap);
2842 // If can't dig, try hand
2843 if(!params.diggable){
2844 const ItemDefinition &hand = itemdef->get("");
2845 const ToolCapabilities *tp = hand.tool_capabilities;
2847 params = getDigParams(nodedef->get(n).groups, tp);
2850 float dig_time_complete = 0.0;
2852 if(params.diggable == false)
2854 // I guess nobody will wait for this long
2855 dig_time_complete = 10000000.0;
2859 dig_time_complete = params.time;
2860 if (g_settings->getBool("enable_particles"))
2862 const ContentFeatures &features =
2863 client.getNodeDefManager()->get(n);
2864 addPunchingParticles
2865 (gamedef, smgr, player, client.getEnv(),
2866 nodepos, features.tiles);
2870 if(dig_time_complete >= 0.001)
2872 dig_index = (u16)((float)crack_animation_length
2873 * dig_time/dig_time_complete);
2875 // This is for torches
2878 dig_index = crack_animation_length;
2881 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2882 if(sound_dig.exists() && params.diggable){
2883 if(sound_dig.name == "__group"){
2884 if(params.main_group != ""){
2885 soundmaker.m_player_leftpunch_sound.gain = 0.5;
2886 soundmaker.m_player_leftpunch_sound.name =
2887 std::string("default_dig_") +
2891 soundmaker.m_player_leftpunch_sound = sound_dig;
2895 // Don't show cracks if not diggable
2896 if(dig_time_complete >= 100000.0)
2899 else if(dig_index < crack_animation_length)
2901 //TimeTaker timer("client.setTempMod");
2902 //infostream<<"dig_index="<<dig_index<<std::endl;
2903 client.setCrack(dig_index, nodepos);
2907 infostream<<"Digging completed"<<std::endl;
2908 client.interact(2, pointed);
2909 client.setCrack(-1, v3s16(0,0,0));
2910 MapNode wasnode = map.getNode(nodepos);
2911 client.removeNode(nodepos);
2913 if (g_settings->getBool("enable_particles"))
2915 const ContentFeatures &features =
2916 client.getNodeDefManager()->get(wasnode);
2918 (gamedef, smgr, player, client.getEnv(),
2919 nodepos, features.tiles);
2925 nodig_delay_timer = dig_time_complete
2926 / (float)crack_animation_length;
2928 // We don't want a corresponding delay to
2929 // very time consuming nodes
2930 if(nodig_delay_timer > 0.3)
2931 nodig_delay_timer = 0.3;
2932 // We want a slight delay to very little
2933 // time consuming nodes
2934 float mindelay = 0.15;
2935 if(nodig_delay_timer < mindelay)
2936 nodig_delay_timer = mindelay;
2938 // Send event to trigger sound
2939 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
2940 gamedef->event()->put(e);
2943 if(dig_time_complete < 100000.0)
2947 client.setCrack(-1, nodepos);
2950 camera.setDigging(0); // left click animation
2953 if((input->getRightClicked() ||
2954 repeat_rightclick_timer >=
2955 g_settings->getFloat("repeat_rightclick_time")) &&
2956 client.checkPrivilege("interact"))
2958 repeat_rightclick_timer = 0;
2959 infostream<<"Ground right-clicked"<<std::endl;
2961 // Sign special case, at least until formspec is properly implemented.
2963 if(meta && meta->getString("formspec") == "hack:sign_text_input"
2965 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2967 infostream<<"Launching metadata text input"<<std::endl;
2969 // Get a new text for it
2971 TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2973 std::wstring wtext = narrow_to_wide(meta->getString("text"));
2975 (new GUITextInputMenu(guienv, guiroot, -1,
2979 // If metadata provides an inventory view, activate it
2980 else if(meta && meta->getString("formspec") != "" && !random_input
2981 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2983 infostream<<"Launching custom inventory view"<<std::endl;
2985 InventoryLocation inventoryloc;
2986 inventoryloc.setNodeMeta(nodepos);
2990 GUIFormSpecMenu *menu =
2991 new GUIFormSpecMenu(device, guiroot, -1,
2993 &client, gamedef, tsrc);
2994 menu->doPause = false;
2995 menu->setFormSpec(meta->getString("formspec"),
2997 menu->setFormSource(new NodeMetadataFormSource(
2998 &client.getEnv().getClientMap(), nodepos));
2999 menu->setTextDest(new TextDestNodeMetadata(nodepos, &client));
3002 // Otherwise report right click to server
3005 camera.setDigging(1); // right click animation (always shown for feedback)
3007 // If the wielded item has node placement prediction,
3009 bool placed = nodePlacementPrediction(client,
3011 nodepos, neighbourpos);
3015 client.interact(3, pointed);
3017 soundmaker.m_player_rightpunch_sound =
3018 playeritem_def.sound_place;
3020 soundmaker.m_player_rightpunch_sound =
3024 if (playeritem_def.node_placement_prediction == "" ||
3025 nodedef->get(map.getNode(nodepos)).rightclickable)
3026 client.interact(3, pointed); // Report to server
3030 else if(pointed.type == POINTEDTHING_OBJECT)
3032 infotext = narrow_to_wide(selected_object->infoText());
3034 if(infotext == L"" && show_debug){
3035 infotext = narrow_to_wide(selected_object->debugInfoText());
3038 //if(input->getLeftClicked())
3039 if(input->getLeftState())
3041 bool do_punch = false;
3042 bool do_punch_damage = false;
3043 if(object_hit_delay_timer <= 0.0){
3045 do_punch_damage = true;
3046 object_hit_delay_timer = object_hit_delay;
3048 if(input->getLeftClicked()){
3052 infostream<<"Left-clicked object"<<std::endl;
3055 if(do_punch_damage){
3056 // Report direct punch
3057 v3f objpos = selected_object->getPosition();
3058 v3f dir = (objpos - player_position).normalize();
3060 bool disable_send = selected_object->directReportPunch(
3061 dir, &playeritem, time_from_last_punch);
3062 time_from_last_punch = 0;
3064 client.interact(0, pointed);
3067 else if(input->getRightClicked())
3069 infostream<<"Right-clicked object"<<std::endl;
3070 client.interact(3, pointed); // place
3073 else if(input->getLeftState())
3075 // When button is held down in air, show continuous animation
3079 pointed_old = pointed;
3081 if(left_punch || input->getLeftClicked())
3083 camera.setDigging(0); // left click animation
3086 input->resetLeftClicked();
3087 input->resetRightClicked();
3089 input->resetLeftReleased();
3090 input->resetRightReleased();
3093 Calculate stuff for drawing
3100 if(draw_control.range_all)
3101 fog_range = 100000*BS;
3103 fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
3104 fog_range = MYMIN(fog_range, (draw_control.farthest_drawn+20)*BS);
3109 Calculate general brightness
3111 u32 daynight_ratio = client.getEnv().getDayNightRatio();
3112 float time_brightness = decode_light_f((float)daynight_ratio/1000.0);
3113 float direct_brightness = 0;
3114 bool sunlight_seen = false;
3115 if(g_settings->getBool("free_move")){
3116 direct_brightness = time_brightness;
3117 sunlight_seen = true;
3119 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3120 float old_brightness = sky->getBrightness();
3121 direct_brightness = (float)client.getEnv().getClientMap()
3122 .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
3123 daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
3127 time_of_day = client.getEnv().getTimeOfDayF();
3129 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
3130 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3131 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3132 time_of_day_smooth = time_of_day;
3134 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
3135 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
3136 + (time_of_day+1.0) * todsm;
3138 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
3139 + time_of_day * todsm;
3141 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3144 video::SColor bgcolor = sky->getBgColor();
3145 video::SColor skycolor = sky->getSkyColor();
3151 if(sky->getCloudsVisible()){
3152 clouds->setVisible(true);
3153 clouds->step(dtime);
3154 clouds->update(v2f(player_position.X, player_position.Z),
3155 sky->getCloudColor());
3157 clouds->setVisible(false);
3165 allparticles_step(dtime);
3166 allparticlespawners_step(dtime, client.getEnv());
3172 if(g_settings->getBool("enable_fog") && !force_fog_off)
3176 video::EFT_FOG_LINEAR,
3188 video::EFT_FOG_LINEAR,
3198 Update gui stuff (0ms)
3201 //TimeTaker guiupdatetimer("Gui updating");
3205 static float drawtime_avg = 0;
3206 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
3207 /*static float beginscenetime_avg = 0;
3208 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
3209 static float scenetime_avg = 0;
3210 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
3211 static float endscenetime_avg = 0;
3212 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
3214 u16 fps = (1.0/dtime_avg1);
3216 std::ostringstream os(std::ios_base::binary);
3218 <<"Minetest "<<minetest_version_hash
3220 <<" (R: range_all="<<draw_control.range_all<<")"
3221 <<std::setprecision(0)
3222 <<" drawtime = "<<drawtime_avg
3223 <<std::setprecision(1)
3224 <<", dtime_jitter = "
3225 <<(dtime_jitter1_max_fraction * 100.0)<<" %"
3226 <<std::setprecision(1)
3227 <<", v_range = "<<draw_control.wanted_range
3228 <<std::setprecision(3)
3229 <<", RTT = "<<client.getRTT();
3230 guitext->setText(narrow_to_wide(os.str()).c_str());
3231 guitext->setVisible(true);
3233 else if(show_hud || show_chat)
3235 std::ostringstream os(std::ios_base::binary);
3236 os<<"Minetest "<<minetest_version_hash;
3237 guitext->setText(narrow_to_wide(os.str()).c_str());
3238 guitext->setVisible(true);
3242 guitext->setVisible(false);
3247 std::ostringstream os(std::ios_base::binary);
3248 os<<std::setprecision(1)<<std::fixed
3249 <<"(" <<(player_position.X/BS)
3250 <<", "<<(player_position.Y/BS)
3251 <<", "<<(player_position.Z/BS)
3252 <<") (yaw="<<(wrapDegrees_0_360(camera_yaw))
3253 <<") (seed = "<<((u64)client.getMapSeed())
3255 guitext2->setText(narrow_to_wide(os.str()).c_str());
3256 guitext2->setVisible(true);
3260 guitext2->setVisible(false);
3264 guitext_info->setText(infotext.c_str());
3265 guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
3269 float statustext_time_max = 1.5;
3270 if(!statustext.empty())
3272 statustext_time += dtime;
3273 if(statustext_time >= statustext_time_max)
3276 statustext_time = 0;
3279 guitext_status->setText(statustext.c_str());
3280 guitext_status->setVisible(!statustext.empty());
3282 if(!statustext.empty())
3284 s32 status_y = screensize.Y - 130;
3285 core::rect<s32> rect(
3287 status_y - guitext_status->getTextHeight(),
3291 guitext_status->setRelativePosition(rect);
3294 video::SColor initial_color(255,0,0,0);
3295 if(guienv->getSkin())
3296 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
3297 video::SColor final_color = initial_color;
3298 final_color.setAlpha(0);
3299 video::SColor fade_color =
3300 initial_color.getInterpolated_quadratic(
3303 pow(statustext_time / (float)statustext_time_max, 2.0f));
3304 guitext_status->setOverrideColor(fade_color);
3305 guitext_status->enableOverrideColor(true);
3310 Get chat messages from client
3313 // Get new messages from error log buffer
3314 while(!chat_log_error_buf.empty())
3316 chat_backend.addMessage(L"", narrow_to_wide(
3317 chat_log_error_buf.get()));
3319 // Get new messages from client
3320 std::wstring message;
3321 while(client.getChatMessage(message))
3323 chat_backend.addUnparsedMessage(message);
3325 // Remove old messages
3326 chat_backend.step(dtime);
3328 // Display all messages in a static text element
3329 u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
3330 std::wstring recent_chat = chat_backend.getRecentChat();
3331 guitext_chat->setText(recent_chat.c_str());
3333 // Update gui element size and position
3334 s32 chat_y = 5+(text_height+5);
3336 chat_y += (text_height+5);
3337 core::rect<s32> rect(
3341 chat_y + guitext_chat->getTextHeight()
3343 guitext_chat->setRelativePosition(rect);
3345 // Don't show chat if disabled or empty or profiler is enabled
3346 guitext_chat->setVisible(show_chat && recent_chat_count != 0
3354 if(client.getPlayerItem() != new_playeritem)
3356 client.selectPlayerItem(new_playeritem);
3358 if(client.getLocalInventoryUpdated())
3360 //infostream<<"Updating local inventory"<<std::endl;
3361 client.getLocalInventory(local_inventory);
3363 update_wielded_item_trigger = true;
3365 if(update_wielded_item_trigger)
3367 update_wielded_item_trigger = false;
3368 // Update wielded tool
3369 InventoryList *mlist = local_inventory.getList("main");
3372 item = mlist->getItem(client.getPlayerItem());
3373 camera.wield(item, client.getPlayerItem());
3377 Update block draw list every 200ms or when camera direction has
3380 update_draw_list_timer += dtime;
3381 if(update_draw_list_timer >= 0.2 ||
3382 update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2 ||
3383 camera_offset_changed){
3384 update_draw_list_timer = 0;
3385 client.getEnv().getClientMap().updateDrawList(driver);
3386 update_draw_list_last_cam_dir = camera_direction;
3393 TimeTaker tt_draw("mainloop: draw");
3396 TimeTaker timer("beginScene");
3397 //driver->beginScene(false, true, bgcolor);
3398 //driver->beginScene(true, true, bgcolor);
3399 driver->beginScene(true, true, skycolor);
3400 beginscenetime = timer.stop(true);
3405 //infostream<<"smgr->drawAll()"<<std::endl;
3407 TimeTaker timer("smgr");
3410 if(g_settings->getBool("anaglyph"))
3412 irr::core::vector3df oldPosition = camera.getCameraNode()->getPosition();
3413 irr::core::vector3df oldTarget = camera.getCameraNode()->getTarget();
3415 irr::core::matrix4 startMatrix = camera.getCameraNode()->getAbsoluteTransformation();
3417 irr::core::vector3df focusPoint = (camera.getCameraNode()->getTarget() -
3418 camera.getCameraNode()->getAbsolutePosition()).setLength(1) +
3419 camera.getCameraNode()->getAbsolutePosition() ;
3422 irr::core::vector3df leftEye;
3423 irr::core::matrix4 leftMove;
3425 leftMove.setTranslation( irr::core::vector3df(-g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
3426 leftEye=(startMatrix*leftMove).getTranslation();
3428 //clear the depth buffer, and color
3429 driver->beginScene( true, true, irr::video::SColor(0,200,200,255) );
3431 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_RED;
3432 driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK;
3433 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
3434 irr::scene::ESNRP_SOLID +
3435 irr::scene::ESNRP_TRANSPARENT +
3436 irr::scene::ESNRP_TRANSPARENT_EFFECT +
3437 irr::scene::ESNRP_SHADOW;
3439 camera.getCameraNode()->setPosition( leftEye );
3440 camera.getCameraNode()->setTarget( focusPoint );
3442 smgr->drawAll(); // 'smgr->drawAll();' may go here
3444 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
3447 hud.drawSelectionBoxes(hilightboxes);
3451 irr::core::vector3df rightEye;
3452 irr::core::matrix4 rightMove;
3454 rightMove.setTranslation( irr::core::vector3df(g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
3455 rightEye=(startMatrix*rightMove).getTranslation();
3457 //clear the depth buffer
3458 driver->clearZBuffer();
3460 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_GREEN + irr::video::ECP_BLUE;
3461 driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK;
3462 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
3463 irr::scene::ESNRP_SOLID +
3464 irr::scene::ESNRP_TRANSPARENT +
3465 irr::scene::ESNRP_TRANSPARENT_EFFECT +
3466 irr::scene::ESNRP_SHADOW;
3468 camera.getCameraNode()->setPosition( rightEye );
3469 camera.getCameraNode()->setTarget( focusPoint );
3471 smgr->drawAll(); // 'smgr->drawAll();' may go here
3473 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
3476 hud.drawSelectionBoxes(hilightboxes);
3479 //driver->endScene();
3481 driver->getOverrideMaterial().Material.ColorMask=irr::video::ECP_ALL;
3482 driver->getOverrideMaterial().EnableFlags=0;
3483 driver->getOverrideMaterial().EnablePasses=0;
3485 camera.getCameraNode()->setPosition( oldPosition );
3486 camera.getCameraNode()->setTarget( oldTarget );
3489 scenetime = timer.stop(true);
3493 //TimeTaker timer9("auxiliary drawings");
3497 //TimeTaker //timer10("//timer10");
3503 driver->setMaterial(m);
3505 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
3506 if((!g_settings->getBool("anaglyph")) && (show_hud))
3508 hud.drawSelectionBoxes(hilightboxes);
3515 (player->hud_flags & HUD_FLAG_WIELDITEM_VISIBLE) &&
3516 current_camera_mode < CAMERA_MODE_THIRD)
3518 // Warning: This clears the Z buffer.
3519 camera.drawWieldedTool();
3526 client.getEnv().getClientMap().renderPostFx();
3532 if(show_profiler_graph)
3534 graph.draw(10, screensize.Y - 10, driver, font);
3541 hud.drawCrosshair();
3546 //TimeTaker //timer11("//timer11");
3554 hud.drawHotbar(v2s32(displaycenter.X, screensize.Y),
3555 client.getHP(), client.getPlayerItem(), client.getBreath());
3561 if(damage_flash > 0.0)
3563 video::SColor color(std::min(damage_flash, 180.0f),180,0,0);
3564 driver->draw2DRectangle(color,
3565 core::rect<s32>(0,0,screensize.X,screensize.Y),
3568 damage_flash -= 100.0*dtime;
3574 if(player->hurt_tilt_timer > 0.0)
3576 player->hurt_tilt_timer -= dtime*5;
3577 if(player->hurt_tilt_timer < 0)
3578 player->hurt_tilt_strength = 0;
3585 hud.drawLuaElements();
3597 TimeTaker timer("endScene");
3599 endscenetime = timer.stop(true);
3602 drawtime = tt_draw.stop(true);
3603 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
3610 Log times and stuff for visualization
3612 Profiler::GraphValues values;
3613 g_profiler->graphGet(values);
3622 if (gui_chat_console)
3623 gui_chat_console->drop();
3629 Draw a "shutting down" screen, which will be shown while the map
3630 generator and other stuff quits
3633 /*gui::IGUIStaticText *gui_shuttingdowntext = */
3634 wchar_t* text = wgettext("Shutting down stuff...");
3635 draw_load_screen(text, device, font, 0, -1, false);
3637 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
3640 gui_shuttingdowntext->remove();*/
3643 chat_backend.addMessage(L"", L"# Disconnected.");
3644 chat_backend.addMessage(L"", L"");
3648 //force answer all texture and shader jobs (TODO return empty values)
3650 while(!client.isShutdown()) {
3651 tsrc->processQueue();
3652 shsrc->processQueue();
3656 // Client scope (client is destructed before destructing *def and tsrc)
3659 catch(SerializationError &e)
3661 error_message = L"A serialization error occurred:\n"
3662 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
3663 L" running a different version of Minetest.";
3664 errorstream<<wide_to_narrow(error_message)<<std::endl;
3666 catch(ServerError &e) {
3667 error_message = narrow_to_wide(e.what());
3668 errorstream << "ServerError: " << e.what() << std::endl;
3670 catch(ModError &e) {
3671 errorstream << "ModError: " << e.what() << std::endl;
3672 error_message = narrow_to_wide(e.what()) + wgettext("\nCheck debug.txt for details.");
3680 //has to be deleted first to stop all server threads
3688 //extended resource accounting
3689 infostream << "Irrlicht resources after cleanup:" << std::endl;
3690 infostream << "\tRemaining meshes : "
3691 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
3692 infostream << "\tRemaining textures : "
3693 << driver->getTextureCount() << std::endl;
3694 for (unsigned int i = 0; i < driver->getTextureCount(); i++ ) {
3695 irr::video::ITexture* texture = driver->getTextureByIndex(i);
3696 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
3699 clearTextureNameCache();
3700 infostream << "\tRemaining materials: "
3701 << driver-> getMaterialRendererCount ()
3702 << " (note: irrlicht doesn't support removing renderers)"<< std::endl;