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 "bgcolor[#320000b4;true]"
999 "label[4.85,1.35;You died.]"
1000 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
1004 /* Note: FormspecFormSource and LocalFormspecHandler
1005 * are deleted by guiFormSpecMenu */
1006 current_formspec = new FormspecFormSource(formspec,¤t_formspec);
1007 current_textdest = new LocalFormspecHandler("MT_DEATH_SCREEN",client);
1008 GUIFormSpecMenu *menu =
1009 new GUIFormSpecMenu(device, guiroot, -1,
1012 menu->doPause = false;
1013 menu->setFormSource(current_formspec);
1014 menu->setTextDest(current_textdest);
1018 /******************************************************************************/
1019 static void show_pause_menu(FormspecFormSource* current_formspec,
1020 TextDest* current_textdest, IWritableTextureSource* tsrc,
1021 IrrlichtDevice * device, bool singleplayermode)
1024 std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1026 "- Space: jump/climb\n"
1027 "- Shift: sneak/go down\n"
1030 "- Mouse: turn/look\n"
1031 "- Mouse left: dig/punch\n"
1032 "- Mouse right: place/use\n"
1033 "- Mouse wheel: select item\n"
1037 float ypos = singleplayermode ? 1.0 : 0.5;
1038 std::ostringstream os;
1040 os << "size[11,5.5,true]"
1041 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1042 << wide_to_narrow(wstrgettext("Continue")) << "]";
1044 if (!singleplayermode) {
1045 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1046 << wide_to_narrow(wstrgettext("Change Password")) << "]";
1049 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1050 << wide_to_narrow(wstrgettext("Sound Volume")) << "]";
1051 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1052 << wide_to_narrow(wstrgettext("Exit to Menu")) << "]";
1053 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1054 << wide_to_narrow(wstrgettext("Exit to OS")) << "]"
1055 << "textarea[7.5,0.25;3.75,6;;" << control_text << ";]"
1056 << "textarea[0.4,0.25;3.5,6;;" << "Minetest\n"
1057 << minetest_build_info << "\n"
1058 << "path_user = " << wrap_rows(porting::path_user, 20)
1062 /* Note: FormspecFormSource and LocalFormspecHandler *
1063 * are deleted by guiFormSpecMenu */
1064 current_formspec = new FormspecFormSource(os.str(),¤t_formspec);
1065 current_textdest = new LocalFormspecHandler("MT_PAUSE_MENU");
1066 GUIFormSpecMenu *menu =
1067 new GUIFormSpecMenu(device, guiroot, -1, &g_menumgr, NULL, NULL, tsrc);
1068 menu->doPause = true;
1069 menu->setFormSource(current_formspec);
1070 menu->setTextDest(current_textdest);
1074 /******************************************************************************/
1075 void the_game(bool &kill, bool random_input, InputHandler *input,
1076 IrrlichtDevice *device, gui::IGUIFont* font, std::string map_dir,
1077 std::string playername, std::string password,
1078 std::string address /* If "", local server is used */,
1079 u16 port, std::wstring &error_message, ChatBackend &chat_backend,
1080 const SubgameSpec &gamespec /* Used for local game */,
1081 bool simple_singleplayer_mode)
1083 FormspecFormSource* current_formspec = 0;
1084 TextDest* current_textdest = 0;
1085 video::IVideoDriver* driver = device->getVideoDriver();
1086 scene::ISceneManager* smgr = device->getSceneManager();
1088 // Calculate text height using the font
1089 u32 text_height = font->getDimension(L"Random test string").Height;
1091 v2u32 last_screensize(0,0);
1092 v2u32 screensize = driver->getScreenSize();
1095 Draw "Loading" screen
1099 wchar_t* text = wgettext("Loading...");
1100 draw_load_screen(text, device, font,0,0);
1104 // Create texture source
1105 IWritableTextureSource *tsrc = createTextureSource(device);
1107 // Create shader source
1108 IWritableShaderSource *shsrc = createShaderSource(device);
1110 // These will be filled by data received from the server
1111 // Create item definition manager
1112 IWritableItemDefManager *itemdef = createItemDefManager();
1113 // Create node definition manager
1114 IWritableNodeDefManager *nodedef = createNodeDefManager();
1116 // Sound fetcher (useful when testing)
1117 GameOnDemandSoundFetcher soundfetcher;
1120 ISoundManager *sound = NULL;
1121 bool sound_is_dummy = false;
1123 if(g_settings->getBool("enable_sound")){
1124 infostream<<"Attempting to use OpenAL audio"<<std::endl;
1125 sound = createOpenALSoundManager(&soundfetcher);
1127 infostream<<"Failed to initialize OpenAL audio"<<std::endl;
1129 infostream<<"Sound disabled."<<std::endl;
1133 infostream<<"Using dummy audio."<<std::endl;
1134 sound = &dummySoundManager;
1135 sound_is_dummy = true;
1138 Server *server = NULL;
1142 EventManager eventmgr;
1145 SoundMaker soundmaker(sound, nodedef);
1146 soundmaker.registerReceiver(&eventmgr);
1148 // Add chat log output for errors to be shown in chat
1149 LogOutputBuffer chat_log_error_buf(LMT_ERROR);
1151 // Create UI for modifying quicktune values
1152 QuicktuneShortcutter quicktune;
1159 wchar_t* text = wgettext("Creating server....");
1160 draw_load_screen(text, device, font,0,25);
1162 infostream<<"Creating server"<<std::endl;
1164 std::string bind_str = g_settings->get("bind_address");
1165 Address bind_addr(0,0,0,0, port);
1167 if (g_settings->getBool("ipv6_server")) {
1168 bind_addr.setAddress((IPv6AddressBytes*) NULL);
1171 bind_addr.Resolve(bind_str.c_str());
1173 } catch (ResolveError &e) {
1174 infostream << "Resolving bind address \"" << bind_str
1175 << "\" failed: " << e.what()
1176 << " -- Listening on all addresses." << std::endl;
1179 if(bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1180 error_message = L"Unable to listen on " +
1181 narrow_to_wide(bind_addr.serializeString()) +
1182 L" because IPv6 is disabled";
1183 errorstream<<wide_to_narrow(error_message)<<std::endl;
1184 // Break out of client scope
1188 server = new Server(map_dir, gamespec,
1189 simple_singleplayer_mode,
1190 bind_addr.isIPv6());
1192 server->start(bind_addr);
1195 do{ // Client scope (breakable do-while(0))
1202 wchar_t* text = wgettext("Creating client...");
1203 draw_load_screen(text, device, font,0,50);
1206 infostream<<"Creating client"<<std::endl;
1208 MapDrawControl draw_control;
1211 wchar_t* text = wgettext("Resolving address...");
1212 draw_load_screen(text, device, font,0,75);
1215 Address connect_address(0,0,0,0, port);
1217 connect_address.Resolve(address.c_str());
1218 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
1219 //connect_address.Resolve("localhost");
1220 if (connect_address.isIPv6()) {
1221 IPv6AddressBytes addr_bytes;
1222 addr_bytes.bytes[15] = 1;
1223 connect_address.setAddress(&addr_bytes);
1225 connect_address.setAddress(127,0,0,1);
1229 catch(ResolveError &e) {
1230 error_message = L"Couldn't resolve address: " + narrow_to_wide(e.what());
1231 errorstream<<wide_to_narrow(error_message)<<std::endl;
1232 // Break out of client scope
1235 if(connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1236 error_message = L"Unable to connect to " +
1237 narrow_to_wide(connect_address.serializeString()) +
1238 L" because IPv6 is disabled";
1239 errorstream<<wide_to_narrow(error_message)<<std::endl;
1240 // Break out of client scope
1247 Client client(device, playername.c_str(), password, draw_control,
1248 tsrc, shsrc, itemdef, nodedef, sound, &eventmgr,
1249 connect_address.isIPv6());
1251 // Client acts as our GameDef
1252 IGameDef *gamedef = &client;
1255 Attempt to connect to the server
1258 infostream<<"Connecting to server at ";
1259 connect_address.print(&infostream);
1260 infostream<<std::endl;
1261 client.connect(connect_address);
1264 Wait for server to accept connection
1266 bool could_connect = false;
1267 bool connect_aborted = false;
1269 float time_counter = 0.0;
1271 float fps_max = g_settings->getFloat("fps_max");
1272 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1273 u32 lasttime = device->getTimer()->getTime();
1274 while(device->run())
1276 f32 dtime = 0.033; // in seconds
1277 if (cloud_menu_background) {
1278 u32 time = device->getTimer()->getTime();
1280 dtime = (time - lasttime) / 1000.0;
1285 // Update client and server
1288 server->step(dtime);
1291 if(client.getState() == LC_Init){
1292 could_connect = true;
1296 if(client.accessDenied()){
1297 error_message = L"Access denied. Reason: "
1298 +client.accessDeniedReason();
1299 errorstream<<wide_to_narrow(error_message)<<std::endl;
1302 if(input->wasKeyDown(EscapeKey)){
1303 connect_aborted = true;
1304 infostream<<"Connect aborted [Escape]"<<std::endl;
1310 wchar_t* text = wgettext("Connecting to server...");
1311 draw_load_screen(text, device, font, dtime, 100);
1315 // On some computers framerate doesn't seem to be
1316 // automatically limited
1317 if (cloud_menu_background) {
1318 // Time of frame without fps limit
1321 // not using getRealTime is necessary for wine
1322 u32 time = device->getTimer()->getTime();
1324 busytime_u32 = time - lasttime;
1327 busytime = busytime_u32 / 1000.0;
1330 u32 frametime_min = 1000./fps_max;
1332 if(busytime_u32 < frametime_min) {
1333 u32 sleeptime = frametime_min - busytime_u32;
1334 device->sleep(sleeptime);
1339 time_counter += dtime;
1342 catch(con::PeerNotFoundException &e)
1346 Handle failure to connect
1349 if(error_message == L"" && !connect_aborted){
1350 error_message = L"Connection failed";
1351 errorstream<<wide_to_narrow(error_message)<<std::endl;
1353 // Break out of client scope
1358 Wait until content has been received
1360 bool got_content = false;
1361 bool content_aborted = false;
1363 float time_counter = 0.0;
1365 float fps_max = g_settings->getFloat("fps_max");
1366 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1367 u32 lasttime = device->getTimer()->getTime();
1368 while(device->run())
1370 f32 dtime = 0.033; // in seconds
1371 if (cloud_menu_background) {
1372 u32 time = device->getTimer()->getTime();
1374 dtime = (time - lasttime) / 1000.0;
1379 // Update client and server
1382 server->step(dtime);
1385 if(client.mediaReceived() &&
1386 client.itemdefReceived() &&
1387 client.nodedefReceived()){
1392 if(client.accessDenied()){
1393 error_message = L"Access denied. Reason: "
1394 +client.accessDeniedReason();
1395 errorstream<<wide_to_narrow(error_message)<<std::endl;
1398 if(client.getState() < LC_Init){
1399 error_message = L"Client disconnected";
1400 errorstream<<wide_to_narrow(error_message)<<std::endl;
1403 if(input->wasKeyDown(EscapeKey)){
1404 content_aborted = true;
1405 infostream<<"Connect aborted [Escape]"<<std::endl;
1411 if (!client.itemdefReceived())
1413 wchar_t* text = wgettext("Item definitions...");
1415 draw_load_screen(text, device, font, dtime, progress);
1418 else if (!client.nodedefReceived())
1420 wchar_t* text = wgettext("Node definitions...");
1422 draw_load_screen(text, device, font, dtime, progress);
1427 wchar_t* text = wgettext("Media...");
1428 progress = 50+client.mediaReceiveProgress()*50+0.5;
1429 draw_load_screen(text, device, font, dtime, progress);
1433 // On some computers framerate doesn't seem to be
1434 // automatically limited
1435 if (cloud_menu_background) {
1436 // Time of frame without fps limit
1439 // not using getRealTime is necessary for wine
1440 u32 time = device->getTimer()->getTime();
1442 busytime_u32 = time - lasttime;
1445 busytime = busytime_u32 / 1000.0;
1448 u32 frametime_min = 1000./fps_max;
1450 if(busytime_u32 < frametime_min) {
1451 u32 sleeptime = frametime_min - busytime_u32;
1452 device->sleep(sleeptime);
1457 time_counter += dtime;
1462 if(error_message == L"" && !content_aborted){
1463 error_message = L"Something failed";
1464 errorstream<<wide_to_narrow(error_message)<<std::endl;
1466 // Break out of client scope
1471 After all content has been received:
1472 Update cached textures, meshes and materials
1474 client.afterContentReceived(device,font);
1477 Create the camera node
1479 Camera camera(smgr, draw_control, gamedef);
1480 if (!camera.successfullyCreated(error_message))
1483 f32 camera_yaw = 0; // "right/left"
1484 f32 camera_pitch = 0; // "up/down"
1486 int current_camera_mode = CAMERA_MODE_FIRST; // start in first-person view
1492 Clouds *clouds = NULL;
1493 if(g_settings->getBool("enable_clouds"))
1495 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1503 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, client.getEnv().getLocalPlayer());
1505 scene::ISceneNode* skybox = NULL;
1508 A copy of the local inventory
1510 Inventory local_inventory(itemdef);
1513 Find out size of crack animation
1515 int crack_animation_length = 5;
1517 video::ITexture *t = tsrc->getTexture("crack_anylength.png");
1518 v2u32 size = t->getOriginalSize();
1519 crack_animation_length = size.Y / size.X;
1526 // First line of debug text
1527 gui::IGUIStaticText *guitext = guienv->addStaticText(
1529 core::rect<s32>(5, 5, 795, 5+text_height),
1531 // Second line of debug text
1532 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1534 core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
1536 // At the middle of the screen
1537 // Object infos are shown in this
1538 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1540 core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1543 // Status text (displays info when showing and hiding GUI stuff, etc.)
1544 gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1546 core::rect<s32>(0,0,0,0),
1548 guitext_status->setVisible(false);
1550 std::wstring statustext;
1551 float statustext_time = 0;
1554 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1556 core::rect<s32>(0,0,0,0),
1557 //false, false); // Disable word wrap as of now
1559 // Remove stale "recent" chat messages from previous connections
1560 chat_backend.clearRecentChat();
1561 // Chat backend and console
1562 GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1564 // Profiler text (size is updated when text is updated)
1565 gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1567 core::rect<s32>(0,0,0,0),
1569 guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1570 guitext_profiler->setVisible(false);
1571 guitext_profiler->setWordWrap(true);
1574 Some statistics are collected in these
1577 u32 beginscenetime = 0;
1579 u32 endscenetime = 0;
1581 float recent_turn_speed = 0.0;
1583 ProfilerGraph graph;
1584 // Initially clear the profiler
1585 Profiler::GraphValues dummyvalues;
1586 g_profiler->graphGet(dummyvalues);
1588 float nodig_delay_timer = 0.0;
1589 float dig_time = 0.0;
1591 PointedThing pointed_old;
1592 bool digging = false;
1593 bool ldown_for_dig = false;
1595 float damage_flash = 0;
1597 float jump_timer = 0;
1598 bool reset_jump_timer = false;
1600 const float object_hit_delay = 0.2;
1601 float object_hit_delay_timer = 0.0;
1602 float time_from_last_punch = 10;
1604 float update_draw_list_timer = 0.0;
1605 v3f update_draw_list_last_cam_dir;
1607 bool invert_mouse = g_settings->getBool("invert_mouse");
1609 bool update_wielded_item_trigger = true;
1611 bool show_hud = true;
1612 bool show_chat = true;
1613 bool force_fog_off = false;
1614 f32 fog_range = 100*BS;
1615 bool disable_camera_update = false;
1616 bool show_debug = g_settings->getBool("show_debug");
1617 bool show_profiler_graph = false;
1618 u32 show_profiler = 0;
1619 u32 show_profiler_max = 3; // Number of pages
1621 float time_of_day = 0;
1622 float time_of_day_smooth = 0;
1624 float repeat_rightclick_timer = 0;
1629 shsrc->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1630 sky, &force_fog_off, &fog_range, &client));
1636 bool first_loop_after_window_activation = true;
1638 // TODO: Convert the static interval timers to these
1639 // Interval limiter for profiler
1640 IntervalLimiter m_profiler_interval;
1642 // Time is in milliseconds
1643 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1644 // NOTE: So we have to use getTime() and call run()s between them
1645 u32 lasttime = device->getTimer()->getTime();
1647 LocalPlayer* player = client.getEnv().getLocalPlayer();
1648 player->hurt_tilt_timer = 0;
1649 player->hurt_tilt_strength = 0;
1654 Hud hud(driver, smgr, guienv, font, text_height,
1655 gamedef, player, &local_inventory);
1657 core::stringw str = L"Minetest [";
1658 str += driver->getName();
1660 device->setWindowCaption(str.c_str());
1663 std::wstring infotext;
1667 if(device->run() == false || kill == true)
1670 // Time of frame without fps limit
1674 // not using getRealTime is necessary for wine
1675 u32 time = device->getTimer()->getTime();
1677 busytime_u32 = time - lasttime;
1680 busytime = busytime_u32 / 1000.0;
1683 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1685 // Necessary for device->getTimer()->getTime()
1693 float fps_max = g_menumgr.pausesGame() ?
1694 g_settings->getFloat("pause_fps_max") :
1695 g_settings->getFloat("fps_max");
1696 u32 frametime_min = 1000./fps_max;
1698 if(busytime_u32 < frametime_min)
1700 u32 sleeptime = frametime_min - busytime_u32;
1701 device->sleep(sleeptime);
1702 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1706 // Necessary for device->getTimer()->getTime()
1710 Time difference calculation
1712 f32 dtime; // in seconds
1714 u32 time = device->getTimer()->getTime();
1716 dtime = (time - lasttime) / 1000.0;
1721 g_profiler->graphAdd("mainloop_dtime", dtime);
1725 if(nodig_delay_timer >= 0)
1726 nodig_delay_timer -= dtime;
1727 if(object_hit_delay_timer >= 0)
1728 object_hit_delay_timer -= dtime;
1729 time_from_last_punch += dtime;
1731 g_profiler->add("Elapsed time", dtime);
1732 g_profiler->avg("FPS", 1./dtime);
1735 Time average and jitter calculation
1738 static f32 dtime_avg1 = 0.0;
1739 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1740 f32 dtime_jitter1 = dtime - dtime_avg1;
1742 static f32 dtime_jitter1_max_sample = 0.0;
1743 static f32 dtime_jitter1_max_fraction = 0.0;
1745 static f32 jitter1_max = 0.0;
1746 static f32 counter = 0.0;
1747 if(dtime_jitter1 > jitter1_max)
1748 jitter1_max = dtime_jitter1;
1753 dtime_jitter1_max_sample = jitter1_max;
1754 dtime_jitter1_max_fraction
1755 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1761 Busytime average and jitter calculation
1764 static f32 busytime_avg1 = 0.0;
1765 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1766 f32 busytime_jitter1 = busytime - busytime_avg1;
1768 static f32 busytime_jitter1_max_sample = 0.0;
1769 static f32 busytime_jitter1_min_sample = 0.0;
1771 static f32 jitter1_max = 0.0;
1772 static f32 jitter1_min = 0.0;
1773 static f32 counter = 0.0;
1774 if(busytime_jitter1 > jitter1_max)
1775 jitter1_max = busytime_jitter1;
1776 if(busytime_jitter1 < jitter1_min)
1777 jitter1_min = busytime_jitter1;
1781 busytime_jitter1_max_sample = jitter1_max;
1782 busytime_jitter1_min_sample = jitter1_min;
1789 Handle miscellaneous stuff
1792 if(client.accessDenied())
1794 error_message = L"Access denied. Reason: "
1795 +client.accessDeniedReason();
1796 errorstream<<wide_to_narrow(error_message)<<std::endl;
1800 if(g_gamecallback->disconnect_requested)
1802 g_gamecallback->disconnect_requested = false;
1806 if(g_gamecallback->changepassword_requested)
1808 (new GUIPasswordChange(guienv, guiroot, -1,
1809 &g_menumgr, &client))->drop();
1810 g_gamecallback->changepassword_requested = false;
1813 if(g_gamecallback->changevolume_requested)
1815 (new GUIVolumeChange(guienv, guiroot, -1,
1816 &g_menumgr, &client))->drop();
1817 g_gamecallback->changevolume_requested = false;
1820 /* Process TextureSource's queue */
1821 tsrc->processQueue();
1823 /* Process ItemDefManager's queue */
1824 itemdef->processQueue(gamedef);
1827 Process ShaderSource's queue
1829 shsrc->processQueue();
1834 last_screensize = screensize;
1835 screensize = driver->getScreenSize();
1836 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1837 //bool screensize_changed = screensize != last_screensize;
1840 // Update HUD values
1841 hud.screensize = screensize;
1842 hud.displaycenter = displaycenter;
1845 // Hilight boxes collected during the loop and displayed
1846 std::vector<aabb3f> hilightboxes;
1848 /* reset infotext */
1853 float profiler_print_interval =
1854 g_settings->getFloat("profiler_print_interval");
1855 bool print_to_log = true;
1856 if(profiler_print_interval == 0){
1857 print_to_log = false;
1858 profiler_print_interval = 5;
1860 if(m_profiler_interval.step(dtime, profiler_print_interval))
1863 infostream<<"Profiler:"<<std::endl;
1864 g_profiler->print(infostream);
1867 update_profiler_gui(guitext_profiler, font, text_height,
1868 show_profiler, show_profiler_max);
1870 g_profiler->clear();
1874 Direct handling of user input
1877 // Reset input if window not active or some menu is active
1878 if(device->isWindowActive() == false
1879 || noMenuActive() == false
1880 || guienv->hasFocus(gui_chat_console))
1884 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen())
1886 gui_chat_console->closeConsoleAtOnce();
1889 // Input handler step() (used by the random input generator)
1892 // Increase timer for doubleclick of "jump"
1893 if(g_settings->getBool("doubletap_jump") && jump_timer <= 0.2)
1894 jump_timer += dtime;
1897 Launch menus and trigger stuff according to keys
1899 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1901 // drop selected item
1902 IDropAction *a = new IDropAction();
1904 a->from_inv.setCurrentPlayer();
1905 a->from_list = "main";
1906 a->from_i = client.getPlayerItem();
1907 client.inventoryAction(a);
1909 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1911 infostream<<"the_game: "
1912 <<"Launching inventory"<<std::endl;
1914 GUIFormSpecMenu *menu =
1915 new GUIFormSpecMenu(device, guiroot, -1,
1917 &client, gamedef, tsrc);
1919 InventoryLocation inventoryloc;
1920 inventoryloc.setCurrentPlayer();
1922 PlayerInventoryFormSource *src = new PlayerInventoryFormSource(&client);
1924 menu->doPause = false;
1925 menu->setFormSpec(src->getForm(), inventoryloc);
1926 menu->setFormSource(src);
1927 menu->setTextDest(new TextDestPlayerInventory(&client));
1930 else if(input->wasKeyDown(EscapeKey))
1932 show_pause_menu(current_formspec, current_textdest, tsrc, device,
1933 simple_singleplayer_mode);
1935 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1937 show_chat_menu(current_formspec, current_textdest, tsrc, device, &client,"");
1939 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1941 show_chat_menu(current_formspec, current_textdest, tsrc, device, &client,"/");
1943 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1945 if (!gui_chat_console->isOpenInhibited())
1947 // Open up to over half of the screen
1948 gui_chat_console->openConsole(0.6);
1949 guienv->setFocus(gui_chat_console);
1952 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1954 if(g_settings->getBool("free_move"))
1956 g_settings->set("free_move","false");
1957 statustext = L"free_move disabled";
1958 statustext_time = 0;
1962 g_settings->set("free_move","true");
1963 statustext = L"free_move enabled";
1964 statustext_time = 0;
1965 if(!client.checkPrivilege("fly"))
1966 statustext += L" (note: no 'fly' privilege)";
1969 else if(input->wasKeyDown(getKeySetting("keymap_jump")))
1971 if(g_settings->getBool("doubletap_jump") && jump_timer < 0.2)
1973 if(g_settings->getBool("free_move"))
1975 g_settings->set("free_move","false");
1976 statustext = L"free_move disabled";
1977 statustext_time = 0;
1981 g_settings->set("free_move","true");
1982 statustext = L"free_move enabled";
1983 statustext_time = 0;
1984 if(!client.checkPrivilege("fly"))
1985 statustext += L" (note: no 'fly' privilege)";
1988 reset_jump_timer = true;
1990 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1992 if(g_settings->getBool("fast_move"))
1994 g_settings->set("fast_move","false");
1995 statustext = L"fast_move disabled";
1996 statustext_time = 0;
2000 g_settings->set("fast_move","true");
2001 statustext = L"fast_move enabled";
2002 statustext_time = 0;
2003 if(!client.checkPrivilege("fast"))
2004 statustext += L" (note: no 'fast' privilege)";
2007 else if(input->wasKeyDown(getKeySetting("keymap_noclip")))
2009 if(g_settings->getBool("noclip"))
2011 g_settings->set("noclip","false");
2012 statustext = L"noclip disabled";
2013 statustext_time = 0;
2017 g_settings->set("noclip","true");
2018 statustext = L"noclip enabled";
2019 statustext_time = 0;
2020 if(!client.checkPrivilege("noclip"))
2021 statustext += L" (note: no 'noclip' privilege)";
2024 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
2026 irr::video::IImage* const image = driver->createScreenShot();
2028 irr::c8 filename[256];
2029 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png",
2030 g_settings->get("screenshot_path").c_str(),
2031 device->getTimer()->getRealTime());
2032 if (driver->writeImageToFile(image, filename)) {
2033 std::wstringstream sstr;
2034 sstr<<"Saved screenshot to '"<<filename<<"'";
2035 infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
2036 statustext = sstr.str();
2037 statustext_time = 0;
2039 infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
2044 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
2046 show_hud = !show_hud;
2048 statustext = L"HUD shown";
2050 statustext = L"HUD hidden";
2051 statustext_time = 0;
2053 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
2055 show_chat = !show_chat;
2057 statustext = L"Chat shown";
2059 statustext = L"Chat hidden";
2060 statustext_time = 0;
2062 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
2064 force_fog_off = !force_fog_off;
2066 statustext = L"Fog disabled";
2068 statustext = L"Fog enabled";
2069 statustext_time = 0;
2071 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
2073 disable_camera_update = !disable_camera_update;
2074 if(disable_camera_update)
2075 statustext = L"Camera update disabled";
2077 statustext = L"Camera update enabled";
2078 statustext_time = 0;
2080 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
2082 // Initial / 3x toggle: Chat only
2083 // 1x toggle: Debug text with chat
2084 // 2x toggle: Debug text with profiler graph
2088 show_profiler_graph = false;
2089 statustext = L"Debug info shown";
2090 statustext_time = 0;
2092 else if(show_profiler_graph)
2095 show_profiler_graph = false;
2096 statustext = L"Debug info and profiler graph hidden";
2097 statustext_time = 0;
2101 show_profiler_graph = true;
2102 statustext = L"Profiler graph shown";
2103 statustext_time = 0;
2106 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
2108 show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
2110 // FIXME: This updates the profiler with incomplete values
2111 update_profiler_gui(guitext_profiler, font, text_height,
2112 show_profiler, show_profiler_max);
2114 if(show_profiler != 0)
2116 std::wstringstream sstr;
2117 sstr<<"Profiler shown (page "<<show_profiler
2118 <<" of "<<show_profiler_max<<")";
2119 statustext = sstr.str();
2120 statustext_time = 0;
2124 statustext = L"Profiler hidden";
2125 statustext_time = 0;
2128 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
2130 s16 range = g_settings->getS16("viewing_range_nodes_min");
2131 s16 range_new = range + 10;
2132 g_settings->set("viewing_range_nodes_min", itos(range_new));
2133 statustext = narrow_to_wide(
2134 "Minimum viewing range changed to "
2136 statustext_time = 0;
2138 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
2140 s16 range = g_settings->getS16("viewing_range_nodes_min");
2141 s16 range_new = range - 10;
2144 g_settings->set("viewing_range_nodes_min",
2146 statustext = narrow_to_wide(
2147 "Minimum viewing range changed to "
2149 statustext_time = 0;
2153 if(!input->isKeyDown(getKeySetting("keymap_jump")) && reset_jump_timer)
2155 reset_jump_timer = false;
2159 // Handle QuicktuneShortcutter
2160 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
2162 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
2164 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
2166 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
2169 std::string msg = quicktune.getMessage();
2171 statustext = narrow_to_wide(msg);
2172 statustext_time = 0;
2176 // Item selection with mouse wheel
2177 u16 new_playeritem = client.getPlayerItem();
2179 s32 wheel = input->getMouseWheel();
2180 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
2181 player->hud_hotbar_itemcount-1);
2185 if(new_playeritem < max_item)
2192 if(new_playeritem > 0)
2195 new_playeritem = max_item;
2200 for(u16 i=0; i<10; i++)
2202 const KeyPress *kp = NumberKey + (i + 1) % 10;
2203 if(input->wasKeyDown(*kp))
2205 if(i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount)
2209 infostream<<"Selected item: "
2210 <<new_playeritem<<std::endl;
2215 // Viewing range selection
2216 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
2218 draw_control.range_all = !draw_control.range_all;
2219 if(draw_control.range_all)
2221 infostream<<"Enabled full viewing range"<<std::endl;
2222 statustext = L"Enabled full viewing range";
2223 statustext_time = 0;
2227 infostream<<"Disabled full viewing range"<<std::endl;
2228 statustext = L"Disabled full viewing range";
2229 statustext_time = 0;
2233 // Print debug stacks
2234 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
2236 dstream<<"-----------------------------------------"
2238 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
2239 dstream<<"-----------------------------------------"
2241 debug_stacks_print();
2245 Mouse and camera control
2246 NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
2249 float turn_amount = 0;
2250 if((device->isWindowActive() && noMenuActive()) || random_input)
2254 // Mac OSX gets upset if this is set every frame
2255 if(device->getCursorControl()->isVisible())
2256 device->getCursorControl()->setVisible(false);
2259 if(first_loop_after_window_activation){
2260 //infostream<<"window active, first loop"<<std::endl;
2261 first_loop_after_window_activation = false;
2264 s32 dx = input->getMousePos().X - displaycenter.X;
2265 s32 dy = input->getMousePos().Y - displaycenter.Y;
2266 if(invert_mouse || player->camera_mode == CAMERA_MODE_THIRD_FRONT)
2268 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
2270 /*const float keyspeed = 500;
2271 if(input->isKeyDown(irr::KEY_UP))
2272 dy -= dtime * keyspeed;
2273 if(input->isKeyDown(irr::KEY_DOWN))
2274 dy += dtime * keyspeed;
2275 if(input->isKeyDown(irr::KEY_LEFT))
2276 dx -= dtime * keyspeed;
2277 if(input->isKeyDown(irr::KEY_RIGHT))
2278 dx += dtime * keyspeed;*/
2280 float d = g_settings->getFloat("mouse_sensitivity");
2281 d = rangelim(d, 0.01, 100.0);
2283 camera_pitch += dy*d;
2284 if(camera_pitch < -89.5) camera_pitch = -89.5;
2285 if(camera_pitch > 89.5) camera_pitch = 89.5;
2287 turn_amount = v2f(dx, dy).getLength() * d;
2289 input->setMousePos(displaycenter.X, displaycenter.Y);
2292 // Mac OSX gets upset if this is set every frame
2293 if(device->getCursorControl()->isVisible() == false)
2294 device->getCursorControl()->setVisible(true);
2296 //infostream<<"window inactive"<<std::endl;
2297 first_loop_after_window_activation = true;
2299 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
2300 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
2303 Player speed control
2317 PlayerControl control(
2318 input->isKeyDown(getKeySetting("keymap_forward")),
2319 input->isKeyDown(getKeySetting("keymap_backward")),
2320 input->isKeyDown(getKeySetting("keymap_left")),
2321 input->isKeyDown(getKeySetting("keymap_right")),
2322 input->isKeyDown(getKeySetting("keymap_jump")),
2323 input->isKeyDown(getKeySetting("keymap_special1")),
2324 input->isKeyDown(getKeySetting("keymap_sneak")),
2325 input->getLeftState(),
2326 input->getRightState(),
2330 client.setPlayerControl(control);
2331 LocalPlayer* player = client.getEnv().getLocalPlayer();
2333 (((int)input->isKeyDown(getKeySetting("keymap_forward")) & 0x1) << 0) |
2334 (((int)input->isKeyDown(getKeySetting("keymap_backward")) & 0x1) << 1) |
2335 (((int)input->isKeyDown(getKeySetting("keymap_left")) & 0x1) << 2) |
2336 (((int)input->isKeyDown(getKeySetting("keymap_right")) & 0x1) << 3) |
2337 (((int)input->isKeyDown(getKeySetting("keymap_jump")) & 0x1) << 4) |
2338 (((int)input->isKeyDown(getKeySetting("keymap_special1")) & 0x1) << 5) |
2339 (((int)input->isKeyDown(getKeySetting("keymap_sneak")) & 0x1) << 6) |
2340 (((int)input->getLeftState() & 0x1) << 7) |
2341 (((int)input->getRightState() & 0x1) << 8);
2345 Run server, client (and process environments)
2347 bool can_be_and_is_paused =
2348 (simple_singleplayer_mode && g_menumgr.pausesGame());
2349 if(can_be_and_is_paused)
2358 //TimeTaker timer("server->step(dtime)");
2359 server->step(dtime);
2362 //TimeTaker timer("client.step(dtime)");
2368 // Read client events
2371 ClientEvent event = client.getClientEvent();
2372 if(event.type == CE_NONE)
2376 else if(event.type == CE_PLAYER_DAMAGE &&
2377 client.getHP() != 0)
2379 //u16 damage = event.player_damage.amount;
2380 //infostream<<"Player damage: "<<damage<<std::endl;
2382 damage_flash += 100.0;
2383 damage_flash += 8.0 * event.player_damage.amount;
2385 player->hurt_tilt_timer = 1.5;
2386 player->hurt_tilt_strength = event.player_damage.amount/2;
2387 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 2.0, 10.0);
2389 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
2390 gamedef->event()->put(e);
2392 else if(event.type == CE_PLAYER_FORCE_MOVE)
2394 camera_yaw = event.player_force_move.yaw;
2395 camera_pitch = event.player_force_move.pitch;
2397 else if(event.type == CE_DEATHSCREEN)
2399 show_deathscreen(current_formspec, current_textdest,
2400 tsrc, device, &client);
2402 chat_backend.addMessage(L"", L"You died.");
2404 /* Handle visualization */
2407 LocalPlayer* player = client.getEnv().getLocalPlayer();
2408 player->hurt_tilt_timer = 0;
2409 player->hurt_tilt_strength = 0;
2412 else if (event.type == CE_SHOW_FORMSPEC)
2414 if (current_formspec == 0)
2417 /* Note: FormspecFormSource and TextDestPlayerInventory
2418 * are deleted by guiFormSpecMenu */
2419 current_formspec = new FormspecFormSource(*(event.show_formspec.formspec),¤t_formspec);
2420 current_textdest = new TextDestPlayerInventory(&client,*(event.show_formspec.formname));
2421 GUIFormSpecMenu *menu =
2422 new GUIFormSpecMenu(device, guiroot, -1,
2424 &client, gamedef, tsrc);
2425 menu->doPause = false;
2426 menu->setFormSource(current_formspec);
2427 menu->setTextDest(current_textdest);
2432 assert(current_textdest != 0);
2434 current_textdest->setFormName(*(event.show_formspec.formname));
2435 current_formspec->setForm(*(event.show_formspec.formspec));
2437 delete(event.show_formspec.formspec);
2438 delete(event.show_formspec.formname);
2440 else if(event.type == CE_SPAWN_PARTICLE)
2442 LocalPlayer* player = client.getEnv().getLocalPlayer();
2443 video::ITexture *texture =
2444 gamedef->tsrc()->getTexture(*(event.spawn_particle.texture));
2446 new Particle(gamedef, smgr, player, client.getEnv(),
2447 *event.spawn_particle.pos,
2448 *event.spawn_particle.vel,
2449 *event.spawn_particle.acc,
2450 event.spawn_particle.expirationtime,
2451 event.spawn_particle.size,
2452 event.spawn_particle.collisiondetection,
2453 event.spawn_particle.vertical,
2458 else if(event.type == CE_ADD_PARTICLESPAWNER)
2460 LocalPlayer* player = client.getEnv().getLocalPlayer();
2461 video::ITexture *texture =
2462 gamedef->tsrc()->getTexture(*(event.add_particlespawner.texture));
2464 new ParticleSpawner(gamedef, smgr, player,
2465 event.add_particlespawner.amount,
2466 event.add_particlespawner.spawntime,
2467 *event.add_particlespawner.minpos,
2468 *event.add_particlespawner.maxpos,
2469 *event.add_particlespawner.minvel,
2470 *event.add_particlespawner.maxvel,
2471 *event.add_particlespawner.minacc,
2472 *event.add_particlespawner.maxacc,
2473 event.add_particlespawner.minexptime,
2474 event.add_particlespawner.maxexptime,
2475 event.add_particlespawner.minsize,
2476 event.add_particlespawner.maxsize,
2477 event.add_particlespawner.collisiondetection,
2478 event.add_particlespawner.vertical,
2480 event.add_particlespawner.id);
2482 else if(event.type == CE_DELETE_PARTICLESPAWNER)
2484 delete_particlespawner (event.delete_particlespawner.id);
2486 else if (event.type == CE_HUDADD)
2488 u32 id = event.hudadd.id;
2489 size_t nhudelem = player->hud.size();
2490 if (id > nhudelem || (id < nhudelem && player->hud[id])) {
2491 delete event.hudadd.pos;
2492 delete event.hudadd.name;
2493 delete event.hudadd.scale;
2494 delete event.hudadd.text;
2495 delete event.hudadd.align;
2496 delete event.hudadd.offset;
2497 delete event.hudadd.world_pos;
2501 HudElement *e = new HudElement;
2502 e->type = (HudElementType)event.hudadd.type;
2503 e->pos = *event.hudadd.pos;
2504 e->name = *event.hudadd.name;
2505 e->scale = *event.hudadd.scale;
2506 e->text = *event.hudadd.text;
2507 e->number = event.hudadd.number;
2508 e->item = event.hudadd.item;
2509 e->dir = event.hudadd.dir;
2510 e->align = *event.hudadd.align;
2511 e->offset = *event.hudadd.offset;
2512 e->world_pos = *event.hudadd.world_pos;
2515 player->hud.push_back(e);
2517 player->hud[id] = e;
2519 delete event.hudadd.pos;
2520 delete event.hudadd.name;
2521 delete event.hudadd.scale;
2522 delete event.hudadd.text;
2523 delete event.hudadd.align;
2524 delete event.hudadd.offset;
2525 delete event.hudadd.world_pos;
2527 else if (event.type == CE_HUDRM)
2529 u32 id = event.hudrm.id;
2530 if (id < player->hud.size() && player->hud[id]) {
2531 delete player->hud[id];
2532 player->hud[id] = NULL;
2535 else if (event.type == CE_HUDCHANGE)
2537 u32 id = event.hudchange.id;
2538 if (id >= player->hud.size() || !player->hud[id]) {
2539 delete event.hudchange.v3fdata;
2540 delete event.hudchange.v2fdata;
2541 delete event.hudchange.sdata;
2545 HudElement* e = player->hud[id];
2546 switch (event.hudchange.stat) {
2548 e->pos = *event.hudchange.v2fdata;
2551 e->name = *event.hudchange.sdata;
2553 case HUD_STAT_SCALE:
2554 e->scale = *event.hudchange.v2fdata;
2557 e->text = *event.hudchange.sdata;
2559 case HUD_STAT_NUMBER:
2560 e->number = event.hudchange.data;
2563 e->item = event.hudchange.data;
2566 e->dir = event.hudchange.data;
2568 case HUD_STAT_ALIGN:
2569 e->align = *event.hudchange.v2fdata;
2571 case HUD_STAT_OFFSET:
2572 e->offset = *event.hudchange.v2fdata;
2574 case HUD_STAT_WORLD_POS:
2575 e->world_pos = *event.hudchange.v3fdata;
2579 delete event.hudchange.v3fdata;
2580 delete event.hudchange.v2fdata;
2581 delete event.hudchange.sdata;
2583 else if (event.type == CE_SET_SKY)
2585 sky->setVisible(false);
2590 // Handle according to type
2591 if(*event.set_sky.type == "regular"){
2592 sky->setVisible(true);
2594 else if(*event.set_sky.type == "skybox" &&
2595 event.set_sky.params->size() == 6){
2596 sky->setFallbackBgColor(*event.set_sky.bgcolor);
2597 skybox = smgr->addSkyBoxSceneNode(
2598 tsrc->getTexture((*event.set_sky.params)[0]),
2599 tsrc->getTexture((*event.set_sky.params)[1]),
2600 tsrc->getTexture((*event.set_sky.params)[2]),
2601 tsrc->getTexture((*event.set_sky.params)[3]),
2602 tsrc->getTexture((*event.set_sky.params)[4]),
2603 tsrc->getTexture((*event.set_sky.params)[5]));
2605 // Handle everything else as plain color
2607 if(*event.set_sky.type != "plain")
2608 infostream<<"Unknown sky type: "
2609 <<(*event.set_sky.type)<<std::endl;
2610 sky->setFallbackBgColor(*event.set_sky.bgcolor);
2613 delete event.set_sky.bgcolor;
2614 delete event.set_sky.type;
2615 delete event.set_sky.params;
2617 else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO)
2619 bool enable = event.override_day_night_ratio.do_override;
2620 u32 value = event.override_day_night_ratio.ratio_f * 1000;
2621 client.getEnv().setDayNightRatioOverride(enable, value);
2626 //TimeTaker //timer2("//timer2");
2629 For interaction purposes, get info about the held item
2631 - Is it a usable item?
2632 - Can it point to liquids?
2634 ItemStack playeritem;
2636 InventoryList *mlist = local_inventory.getList("main");
2639 playeritem = mlist->getItem(client.getPlayerItem());
2642 const ItemDefinition &playeritem_def =
2643 playeritem.getDefinition(itemdef);
2644 ToolCapabilities playeritem_toolcap =
2645 playeritem.getToolCapabilities(itemdef);
2651 v3s16 old_camera_offset = camera.getOffset();
2653 LocalPlayer* player = client.getEnv().getLocalPlayer();
2654 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2655 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
2657 if(input->wasKeyDown(getKeySetting("keymap_camera_mode"))) {
2659 if (current_camera_mode == CAMERA_MODE_FIRST)
2660 current_camera_mode = CAMERA_MODE_THIRD;
2661 else if (current_camera_mode == CAMERA_MODE_THIRD)
2662 current_camera_mode = CAMERA_MODE_THIRD_FRONT;
2664 current_camera_mode = CAMERA_MODE_FIRST;
2667 player->camera_mode = current_camera_mode;
2668 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2669 camera.update(player, dtime, busytime, screensize, tool_reload_ratio,
2670 current_camera_mode, client.getEnv());
2673 v3f player_position = player->getPosition();
2674 v3f camera_position = camera.getPosition();
2675 v3f camera_direction = camera.getDirection();
2676 f32 camera_fov = camera.getFovMax();
2677 v3s16 camera_offset = camera.getOffset();
2679 bool camera_offset_changed = (camera_offset != old_camera_offset);
2681 if(!disable_camera_update){
2682 client.getEnv().getClientMap().updateCamera(camera_position,
2683 camera_direction, camera_fov, camera_offset);
2684 if (camera_offset_changed){
2685 client.updateCameraOffset(camera_offset);
2686 client.getEnv().updateCameraOffset(camera_offset);
2688 clouds->updateCameraOffset(camera_offset);
2692 // Update sound listener
2693 sound->updateListener(camera.getCameraNode()->getPosition()+intToFloat(camera_offset, BS),
2694 v3f(0,0,0), // velocity
2695 camera.getDirection(),
2696 camera.getCameraNode()->getUpVector());
2697 sound->setListenerGain(g_settings->getFloat("sound_volume"));
2703 soundmaker.step(dtime);
2705 ClientMap &map = client.getEnv().getClientMap();
2706 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
2707 soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
2711 Calculate what block is the crosshair pointing to
2714 //u32 t1 = device->getTimer()->getRealTime();
2716 f32 d = playeritem_def.range; // max. distance
2717 f32 d_hand = itemdef->get("").range;
2718 if(d < 0 && d_hand >= 0)
2722 core::line3d<f32> shootline(camera_position,
2723 camera_position + camera_direction * BS * (d+1));
2725 // prevent player pointing anything in front-view
2726 if (current_camera_mode == CAMERA_MODE_THIRD_FRONT)
2727 shootline = core::line3d<f32>(0,0,0,0,0,0);
2729 ClientActiveObject *selected_object = NULL;
2731 PointedThing pointed = getPointedThing(
2733 &client, player_position, camera_direction,
2734 camera_position, shootline, d,
2735 playeritem_def.liquids_pointable, !ldown_for_dig,
2741 if(pointed != pointed_old)
2743 infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2744 //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
2749 - releasing left mouse button
2750 - pointing away from node
2754 if(input->getLeftReleased())
2756 infostream<<"Left button released"
2757 <<" (stopped digging)"<<std::endl;
2760 else if(pointed != pointed_old)
2762 if (pointed.type == POINTEDTHING_NODE
2763 && pointed_old.type == POINTEDTHING_NODE
2764 && pointed.node_undersurface == pointed_old.node_undersurface)
2766 // Still pointing to the same node,
2767 // but a different face. Don't reset.
2771 infostream<<"Pointing away from node"
2772 <<" (stopped digging)"<<std::endl;
2778 client.interact(1, pointed_old);
2779 client.setCrack(-1, v3s16(0,0,0));
2783 if(!digging && ldown_for_dig && !input->getLeftState())
2785 ldown_for_dig = false;
2788 bool left_punch = false;
2789 soundmaker.m_player_leftpunch_sound.name = "";
2791 if(input->getRightState())
2792 repeat_rightclick_timer += dtime;
2794 repeat_rightclick_timer = 0;
2796 if(playeritem_def.usable && input->getLeftState())
2798 if(input->getLeftClicked())
2799 client.interact(4, pointed);
2801 else if(pointed.type == POINTEDTHING_NODE)
2803 v3s16 nodepos = pointed.node_undersurface;
2804 v3s16 neighbourpos = pointed.node_abovesurface;
2807 Check information text of node
2810 ClientMap &map = client.getEnv().getClientMap();
2811 NodeMetadata *meta = map.getNodeMetadata(nodepos);
2813 infotext = narrow_to_wide(meta->getString("infotext"));
2815 MapNode n = map.getNode(nodepos);
2816 if(nodedef->get(n).tiledef[0].name == "unknown_node.png"){
2817 infotext = L"Unknown node: ";
2818 infotext += narrow_to_wide(nodedef->get(n).name);
2826 if(nodig_delay_timer <= 0.0 && input->getLeftState()
2827 && client.checkPrivilege("interact"))
2831 infostream<<"Started digging"<<std::endl;
2832 client.interact(0, pointed);
2834 ldown_for_dig = true;
2836 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2838 // NOTE: Similar piece of code exists on the server side for
2840 // Get digging parameters
2841 DigParams params = getDigParams(nodedef->get(n).groups,
2842 &playeritem_toolcap);
2843 // If can't dig, try hand
2844 if(!params.diggable){
2845 const ItemDefinition &hand = itemdef->get("");
2846 const ToolCapabilities *tp = hand.tool_capabilities;
2848 params = getDigParams(nodedef->get(n).groups, tp);
2851 float dig_time_complete = 0.0;
2853 if(params.diggable == false)
2855 // I guess nobody will wait for this long
2856 dig_time_complete = 10000000.0;
2860 dig_time_complete = params.time;
2861 if (g_settings->getBool("enable_particles"))
2863 const ContentFeatures &features =
2864 client.getNodeDefManager()->get(n);
2865 addPunchingParticles
2866 (gamedef, smgr, player, client.getEnv(),
2867 nodepos, features.tiles);
2871 if(dig_time_complete >= 0.001)
2873 dig_index = (u16)((float)crack_animation_length
2874 * dig_time/dig_time_complete);
2876 // This is for torches
2879 dig_index = crack_animation_length;
2882 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2883 if(sound_dig.exists() && params.diggable){
2884 if(sound_dig.name == "__group"){
2885 if(params.main_group != ""){
2886 soundmaker.m_player_leftpunch_sound.gain = 0.5;
2887 soundmaker.m_player_leftpunch_sound.name =
2888 std::string("default_dig_") +
2892 soundmaker.m_player_leftpunch_sound = sound_dig;
2896 // Don't show cracks if not diggable
2897 if(dig_time_complete >= 100000.0)
2900 else if(dig_index < crack_animation_length)
2902 //TimeTaker timer("client.setTempMod");
2903 //infostream<<"dig_index="<<dig_index<<std::endl;
2904 client.setCrack(dig_index, nodepos);
2908 infostream<<"Digging completed"<<std::endl;
2909 client.interact(2, pointed);
2910 client.setCrack(-1, v3s16(0,0,0));
2911 MapNode wasnode = map.getNode(nodepos);
2912 client.removeNode(nodepos);
2914 if (g_settings->getBool("enable_particles"))
2916 const ContentFeatures &features =
2917 client.getNodeDefManager()->get(wasnode);
2919 (gamedef, smgr, player, client.getEnv(),
2920 nodepos, features.tiles);
2926 nodig_delay_timer = dig_time_complete
2927 / (float)crack_animation_length;
2929 // We don't want a corresponding delay to
2930 // very time consuming nodes
2931 if(nodig_delay_timer > 0.3)
2932 nodig_delay_timer = 0.3;
2933 // We want a slight delay to very little
2934 // time consuming nodes
2935 float mindelay = 0.15;
2936 if(nodig_delay_timer < mindelay)
2937 nodig_delay_timer = mindelay;
2939 // Send event to trigger sound
2940 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
2941 gamedef->event()->put(e);
2944 if(dig_time_complete < 100000.0)
2948 client.setCrack(-1, nodepos);
2951 camera.setDigging(0); // left click animation
2954 if((input->getRightClicked() ||
2955 repeat_rightclick_timer >=
2956 g_settings->getFloat("repeat_rightclick_time")) &&
2957 client.checkPrivilege("interact"))
2959 repeat_rightclick_timer = 0;
2960 infostream<<"Ground right-clicked"<<std::endl;
2962 // Sign special case, at least until formspec is properly implemented.
2964 if(meta && meta->getString("formspec") == "hack:sign_text_input"
2966 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2968 infostream<<"Launching metadata text input"<<std::endl;
2970 // Get a new text for it
2972 TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2974 std::wstring wtext = narrow_to_wide(meta->getString("text"));
2976 (new GUITextInputMenu(guienv, guiroot, -1,
2980 // If metadata provides an inventory view, activate it
2981 else if(meta && meta->getString("formspec") != "" && !random_input
2982 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2984 infostream<<"Launching custom inventory view"<<std::endl;
2986 InventoryLocation inventoryloc;
2987 inventoryloc.setNodeMeta(nodepos);
2991 GUIFormSpecMenu *menu =
2992 new GUIFormSpecMenu(device, guiroot, -1,
2994 &client, gamedef, tsrc);
2995 menu->doPause = false;
2996 menu->setFormSpec(meta->getString("formspec"),
2998 menu->setFormSource(new NodeMetadataFormSource(
2999 &client.getEnv().getClientMap(), nodepos));
3000 menu->setTextDest(new TextDestNodeMetadata(nodepos, &client));
3003 // Otherwise report right click to server
3006 camera.setDigging(1); // right click animation (always shown for feedback)
3008 // If the wielded item has node placement prediction,
3010 bool placed = nodePlacementPrediction(client,
3012 nodepos, neighbourpos);
3016 client.interact(3, pointed);
3018 soundmaker.m_player_rightpunch_sound =
3019 playeritem_def.sound_place;
3021 soundmaker.m_player_rightpunch_sound =
3025 if (playeritem_def.node_placement_prediction == "" ||
3026 nodedef->get(map.getNode(nodepos)).rightclickable)
3027 client.interact(3, pointed); // Report to server
3031 else if(pointed.type == POINTEDTHING_OBJECT)
3033 infotext = narrow_to_wide(selected_object->infoText());
3035 if(infotext == L"" && show_debug){
3036 infotext = narrow_to_wide(selected_object->debugInfoText());
3039 //if(input->getLeftClicked())
3040 if(input->getLeftState())
3042 bool do_punch = false;
3043 bool do_punch_damage = false;
3044 if(object_hit_delay_timer <= 0.0){
3046 do_punch_damage = true;
3047 object_hit_delay_timer = object_hit_delay;
3049 if(input->getLeftClicked()){
3053 infostream<<"Left-clicked object"<<std::endl;
3056 if(do_punch_damage){
3057 // Report direct punch
3058 v3f objpos = selected_object->getPosition();
3059 v3f dir = (objpos - player_position).normalize();
3061 bool disable_send = selected_object->directReportPunch(
3062 dir, &playeritem, time_from_last_punch);
3063 time_from_last_punch = 0;
3065 client.interact(0, pointed);
3068 else if(input->getRightClicked())
3070 infostream<<"Right-clicked object"<<std::endl;
3071 client.interact(3, pointed); // place
3074 else if(input->getLeftState())
3076 // When button is held down in air, show continuous animation
3080 pointed_old = pointed;
3082 if(left_punch || input->getLeftClicked())
3084 camera.setDigging(0); // left click animation
3087 input->resetLeftClicked();
3088 input->resetRightClicked();
3090 input->resetLeftReleased();
3091 input->resetRightReleased();
3094 Calculate stuff for drawing
3101 if(draw_control.range_all)
3102 fog_range = 100000*BS;
3104 fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
3105 fog_range = MYMIN(fog_range, (draw_control.farthest_drawn+20)*BS);
3110 Calculate general brightness
3112 u32 daynight_ratio = client.getEnv().getDayNightRatio();
3113 float time_brightness = decode_light_f((float)daynight_ratio/1000.0);
3114 float direct_brightness = 0;
3115 bool sunlight_seen = false;
3116 if(g_settings->getBool("free_move")){
3117 direct_brightness = time_brightness;
3118 sunlight_seen = true;
3120 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3121 float old_brightness = sky->getBrightness();
3122 direct_brightness = (float)client.getEnv().getClientMap()
3123 .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
3124 daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
3128 time_of_day = client.getEnv().getTimeOfDayF();
3130 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
3131 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3132 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3133 time_of_day_smooth = time_of_day;
3135 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
3136 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
3137 + (time_of_day+1.0) * todsm;
3139 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
3140 + time_of_day * todsm;
3142 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3145 video::SColor bgcolor = sky->getBgColor();
3146 video::SColor skycolor = sky->getSkyColor();
3152 if(sky->getCloudsVisible()){
3153 clouds->setVisible(true);
3154 clouds->step(dtime);
3155 clouds->update(v2f(player_position.X, player_position.Z),
3156 sky->getCloudColor());
3158 clouds->setVisible(false);
3166 allparticles_step(dtime);
3167 allparticlespawners_step(dtime, client.getEnv());
3173 if(g_settings->getBool("enable_fog") && !force_fog_off)
3177 video::EFT_FOG_LINEAR,
3189 video::EFT_FOG_LINEAR,
3199 Update gui stuff (0ms)
3202 //TimeTaker guiupdatetimer("Gui updating");
3206 static float drawtime_avg = 0;
3207 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
3208 /*static float beginscenetime_avg = 0;
3209 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
3210 static float scenetime_avg = 0;
3211 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
3212 static float endscenetime_avg = 0;
3213 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
3215 u16 fps = (1.0/dtime_avg1);
3217 std::ostringstream os(std::ios_base::binary);
3219 <<"Minetest "<<minetest_version_hash
3221 <<" (R: range_all="<<draw_control.range_all<<")"
3222 <<std::setprecision(0)
3223 <<" drawtime = "<<drawtime_avg
3224 <<std::setprecision(1)
3225 <<", dtime_jitter = "
3226 <<(dtime_jitter1_max_fraction * 100.0)<<" %"
3227 <<std::setprecision(1)
3228 <<", v_range = "<<draw_control.wanted_range
3229 <<std::setprecision(3)
3230 <<", RTT = "<<client.getRTT();
3231 guitext->setText(narrow_to_wide(os.str()).c_str());
3232 guitext->setVisible(true);
3234 else if(show_hud || show_chat)
3236 std::ostringstream os(std::ios_base::binary);
3237 os<<"Minetest "<<minetest_version_hash;
3238 guitext->setText(narrow_to_wide(os.str()).c_str());
3239 guitext->setVisible(true);
3243 guitext->setVisible(false);
3248 std::ostringstream os(std::ios_base::binary);
3249 os<<std::setprecision(1)<<std::fixed
3250 <<"(" <<(player_position.X/BS)
3251 <<", "<<(player_position.Y/BS)
3252 <<", "<<(player_position.Z/BS)
3253 <<") (yaw="<<(wrapDegrees_0_360(camera_yaw))
3254 <<") (seed = "<<((u64)client.getMapSeed())
3256 guitext2->setText(narrow_to_wide(os.str()).c_str());
3257 guitext2->setVisible(true);
3261 guitext2->setVisible(false);
3265 guitext_info->setText(infotext.c_str());
3266 guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
3270 float statustext_time_max = 1.5;
3271 if(!statustext.empty())
3273 statustext_time += dtime;
3274 if(statustext_time >= statustext_time_max)
3277 statustext_time = 0;
3280 guitext_status->setText(statustext.c_str());
3281 guitext_status->setVisible(!statustext.empty());
3283 if(!statustext.empty())
3285 s32 status_y = screensize.Y - 130;
3286 core::rect<s32> rect(
3288 status_y - guitext_status->getTextHeight(),
3292 guitext_status->setRelativePosition(rect);
3295 video::SColor initial_color(255,0,0,0);
3296 if(guienv->getSkin())
3297 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
3298 video::SColor final_color = initial_color;
3299 final_color.setAlpha(0);
3300 video::SColor fade_color =
3301 initial_color.getInterpolated_quadratic(
3304 pow(statustext_time / (float)statustext_time_max, 2.0f));
3305 guitext_status->setOverrideColor(fade_color);
3306 guitext_status->enableOverrideColor(true);
3311 Get chat messages from client
3314 // Get new messages from error log buffer
3315 while(!chat_log_error_buf.empty())
3317 chat_backend.addMessage(L"", narrow_to_wide(
3318 chat_log_error_buf.get()));
3320 // Get new messages from client
3321 std::wstring message;
3322 while(client.getChatMessage(message))
3324 chat_backend.addUnparsedMessage(message);
3326 // Remove old messages
3327 chat_backend.step(dtime);
3329 // Display all messages in a static text element
3330 u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
3331 std::wstring recent_chat = chat_backend.getRecentChat();
3332 guitext_chat->setText(recent_chat.c_str());
3334 // Update gui element size and position
3335 s32 chat_y = 5+(text_height+5);
3337 chat_y += (text_height+5);
3338 core::rect<s32> rect(
3342 chat_y + guitext_chat->getTextHeight()
3344 guitext_chat->setRelativePosition(rect);
3346 // Don't show chat if disabled or empty or profiler is enabled
3347 guitext_chat->setVisible(show_chat && recent_chat_count != 0
3355 if(client.getPlayerItem() != new_playeritem)
3357 client.selectPlayerItem(new_playeritem);
3359 if(client.getLocalInventoryUpdated())
3361 //infostream<<"Updating local inventory"<<std::endl;
3362 client.getLocalInventory(local_inventory);
3364 update_wielded_item_trigger = true;
3366 if(update_wielded_item_trigger)
3368 update_wielded_item_trigger = false;
3369 // Update wielded tool
3370 InventoryList *mlist = local_inventory.getList("main");
3373 item = mlist->getItem(client.getPlayerItem());
3374 camera.wield(item, client.getPlayerItem());
3378 Update block draw list every 200ms or when camera direction has
3381 update_draw_list_timer += dtime;
3382 if(update_draw_list_timer >= 0.2 ||
3383 update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2 ||
3384 camera_offset_changed){
3385 update_draw_list_timer = 0;
3386 client.getEnv().getClientMap().updateDrawList(driver);
3387 update_draw_list_last_cam_dir = camera_direction;
3394 TimeTaker tt_draw("mainloop: draw");
3397 TimeTaker timer("beginScene");
3398 //driver->beginScene(false, true, bgcolor);
3399 //driver->beginScene(true, true, bgcolor);
3400 driver->beginScene(true, true, skycolor);
3401 beginscenetime = timer.stop(true);
3406 //infostream<<"smgr->drawAll()"<<std::endl;
3408 TimeTaker timer("smgr");
3411 if(g_settings->getBool("anaglyph"))
3413 irr::core::vector3df oldPosition = camera.getCameraNode()->getPosition();
3414 irr::core::vector3df oldTarget = camera.getCameraNode()->getTarget();
3416 irr::core::matrix4 startMatrix = camera.getCameraNode()->getAbsoluteTransformation();
3418 irr::core::vector3df focusPoint = (camera.getCameraNode()->getTarget() -
3419 camera.getCameraNode()->getAbsolutePosition()).setLength(1) +
3420 camera.getCameraNode()->getAbsolutePosition() ;
3423 irr::core::vector3df leftEye;
3424 irr::core::matrix4 leftMove;
3426 leftMove.setTranslation( irr::core::vector3df(-g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
3427 leftEye=(startMatrix*leftMove).getTranslation();
3429 //clear the depth buffer, and color
3430 driver->beginScene( true, true, irr::video::SColor(0,200,200,255) );
3432 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_RED;
3433 driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK;
3434 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
3435 irr::scene::ESNRP_SOLID +
3436 irr::scene::ESNRP_TRANSPARENT +
3437 irr::scene::ESNRP_TRANSPARENT_EFFECT +
3438 irr::scene::ESNRP_SHADOW;
3440 camera.getCameraNode()->setPosition( leftEye );
3441 camera.getCameraNode()->setTarget( focusPoint );
3443 smgr->drawAll(); // 'smgr->drawAll();' may go here
3445 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
3448 hud.drawSelectionBoxes(hilightboxes);
3452 irr::core::vector3df rightEye;
3453 irr::core::matrix4 rightMove;
3455 rightMove.setTranslation( irr::core::vector3df(g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
3456 rightEye=(startMatrix*rightMove).getTranslation();
3458 //clear the depth buffer
3459 driver->clearZBuffer();
3461 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_GREEN + irr::video::ECP_BLUE;
3462 driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK;
3463 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
3464 irr::scene::ESNRP_SOLID +
3465 irr::scene::ESNRP_TRANSPARENT +
3466 irr::scene::ESNRP_TRANSPARENT_EFFECT +
3467 irr::scene::ESNRP_SHADOW;
3469 camera.getCameraNode()->setPosition( rightEye );
3470 camera.getCameraNode()->setTarget( focusPoint );
3472 smgr->drawAll(); // 'smgr->drawAll();' may go here
3474 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
3477 hud.drawSelectionBoxes(hilightboxes);
3480 //driver->endScene();
3482 driver->getOverrideMaterial().Material.ColorMask=irr::video::ECP_ALL;
3483 driver->getOverrideMaterial().EnableFlags=0;
3484 driver->getOverrideMaterial().EnablePasses=0;
3486 camera.getCameraNode()->setPosition( oldPosition );
3487 camera.getCameraNode()->setTarget( oldTarget );
3490 scenetime = timer.stop(true);
3494 //TimeTaker timer9("auxiliary drawings");
3498 //TimeTaker //timer10("//timer10");
3504 driver->setMaterial(m);
3506 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
3507 if((!g_settings->getBool("anaglyph")) && (show_hud))
3509 hud.drawSelectionBoxes(hilightboxes);
3516 (player->hud_flags & HUD_FLAG_WIELDITEM_VISIBLE) &&
3517 current_camera_mode < CAMERA_MODE_THIRD)
3519 // Warning: This clears the Z buffer.
3520 camera.drawWieldedTool();
3527 client.getEnv().getClientMap().renderPostFx();
3533 if(show_profiler_graph)
3535 graph.draw(10, screensize.Y - 10, driver, font);
3542 hud.drawCrosshair();
3547 //TimeTaker //timer11("//timer11");
3555 hud.drawHotbar(v2s32(displaycenter.X, screensize.Y),
3556 client.getHP(), client.getPlayerItem(), client.getBreath());
3562 if(damage_flash > 0.0)
3564 video::SColor color(std::min(damage_flash, 180.0f),180,0,0);
3565 driver->draw2DRectangle(color,
3566 core::rect<s32>(0,0,screensize.X,screensize.Y),
3569 damage_flash -= 100.0*dtime;
3575 if(player->hurt_tilt_timer > 0.0)
3577 player->hurt_tilt_timer -= dtime*5;
3578 if(player->hurt_tilt_timer < 0)
3579 player->hurt_tilt_strength = 0;
3586 hud.drawLuaElements();
3598 TimeTaker timer("endScene");
3600 endscenetime = timer.stop(true);
3603 drawtime = tt_draw.stop(true);
3604 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
3611 Log times and stuff for visualization
3613 Profiler::GraphValues values;
3614 g_profiler->graphGet(values);
3623 if (gui_chat_console)
3624 gui_chat_console->drop();
3630 Draw a "shutting down" screen, which will be shown while the map
3631 generator and other stuff quits
3634 /*gui::IGUIStaticText *gui_shuttingdowntext = */
3635 wchar_t* text = wgettext("Shutting down stuff...");
3636 draw_load_screen(text, device, font, 0, -1, false);
3638 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
3641 gui_shuttingdowntext->remove();*/
3644 chat_backend.addMessage(L"", L"# Disconnected.");
3645 chat_backend.addMessage(L"", L"");
3649 //force answer all texture and shader jobs (TODO return empty values)
3651 while(!client.isShutdown()) {
3652 tsrc->processQueue();
3653 shsrc->processQueue();
3657 // Client scope (client is destructed before destructing *def and tsrc)
3660 catch(SerializationError &e)
3662 error_message = L"A serialization error occurred:\n"
3663 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
3664 L" running a different version of Minetest.";
3665 errorstream<<wide_to_narrow(error_message)<<std::endl;
3667 catch(ServerError &e) {
3668 error_message = narrow_to_wide(e.what());
3669 errorstream << "ServerError: " << e.what() << std::endl;
3671 catch(ModError &e) {
3672 errorstream << "ModError: " << e.what() << std::endl;
3673 error_message = narrow_to_wide(e.what()) + wgettext("\nCheck debug.txt for details.");
3681 //has to be deleted first to stop all server threads
3689 //extended resource accounting
3690 infostream << "Irrlicht resources after cleanup:" << std::endl;
3691 infostream << "\tRemaining meshes : "
3692 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
3693 infostream << "\tRemaining textures : "
3694 << driver->getTextureCount() << std::endl;
3695 for (unsigned int i = 0; i < driver->getTextureCount(); i++ ) {
3696 irr::video::ITexture* texture = driver->getTextureByIndex(i);
3697 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
3700 clearTextureNameCache();
3701 infostream << "\tRemaining materials: "
3702 << driver-> getMaterialRendererCount ()
3703 << " (note: irrlicht doesn't support removing renderers)"<< std::endl;