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"
35 #include "guiDeathScreen.h"
37 #include "guiChatConsole.h"
41 #include "particles.h"
46 #include "mainmenumanager.h"
50 // Needed for determining pointing to nodes
52 #include "nodemetadata.h"
53 #include "main.h" // For g_settings
55 #include "tile.h" // For TextureSource
56 #include "shader.h" // For ShaderSource
57 #include "logoutputbuffer.h"
59 #include "quicktune_shortcutter.h"
60 #include "clientmap.h"
65 #include "sound_openal.h"
67 #include "event_manager.h"
70 #include "util/directiontables.h"
71 #include "util/pointedthing.h"
77 struct TextDestNodeMetadata : public TextDest
79 TextDestNodeMetadata(v3s16 p, Client *client)
84 // This is deprecated I guess? -celeron55
85 void gotText(std::wstring text)
87 std::string ntext = wide_to_narrow(text);
88 infostream<<"Submitting 'text' field of node at ("<<m_p.X<<","
89 <<m_p.Y<<","<<m_p.Z<<"): "<<ntext<<std::endl;
90 std::map<std::string, std::string> fields;
91 fields["text"] = ntext;
92 m_client->sendNodemetaFields(m_p, "", fields);
94 void gotText(std::map<std::string, std::string> fields)
96 m_client->sendNodemetaFields(m_p, "", fields);
103 struct TextDestPlayerInventory : public TextDest
105 TextDestPlayerInventory(Client *client)
110 TextDestPlayerInventory(Client *client, std::string formname)
113 m_formname = formname;
115 void gotText(std::map<std::string, std::string> fields)
117 m_client->sendInventoryFields(m_formname, fields);
123 struct LocalFormspecHandler : public TextDest
125 LocalFormspecHandler();
126 LocalFormspecHandler(std::string formname) {
127 m_formname = formname;
130 LocalFormspecHandler(std::string formname,Client *client) {
131 m_formname = formname;
135 void gotText(std::wstring message) {
136 errorstream << "LocalFormspecHandler::gotText old style message received" << std::endl;
139 void gotText(std::map<std::string, std::string> fields)
141 if (m_formname == "MT_PAUSE_MENU") {
142 if (fields.find("btn_sound") != fields.end()) {
143 g_gamecallback->changeVolume();
147 if (fields.find("btn_exit_menu") != fields.end()) {
148 g_gamecallback->disconnect();
152 if (fields.find("btn_exit_os") != fields.end()) {
153 g_gamecallback->exitToOS();
157 if (fields.find("btn_change_password") != fields.end()) {
158 g_gamecallback->changePassword();
162 if (fields.find("quit") != fields.end()) {
166 if (fields.find("btn_continue") != fields.end()) {
170 if (m_formname == "MT_CHAT_MENU") {
171 if ((fields.find("btn_send") != fields.end()) ||
172 (fields.find("quit") != fields.end())) {
173 if (fields.find("f_text") != fields.end()) {
175 m_client->typeChatMessage(narrow_to_wide(fields["f_text"]));
178 errorstream << "LocalFormspecHandler::gotText received chat message but m_client is NULL" << std::endl;
185 errorstream << "LocalFormspecHandler::gotText unhandled >" << m_formname << "< event" << std::endl;
187 for (std::map<std::string,std::string>::iterator iter = fields.begin();
188 iter != fields.end(); iter++) {
189 errorstream << "\t"<< i << ": " << iter->first << "=" << iter->second << std::endl;
197 /* Respawn menu callback */
199 class MainRespawnInitiator: public IRespawnInitiator
202 MainRespawnInitiator(bool *active, Client *client):
203 m_active(active), m_client(client)
210 m_client->sendRespawn();
217 /* Form update callback */
219 class NodeMetadataFormSource: public IFormSource
222 NodeMetadataFormSource(ClientMap *map, v3s16 p):
227 std::string getForm()
229 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
232 return meta->getString("formspec");
234 std::string resolveText(std::string str)
236 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
239 return meta->resolveString(str);
246 class PlayerInventoryFormSource: public IFormSource
249 PlayerInventoryFormSource(Client *client):
253 std::string getForm()
255 LocalPlayer* player = m_client->getEnv().getLocalPlayer();
256 return player->inventory_formspec;
263 Check if a node is pointable
265 inline bool isPointableNode(const MapNode& n,
266 Client *client, bool liquids_pointable)
268 const ContentFeatures &features = client->getNodeDefManager()->get(n);
269 return features.pointable ||
270 (liquids_pointable && features.isLiquid());
274 Find what the player is pointing at
276 PointedThing getPointedThing(Client *client, v3f player_position,
277 v3f camera_direction, v3f camera_position, core::line3d<f32> shootline,
278 f32 d, bool liquids_pointable, bool look_for_object, v3s16 camera_offset,
279 std::vector<aabb3f> &hilightboxes, ClientActiveObject *&selected_object)
283 hilightboxes.clear();
284 selected_object = NULL;
286 INodeDefManager *nodedef = client->getNodeDefManager();
287 ClientMap &map = client->getEnv().getClientMap();
289 f32 mindistance = BS * 1001;
291 // First try to find a pointed at active object
294 selected_object = client->getSelectedActiveObject(d*BS,
295 camera_position, shootline);
297 if(selected_object != NULL)
299 if(selected_object->doShowSelectionBox())
301 aabb3f *selection_box = selected_object->getSelectionBox();
302 // Box should exist because object was
303 // returned in the first place
304 assert(selection_box);
306 v3f pos = selected_object->getPosition();
307 hilightboxes.push_back(aabb3f(
308 selection_box->MinEdge + pos - intToFloat(camera_offset, BS),
309 selection_box->MaxEdge + pos - intToFloat(camera_offset, BS)));
312 mindistance = (selected_object->getPosition() - camera_position).getLength();
314 result.type = POINTEDTHING_OBJECT;
315 result.object_id = selected_object->getId();
319 // That didn't work, try to find a pointed at node
322 v3s16 pos_i = floatToInt(player_position, BS);
324 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
328 s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
329 s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
330 s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
331 s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
332 s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
333 s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
335 // Prevent signed number overflow
343 for(s16 y = ystart; y <= yend; y++)
344 for(s16 z = zstart; z <= zend; z++)
345 for(s16 x = xstart; x <= xend; x++)
350 n = map.getNode(v3s16(x,y,z));
352 catch(InvalidPositionException &e)
356 if(!isPointableNode(n, client, liquids_pointable))
359 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
362 v3f npf = intToFloat(np, BS);
364 for(std::vector<aabb3f>::const_iterator
366 i != boxes.end(); i++)
372 for(u16 j=0; j<6; j++)
374 v3s16 facedir = g_6dirs[j];
375 aabb3f facebox = box;
379 facebox.MinEdge.X = facebox.MaxEdge.X-d;
380 else if(facedir.X < 0)
381 facebox.MaxEdge.X = facebox.MinEdge.X+d;
382 else if(facedir.Y > 0)
383 facebox.MinEdge.Y = facebox.MaxEdge.Y-d;
384 else if(facedir.Y < 0)
385 facebox.MaxEdge.Y = facebox.MinEdge.Y+d;
386 else if(facedir.Z > 0)
387 facebox.MinEdge.Z = facebox.MaxEdge.Z-d;
388 else if(facedir.Z < 0)
389 facebox.MaxEdge.Z = facebox.MinEdge.Z+d;
391 v3f centerpoint = facebox.getCenter();
392 f32 distance = (centerpoint - camera_position).getLength();
393 if(distance >= mindistance)
395 if(!facebox.intersectsWithLine(shootline))
398 v3s16 np_above = np + facedir;
400 result.type = POINTEDTHING_NODE;
401 result.node_undersurface = np;
402 result.node_abovesurface = np_above;
403 mindistance = distance;
405 hilightboxes.clear();
406 for(std::vector<aabb3f>::const_iterator
408 i2 != boxes.end(); i2++)
411 box.MinEdge += npf + v3f(-d,-d,-d) - intToFloat(camera_offset, BS);
412 box.MaxEdge += npf + v3f(d,d,d) - intToFloat(camera_offset, BS);
413 hilightboxes.push_back(box);
423 Draws a screen with a single text on it.
424 Text will be removed when the screen is drawn the next time.
425 Additionally, a progressbar can be drawn when percent is set between 0 and 100.
427 /*gui::IGUIStaticText **/
428 void draw_load_screen(const std::wstring &text, IrrlichtDevice* device,
429 gui::IGUIFont* font, float dtime=0 ,int percent=0, bool clouds=true)
431 video::IVideoDriver* driver = device->getVideoDriver();
432 v2u32 screensize = driver->getScreenSize();
433 const wchar_t *loadingtext = text.c_str();
434 core::vector2d<u32> textsize_u = font->getDimension(loadingtext);
435 core::vector2d<s32> textsize(textsize_u.X,textsize_u.Y);
436 core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
437 core::rect<s32> textrect(center - textsize/2, center + textsize/2);
439 gui::IGUIStaticText *guitext = guienv->addStaticText(
440 loadingtext, textrect, false, false);
441 guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
443 bool cloud_menu_background = clouds && g_settings->getBool("menu_clouds");
444 if (cloud_menu_background)
446 g_menuclouds->step(dtime*3);
447 g_menuclouds->render();
448 driver->beginScene(true, true, video::SColor(255,140,186,250));
449 g_menucloudsmgr->drawAll();
452 driver->beginScene(true, true, video::SColor(255,0,0,0));
453 if (percent >= 0 && percent <= 100) // draw progress bar
455 core::vector2d<s32> barsize(256,32);
456 core::rect<s32> barrect(center-barsize/2, center+barsize/2);
457 driver->draw2DRectangle(video::SColor(255,255,255,255),barrect, NULL); // border
458 driver->draw2DRectangle(video::SColor(255,64,64,64), core::rect<s32> (
459 barrect.UpperLeftCorner+1,
460 barrect.LowerRightCorner-1), NULL); // black inside the bar
461 driver->draw2DRectangle(video::SColor(255,128,128,128), core::rect<s32> (
462 barrect.UpperLeftCorner+1,
464 barrect.LowerRightCorner.X-(barsize.X-1)+percent*(barsize.X-2)/100,
465 barrect.LowerRightCorner.Y-1)), NULL); // the actual progress
475 /* Profiler display */
477 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler,
478 gui::IGUIFont *font, u32 text_height, u32 show_profiler,
479 u32 show_profiler_max)
481 if(show_profiler == 0)
483 guitext_profiler->setVisible(false);
488 std::ostringstream os(std::ios_base::binary);
489 g_profiler->printPage(os, show_profiler, show_profiler_max);
490 std::wstring text = narrow_to_wide(os.str());
491 guitext_profiler->setText(text.c_str());
492 guitext_profiler->setVisible(true);
494 s32 w = font->getDimension(text.c_str()).Width;
497 core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
498 8+(text_height+5)*2 +
499 font->getDimension(text.c_str()).Height);
500 guitext_profiler->setRelativePosition(rect);
501 guitext_profiler->setVisible(true);
509 Profiler::GraphValues values;
515 Meta(float initial=0, video::SColor color=
516 video::SColor(255,255,255,255)):
522 std::list<Piece> m_log;
530 void put(const Profiler::GraphValues &values)
533 piece.values = values;
534 m_log.push_back(piece);
535 while(m_log.size() > m_log_max_size)
536 m_log.erase(m_log.begin());
539 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
540 gui::IGUIFont* font) const
542 std::map<std::string, Meta> m_meta;
543 for(std::list<Piece>::const_iterator k = m_log.begin();
544 k != m_log.end(); k++)
546 const Piece &piece = *k;
547 for(Profiler::GraphValues::const_iterator i = piece.values.begin();
548 i != piece.values.end(); i++){
549 const std::string &id = i->first;
550 const float &value = i->second;
551 std::map<std::string, Meta>::iterator j =
553 if(j == m_meta.end()){
554 m_meta[id] = Meta(value);
557 if(value < j->second.min)
558 j->second.min = value;
559 if(value > j->second.max)
560 j->second.max = value;
565 static const video::SColor usable_colors[] = {
566 video::SColor(255,255,100,100),
567 video::SColor(255,90,225,90),
568 video::SColor(255,100,100,255),
569 video::SColor(255,255,150,50),
570 video::SColor(255,220,220,100)
572 static const u32 usable_colors_count =
573 sizeof(usable_colors) / sizeof(*usable_colors);
574 u32 next_color_i = 0;
575 for(std::map<std::string, Meta>::iterator i = m_meta.begin();
576 i != m_meta.end(); i++){
577 Meta &meta = i->second;
578 video::SColor color(255,200,200,200);
579 if(next_color_i < usable_colors_count)
580 color = usable_colors[next_color_i++];
585 s32 textx = x_left + m_log_max_size + 15;
586 s32 textx2 = textx + 200 - 15;
590 u32 num_graphs = m_meta.size();
591 core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
593 video::SColor bgcolor(120,0,0,0);
594 driver->draw2DRectangle(bgcolor, rect, NULL);
598 for(std::map<std::string, Meta>::const_iterator i = m_meta.begin();
599 i != m_meta.end(); i++){
600 const std::string &id = i->first;
601 const Meta &meta = i->second;
603 s32 y = y_bottom - meta_i * 50;
604 float show_min = meta.min;
605 float show_max = meta.max;
606 if(show_min >= -0.0001 && show_max >= -0.0001){
607 if(show_min <= show_max * 0.5)
612 snprintf(buf, 10, "%.3g", show_max);
613 font->draw(narrow_to_wide(buf).c_str(),
614 core::rect<s32>(textx, y - graphh,
615 textx2, y - graphh + texth),
617 snprintf(buf, 10, "%.3g", show_min);
618 font->draw(narrow_to_wide(buf).c_str(),
619 core::rect<s32>(textx, y - texth,
622 font->draw(narrow_to_wide(id).c_str(),
623 core::rect<s32>(textx, y - graphh/2 - texth/2,
624 textx2, y - graphh/2 + texth/2),
627 s32 graph1h = graphh;
628 bool relativegraph = (show_min != 0 && show_min != show_max);
629 float lastscaledvalue = 0.0;
630 bool lastscaledvalue_exists = false;
631 for(std::list<Piece>::const_iterator j = m_log.begin();
632 j != m_log.end(); j++)
634 const Piece &piece = *j;
636 bool value_exists = false;
637 Profiler::GraphValues::const_iterator k =
638 piece.values.find(id);
639 if(k != piece.values.end()){
645 lastscaledvalue_exists = false;
648 float scaledvalue = 1.0;
649 if(show_max != show_min)
650 scaledvalue = (value - show_min) / (show_max - show_min);
651 if(scaledvalue == 1.0 && value == 0){
653 lastscaledvalue_exists = false;
657 if(lastscaledvalue_exists){
658 s32 ivalue1 = lastscaledvalue * graph1h;
659 s32 ivalue2 = scaledvalue * graph1h;
660 driver->draw2DLine(v2s32(x-1, graph1y - ivalue1),
661 v2s32(x, graph1y - ivalue2), meta.color);
663 lastscaledvalue = scaledvalue;
664 lastscaledvalue_exists = true;
666 s32 ivalue = scaledvalue * graph1h;
667 driver->draw2DLine(v2s32(x, graph1y),
668 v2s32(x, graph1y - ivalue), meta.color);
677 class NodeDugEvent: public MtEvent
683 NodeDugEvent(v3s16 p, MapNode n):
687 const char* getType() const
693 ISoundManager *m_sound;
694 INodeDefManager *m_ndef;
696 float m_player_step_timer;
698 SimpleSoundSpec m_player_step_sound;
699 SimpleSoundSpec m_player_leftpunch_sound;
700 SimpleSoundSpec m_player_rightpunch_sound;
702 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
705 m_player_step_timer(0)
709 void playPlayerStep()
711 if(m_player_step_timer <= 0 && m_player_step_sound.exists()){
712 m_player_step_timer = 0.03;
713 m_sound->playSound(m_player_step_sound, false);
717 static void viewBobbingStep(MtEvent *e, void *data)
719 SoundMaker *sm = (SoundMaker*)data;
720 sm->playPlayerStep();
723 static void playerRegainGround(MtEvent *e, void *data)
725 SoundMaker *sm = (SoundMaker*)data;
726 sm->playPlayerStep();
729 static void playerJump(MtEvent *e, void *data)
731 //SoundMaker *sm = (SoundMaker*)data;
734 static void cameraPunchLeft(MtEvent *e, void *data)
736 SoundMaker *sm = (SoundMaker*)data;
737 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
740 static void cameraPunchRight(MtEvent *e, void *data)
742 SoundMaker *sm = (SoundMaker*)data;
743 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
746 static void nodeDug(MtEvent *e, void *data)
748 SoundMaker *sm = (SoundMaker*)data;
749 NodeDugEvent *nde = (NodeDugEvent*)e;
750 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
753 static void playerDamage(MtEvent *e, void *data)
755 SoundMaker *sm = (SoundMaker*)data;
756 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
759 static void playerFallingDamage(MtEvent *e, void *data)
761 SoundMaker *sm = (SoundMaker*)data;
762 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
765 void registerReceiver(MtEventManager *mgr)
767 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
768 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
769 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
770 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
771 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
772 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
773 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
774 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
777 void step(float dtime)
779 m_player_step_timer -= dtime;
783 // Locally stored sounds don't need to be preloaded because of this
784 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
786 std::set<std::string> m_fetched;
789 void fetchSounds(const std::string &name,
790 std::set<std::string> &dst_paths,
791 std::set<std::string> &dst_datas)
793 if(m_fetched.count(name))
795 m_fetched.insert(name);
796 std::string base = porting::path_share + DIR_DELIM + "testsounds";
797 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
798 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
799 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
800 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
801 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
802 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
803 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
804 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
805 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
806 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
807 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
811 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
814 bool *m_force_fog_off;
819 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
820 f32 *fog_range, Client *client):
822 m_force_fog_off(force_fog_off),
823 m_fog_range(fog_range),
826 ~GameGlobalShaderConstantSetter() {}
828 virtual void onSetConstants(video::IMaterialRendererServices *services,
835 video::SColor bgcolor = m_sky->getBgColor();
836 video::SColorf bgcolorf(bgcolor);
837 float bgcolorfa[4] = {
843 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
846 float fog_distance = 10000*BS;
847 if(g_settings->getBool("enable_fog") && !*m_force_fog_off)
848 fog_distance = *m_fog_range;
849 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
852 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
853 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
854 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
856 u32 animation_timer = porting::getTimeMs() % 100000;
857 float animation_timer_f = (float)animation_timer / 100000.0;
858 services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
859 services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
861 LocalPlayer* player = m_client->getEnv().getLocalPlayer();
862 v3f eye_position = player->getEyePosition();
863 services->setPixelShaderConstant("eyePosition", (irr::f32*)&eye_position, 3);
864 services->setVertexShaderConstant("eyePosition", (irr::f32*)&eye_position, 3);
866 // Uniform sampler layers
870 // before 1.8 there isn't a "integer interface", only float
871 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
872 services->setPixelShaderConstant("baseTexture" , (irr::f32*)&layer0, 1);
873 services->setPixelShaderConstant("normalTexture" , (irr::f32*)&layer1, 1);
874 services->setPixelShaderConstant("useNormalmap" , (irr::f32*)&layer2, 1);
876 services->setPixelShaderConstant("baseTexture" , (irr::s32*)&layer0, 1);
877 services->setPixelShaderConstant("normalTexture" , (irr::s32*)&layer1, 1);
878 services->setPixelShaderConstant("useNormalmap" , (irr::s32*)&layer2, 1);
883 bool nodePlacementPrediction(Client &client,
884 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
886 std::string prediction = playeritem_def.node_placement_prediction;
887 INodeDefManager *nodedef = client.ndef();
888 ClientMap &map = client.getEnv().getClientMap();
890 if(prediction != "" && !nodedef->get(map.getNode(nodepos)).rightclickable)
892 verbosestream<<"Node placement prediction for "
893 <<playeritem_def.name<<" is "
894 <<prediction<<std::endl;
895 v3s16 p = neighbourpos;
896 // Place inside node itself if buildable_to
898 MapNode n_under = map.getNode(nodepos);
899 if(nodedef->get(n_under).buildable_to)
901 else if (!nodedef->get(map.getNode(p)).buildable_to)
903 }catch(InvalidPositionException &e){}
904 // Find id of predicted node
906 bool found = nodedef->getId(prediction, id);
908 errorstream<<"Node placement prediction failed for "
909 <<playeritem_def.name<<" (places "
911 <<") - Name not known"<<std::endl;
914 // Predict param2 for facedir and wallmounted nodes
916 if(nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED){
917 v3s16 dir = nodepos - neighbourpos;
918 if(abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))){
919 param2 = dir.Y < 0 ? 1 : 0;
920 } else if(abs(dir.X) > abs(dir.Z)){
921 param2 = dir.X < 0 ? 3 : 2;
923 param2 = dir.Z < 0 ? 5 : 4;
926 if(nodedef->get(id).param_type_2 == CPT2_FACEDIR){
927 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
928 if(abs(dir.X) > abs(dir.Z)){
929 param2 = dir.X < 0 ? 3 : 1;
931 param2 = dir.Z < 0 ? 2 : 0;
934 assert(param2 >= 0 && param2 <= 5);
935 //Check attachment if node is in group attached_node
936 if(((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0){
937 static v3s16 wallmounted_dirs[8] = {
946 if(nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
947 pp = p + wallmounted_dirs[param2];
949 pp = p + v3s16(0,-1,0);
950 if(!nodedef->get(map.getNode(pp)).walkable)
953 // Add node to client map
954 MapNode n(id, 0, param2);
956 LocalPlayer* player = client.getEnv().getLocalPlayer();
958 // Dont place node when player would be inside new node
959 // NOTE: This is to be eventually implemented by a mod as client-side Lua
960 if (!nodedef->get(n).walkable ||
961 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
962 (nodedef->get(n).walkable &&
963 neighbourpos != player->getStandingNodePos() + v3s16(0,1,0) &&
964 neighbourpos != player->getStandingNodePos() + v3s16(0,2,0))) {
966 // This triggers the required mesh update too
967 client.addNode(p, n);
970 }catch(InvalidPositionException &e){
971 errorstream<<"Node placement prediction failed for "
972 <<playeritem_def.name<<" (places "
974 <<") - Position not loaded"<<std::endl;
980 static void show_chat_menu(FormspecFormSource* current_formspec,
981 TextDest* current_textdest, IWritableTextureSource* tsrc,
982 IrrlichtDevice * device, Client* client, std::string text)
984 std::string formspec =
986 "field[3,2.35;6,0.5;f_text;;" + text + "]"
987 "button_exit[4,3;3,0.5;btn_send;" + wide_to_narrow(wstrgettext("Proceed")) + "]"
991 /* Note: FormspecFormSource and LocalFormspecHandler
992 * are deleted by guiFormSpecMenu */
993 current_formspec = new FormspecFormSource(formspec,¤t_formspec);
994 current_textdest = new LocalFormspecHandler("MT_CHAT_MENU",client);
995 GUIFormSpecMenu *menu =
996 new GUIFormSpecMenu(device, guiroot, -1,
999 menu->doPause = false;
1000 menu->setFormSource(current_formspec);
1001 menu->setTextDest(current_textdest);
1005 /******************************************************************************/
1006 static void show_pause_menu(FormspecFormSource* current_formspec,
1007 TextDest* current_textdest, IWritableTextureSource* tsrc,
1008 IrrlichtDevice * device, bool singleplayermode)
1011 std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1013 "- Space: jump/climb\n"
1014 "- Shift: sneak/go down\n"
1017 "- Mouse: turn/look\n"
1018 "- Mouse left: dig/punch\n"
1019 "- Mouse right: place/use\n"
1020 "- Mouse wheel: select item\n"
1024 float ypos = singleplayermode ? 1.0 : 0.5;
1025 std::ostringstream os;
1027 os << "size[11,5.5,true]"
1028 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1029 << wide_to_narrow(wstrgettext("Continue")) << "]";
1031 if (!singleplayermode) {
1032 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1033 << wide_to_narrow(wstrgettext("Change Password")) << "]";
1036 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1037 << wide_to_narrow(wstrgettext("Sound Volume")) << "]";
1038 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1039 << wide_to_narrow(wstrgettext("Exit to Menu")) << "]";
1040 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1041 << wide_to_narrow(wstrgettext("Exit to OS")) << "]"
1042 << "textarea[7.5,0.25;3.75,6;;" << control_text << ";]"
1043 << "textarea[0.4,0.25;3.5,6;;" << "Minetest\n"
1044 << minetest_build_info << "\n"
1045 << "path_user = " << wrap_rows(porting::path_user, 20)
1049 /* Note: FormspecFormSource and LocalFormspecHandler *
1050 * are deleted by guiFormSpecMenu */
1051 current_formspec = new FormspecFormSource(os.str(),¤t_formspec);
1052 current_textdest = new LocalFormspecHandler("MT_PAUSE_MENU");
1053 GUIFormSpecMenu *menu =
1054 new GUIFormSpecMenu(device, guiroot, -1, &g_menumgr, NULL, NULL, tsrc);
1055 menu->doPause = true;
1056 menu->setFormSource(current_formspec);
1057 menu->setTextDest(current_textdest);
1061 /******************************************************************************/
1062 void the_game(bool &kill, bool random_input, InputHandler *input,
1063 IrrlichtDevice *device, gui::IGUIFont* font, std::string map_dir,
1064 std::string playername, std::string password,
1065 std::string address /* If "", local server is used */,
1066 u16 port, std::wstring &error_message, ChatBackend &chat_backend,
1067 const SubgameSpec &gamespec /* Used for local game */,
1068 bool simple_singleplayer_mode)
1070 FormspecFormSource* current_formspec = 0;
1071 TextDest* current_textdest = 0;
1072 video::IVideoDriver* driver = device->getVideoDriver();
1073 scene::ISceneManager* smgr = device->getSceneManager();
1075 // Calculate text height using the font
1076 u32 text_height = font->getDimension(L"Random test string").Height;
1078 v2u32 last_screensize(0,0);
1079 v2u32 screensize = driver->getScreenSize();
1082 Draw "Loading" screen
1086 wchar_t* text = wgettext("Loading...");
1087 draw_load_screen(text, device, font,0,0);
1091 // Create texture source
1092 IWritableTextureSource *tsrc = createTextureSource(device);
1094 // Create shader source
1095 IWritableShaderSource *shsrc = createShaderSource(device);
1097 // These will be filled by data received from the server
1098 // Create item definition manager
1099 IWritableItemDefManager *itemdef = createItemDefManager();
1100 // Create node definition manager
1101 IWritableNodeDefManager *nodedef = createNodeDefManager();
1103 // Sound fetcher (useful when testing)
1104 GameOnDemandSoundFetcher soundfetcher;
1107 ISoundManager *sound = NULL;
1108 bool sound_is_dummy = false;
1110 if(g_settings->getBool("enable_sound")){
1111 infostream<<"Attempting to use OpenAL audio"<<std::endl;
1112 sound = createOpenALSoundManager(&soundfetcher);
1114 infostream<<"Failed to initialize OpenAL audio"<<std::endl;
1116 infostream<<"Sound disabled."<<std::endl;
1120 infostream<<"Using dummy audio."<<std::endl;
1121 sound = &dummySoundManager;
1122 sound_is_dummy = true;
1125 Server *server = NULL;
1129 EventManager eventmgr;
1132 SoundMaker soundmaker(sound, nodedef);
1133 soundmaker.registerReceiver(&eventmgr);
1135 // Add chat log output for errors to be shown in chat
1136 LogOutputBuffer chat_log_error_buf(LMT_ERROR);
1138 // Create UI for modifying quicktune values
1139 QuicktuneShortcutter quicktune;
1146 wchar_t* text = wgettext("Creating server....");
1147 draw_load_screen(text, device, font,0,25);
1149 infostream<<"Creating server"<<std::endl;
1151 std::string bind_str = g_settings->get("bind_address");
1152 Address bind_addr(0,0,0,0, port);
1154 if (g_settings->getBool("ipv6_server")) {
1155 bind_addr.setAddress((IPv6AddressBytes*) NULL);
1158 bind_addr.Resolve(bind_str.c_str());
1160 } catch (ResolveError &e) {
1161 infostream << "Resolving bind address \"" << bind_str
1162 << "\" failed: " << e.what()
1163 << " -- Listening on all addresses." << std::endl;
1166 if(bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1167 error_message = L"Unable to listen on " +
1168 narrow_to_wide(bind_addr.serializeString()) +
1169 L" because IPv6 is disabled";
1170 errorstream<<wide_to_narrow(error_message)<<std::endl;
1171 // Break out of client scope
1175 server = new Server(map_dir, gamespec,
1176 simple_singleplayer_mode,
1177 bind_addr.isIPv6());
1179 server->start(bind_addr);
1182 do{ // Client scope (breakable do-while(0))
1189 wchar_t* text = wgettext("Creating client...");
1190 draw_load_screen(text, device, font,0,50);
1193 infostream<<"Creating client"<<std::endl;
1195 MapDrawControl draw_control;
1198 wchar_t* text = wgettext("Resolving address...");
1199 draw_load_screen(text, device, font,0,75);
1202 Address connect_address(0,0,0,0, port);
1204 connect_address.Resolve(address.c_str());
1205 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
1206 //connect_address.Resolve("localhost");
1207 if (connect_address.isIPv6()) {
1208 IPv6AddressBytes addr_bytes;
1209 addr_bytes.bytes[15] = 1;
1210 connect_address.setAddress(&addr_bytes);
1212 connect_address.setAddress(127,0,0,1);
1216 catch(ResolveError &e) {
1217 error_message = L"Couldn't resolve address: " + narrow_to_wide(e.what());
1218 errorstream<<wide_to_narrow(error_message)<<std::endl;
1219 // Break out of client scope
1222 if(connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1223 error_message = L"Unable to connect to " +
1224 narrow_to_wide(connect_address.serializeString()) +
1225 L" because IPv6 is disabled";
1226 errorstream<<wide_to_narrow(error_message)<<std::endl;
1227 // Break out of client scope
1234 Client client(device, playername.c_str(), password, draw_control,
1235 tsrc, shsrc, itemdef, nodedef, sound, &eventmgr,
1236 connect_address.isIPv6());
1238 // Client acts as our GameDef
1239 IGameDef *gamedef = &client;
1242 Attempt to connect to the server
1245 infostream<<"Connecting to server at ";
1246 connect_address.print(&infostream);
1247 infostream<<std::endl;
1248 client.connect(connect_address);
1251 Wait for server to accept connection
1253 bool could_connect = false;
1254 bool connect_aborted = false;
1256 float time_counter = 0.0;
1258 float fps_max = g_settings->getFloat("fps_max");
1259 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1260 u32 lasttime = device->getTimer()->getTime();
1261 while(device->run())
1263 f32 dtime = 0.033; // in seconds
1264 if (cloud_menu_background) {
1265 u32 time = device->getTimer()->getTime();
1267 dtime = (time - lasttime) / 1000.0;
1272 // Update client and server
1275 server->step(dtime);
1278 if(client.getState() == LC_Init){
1279 could_connect = true;
1283 if(client.accessDenied()){
1284 error_message = L"Access denied. Reason: "
1285 +client.accessDeniedReason();
1286 errorstream<<wide_to_narrow(error_message)<<std::endl;
1289 if(input->wasKeyDown(EscapeKey)){
1290 connect_aborted = true;
1291 infostream<<"Connect aborted [Escape]"<<std::endl;
1297 wchar_t* text = wgettext("Connecting to server...");
1298 draw_load_screen(text, device, font, dtime, 100);
1302 // On some computers framerate doesn't seem to be
1303 // automatically limited
1304 if (cloud_menu_background) {
1305 // Time of frame without fps limit
1308 // not using getRealTime is necessary for wine
1309 u32 time = device->getTimer()->getTime();
1311 busytime_u32 = time - lasttime;
1314 busytime = busytime_u32 / 1000.0;
1317 u32 frametime_min = 1000./fps_max;
1319 if(busytime_u32 < frametime_min) {
1320 u32 sleeptime = frametime_min - busytime_u32;
1321 device->sleep(sleeptime);
1326 time_counter += dtime;
1329 catch(con::PeerNotFoundException &e)
1333 Handle failure to connect
1336 if(error_message == L"" && !connect_aborted){
1337 error_message = L"Connection failed";
1338 errorstream<<wide_to_narrow(error_message)<<std::endl;
1340 // Break out of client scope
1345 Wait until content has been received
1347 bool got_content = false;
1348 bool content_aborted = false;
1350 float time_counter = 0.0;
1352 float fps_max = g_settings->getFloat("fps_max");
1353 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1354 u32 lasttime = device->getTimer()->getTime();
1355 while(device->run())
1357 f32 dtime = 0.033; // in seconds
1358 if (cloud_menu_background) {
1359 u32 time = device->getTimer()->getTime();
1361 dtime = (time - lasttime) / 1000.0;
1366 // Update client and server
1369 server->step(dtime);
1372 if(client.mediaReceived() &&
1373 client.itemdefReceived() &&
1374 client.nodedefReceived()){
1379 if(client.accessDenied()){
1380 error_message = L"Access denied. Reason: "
1381 +client.accessDeniedReason();
1382 errorstream<<wide_to_narrow(error_message)<<std::endl;
1385 if(client.getState() < LC_Init){
1386 error_message = L"Client disconnected";
1387 errorstream<<wide_to_narrow(error_message)<<std::endl;
1390 if(input->wasKeyDown(EscapeKey)){
1391 content_aborted = true;
1392 infostream<<"Connect aborted [Escape]"<<std::endl;
1398 if (!client.itemdefReceived())
1400 wchar_t* text = wgettext("Item definitions...");
1402 draw_load_screen(text, device, font, dtime, progress);
1405 else if (!client.nodedefReceived())
1407 wchar_t* text = wgettext("Node definitions...");
1409 draw_load_screen(text, device, font, dtime, progress);
1414 wchar_t* text = wgettext("Media...");
1415 progress = 50+client.mediaReceiveProgress()*50+0.5;
1416 draw_load_screen(text, device, font, dtime, progress);
1420 // On some computers framerate doesn't seem to be
1421 // automatically limited
1422 if (cloud_menu_background) {
1423 // Time of frame without fps limit
1426 // not using getRealTime is necessary for wine
1427 u32 time = device->getTimer()->getTime();
1429 busytime_u32 = time - lasttime;
1432 busytime = busytime_u32 / 1000.0;
1435 u32 frametime_min = 1000./fps_max;
1437 if(busytime_u32 < frametime_min) {
1438 u32 sleeptime = frametime_min - busytime_u32;
1439 device->sleep(sleeptime);
1444 time_counter += dtime;
1449 if(error_message == L"" && !content_aborted){
1450 error_message = L"Something failed";
1451 errorstream<<wide_to_narrow(error_message)<<std::endl;
1453 // Break out of client scope
1458 After all content has been received:
1459 Update cached textures, meshes and materials
1461 client.afterContentReceived(device,font);
1464 Create the camera node
1466 Camera camera(smgr, draw_control, gamedef);
1467 if (!camera.successfullyCreated(error_message))
1470 f32 camera_yaw = 0; // "right/left"
1471 f32 camera_pitch = 0; // "up/down"
1473 int current_camera_mode = CAMERA_MODE_FIRST; // start in first-person view
1479 Clouds *clouds = NULL;
1480 if(g_settings->getBool("enable_clouds"))
1482 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1490 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, client.getEnv().getLocalPlayer());
1492 scene::ISceneNode* skybox = NULL;
1495 A copy of the local inventory
1497 Inventory local_inventory(itemdef);
1500 Find out size of crack animation
1502 int crack_animation_length = 5;
1504 video::ITexture *t = tsrc->getTexture("crack_anylength.png");
1505 v2u32 size = t->getOriginalSize();
1506 crack_animation_length = size.Y / size.X;
1513 // First line of debug text
1514 gui::IGUIStaticText *guitext = guienv->addStaticText(
1516 core::rect<s32>(5, 5, 795, 5+text_height),
1518 // Second line of debug text
1519 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1521 core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
1523 // At the middle of the screen
1524 // Object infos are shown in this
1525 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1527 core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1530 // Status text (displays info when showing and hiding GUI stuff, etc.)
1531 gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1533 core::rect<s32>(0,0,0,0),
1535 guitext_status->setVisible(false);
1537 std::wstring statustext;
1538 float statustext_time = 0;
1541 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1543 core::rect<s32>(0,0,0,0),
1544 //false, false); // Disable word wrap as of now
1546 // Remove stale "recent" chat messages from previous connections
1547 chat_backend.clearRecentChat();
1548 // Chat backend and console
1549 GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1551 // Profiler text (size is updated when text is updated)
1552 gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1554 core::rect<s32>(0,0,0,0),
1556 guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1557 guitext_profiler->setVisible(false);
1558 guitext_profiler->setWordWrap(true);
1561 Some statistics are collected in these
1564 u32 beginscenetime = 0;
1566 u32 endscenetime = 0;
1568 float recent_turn_speed = 0.0;
1570 ProfilerGraph graph;
1571 // Initially clear the profiler
1572 Profiler::GraphValues dummyvalues;
1573 g_profiler->graphGet(dummyvalues);
1575 float nodig_delay_timer = 0.0;
1576 float dig_time = 0.0;
1578 PointedThing pointed_old;
1579 bool digging = false;
1580 bool ldown_for_dig = false;
1582 float damage_flash = 0;
1584 float jump_timer = 0;
1585 bool reset_jump_timer = false;
1587 const float object_hit_delay = 0.2;
1588 float object_hit_delay_timer = 0.0;
1589 float time_from_last_punch = 10;
1591 float update_draw_list_timer = 0.0;
1592 v3f update_draw_list_last_cam_dir;
1594 bool invert_mouse = g_settings->getBool("invert_mouse");
1596 bool respawn_menu_active = false;
1597 bool update_wielded_item_trigger = true;
1599 bool show_hud = true;
1600 bool show_chat = true;
1601 bool force_fog_off = false;
1602 f32 fog_range = 100*BS;
1603 bool disable_camera_update = false;
1604 bool show_debug = g_settings->getBool("show_debug");
1605 bool show_profiler_graph = false;
1606 u32 show_profiler = 0;
1607 u32 show_profiler_max = 3; // Number of pages
1609 float time_of_day = 0;
1610 float time_of_day_smooth = 0;
1612 float repeat_rightclick_timer = 0;
1617 shsrc->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1618 sky, &force_fog_off, &fog_range, &client));
1624 bool first_loop_after_window_activation = true;
1626 // TODO: Convert the static interval timers to these
1627 // Interval limiter for profiler
1628 IntervalLimiter m_profiler_interval;
1630 // Time is in milliseconds
1631 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1632 // NOTE: So we have to use getTime() and call run()s between them
1633 u32 lasttime = device->getTimer()->getTime();
1635 LocalPlayer* player = client.getEnv().getLocalPlayer();
1636 player->hurt_tilt_timer = 0;
1637 player->hurt_tilt_strength = 0;
1642 Hud hud(driver, smgr, guienv, font, text_height,
1643 gamedef, player, &local_inventory);
1645 bool use_weather = g_settings->getBool("weather");
1647 core::stringw str = L"Minetest [";
1648 str += driver->getName();
1650 device->setWindowCaption(str.c_str());
1653 std::wstring infotext;
1657 if(device->run() == false || kill == true)
1660 // Time of frame without fps limit
1664 // not using getRealTime is necessary for wine
1665 u32 time = device->getTimer()->getTime();
1667 busytime_u32 = time - lasttime;
1670 busytime = busytime_u32 / 1000.0;
1673 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1675 // Necessary for device->getTimer()->getTime()
1683 float fps_max = g_menumgr.pausesGame() ?
1684 g_settings->getFloat("pause_fps_max") :
1685 g_settings->getFloat("fps_max");
1686 u32 frametime_min = 1000./fps_max;
1688 if(busytime_u32 < frametime_min)
1690 u32 sleeptime = frametime_min - busytime_u32;
1691 device->sleep(sleeptime);
1692 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1696 // Necessary for device->getTimer()->getTime()
1700 Time difference calculation
1702 f32 dtime; // in seconds
1704 u32 time = device->getTimer()->getTime();
1706 dtime = (time - lasttime) / 1000.0;
1711 g_profiler->graphAdd("mainloop_dtime", dtime);
1715 if(nodig_delay_timer >= 0)
1716 nodig_delay_timer -= dtime;
1717 if(object_hit_delay_timer >= 0)
1718 object_hit_delay_timer -= dtime;
1719 time_from_last_punch += dtime;
1721 g_profiler->add("Elapsed time", dtime);
1722 g_profiler->avg("FPS", 1./dtime);
1725 Time average and jitter calculation
1728 static f32 dtime_avg1 = 0.0;
1729 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1730 f32 dtime_jitter1 = dtime - dtime_avg1;
1732 static f32 dtime_jitter1_max_sample = 0.0;
1733 static f32 dtime_jitter1_max_fraction = 0.0;
1735 static f32 jitter1_max = 0.0;
1736 static f32 counter = 0.0;
1737 if(dtime_jitter1 > jitter1_max)
1738 jitter1_max = dtime_jitter1;
1743 dtime_jitter1_max_sample = jitter1_max;
1744 dtime_jitter1_max_fraction
1745 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1751 Busytime average and jitter calculation
1754 static f32 busytime_avg1 = 0.0;
1755 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1756 f32 busytime_jitter1 = busytime - busytime_avg1;
1758 static f32 busytime_jitter1_max_sample = 0.0;
1759 static f32 busytime_jitter1_min_sample = 0.0;
1761 static f32 jitter1_max = 0.0;
1762 static f32 jitter1_min = 0.0;
1763 static f32 counter = 0.0;
1764 if(busytime_jitter1 > jitter1_max)
1765 jitter1_max = busytime_jitter1;
1766 if(busytime_jitter1 < jitter1_min)
1767 jitter1_min = busytime_jitter1;
1771 busytime_jitter1_max_sample = jitter1_max;
1772 busytime_jitter1_min_sample = jitter1_min;
1779 Handle miscellaneous stuff
1782 if(client.accessDenied())
1784 error_message = L"Access denied. Reason: "
1785 +client.accessDeniedReason();
1786 errorstream<<wide_to_narrow(error_message)<<std::endl;
1790 if(g_gamecallback->disconnect_requested)
1792 g_gamecallback->disconnect_requested = false;
1796 if(g_gamecallback->changepassword_requested)
1798 (new GUIPasswordChange(guienv, guiroot, -1,
1799 &g_menumgr, &client))->drop();
1800 g_gamecallback->changepassword_requested = false;
1803 if(g_gamecallback->changevolume_requested)
1805 (new GUIVolumeChange(guienv, guiroot, -1,
1806 &g_menumgr, &client))->drop();
1807 g_gamecallback->changevolume_requested = false;
1810 /* Process TextureSource's queue */
1811 tsrc->processQueue();
1813 /* Process ItemDefManager's queue */
1814 itemdef->processQueue(gamedef);
1817 Process ShaderSource's queue
1819 shsrc->processQueue();
1824 last_screensize = screensize;
1825 screensize = driver->getScreenSize();
1826 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1827 //bool screensize_changed = screensize != last_screensize;
1830 // Update HUD values
1831 hud.screensize = screensize;
1832 hud.displaycenter = displaycenter;
1835 // Hilight boxes collected during the loop and displayed
1836 std::vector<aabb3f> hilightboxes;
1838 /* reset infotext */
1843 float profiler_print_interval =
1844 g_settings->getFloat("profiler_print_interval");
1845 bool print_to_log = true;
1846 if(profiler_print_interval == 0){
1847 print_to_log = false;
1848 profiler_print_interval = 5;
1850 if(m_profiler_interval.step(dtime, profiler_print_interval))
1853 infostream<<"Profiler:"<<std::endl;
1854 g_profiler->print(infostream);
1857 update_profiler_gui(guitext_profiler, font, text_height,
1858 show_profiler, show_profiler_max);
1860 g_profiler->clear();
1864 Direct handling of user input
1867 // Reset input if window not active or some menu is active
1868 if(device->isWindowActive() == false
1869 || noMenuActive() == false
1870 || guienv->hasFocus(gui_chat_console))
1874 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen())
1876 gui_chat_console->closeConsoleAtOnce();
1879 // Input handler step() (used by the random input generator)
1882 // Increase timer for doubleclick of "jump"
1883 if(g_settings->getBool("doubletap_jump") && jump_timer <= 0.2)
1884 jump_timer += dtime;
1887 Launch menus and trigger stuff according to keys
1889 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1891 // drop selected item
1892 IDropAction *a = new IDropAction();
1894 a->from_inv.setCurrentPlayer();
1895 a->from_list = "main";
1896 a->from_i = client.getPlayerItem();
1897 client.inventoryAction(a);
1899 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1901 infostream<<"the_game: "
1902 <<"Launching inventory"<<std::endl;
1904 GUIFormSpecMenu *menu =
1905 new GUIFormSpecMenu(device, guiroot, -1,
1907 &client, gamedef, tsrc);
1909 InventoryLocation inventoryloc;
1910 inventoryloc.setCurrentPlayer();
1912 PlayerInventoryFormSource *src = new PlayerInventoryFormSource(&client);
1914 menu->doPause = false;
1915 menu->setFormSpec(src->getForm(), inventoryloc);
1916 menu->setFormSource(src);
1917 menu->setTextDest(new TextDestPlayerInventory(&client));
1920 else if(input->wasKeyDown(EscapeKey))
1922 show_pause_menu(current_formspec, current_textdest, tsrc, device,
1923 simple_singleplayer_mode);
1925 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1927 show_chat_menu(current_formspec, current_textdest, tsrc, device, &client,"");
1929 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1931 show_chat_menu(current_formspec, current_textdest, tsrc, device, &client,"/");
1933 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1935 if (!gui_chat_console->isOpenInhibited())
1937 // Open up to over half of the screen
1938 gui_chat_console->openConsole(0.6);
1939 guienv->setFocus(gui_chat_console);
1942 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1944 if(g_settings->getBool("free_move"))
1946 g_settings->set("free_move","false");
1947 statustext = L"free_move disabled";
1948 statustext_time = 0;
1952 g_settings->set("free_move","true");
1953 statustext = L"free_move enabled";
1954 statustext_time = 0;
1955 if(!client.checkPrivilege("fly"))
1956 statustext += L" (note: no 'fly' privilege)";
1959 else if(input->wasKeyDown(getKeySetting("keymap_jump")))
1961 if(g_settings->getBool("doubletap_jump") && jump_timer < 0.2)
1963 if(g_settings->getBool("free_move"))
1965 g_settings->set("free_move","false");
1966 statustext = L"free_move disabled";
1967 statustext_time = 0;
1971 g_settings->set("free_move","true");
1972 statustext = L"free_move enabled";
1973 statustext_time = 0;
1974 if(!client.checkPrivilege("fly"))
1975 statustext += L" (note: no 'fly' privilege)";
1978 reset_jump_timer = true;
1980 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1982 if(g_settings->getBool("fast_move"))
1984 g_settings->set("fast_move","false");
1985 statustext = L"fast_move disabled";
1986 statustext_time = 0;
1990 g_settings->set("fast_move","true");
1991 statustext = L"fast_move enabled";
1992 statustext_time = 0;
1993 if(!client.checkPrivilege("fast"))
1994 statustext += L" (note: no 'fast' privilege)";
1997 else if(input->wasKeyDown(getKeySetting("keymap_noclip")))
1999 if(g_settings->getBool("noclip"))
2001 g_settings->set("noclip","false");
2002 statustext = L"noclip disabled";
2003 statustext_time = 0;
2007 g_settings->set("noclip","true");
2008 statustext = L"noclip enabled";
2009 statustext_time = 0;
2010 if(!client.checkPrivilege("noclip"))
2011 statustext += L" (note: no 'noclip' privilege)";
2014 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
2016 irr::video::IImage* const image = driver->createScreenShot();
2018 irr::c8 filename[256];
2019 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png",
2020 g_settings->get("screenshot_path").c_str(),
2021 device->getTimer()->getRealTime());
2022 if (driver->writeImageToFile(image, filename)) {
2023 std::wstringstream sstr;
2024 sstr<<"Saved screenshot to '"<<filename<<"'";
2025 infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
2026 statustext = sstr.str();
2027 statustext_time = 0;
2029 infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
2034 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
2036 show_hud = !show_hud;
2038 statustext = L"HUD shown";
2040 statustext = L"HUD hidden";
2041 statustext_time = 0;
2043 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
2045 show_chat = !show_chat;
2047 statustext = L"Chat shown";
2049 statustext = L"Chat hidden";
2050 statustext_time = 0;
2052 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
2054 force_fog_off = !force_fog_off;
2056 statustext = L"Fog disabled";
2058 statustext = L"Fog enabled";
2059 statustext_time = 0;
2061 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
2063 disable_camera_update = !disable_camera_update;
2064 if(disable_camera_update)
2065 statustext = L"Camera update disabled";
2067 statustext = L"Camera update enabled";
2068 statustext_time = 0;
2070 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
2072 // Initial / 3x toggle: Chat only
2073 // 1x toggle: Debug text with chat
2074 // 2x toggle: Debug text with profiler graph
2078 show_profiler_graph = false;
2079 statustext = L"Debug info shown";
2080 statustext_time = 0;
2082 else if(show_profiler_graph)
2085 show_profiler_graph = false;
2086 statustext = L"Debug info and profiler graph hidden";
2087 statustext_time = 0;
2091 show_profiler_graph = true;
2092 statustext = L"Profiler graph shown";
2093 statustext_time = 0;
2096 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
2098 show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
2100 // FIXME: This updates the profiler with incomplete values
2101 update_profiler_gui(guitext_profiler, font, text_height,
2102 show_profiler, show_profiler_max);
2104 if(show_profiler != 0)
2106 std::wstringstream sstr;
2107 sstr<<"Profiler shown (page "<<show_profiler
2108 <<" of "<<show_profiler_max<<")";
2109 statustext = sstr.str();
2110 statustext_time = 0;
2114 statustext = L"Profiler hidden";
2115 statustext_time = 0;
2118 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
2120 s16 range = g_settings->getS16("viewing_range_nodes_min");
2121 s16 range_new = range + 10;
2122 g_settings->set("viewing_range_nodes_min", itos(range_new));
2123 statustext = narrow_to_wide(
2124 "Minimum viewing range changed to "
2126 statustext_time = 0;
2128 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
2130 s16 range = g_settings->getS16("viewing_range_nodes_min");
2131 s16 range_new = range - 10;
2134 g_settings->set("viewing_range_nodes_min",
2136 statustext = narrow_to_wide(
2137 "Minimum viewing range changed to "
2139 statustext_time = 0;
2143 if(!input->isKeyDown(getKeySetting("keymap_jump")) && reset_jump_timer)
2145 reset_jump_timer = false;
2149 // Handle QuicktuneShortcutter
2150 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
2152 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
2154 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
2156 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
2159 std::string msg = quicktune.getMessage();
2161 statustext = narrow_to_wide(msg);
2162 statustext_time = 0;
2166 // Item selection with mouse wheel
2167 u16 new_playeritem = client.getPlayerItem();
2169 s32 wheel = input->getMouseWheel();
2170 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
2171 player->hud_hotbar_itemcount-1);
2175 if(new_playeritem < max_item)
2182 if(new_playeritem > 0)
2185 new_playeritem = max_item;
2190 for(u16 i=0; i<10; i++)
2192 const KeyPress *kp = NumberKey + (i + 1) % 10;
2193 if(input->wasKeyDown(*kp))
2195 if(i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount)
2199 infostream<<"Selected item: "
2200 <<new_playeritem<<std::endl;
2205 // Viewing range selection
2206 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
2208 draw_control.range_all = !draw_control.range_all;
2209 if(draw_control.range_all)
2211 infostream<<"Enabled full viewing range"<<std::endl;
2212 statustext = L"Enabled full viewing range";
2213 statustext_time = 0;
2217 infostream<<"Disabled full viewing range"<<std::endl;
2218 statustext = L"Disabled full viewing range";
2219 statustext_time = 0;
2223 // Print debug stacks
2224 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
2226 dstream<<"-----------------------------------------"
2228 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
2229 dstream<<"-----------------------------------------"
2231 debug_stacks_print();
2235 Mouse and camera control
2236 NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
2239 float turn_amount = 0;
2240 if((device->isWindowActive() && noMenuActive()) || random_input)
2244 // Mac OSX gets upset if this is set every frame
2245 if(device->getCursorControl()->isVisible())
2246 device->getCursorControl()->setVisible(false);
2249 if(first_loop_after_window_activation){
2250 //infostream<<"window active, first loop"<<std::endl;
2251 first_loop_after_window_activation = false;
2254 s32 dx = input->getMousePos().X - displaycenter.X;
2255 s32 dy = input->getMousePos().Y - displaycenter.Y;
2256 if(invert_mouse || player->camera_mode == CAMERA_MODE_THIRD_FRONT)
2258 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
2260 /*const float keyspeed = 500;
2261 if(input->isKeyDown(irr::KEY_UP))
2262 dy -= dtime * keyspeed;
2263 if(input->isKeyDown(irr::KEY_DOWN))
2264 dy += dtime * keyspeed;
2265 if(input->isKeyDown(irr::KEY_LEFT))
2266 dx -= dtime * keyspeed;
2267 if(input->isKeyDown(irr::KEY_RIGHT))
2268 dx += dtime * keyspeed;*/
2270 float d = g_settings->getFloat("mouse_sensitivity");
2271 d = rangelim(d, 0.01, 100.0);
2273 camera_pitch += dy*d;
2274 if(camera_pitch < -89.5) camera_pitch = -89.5;
2275 if(camera_pitch > 89.5) camera_pitch = 89.5;
2277 turn_amount = v2f(dx, dy).getLength() * d;
2279 input->setMousePos(displaycenter.X, displaycenter.Y);
2282 // Mac OSX gets upset if this is set every frame
2283 if(device->getCursorControl()->isVisible() == false)
2284 device->getCursorControl()->setVisible(true);
2286 //infostream<<"window inactive"<<std::endl;
2287 first_loop_after_window_activation = true;
2289 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
2290 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
2293 Player speed control
2307 PlayerControl control(
2308 input->isKeyDown(getKeySetting("keymap_forward")),
2309 input->isKeyDown(getKeySetting("keymap_backward")),
2310 input->isKeyDown(getKeySetting("keymap_left")),
2311 input->isKeyDown(getKeySetting("keymap_right")),
2312 input->isKeyDown(getKeySetting("keymap_jump")),
2313 input->isKeyDown(getKeySetting("keymap_special1")),
2314 input->isKeyDown(getKeySetting("keymap_sneak")),
2315 input->getLeftState(),
2316 input->getRightState(),
2320 client.setPlayerControl(control);
2321 LocalPlayer* player = client.getEnv().getLocalPlayer();
2323 (((int)input->isKeyDown(getKeySetting("keymap_forward")) & 0x1) << 0) |
2324 (((int)input->isKeyDown(getKeySetting("keymap_backward")) & 0x1) << 1) |
2325 (((int)input->isKeyDown(getKeySetting("keymap_left")) & 0x1) << 2) |
2326 (((int)input->isKeyDown(getKeySetting("keymap_right")) & 0x1) << 3) |
2327 (((int)input->isKeyDown(getKeySetting("keymap_jump")) & 0x1) << 4) |
2328 (((int)input->isKeyDown(getKeySetting("keymap_special1")) & 0x1) << 5) |
2329 (((int)input->isKeyDown(getKeySetting("keymap_sneak")) & 0x1) << 6) |
2330 (((int)input->getLeftState() & 0x1) << 7) |
2331 (((int)input->getRightState() & 0x1) << 8);
2335 Run server, client (and process environments)
2337 bool can_be_and_is_paused =
2338 (simple_singleplayer_mode && g_menumgr.pausesGame());
2339 if(can_be_and_is_paused)
2348 //TimeTaker timer("server->step(dtime)");
2349 server->step(dtime);
2352 //TimeTaker timer("client.step(dtime)");
2358 // Read client events
2361 ClientEvent event = client.getClientEvent();
2362 if(event.type == CE_NONE)
2366 else if(event.type == CE_PLAYER_DAMAGE &&
2367 client.getHP() != 0)
2369 //u16 damage = event.player_damage.amount;
2370 //infostream<<"Player damage: "<<damage<<std::endl;
2372 damage_flash += 100.0;
2373 damage_flash += 8.0 * event.player_damage.amount;
2375 player->hurt_tilt_timer = 1.5;
2376 player->hurt_tilt_strength = event.player_damage.amount/2;
2377 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 2.0, 10.0);
2379 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
2380 gamedef->event()->put(e);
2382 else if(event.type == CE_PLAYER_FORCE_MOVE)
2384 camera_yaw = event.player_force_move.yaw;
2385 camera_pitch = event.player_force_move.pitch;
2387 else if(event.type == CE_DEATHSCREEN)
2389 if(respawn_menu_active)
2392 /*bool set_camera_point_target =
2393 event.deathscreen.set_camera_point_target;
2394 v3f camera_point_target;
2395 camera_point_target.X = event.deathscreen.camera_point_target_x;
2396 camera_point_target.Y = event.deathscreen.camera_point_target_y;
2397 camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
2398 MainRespawnInitiator *respawner =
2399 new MainRespawnInitiator(
2400 &respawn_menu_active, &client);
2401 GUIDeathScreen *menu =
2402 new GUIDeathScreen(guienv, guiroot, -1,
2403 &g_menumgr, respawner);
2406 chat_backend.addMessage(L"", L"You died.");
2408 /* Handle visualization */
2412 LocalPlayer* player = client.getEnv().getLocalPlayer();
2413 player->hurt_tilt_timer = 0;
2414 player->hurt_tilt_strength = 0;
2416 /*LocalPlayer* player = client.getLocalPlayer();
2417 player->setPosition(player->getPosition() + v3f(0,-BS,0));
2418 camera.update(player, busytime, screensize);*/
2420 else if (event.type == CE_SHOW_FORMSPEC)
2422 if (current_formspec == 0)
2425 /* Note: FormspecFormSource and TextDestPlayerInventory
2426 * are deleted by guiFormSpecMenu */
2427 current_formspec = new FormspecFormSource(*(event.show_formspec.formspec),¤t_formspec);
2428 current_textdest = new TextDestPlayerInventory(&client,*(event.show_formspec.formname));
2429 GUIFormSpecMenu *menu =
2430 new GUIFormSpecMenu(device, guiroot, -1,
2432 &client, gamedef, tsrc);
2433 menu->doPause = false;
2434 menu->setFormSource(current_formspec);
2435 menu->setTextDest(current_textdest);
2440 assert(current_textdest != 0);
2442 current_textdest->setFormName(*(event.show_formspec.formname));
2443 current_formspec->setForm(*(event.show_formspec.formspec));
2445 delete(event.show_formspec.formspec);
2446 delete(event.show_formspec.formname);
2448 else if(event.type == CE_SPAWN_PARTICLE)
2450 LocalPlayer* player = client.getEnv().getLocalPlayer();
2451 video::ITexture *texture =
2452 gamedef->tsrc()->getTexture(*(event.spawn_particle.texture));
2454 new Particle(gamedef, smgr, player, client.getEnv(),
2455 *event.spawn_particle.pos,
2456 *event.spawn_particle.vel,
2457 *event.spawn_particle.acc,
2458 event.spawn_particle.expirationtime,
2459 event.spawn_particle.size,
2460 event.spawn_particle.collisiondetection,
2461 event.spawn_particle.vertical,
2466 else if(event.type == CE_ADD_PARTICLESPAWNER)
2468 LocalPlayer* player = client.getEnv().getLocalPlayer();
2469 video::ITexture *texture =
2470 gamedef->tsrc()->getTexture(*(event.add_particlespawner.texture));
2472 new ParticleSpawner(gamedef, smgr, player,
2473 event.add_particlespawner.amount,
2474 event.add_particlespawner.spawntime,
2475 *event.add_particlespawner.minpos,
2476 *event.add_particlespawner.maxpos,
2477 *event.add_particlespawner.minvel,
2478 *event.add_particlespawner.maxvel,
2479 *event.add_particlespawner.minacc,
2480 *event.add_particlespawner.maxacc,
2481 event.add_particlespawner.minexptime,
2482 event.add_particlespawner.maxexptime,
2483 event.add_particlespawner.minsize,
2484 event.add_particlespawner.maxsize,
2485 event.add_particlespawner.collisiondetection,
2486 event.add_particlespawner.vertical,
2488 event.add_particlespawner.id);
2490 else if(event.type == CE_DELETE_PARTICLESPAWNER)
2492 delete_particlespawner (event.delete_particlespawner.id);
2494 else if (event.type == CE_HUDADD)
2496 u32 id = event.hudadd.id;
2497 size_t nhudelem = player->hud.size();
2498 if (id > nhudelem || (id < nhudelem && player->hud[id])) {
2499 delete event.hudadd.pos;
2500 delete event.hudadd.name;
2501 delete event.hudadd.scale;
2502 delete event.hudadd.text;
2503 delete event.hudadd.align;
2504 delete event.hudadd.offset;
2505 delete event.hudadd.world_pos;
2509 HudElement *e = new HudElement;
2510 e->type = (HudElementType)event.hudadd.type;
2511 e->pos = *event.hudadd.pos;
2512 e->name = *event.hudadd.name;
2513 e->scale = *event.hudadd.scale;
2514 e->text = *event.hudadd.text;
2515 e->number = event.hudadd.number;
2516 e->item = event.hudadd.item;
2517 e->dir = event.hudadd.dir;
2518 e->align = *event.hudadd.align;
2519 e->offset = *event.hudadd.offset;
2520 e->world_pos = *event.hudadd.world_pos;
2523 player->hud.push_back(e);
2525 player->hud[id] = e;
2527 delete event.hudadd.pos;
2528 delete event.hudadd.name;
2529 delete event.hudadd.scale;
2530 delete event.hudadd.text;
2531 delete event.hudadd.align;
2532 delete event.hudadd.offset;
2533 delete event.hudadd.world_pos;
2535 else if (event.type == CE_HUDRM)
2537 u32 id = event.hudrm.id;
2538 if (id < player->hud.size() && player->hud[id]) {
2539 delete player->hud[id];
2540 player->hud[id] = NULL;
2543 else if (event.type == CE_HUDCHANGE)
2545 u32 id = event.hudchange.id;
2546 if (id >= player->hud.size() || !player->hud[id]) {
2547 delete event.hudchange.v3fdata;
2548 delete event.hudchange.v2fdata;
2549 delete event.hudchange.sdata;
2553 HudElement* e = player->hud[id];
2554 switch (event.hudchange.stat) {
2556 e->pos = *event.hudchange.v2fdata;
2559 e->name = *event.hudchange.sdata;
2561 case HUD_STAT_SCALE:
2562 e->scale = *event.hudchange.v2fdata;
2565 e->text = *event.hudchange.sdata;
2567 case HUD_STAT_NUMBER:
2568 e->number = event.hudchange.data;
2571 e->item = event.hudchange.data;
2574 e->dir = event.hudchange.data;
2576 case HUD_STAT_ALIGN:
2577 e->align = *event.hudchange.v2fdata;
2579 case HUD_STAT_OFFSET:
2580 e->offset = *event.hudchange.v2fdata;
2582 case HUD_STAT_WORLD_POS:
2583 e->world_pos = *event.hudchange.v3fdata;
2587 delete event.hudchange.v3fdata;
2588 delete event.hudchange.v2fdata;
2589 delete event.hudchange.sdata;
2591 else if (event.type == CE_SET_SKY)
2593 sky->setVisible(false);
2598 // Handle according to type
2599 if(*event.set_sky.type == "regular"){
2600 sky->setVisible(true);
2602 else if(*event.set_sky.type == "skybox" &&
2603 event.set_sky.params->size() == 6){
2604 sky->setFallbackBgColor(*event.set_sky.bgcolor);
2605 skybox = smgr->addSkyBoxSceneNode(
2606 tsrc->getTexture((*event.set_sky.params)[0]),
2607 tsrc->getTexture((*event.set_sky.params)[1]),
2608 tsrc->getTexture((*event.set_sky.params)[2]),
2609 tsrc->getTexture((*event.set_sky.params)[3]),
2610 tsrc->getTexture((*event.set_sky.params)[4]),
2611 tsrc->getTexture((*event.set_sky.params)[5]));
2613 // Handle everything else as plain color
2615 if(*event.set_sky.type != "plain")
2616 infostream<<"Unknown sky type: "
2617 <<(*event.set_sky.type)<<std::endl;
2618 sky->setFallbackBgColor(*event.set_sky.bgcolor);
2621 delete event.set_sky.bgcolor;
2622 delete event.set_sky.type;
2623 delete event.set_sky.params;
2625 else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO)
2627 bool enable = event.override_day_night_ratio.do_override;
2628 u32 value = event.override_day_night_ratio.ratio_f * 1000;
2629 client.getEnv().setDayNightRatioOverride(enable, value);
2634 //TimeTaker //timer2("//timer2");
2637 For interaction purposes, get info about the held item
2639 - Is it a usable item?
2640 - Can it point to liquids?
2642 ItemStack playeritem;
2644 InventoryList *mlist = local_inventory.getList("main");
2647 playeritem = mlist->getItem(client.getPlayerItem());
2650 const ItemDefinition &playeritem_def =
2651 playeritem.getDefinition(itemdef);
2652 ToolCapabilities playeritem_toolcap =
2653 playeritem.getToolCapabilities(itemdef);
2659 v3s16 old_camera_offset = camera.getOffset();
2661 LocalPlayer* player = client.getEnv().getLocalPlayer();
2662 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2663 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
2665 if(input->wasKeyDown(getKeySetting("keymap_camera_mode"))) {
2667 if (current_camera_mode == CAMERA_MODE_FIRST)
2668 current_camera_mode = CAMERA_MODE_THIRD;
2669 else if (current_camera_mode == CAMERA_MODE_THIRD)
2670 current_camera_mode = CAMERA_MODE_THIRD_FRONT;
2672 current_camera_mode = CAMERA_MODE_FIRST;
2675 player->camera_mode = current_camera_mode;
2676 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2677 camera.update(player, dtime, busytime, screensize, tool_reload_ratio,
2678 current_camera_mode, client.getEnv());
2681 v3f player_position = player->getPosition();
2682 v3s16 pos_i = floatToInt(player_position, BS);
2683 v3f camera_position = camera.getPosition();
2684 v3f camera_direction = camera.getDirection();
2685 f32 camera_fov = camera.getFovMax();
2686 v3s16 camera_offset = camera.getOffset();
2688 bool camera_offset_changed = (camera_offset != old_camera_offset);
2690 if(!disable_camera_update){
2691 client.getEnv().getClientMap().updateCamera(camera_position,
2692 camera_direction, camera_fov, camera_offset);
2693 if (camera_offset_changed){
2694 client.updateCameraOffset(camera_offset);
2695 client.getEnv().updateCameraOffset(camera_offset);
2697 clouds->updateCameraOffset(camera_offset);
2701 // Update sound listener
2702 sound->updateListener(camera.getCameraNode()->getPosition()+intToFloat(camera_offset, BS),
2703 v3f(0,0,0), // velocity
2704 camera.getDirection(),
2705 camera.getCameraNode()->getUpVector());
2706 sound->setListenerGain(g_settings->getFloat("sound_volume"));
2712 soundmaker.step(dtime);
2714 ClientMap &map = client.getEnv().getClientMap();
2715 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
2716 soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
2720 Calculate what block is the crosshair pointing to
2723 //u32 t1 = device->getTimer()->getRealTime();
2725 f32 d = playeritem_def.range; // max. distance
2726 f32 d_hand = itemdef->get("").range;
2727 if(d < 0 && d_hand >= 0)
2731 core::line3d<f32> shootline(camera_position,
2732 camera_position + camera_direction * BS * (d+1));
2734 // prevent player pointing anything in front-view
2735 if (current_camera_mode == CAMERA_MODE_THIRD_FRONT)
2736 shootline = core::line3d<f32>(0,0,0,0,0,0);
2738 ClientActiveObject *selected_object = NULL;
2740 PointedThing pointed = getPointedThing(
2742 &client, player_position, camera_direction,
2743 camera_position, shootline, d,
2744 playeritem_def.liquids_pointable, !ldown_for_dig,
2750 if(pointed != pointed_old)
2752 infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2753 //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
2758 - releasing left mouse button
2759 - pointing away from node
2763 if(input->getLeftReleased())
2765 infostream<<"Left button released"
2766 <<" (stopped digging)"<<std::endl;
2769 else if(pointed != pointed_old)
2771 if (pointed.type == POINTEDTHING_NODE
2772 && pointed_old.type == POINTEDTHING_NODE
2773 && pointed.node_undersurface == pointed_old.node_undersurface)
2775 // Still pointing to the same node,
2776 // but a different face. Don't reset.
2780 infostream<<"Pointing away from node"
2781 <<" (stopped digging)"<<std::endl;
2787 client.interact(1, pointed_old);
2788 client.setCrack(-1, v3s16(0,0,0));
2792 if(!digging && ldown_for_dig && !input->getLeftState())
2794 ldown_for_dig = false;
2797 bool left_punch = false;
2798 soundmaker.m_player_leftpunch_sound.name = "";
2800 if(input->getRightState())
2801 repeat_rightclick_timer += dtime;
2803 repeat_rightclick_timer = 0;
2805 if(playeritem_def.usable && input->getLeftState())
2807 if(input->getLeftClicked())
2808 client.interact(4, pointed);
2810 else if(pointed.type == POINTEDTHING_NODE)
2812 v3s16 nodepos = pointed.node_undersurface;
2813 v3s16 neighbourpos = pointed.node_abovesurface;
2816 Check information text of node
2819 ClientMap &map = client.getEnv().getClientMap();
2820 NodeMetadata *meta = map.getNodeMetadata(nodepos);
2822 infotext = narrow_to_wide(meta->getString("infotext"));
2824 MapNode n = map.getNode(nodepos);
2825 if(nodedef->get(n).tiledef[0].name == "unknown_node.png"){
2826 infotext = L"Unknown node: ";
2827 infotext += narrow_to_wide(nodedef->get(n).name);
2835 if(nodig_delay_timer <= 0.0 && input->getLeftState()
2836 && client.checkPrivilege("interact"))
2840 infostream<<"Started digging"<<std::endl;
2841 client.interact(0, pointed);
2843 ldown_for_dig = true;
2845 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2847 // NOTE: Similar piece of code exists on the server side for
2849 // Get digging parameters
2850 DigParams params = getDigParams(nodedef->get(n).groups,
2851 &playeritem_toolcap);
2852 // If can't dig, try hand
2853 if(!params.diggable){
2854 const ItemDefinition &hand = itemdef->get("");
2855 const ToolCapabilities *tp = hand.tool_capabilities;
2857 params = getDigParams(nodedef->get(n).groups, tp);
2860 float dig_time_complete = 0.0;
2862 if(params.diggable == false)
2864 // I guess nobody will wait for this long
2865 dig_time_complete = 10000000.0;
2869 dig_time_complete = params.time;
2870 if (g_settings->getBool("enable_particles"))
2872 const ContentFeatures &features =
2873 client.getNodeDefManager()->get(n);
2874 addPunchingParticles
2875 (gamedef, smgr, player, client.getEnv(),
2876 nodepos, features.tiles);
2880 if(dig_time_complete >= 0.001)
2882 dig_index = (u16)((float)crack_animation_length
2883 * dig_time/dig_time_complete);
2885 // This is for torches
2888 dig_index = crack_animation_length;
2891 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2892 if(sound_dig.exists() && params.diggable){
2893 if(sound_dig.name == "__group"){
2894 if(params.main_group != ""){
2895 soundmaker.m_player_leftpunch_sound.gain = 0.5;
2896 soundmaker.m_player_leftpunch_sound.name =
2897 std::string("default_dig_") +
2901 soundmaker.m_player_leftpunch_sound = sound_dig;
2905 // Don't show cracks if not diggable
2906 if(dig_time_complete >= 100000.0)
2909 else if(dig_index < crack_animation_length)
2911 //TimeTaker timer("client.setTempMod");
2912 //infostream<<"dig_index="<<dig_index<<std::endl;
2913 client.setCrack(dig_index, nodepos);
2917 infostream<<"Digging completed"<<std::endl;
2918 client.interact(2, pointed);
2919 client.setCrack(-1, v3s16(0,0,0));
2920 MapNode wasnode = map.getNode(nodepos);
2921 client.removeNode(nodepos);
2923 if (g_settings->getBool("enable_particles"))
2925 const ContentFeatures &features =
2926 client.getNodeDefManager()->get(wasnode);
2928 (gamedef, smgr, player, client.getEnv(),
2929 nodepos, features.tiles);
2935 nodig_delay_timer = dig_time_complete
2936 / (float)crack_animation_length;
2938 // We don't want a corresponding delay to
2939 // very time consuming nodes
2940 if(nodig_delay_timer > 0.3)
2941 nodig_delay_timer = 0.3;
2942 // We want a slight delay to very little
2943 // time consuming nodes
2944 float mindelay = 0.15;
2945 if(nodig_delay_timer < mindelay)
2946 nodig_delay_timer = mindelay;
2948 // Send event to trigger sound
2949 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
2950 gamedef->event()->put(e);
2953 if(dig_time_complete < 100000.0)
2957 client.setCrack(-1, nodepos);
2960 camera.setDigging(0); // left click animation
2963 if((input->getRightClicked() ||
2964 repeat_rightclick_timer >=
2965 g_settings->getFloat("repeat_rightclick_time")) &&
2966 client.checkPrivilege("interact"))
2968 repeat_rightclick_timer = 0;
2969 infostream<<"Ground right-clicked"<<std::endl;
2971 // Sign special case, at least until formspec is properly implemented.
2973 if(meta && meta->getString("formspec") == "hack:sign_text_input"
2975 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2977 infostream<<"Launching metadata text input"<<std::endl;
2979 // Get a new text for it
2981 TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2983 std::wstring wtext = narrow_to_wide(meta->getString("text"));
2985 (new GUITextInputMenu(guienv, guiroot, -1,
2989 // If metadata provides an inventory view, activate it
2990 else if(meta && meta->getString("formspec") != "" && !random_input
2991 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2993 infostream<<"Launching custom inventory view"<<std::endl;
2995 InventoryLocation inventoryloc;
2996 inventoryloc.setNodeMeta(nodepos);
3000 GUIFormSpecMenu *menu =
3001 new GUIFormSpecMenu(device, guiroot, -1,
3003 &client, gamedef, tsrc);
3004 menu->doPause = false;
3005 menu->setFormSpec(meta->getString("formspec"),
3007 menu->setFormSource(new NodeMetadataFormSource(
3008 &client.getEnv().getClientMap(), nodepos));
3009 menu->setTextDest(new TextDestNodeMetadata(nodepos, &client));
3012 // Otherwise report right click to server
3015 camera.setDigging(1); // right click animation (always shown for feedback)
3017 // If the wielded item has node placement prediction,
3019 bool placed = nodePlacementPrediction(client,
3021 nodepos, neighbourpos);
3025 client.interact(3, pointed);
3027 soundmaker.m_player_rightpunch_sound =
3028 playeritem_def.sound_place;
3030 soundmaker.m_player_rightpunch_sound =
3034 if (playeritem_def.node_placement_prediction == "" ||
3035 nodedef->get(map.getNode(nodepos)).rightclickable)
3036 client.interact(3, pointed); // Report to server
3040 else if(pointed.type == POINTEDTHING_OBJECT)
3042 infotext = narrow_to_wide(selected_object->infoText());
3044 if(infotext == L"" && show_debug){
3045 infotext = narrow_to_wide(selected_object->debugInfoText());
3048 //if(input->getLeftClicked())
3049 if(input->getLeftState())
3051 bool do_punch = false;
3052 bool do_punch_damage = false;
3053 if(object_hit_delay_timer <= 0.0){
3055 do_punch_damage = true;
3056 object_hit_delay_timer = object_hit_delay;
3058 if(input->getLeftClicked()){
3062 infostream<<"Left-clicked object"<<std::endl;
3065 if(do_punch_damage){
3066 // Report direct punch
3067 v3f objpos = selected_object->getPosition();
3068 v3f dir = (objpos - player_position).normalize();
3070 bool disable_send = selected_object->directReportPunch(
3071 dir, &playeritem, time_from_last_punch);
3072 time_from_last_punch = 0;
3074 client.interact(0, pointed);
3077 else if(input->getRightClicked())
3079 infostream<<"Right-clicked object"<<std::endl;
3080 client.interact(3, pointed); // place
3083 else if(input->getLeftState())
3085 // When button is held down in air, show continuous animation
3089 pointed_old = pointed;
3091 if(left_punch || input->getLeftClicked())
3093 camera.setDigging(0); // left click animation
3096 input->resetLeftClicked();
3097 input->resetRightClicked();
3099 input->resetLeftReleased();
3100 input->resetRightReleased();
3103 Calculate stuff for drawing
3110 if(draw_control.range_all)
3111 fog_range = 100000*BS;
3113 fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
3115 fog_range *= (1.5 - 1.4*(float)client.getEnv().getClientMap().getHumidity(pos_i)/100);
3116 fog_range = MYMIN(fog_range, (draw_control.farthest_drawn+20)*BS);
3121 Calculate general brightness
3123 u32 daynight_ratio = client.getEnv().getDayNightRatio();
3124 float time_brightness = decode_light_f((float)daynight_ratio/1000.0);
3125 float direct_brightness = 0;
3126 bool sunlight_seen = false;
3127 if(g_settings->getBool("free_move")){
3128 direct_brightness = time_brightness;
3129 sunlight_seen = true;
3131 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3132 float old_brightness = sky->getBrightness();
3133 direct_brightness = (float)client.getEnv().getClientMap()
3134 .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
3135 daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
3139 time_of_day = client.getEnv().getTimeOfDayF();
3141 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
3142 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3143 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3144 time_of_day_smooth = time_of_day;
3146 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
3147 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
3148 + (time_of_day+1.0) * todsm;
3150 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
3151 + time_of_day * todsm;
3153 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3156 video::SColor bgcolor = sky->getBgColor();
3157 video::SColor skycolor = sky->getSkyColor();
3163 if(sky->getCloudsVisible()){
3164 clouds->setVisible(true);
3165 clouds->step(dtime);
3166 clouds->update(v2f(player_position.X, player_position.Z),
3167 sky->getCloudColor());
3169 clouds->setVisible(false);
3177 allparticles_step(dtime);
3178 allparticlespawners_step(dtime, client.getEnv());
3184 if(g_settings->getBool("enable_fog") && !force_fog_off)
3188 video::EFT_FOG_LINEAR,
3200 video::EFT_FOG_LINEAR,
3210 Update gui stuff (0ms)
3213 //TimeTaker guiupdatetimer("Gui updating");
3217 static float drawtime_avg = 0;
3218 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
3219 /*static float beginscenetime_avg = 0;
3220 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
3221 static float scenetime_avg = 0;
3222 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
3223 static float endscenetime_avg = 0;
3224 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
3226 u16 fps = (1.0/dtime_avg1);
3228 std::ostringstream os(std::ios_base::binary);
3230 <<"Minetest "<<minetest_version_hash
3232 <<" (R: range_all="<<draw_control.range_all<<")"
3233 <<std::setprecision(0)
3234 <<" drawtime = "<<drawtime_avg
3235 <<std::setprecision(1)
3236 <<", dtime_jitter = "
3237 <<(dtime_jitter1_max_fraction * 100.0)<<" %"
3238 <<std::setprecision(1)
3239 <<", v_range = "<<draw_control.wanted_range
3240 <<std::setprecision(3)
3241 <<", RTT = "<<client.getRTT();
3242 guitext->setText(narrow_to_wide(os.str()).c_str());
3243 guitext->setVisible(true);
3245 else if(show_hud || show_chat)
3247 std::ostringstream os(std::ios_base::binary);
3248 os<<"Minetest "<<minetest_version_hash;
3249 guitext->setText(narrow_to_wide(os.str()).c_str());
3250 guitext->setVisible(true);
3254 guitext->setVisible(false);
3259 std::ostringstream os(std::ios_base::binary);
3260 os<<std::setprecision(1)<<std::fixed
3261 <<"(" <<(player_position.X/BS)
3262 <<", "<<(player_position.Y/BS)
3263 <<", "<<(player_position.Z/BS)
3264 <<") (yaw="<<(wrapDegrees_0_360(camera_yaw))
3265 <<") (t="<<client.getEnv().getClientMap().getHeat(pos_i)
3266 <<"C, h="<<client.getEnv().getClientMap().getHumidity(pos_i)
3267 <<"%) (seed = "<<((u64)client.getMapSeed())
3269 guitext2->setText(narrow_to_wide(os.str()).c_str());
3270 guitext2->setVisible(true);
3274 guitext2->setVisible(false);
3278 guitext_info->setText(infotext.c_str());
3279 guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
3283 float statustext_time_max = 1.5;
3284 if(!statustext.empty())
3286 statustext_time += dtime;
3287 if(statustext_time >= statustext_time_max)
3290 statustext_time = 0;
3293 guitext_status->setText(statustext.c_str());
3294 guitext_status->setVisible(!statustext.empty());
3296 if(!statustext.empty())
3298 s32 status_y = screensize.Y - 130;
3299 core::rect<s32> rect(
3301 status_y - guitext_status->getTextHeight(),
3305 guitext_status->setRelativePosition(rect);
3308 video::SColor initial_color(255,0,0,0);
3309 if(guienv->getSkin())
3310 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
3311 video::SColor final_color = initial_color;
3312 final_color.setAlpha(0);
3313 video::SColor fade_color =
3314 initial_color.getInterpolated_quadratic(
3317 pow(statustext_time / (float)statustext_time_max, 2.0f));
3318 guitext_status->setOverrideColor(fade_color);
3319 guitext_status->enableOverrideColor(true);
3324 Get chat messages from client
3327 // Get new messages from error log buffer
3328 while(!chat_log_error_buf.empty())
3330 chat_backend.addMessage(L"", narrow_to_wide(
3331 chat_log_error_buf.get()));
3333 // Get new messages from client
3334 std::wstring message;
3335 while(client.getChatMessage(message))
3337 chat_backend.addUnparsedMessage(message);
3339 // Remove old messages
3340 chat_backend.step(dtime);
3342 // Display all messages in a static text element
3343 u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
3344 std::wstring recent_chat = chat_backend.getRecentChat();
3345 guitext_chat->setText(recent_chat.c_str());
3347 // Update gui element size and position
3348 s32 chat_y = 5+(text_height+5);
3350 chat_y += (text_height+5);
3351 core::rect<s32> rect(
3355 chat_y + guitext_chat->getTextHeight()
3357 guitext_chat->setRelativePosition(rect);
3359 // Don't show chat if disabled or empty or profiler is enabled
3360 guitext_chat->setVisible(show_chat && recent_chat_count != 0
3368 if(client.getPlayerItem() != new_playeritem)
3370 client.selectPlayerItem(new_playeritem);
3372 if(client.getLocalInventoryUpdated())
3374 //infostream<<"Updating local inventory"<<std::endl;
3375 client.getLocalInventory(local_inventory);
3377 update_wielded_item_trigger = true;
3379 if(update_wielded_item_trigger)
3381 update_wielded_item_trigger = false;
3382 // Update wielded tool
3383 InventoryList *mlist = local_inventory.getList("main");
3386 item = mlist->getItem(client.getPlayerItem());
3387 camera.wield(item, client.getPlayerItem());
3391 Update block draw list every 200ms or when camera direction has
3394 update_draw_list_timer += dtime;
3395 if(update_draw_list_timer >= 0.2 ||
3396 update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2 ||
3397 camera_offset_changed){
3398 update_draw_list_timer = 0;
3399 client.getEnv().getClientMap().updateDrawList(driver);
3400 update_draw_list_last_cam_dir = camera_direction;
3407 TimeTaker tt_draw("mainloop: draw");
3410 TimeTaker timer("beginScene");
3411 //driver->beginScene(false, true, bgcolor);
3412 //driver->beginScene(true, true, bgcolor);
3413 driver->beginScene(true, true, skycolor);
3414 beginscenetime = timer.stop(true);
3419 //infostream<<"smgr->drawAll()"<<std::endl;
3421 TimeTaker timer("smgr");
3424 if(g_settings->getBool("anaglyph"))
3426 irr::core::vector3df oldPosition = camera.getCameraNode()->getPosition();
3427 irr::core::vector3df oldTarget = camera.getCameraNode()->getTarget();
3429 irr::core::matrix4 startMatrix = camera.getCameraNode()->getAbsoluteTransformation();
3431 irr::core::vector3df focusPoint = (camera.getCameraNode()->getTarget() -
3432 camera.getCameraNode()->getAbsolutePosition()).setLength(1) +
3433 camera.getCameraNode()->getAbsolutePosition() ;
3436 irr::core::vector3df leftEye;
3437 irr::core::matrix4 leftMove;
3439 leftMove.setTranslation( irr::core::vector3df(-g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
3440 leftEye=(startMatrix*leftMove).getTranslation();
3442 //clear the depth buffer, and color
3443 driver->beginScene( true, true, irr::video::SColor(0,200,200,255) );
3445 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_RED;
3446 driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK;
3447 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
3448 irr::scene::ESNRP_SOLID +
3449 irr::scene::ESNRP_TRANSPARENT +
3450 irr::scene::ESNRP_TRANSPARENT_EFFECT +
3451 irr::scene::ESNRP_SHADOW;
3453 camera.getCameraNode()->setPosition( leftEye );
3454 camera.getCameraNode()->setTarget( focusPoint );
3456 smgr->drawAll(); // 'smgr->drawAll();' may go here
3458 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
3461 hud.drawSelectionBoxes(hilightboxes);
3465 irr::core::vector3df rightEye;
3466 irr::core::matrix4 rightMove;
3468 rightMove.setTranslation( irr::core::vector3df(g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
3469 rightEye=(startMatrix*rightMove).getTranslation();
3471 //clear the depth buffer
3472 driver->clearZBuffer();
3474 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_GREEN + irr::video::ECP_BLUE;
3475 driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK;
3476 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
3477 irr::scene::ESNRP_SOLID +
3478 irr::scene::ESNRP_TRANSPARENT +
3479 irr::scene::ESNRP_TRANSPARENT_EFFECT +
3480 irr::scene::ESNRP_SHADOW;
3482 camera.getCameraNode()->setPosition( rightEye );
3483 camera.getCameraNode()->setTarget( focusPoint );
3485 smgr->drawAll(); // 'smgr->drawAll();' may go here
3487 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
3490 hud.drawSelectionBoxes(hilightboxes);
3493 //driver->endScene();
3495 driver->getOverrideMaterial().Material.ColorMask=irr::video::ECP_ALL;
3496 driver->getOverrideMaterial().EnableFlags=0;
3497 driver->getOverrideMaterial().EnablePasses=0;
3499 camera.getCameraNode()->setPosition( oldPosition );
3500 camera.getCameraNode()->setTarget( oldTarget );
3503 scenetime = timer.stop(true);
3507 //TimeTaker timer9("auxiliary drawings");
3511 //TimeTaker //timer10("//timer10");
3517 driver->setMaterial(m);
3519 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
3520 if((!g_settings->getBool("anaglyph")) && (show_hud))
3522 hud.drawSelectionBoxes(hilightboxes);
3529 (player->hud_flags & HUD_FLAG_WIELDITEM_VISIBLE) &&
3530 current_camera_mode < CAMERA_MODE_THIRD)
3532 // Warning: This clears the Z buffer.
3533 camera.drawWieldedTool();
3540 client.getEnv().getClientMap().renderPostFx();
3546 if(show_profiler_graph)
3548 graph.draw(10, screensize.Y - 10, driver, font);
3555 hud.drawCrosshair();
3560 //TimeTaker //timer11("//timer11");
3568 hud.drawHotbar(v2s32(displaycenter.X, screensize.Y),
3569 client.getHP(), client.getPlayerItem(), client.getBreath());
3575 if(damage_flash > 0.0)
3577 video::SColor color(std::min(damage_flash, 180.0f),180,0,0);
3578 driver->draw2DRectangle(color,
3579 core::rect<s32>(0,0,screensize.X,screensize.Y),
3582 damage_flash -= 100.0*dtime;
3588 if(player->hurt_tilt_timer > 0.0)
3590 player->hurt_tilt_timer -= dtime*5;
3591 if(player->hurt_tilt_timer < 0)
3592 player->hurt_tilt_strength = 0;
3599 hud.drawLuaElements();
3611 TimeTaker timer("endScene");
3613 endscenetime = timer.stop(true);
3616 drawtime = tt_draw.stop(true);
3617 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
3624 Log times and stuff for visualization
3626 Profiler::GraphValues values;
3627 g_profiler->graphGet(values);
3636 if (gui_chat_console)
3637 gui_chat_console->drop();
3643 Draw a "shutting down" screen, which will be shown while the map
3644 generator and other stuff quits
3647 /*gui::IGUIStaticText *gui_shuttingdowntext = */
3648 wchar_t* text = wgettext("Shutting down stuff...");
3649 draw_load_screen(text, device, font, 0, -1, false);
3651 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
3654 gui_shuttingdowntext->remove();*/
3657 chat_backend.addMessage(L"", L"# Disconnected.");
3658 chat_backend.addMessage(L"", L"");
3662 //force answer all texture and shader jobs (TODO return empty values)
3664 while(!client.isShutdown()) {
3665 tsrc->processQueue();
3666 shsrc->processQueue();
3670 // Client scope (client is destructed before destructing *def and tsrc)
3673 catch(SerializationError &e)
3675 error_message = L"A serialization error occurred:\n"
3676 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
3677 L" running a different version of Minetest.";
3678 errorstream<<wide_to_narrow(error_message)<<std::endl;
3680 catch(ServerError &e) {
3681 error_message = narrow_to_wide(e.what());
3682 errorstream << "ServerError: " << e.what() << std::endl;
3684 catch(ModError &e) {
3685 errorstream << "ModError: " << e.what() << std::endl;
3686 error_message = narrow_to_wide(e.what()) + wgettext("\nCheck debug.txt for details.");
3694 //has to be deleted first to stop all server threads
3702 //extended resource accounting
3703 infostream << "Irrlicht resources after cleanup:" << std::endl;
3704 infostream << "\tRemaining meshes : "
3705 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
3706 infostream << "\tRemaining textures : "
3707 << driver->getTextureCount() << std::endl;
3708 for (unsigned int i = 0; i < driver->getTextureCount(); i++ ) {
3709 irr::video::ITexture* texture = driver->getTextureByIndex(i);
3710 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
3713 clearTextureNameCache();
3714 infostream << "\tRemaining materials: "
3715 << driver-> getMaterialRendererCount ()
3716 << " (note: irrlicht doesn't support removing renderers)"<< std::endl;