3 Copyright (C) 2010-2011 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 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 General Public License for more details.
15 You should have received a copy of the GNU 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 =============================== NOTES ==============================
22 NOTE: Things starting with TODO are sometimes only suggestions.
24 NOTE: iostream.imbue(std::locale("C")) is very slow
25 NOTE: Global locale is now set at initialization
27 NOTE: If VBO (EHM_STATIC) is used, remember to explicitly free the
28 hardware buffer (it is not freed automatically)
30 NOTE: A random to-do list saved here as documentation:
31 A list of "active blocks" in which stuff happens. (+=done)
32 + Add a never-resetted game timer to the server
33 + Add a timestamp value to blocks
34 + The simple rule: All blocks near some player are "active"
35 - Do stuff in real time in active blocks
37 - Grow grass, delete leaves without a tree
38 - Spawn some mobs based on some rules
39 - Transform cobble to mossy cobble near water
41 - ...And all kinds of other dynamic stuff
42 + Keep track of when a block becomes active and becomes inactive
43 + When a block goes inactive:
44 + Store objects statically to block
45 + Store timer value as the timestamp
46 + When a block goes active:
47 + Create active objects out of static objects
48 - Simulate the results of what would have happened if it would have
49 been active for all the time
50 - Grow a lot of grass and so on
51 + Initially it is fine to send information about every active object
52 to every player. Eventually it should be modified to only send info
53 about the nearest ones.
54 + This was left to be done by the old system and it sends only the
57 NOTE: Seeds in 1260:6c77e7dbfd29:
59 Spawns you on a small sand island with a surface dungeon
61 Enormous jungle + a surface dungeon at ~(250,0,0)
63 Old, wild and random suggestions that probably won't be done:
64 -------------------------------------------------------------
66 SUGG: If player is on ground, mainly fetch ground-level blocks
68 SUGG: Expose Connection's seqnums and ACKs to server and client.
69 - This enables saving many packets and making a faster connection
70 - This also enables server to check if client has received the
71 most recent block sent, for example.
72 SUGG: Add a sane bandwidth throttling system to Connection
74 SUGG: More fine-grained control of client's dumping of blocks from
76 - ...What does this mean in the first place?
78 SUGG: A map editing mode (similar to dedicated server mode)
80 SUGG: Transfer more blocks in a single packet
81 SUGG: A blockdata combiner class, to which blocks are added and at
82 destruction it sends all the stuff in as few packets as possible.
83 SUGG: Make a PACKET_COMBINED which contains many subpackets. Utilize
84 it by sending more stuff in a single packet.
85 - Add a packet queue to RemoteClient, from which packets will be
86 combined with object data packets
87 - This is not exactly trivial: the object data packets are
88 sometimes very big by themselves
89 - This might not give much network performance gain though.
91 SUGG: Precalculate lighting translation table at runtime (at startup)
92 - This is not doable because it is currently hand-made and not
93 based on some mathematical function.
94 - Note: This has been changing lately
96 SUGG: A version number to blocks, which increments when the block is
97 modified (node add/remove, water update, lighting update)
98 - This can then be used to make sure the most recent version of
99 a block has been sent to client, for example
101 SUGG: Make the amount of blocks sending to client and the total
102 amount of blocks dynamically limited. Transferring blocks is the
103 main network eater of this system, so it is the one that has
104 to be throttled so that RTTs stay low.
106 SUGG: Meshes of blocks could be split into 6 meshes facing into
107 different directions and then only those drawn that need to be
109 SUGG: Background music based on cellular automata?
110 http://www.earslap.com/projectslab/otomata
112 SUGG: Simple light color information to air
114 SUGG: Server-side objects could be moved based on nodes to enable very
115 lightweight operation and simple AI
116 - Not practical; client would still need to show smooth movement.
118 SUGG: Make a system for pregenerating quick information for mapblocks, so
119 that the client can show them as cubes before they are actually sent
122 SUGG: Erosion simulation at map generation time
123 - This might be plausible if larger areas of map were pregenerated
124 without lighting (which is slow)
125 - Simulate water flows, which would carve out dirt fast and
126 then turn stone into gravel and sand and relocate it.
127 - How about relocating minerals, too? Coal and gold in
128 downstream sand and gravel would be kind of cool
129 - This would need a better way of handling minerals, mainly
130 to have mineral content as a separate field. the first
131 parameter field is free for this.
132 - Simulate rock falling from cliffs when water has removed
133 enough solid rock from the bottom
135 SUGG: For non-mapgen FarMesh: Add a per-sector database to store surface
136 stuff as simple flags/values
139 And at some point make the server send this data to the client too,
140 instead of referring to the noise functions
142 - Surface ground type
148 - Aim for something like controlling a single dwarf in Dwarf Fortress
149 - The player could go faster by a crafting a boat, or riding an animal
150 - Random NPC traders. what else?
155 - When furnace is destroyed, move items to player's inventory
158 - Growing grass, decaying leaves
159 - This can be done in the active blocks I guess.
160 - Lots of stuff can be done in the active blocks.
161 - Uh, is there an active block list somewhere? I think not. Add it.
162 - Breaking weak structures
163 - This can probably be accomplished in the same way as grass
164 - Player health points
165 - When player dies, throw items on map (needs better item-on-map
167 - Cobble to get mossy if near water
168 - More slots in furnace source list, so that multiple ingredients
172 - The Treasure Guard; a big monster with a hammer
173 - The hammer does great damage, shakes the ground and removes a block
174 - You can drop on top of it, and have some time to attack there
175 before he shakes you off
177 - Maybe the difficulty could come from monsters getting tougher in
178 far-away places, and the player starting to need something from
179 there when time goes by.
180 - The player would have some of that stuff at the beginning, and
181 would need new supplies of it when it runs out
184 - A spread-items-on-map routine for the bomb, and for dying players
187 - Proper sword swing simulation
188 - Player should get damage from colliding to a wall at high speed
193 Build system / running:
194 -----------------------
196 Networking and serialization:
197 -----------------------------
199 SUGG: Fix address to be ipv6 compatible
207 SUGG: Combine MapBlock's face caches to so big pieces that VBO
209 - That is >500 vertices
210 - This is not easy; all the MapBlocks close to the player would
211 still need to be drawn separately and combining the blocks
212 would have to happen in a background thread
214 SUGG: Make fetching sector's blocks more efficient when rendering
215 sectors that have very large amounts of blocks (on client)
216 - Is this necessary at all?
218 SUGG: Draw cubes in inventory directly with 3D drawing commands, so that
219 animating them is easier.
221 SUGG: Option for enabling proper alpha channel for textures
223 TODO: Flowing water animation
225 TODO: A setting for enabling bilinear filtering for textures
227 TODO: Better control of draw_control.wanted_max_blocks
229 TODO: Further investigate the use of GPU lighting in addition to the
232 TODO: Artificial (night) light could be more yellow colored than sunlight.
233 - This is technically doable.
234 - Also the actual colors of the textures could be made less colorful
235 in the dark but it's a bit more difficult.
237 SUGG: Somehow make the night less colorful
239 TODO: Occlusion culling
240 - At the same time, move some of the renderMap() block choosing code
241 to the same place as where the new culling happens.
242 - Shoot some rays per frame and when ready, make a new list of
243 blocks for usage of renderMap and give it a new pointer to it.
251 TODO: Untie client network operations from framerate
252 - Needs some input queues or something
253 - This won't give much performance boost because calculating block
256 SUGG: Make morning and evening transition more smooth and maybe shorter
258 TODO: Don't update all meshes always on single node changes, but
259 check which ones should be updated
260 - implement Map::updateNodeMeshes() and the usage of it
261 - It will give almost always a 4x boost in mesh update performance.
265 - Tool/weapon visualization
267 FIXME: When disconnected to the menu, memory is not freed properly
269 TODO: Investigate how much the mesh generator thread gets used when
270 transferring map data
275 SUGG: Make an option to the server to disable building and digging near
276 the starting position
278 FIXME: Server sometimes goes into some infinite PeerNotFoundException loop
280 * Fix the problem with the server constantly saving one or a few
281 blocks? List the first saved block, maybe it explains.
282 - It is probably caused by oscillating water
283 - TODO: Investigate if this still happens (this is a very old one)
284 * Make a small history check to transformLiquids to detect and log
285 continuous oscillations, in such detail that they can be fixed.
287 FIXME: The new optimized map sending doesn't sometimes send enough blocks
288 from big caves and such
289 FIXME: Block send distance configuration does not take effect for some reason
294 TODO: Add proper hooks to when adding and removing active blocks
296 TODO: Finish the ActiveBlockModifier stuff and use it for something
301 TODO: Get rid of MapBlockObjects and use only ActiveObjects
302 - Skipping the MapBlockObject data is nasty - there is no "total
303 length" stored; have to make a SkipMBOs function which contains
304 enough of the current code to skip them properly.
306 SUGG: MovingObject::move and Player::move are basically the same.
308 - NOTE: This is a bit tricky because player has the sneaking ability
309 - NOTE: Player::move is more up-to-date.
310 - NOTE: There is a simple move implementation now in collision.{h,cpp}
311 - NOTE: MovingObject will be deleted (MapBlockObject)
313 TODO: Add a long step function to objects that is called with the time
314 difference when block activates
319 TODO: Flowing water to actually contain flow direction information
320 - There is a space for this - it just has to be implemented.
322 TODO: Consider smoothening cave floors after generating them
324 TODO: Fix make_tree, make_* to use seed-position-consistent pseudorandom
329 TODO: Make sure server handles removing grass when a block is placed (etc)
330 - The client should not do it by itself
331 - NOTE: I think nobody does it currently...
332 TODO: Block cube placement around player's head
333 TODO: Protocol version field
334 TODO: Think about using same bits for material for fences and doors, for
337 SUGG: Restart irrlicht completely when coming back to main menu from game.
338 - This gets rid of everything that is stored in irrlicht's caches.
339 - This might be needed for texture pack selection in menu
341 TODO: Merge bahamada's audio stuff (clean patch available)
343 Making it more portable:
344 ------------------------
346 Stuff to do before release:
347 ---------------------------
349 Fixes to the current release:
350 -----------------------------
352 Stuff to do after release:
353 ---------------------------
358 ======================================================================
364 #pragma message ("Disabling unit tests")
366 #warning "Disabling unit tests"
368 // Disable unit tests
369 #define ENABLE_TESTS 0
372 #define ENABLE_TESTS 1
376 #pragma comment(lib, "Irrlicht.lib")
377 //#pragma comment(lib, "jthread.lib")
378 #pragma comment(lib, "zlibwapi.lib")
379 #pragma comment(lib, "Shell32.lib")
380 // This would get rid of the console window
381 //#pragma comment(linker, "/subsystem:windows /ENTRY:mainCRTStartup")
384 #include "irrlicht.h" // createDevice
387 #include "mainmenumanager.h"
391 #include "common_irrlicht.h"
395 #include "constants.h"
398 #include "guiMessageMenu.h"
401 #include "guiMainMenu.h"
405 #include "defaultsettings.h"
407 #include "settings.h"
408 #include "profiler.h"
414 These are loaded from the config file.
416 Settings main_settings;
417 Settings *g_settings = &main_settings;
420 Profiler main_profiler;
421 Profiler *g_profiler = &main_profiler;
431 gui::IGUIEnvironment* guienv = NULL;
432 gui::IGUIStaticText *guiroot = NULL;
433 MainMenuManager g_menumgr;
437 return (g_menumgr.menuCount() == 0);
440 // Passed to menus to allow disconnecting and exiting
441 MainGameCallback *g_gamecallback = NULL;
448 std::ostream *dout_con_ptr = &dummyout;
449 std::ostream *derr_con_ptr = &verbosestream;
450 //std::ostream *dout_con_ptr = &infostream;
451 //std::ostream *derr_con_ptr = &errorstream;
454 std::ostream *dout_server_ptr = &infostream;
455 std::ostream *derr_server_ptr = &errorstream;
458 std::ostream *dout_client_ptr = &infostream;
459 std::ostream *derr_client_ptr = &errorstream;
462 gettime.h implementation
465 // A small helper class
469 virtual u32 getTime() = 0;
472 // A precise irrlicht one
473 class IrrlichtTimeGetter: public TimeGetter
476 IrrlichtTimeGetter(IrrlichtDevice *device):
483 return m_device->getTimer()->getRealTime();
486 IrrlichtDevice *m_device;
488 // Not so precise one which works without irrlicht
489 class SimpleTimeGetter: public TimeGetter
494 return porting::getTimeMs();
498 // A pointer to a global instance of the time getter
500 TimeGetter *g_timegetter = NULL;
504 if(g_timegetter == NULL)
506 return g_timegetter->getTime();
510 Event handler for Irrlicht
512 NOTE: Everything possible should be moved out from here,
513 probably to InputHandler and the_game
516 class MyEventReceiver : public IEventReceiver
519 // This is the one method that we have to implement
520 virtual bool OnEvent(const SEvent& event)
523 React to nothing here if a menu is active
525 if(noMenuActive() == false)
530 // Remember whether each key is down or up
531 if(event.EventType == irr::EET_KEY_INPUT_EVENT)
533 if(event.KeyInput.PressedDown) {
534 keyIsDown.set(event.KeyInput);
535 keyWasDown.set(event.KeyInput);
537 keyIsDown.unset(event.KeyInput);
541 if(event.EventType == irr::EET_MOUSE_INPUT_EVENT)
543 if(noMenuActive() == false)
546 middle_active = false;
547 right_active = false;
551 left_active = event.MouseInput.isLeftPressed();
552 middle_active = event.MouseInput.isMiddlePressed();
553 right_active = event.MouseInput.isRightPressed();
555 if(event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)
559 if(event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN)
563 if(event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP)
567 if(event.MouseInput.Event == EMIE_RMOUSE_LEFT_UP)
569 rightreleased = true;
571 if(event.MouseInput.Event == EMIE_MOUSE_WHEEL)
573 mouse_wheel += event.MouseInput.Wheel;
581 bool IsKeyDown(const KeyPress &keyCode) const
583 return keyIsDown[keyCode];
586 // Checks whether a key was down and resets the state
587 bool WasKeyDown(const KeyPress &keyCode)
589 bool b = keyWasDown[keyCode];
591 keyWasDown.unset(keyCode);
608 rightclicked = false;
609 leftreleased = false;
610 rightreleased = false;
613 middle_active = false;
614 right_active = false;
636 IrrlichtDevice *m_device;
638 // The current state of keys
640 // Whether a key has been pressed or not
645 Separated input handler
648 class RealInputHandler : public InputHandler
651 RealInputHandler(IrrlichtDevice *device, MyEventReceiver *receiver):
656 virtual bool isKeyDown(const KeyPress &keyCode)
658 return m_receiver->IsKeyDown(keyCode);
660 virtual bool wasKeyDown(const KeyPress &keyCode)
662 return m_receiver->WasKeyDown(keyCode);
664 virtual v2s32 getMousePos()
666 return m_device->getCursorControl()->getPosition();
668 virtual void setMousePos(s32 x, s32 y)
670 m_device->getCursorControl()->setPosition(x, y);
673 virtual bool getLeftState()
675 return m_receiver->left_active;
677 virtual bool getRightState()
679 return m_receiver->right_active;
682 virtual bool getLeftClicked()
684 return m_receiver->leftclicked;
686 virtual bool getRightClicked()
688 return m_receiver->rightclicked;
690 virtual void resetLeftClicked()
692 m_receiver->leftclicked = false;
694 virtual void resetRightClicked()
696 m_receiver->rightclicked = false;
699 virtual bool getLeftReleased()
701 return m_receiver->leftreleased;
703 virtual bool getRightReleased()
705 return m_receiver->rightreleased;
707 virtual void resetLeftReleased()
709 m_receiver->leftreleased = false;
711 virtual void resetRightReleased()
713 m_receiver->rightreleased = false;
716 virtual s32 getMouseWheel()
718 return m_receiver->getMouseWheel();
723 m_receiver->clearInput();
726 IrrlichtDevice *m_device;
727 MyEventReceiver *m_receiver;
730 class RandomInputHandler : public InputHandler
738 rightclicked = false;
739 leftreleased = false;
740 rightreleased = false;
743 virtual bool isKeyDown(const KeyPress &keyCode)
745 return keydown[keyCode];
747 virtual bool wasKeyDown(const KeyPress &keyCode)
751 virtual v2s32 getMousePos()
755 virtual void setMousePos(s32 x, s32 y)
757 mousepos = v2s32(x,y);
760 virtual bool getLeftState()
764 virtual bool getRightState()
769 virtual bool getLeftClicked()
773 virtual bool getRightClicked()
777 virtual void resetLeftClicked()
781 virtual void resetRightClicked()
783 rightclicked = false;
786 virtual bool getLeftReleased()
790 virtual bool getRightReleased()
792 return rightreleased;
794 virtual void resetLeftReleased()
796 leftreleased = false;
798 virtual void resetRightReleased()
800 rightreleased = false;
803 virtual s32 getMouseWheel()
808 virtual void step(float dtime)
811 static float counter1 = 0;
815 counter1 = 0.1*Rand(1, 40);
816 keydown.toggle(getKeySetting("keymap_jump"));
820 static float counter1 = 0;
824 counter1 = 0.1*Rand(1, 40);
825 keydown.toggle(getKeySetting("keymap_special1"));
829 static float counter1 = 0;
833 counter1 = 0.1*Rand(1, 40);
834 keydown.toggle(getKeySetting("keymap_forward"));
838 static float counter1 = 0;
842 counter1 = 0.1*Rand(1, 40);
843 keydown.toggle(getKeySetting("keymap_left"));
847 static float counter1 = 0;
851 counter1 = 0.1*Rand(1, 20);
852 mousespeed = v2s32(Rand(-20,20), Rand(-15,20));
856 static float counter1 = 0;
860 counter1 = 0.1*Rand(1, 30);
861 leftdown = !leftdown;
869 static float counter1 = 0;
873 counter1 = 0.1*Rand(1, 15);
874 rightdown = !rightdown;
878 rightreleased = true;
881 mousepos += mousespeed;
884 s32 Rand(s32 min, s32 max)
886 return (myrand()%(max-min+1))+min;
900 // These are defined global so that they're not optimized too much.
901 // Can't change them to volatile.
906 std::string tempstring;
907 std::string tempstring2;
912 dstream<<"The following test should take around 20ms."<<std::endl;
913 TimeTaker timer("Testing std::string speed");
914 const u32 jj = 10000;
915 for(u32 j=0; j<jj; j++)
920 for(u32 i=0; i<ii; i++){
921 tempstring2 += "asd";
923 for(u32 i=0; i<ii+1; i++){
925 if(tempstring == tempstring2)
931 dstream<<"All of the following tests should take around 100ms each."
935 TimeTaker timer("Testing floating-point conversion speed");
937 for(u32 i=0; i<4000000; i++){
944 TimeTaker timer("Testing floating-point vector speed");
946 tempv3f1 = v3f(1,2,3);
947 tempv3f2 = v3f(4,5,6);
948 for(u32 i=0; i<10000000; i++){
949 tempf += tempv3f1.dotProduct(tempv3f2);
950 tempv3f2 += v3f(7,8,9);
955 TimeTaker timer("Testing core::map speed");
957 core::map<v2s16, f32> map1;
960 for(s16 y=0; y<ii; y++){
961 for(s16 x=0; x<ii; x++){
962 map1.insert(v2s16(x,y), tempf);
966 for(s16 y=ii-1; y>=0; y--){
967 for(s16 x=0; x<ii; x++){
968 tempf = map1[v2s16(x,y)];
974 dstream<<"Around 5000/ms should do well here."<<std::endl;
975 TimeTaker timer("Testing mutex speed");
989 while(timer.getTime() < 10);
991 u32 dtime = timer.stop();
992 u32 per_ms = n / dtime;
993 dstream<<"Done. "<<dtime<<"ms, "
994 <<per_ms<<"/ms"<<std::endl;
998 void drawMenuBackground(video::IVideoDriver* driver)
1000 core::dimension2d<u32> screensize = driver->getScreenSize();
1002 video::ITexture *bgtexture =
1003 driver->getTexture(getTexturePath("menubg.png").c_str());
1006 s32 texturesize = 128;
1007 s32 tiled_y = screensize.Height / texturesize + 1;
1008 s32 tiled_x = screensize.Width / texturesize + 1;
1010 for(s32 y=0; y<tiled_y; y++)
1011 for(s32 x=0; x<tiled_x; x++)
1013 core::rect<s32> rect(0,0,texturesize,texturesize);
1014 rect += v2s32(x*texturesize, y*texturesize);
1015 driver->draw2DImage(bgtexture, rect,
1016 core::rect<s32>(core::position2d<s32>(0,0),
1017 core::dimension2di(bgtexture->getSize())),
1022 video::ITexture *logotexture =
1023 driver->getTexture(getTexturePath("menulogo.png").c_str());
1026 v2s32 logosize(logotexture->getOriginalSize().Width,
1027 logotexture->getOriginalSize().Height);
1030 video::SColor bgcolor(255,50,50,50);
1031 core::rect<s32> bgrect(0, screensize.Height-logosize.Y-20,
1032 screensize.Width, screensize.Height);
1033 driver->draw2DRectangle(bgcolor, bgrect, NULL);
1035 core::rect<s32> rect(0,0,logosize.X,logosize.Y);
1036 rect += v2s32(screensize.Width/2,screensize.Height-10-logosize.Y);
1037 rect -= v2s32(logosize.X/2, 0);
1038 driver->draw2DImage(logotexture, rect,
1039 core::rect<s32>(core::position2d<s32>(0,0),
1040 core::dimension2di(logotexture->getSize())),
1045 class StderrLogOutput: public ILogOutput
1048 /* line: Full line with timestamp, level and thread */
1049 void printLog(const std::string &line)
1051 std::cerr<<line<<std::endl;
1053 } main_stderr_log_out;
1055 class DstreamNoStderrLogOutput: public ILogOutput
1058 /* line: Full line with timestamp, level and thread */
1059 void printLog(const std::string &line)
1061 dstream_no_stderr<<line<<std::endl;
1063 } main_dstream_no_stderr_log_out;
1065 int main(int argc, char *argv[])
1071 log_add_output_maxlev(&main_stderr_log_out, LMT_ACTION);
1072 log_add_output_all_levs(&main_dstream_no_stderr_log_out);
1074 log_register_thread("main");
1076 // Set locale. This is for forcing '.' as the decimal point.
1077 std::locale::global(std::locale("C"));
1078 // This enables printing all characters in bitmap font
1079 setlocale(LC_CTYPE, "en_US");
1085 // List all allowed options
1086 core::map<std::string, ValueSpec> allowed_options;
1087 allowed_options.insert("help", ValueSpec(VALUETYPE_FLAG,
1088 "Show allowed options"));
1089 allowed_options.insert("server", ValueSpec(VALUETYPE_FLAG,
1090 "Run server directly"));
1091 allowed_options.insert("config", ValueSpec(VALUETYPE_STRING,
1092 "Load configuration from specified file"));
1093 allowed_options.insert("port", ValueSpec(VALUETYPE_STRING,
1094 "Set network port to connect to"));
1095 allowed_options.insert("address", ValueSpec(VALUETYPE_STRING,
1096 "Address to connect to"));
1097 allowed_options.insert("random-input", ValueSpec(VALUETYPE_FLAG,
1098 "Enable random user input, for testing"));
1099 allowed_options.insert("disable-unittests", ValueSpec(VALUETYPE_FLAG,
1100 "Disable unit tests"));
1101 allowed_options.insert("enable-unittests", ValueSpec(VALUETYPE_FLAG,
1102 "Enable unit tests"));
1103 allowed_options.insert("map-dir", ValueSpec(VALUETYPE_STRING,
1104 "Map directory (where everything in the world is stored)"));
1106 allowed_options.insert("dstream-on-stderr", ValueSpec(VALUETYPE_FLAG));
1108 allowed_options.insert("speedtests", ValueSpec(VALUETYPE_FLAG,
1109 "Run speed tests"));
1110 allowed_options.insert("info-on-stderr", ValueSpec(VALUETYPE_FLAG,
1111 "Print debug information to console"));
1115 bool ret = cmd_args.parseCommandLine(argc, argv, allowed_options);
1117 if(ret == false || cmd_args.getFlag("help"))
1119 dstream<<"Allowed options:"<<std::endl;
1120 for(core::map<std::string, ValueSpec>::Iterator
1121 i = allowed_options.getIterator();
1122 i.atEnd() == false; i++)
1124 dstream<<" --"<<i.getNode()->getKey();
1125 if(i.getNode()->getValue().type == VALUETYPE_FLAG)
1130 dstream<<" <value>";
1134 if(i.getNode()->getValue().help != NULL)
1136 dstream<<" "<<i.getNode()->getValue().help
1141 return cmd_args.getFlag("help") ? 0 : 1;
1145 Low-level initialization
1148 bool disable_stderr = false;
1150 if(cmd_args.getFlag("dstream-on-stderr") == false)
1151 disable_stderr = true;
1154 if(cmd_args.getFlag("info-on-stderr"))
1155 log_add_output(&main_stderr_log_out, LMT_INFO);
1157 porting::signal_handler_init();
1158 bool &kill = *porting::signal_handler_killstatus();
1160 // Initialize porting::path_data and porting::path_userdata
1161 porting::initializePaths();
1163 // Create user data directory
1164 fs::CreateDir(porting::path_userdata);
1166 init_gettext((porting::path_data+DIR_DELIM+".."+DIR_DELIM+"locale").c_str());
1168 // Initialize debug streams
1170 std::string debugfile = DEBUGFILE;
1172 std::string debugfile = porting::path_userdata+DIR_DELIM+DEBUGFILE;
1174 debugstreams_init(disable_stderr, debugfile.c_str());
1175 // Initialize debug stacks
1176 debug_stacks_init();
1178 DSTACK(__FUNCTION_NAME);
1180 // Init material properties table
1181 //initializeMaterialProperties();
1184 BEGIN_DEBUG_EXCEPTION_HANDLER
1186 // Print startup message
1187 actionstream<<PROJECT_NAME<<
1188 " with SER_FMT_VER_HIGHEST="<<(int)SER_FMT_VER_HIGHEST
1193 Basic initialization
1196 // Initialize default settings
1197 set_default_settings(g_settings);
1199 // Initialize sockets
1201 atexit(sockets_cleanup);
1207 // Path of configuration file in use
1208 std::string configpath = "";
1210 if(cmd_args.exists("config"))
1212 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
1215 errorstream<<"Could not read configuration from \""
1216 <<cmd_args.get("config")<<"\""<<std::endl;
1219 configpath = cmd_args.get("config");
1223 core::array<std::string> filenames;
1224 filenames.push_back(porting::path_userdata +
1225 DIR_DELIM + "minetest.conf");
1227 filenames.push_back(porting::path_userdata +
1228 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
1231 for(u32 i=0; i<filenames.size(); i++)
1233 bool r = g_settings->readConfigFile(filenames[i].c_str());
1236 configpath = filenames[i];
1241 // If no path found, use the first one (menu creates the file)
1242 if(configpath == "")
1243 configpath = filenames[0];
1246 // Initialize random seed
1254 if((ENABLE_TESTS && cmd_args.getFlag("disable-unittests") == false)
1255 || cmd_args.getFlag("enable-unittests") == true)
1260 /*for(s16 y=-100; y<100; y++)
1261 for(s16 x=-100; x<100; x++)
1263 std::cout<<noise2d_gradient((double)x/10,(double)y/10, 32415)<<std::endl;
1273 if(cmd_args.exists("port"))
1274 port = cmd_args.getU16("port");
1275 else if(g_settings->exists("port"))
1276 port = g_settings->getU16("port");
1281 std::string map_dir = porting::path_userdata+DIR_DELIM+"world";
1282 if(cmd_args.exists("map-dir"))
1283 map_dir = cmd_args.get("map-dir");
1284 else if(g_settings->exists("map-dir"))
1285 map_dir = g_settings->get("map-dir");
1287 // Run dedicated server if asked to
1288 if(cmd_args.getFlag("server"))
1290 DSTACK("Dedicated server branch");
1292 // Create time getter
1293 g_timegetter = new SimpleTimeGetter();
1296 Server server(map_dir.c_str(), configpath);
1300 dedicated_server_loop(server, kill);
1310 // Address to connect to
1311 std::string address = "";
1313 if(cmd_args.exists("address"))
1315 address = cmd_args.get("address");
1319 address = g_settings->get("address");
1322 std::string playername = g_settings->get("name");
1325 Device initialization
1328 // Resolution selection
1330 bool fullscreen = false;
1331 u16 screenW = g_settings->getU16("screenW");
1332 u16 screenH = g_settings->getU16("screenH");
1336 video::E_DRIVER_TYPE driverType;
1338 std::string driverstring = g_settings->get("video_driver");
1340 if(driverstring == "null")
1341 driverType = video::EDT_NULL;
1342 else if(driverstring == "software")
1343 driverType = video::EDT_SOFTWARE;
1344 else if(driverstring == "burningsvideo")
1345 driverType = video::EDT_BURNINGSVIDEO;
1346 else if(driverstring == "direct3d8")
1347 driverType = video::EDT_DIRECT3D8;
1348 else if(driverstring == "direct3d9")
1349 driverType = video::EDT_DIRECT3D9;
1350 else if(driverstring == "opengl")
1351 driverType = video::EDT_OPENGL;
1354 errorstream<<"WARNING: Invalid video_driver specified; defaulting "
1355 "to opengl"<<std::endl;
1356 driverType = video::EDT_OPENGL;
1360 Create device and exit if creation failed
1363 MyEventReceiver receiver;
1365 IrrlichtDevice *device;
1366 device = createDevice(driverType,
1367 core::dimension2d<u32>(screenW, screenH),
1368 16, fullscreen, false, false, &receiver);
1371 return 1; // could not create selected driver.
1374 Continue initialization
1377 video::IVideoDriver* driver = device->getVideoDriver();
1379 // Disable mipmaps (because some of them look ugly)
1380 driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, false);
1383 This changes the minimum allowed number of vertices in a VBO.
1386 //driver->setMinHardwareBufferVertexCount(50);
1388 // Set the window caption
1389 device->setWindowCaption(L"Minetest [Main Menu]");
1391 // Create time getter
1392 g_timegetter = new IrrlichtTimeGetter(device);
1394 // Create game callback for menus
1395 g_gamecallback = new MainGameCallback(device);
1398 Speed tests (done after irrlicht is loaded to get timer)
1400 if(cmd_args.getFlag("speedtests"))
1402 dstream<<"Running speed tests"<<std::endl;
1407 device->setResizable(true);
1409 bool random_input = g_settings->getBool("random_input")
1410 || cmd_args.getFlag("random-input");
1411 InputHandler *input = NULL;
1413 input = new RandomInputHandler();
1415 input = new RealInputHandler(device, &receiver);
1417 scene::ISceneManager* smgr = device->getSceneManager();
1419 guienv = device->getGUIEnvironment();
1420 gui::IGUISkin* skin = guienv->getSkin();
1421 gui::IGUIFont* font = guienv->getFont(getTexturePath("fontlucida.png").c_str());
1423 skin->setFont(font);
1425 errorstream<<"WARNING: Font file was not found."
1426 " Using default font."<<std::endl;
1427 // If font was not found, this will get us one
1428 font = skin->getFont();
1431 u32 text_height = font->getDimension(L"Hello, world!").Height;
1432 infostream<<"text_height="<<text_height<<std::endl;
1434 //skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,0,0,0));
1435 skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,255,255,255));
1436 //skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(0,0,0,0));
1437 //skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(0,0,0,0));
1438 skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255,0,0,0));
1439 skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255,0,0,0));
1446 If an error occurs, this is set to something and the
1447 menu-game loop is restarted. It is then displayed before
1450 std::wstring error_message = L"";
1452 // The password entered during the menu screen,
1453 std::string password;
1458 while(device->run() && kill == false)
1461 // This is used for catching disconnects
1466 Clear everything from the GUIEnvironment
1471 We need some kind of a root node to be able to add
1472 custom gui elements directly on the screen.
1473 Otherwise they won't be automatically drawn.
1475 guiroot = guienv->addStaticText(L"",
1476 core::rect<s32>(0, 0, 10000, 10000));
1479 Out-of-game menu loop.
1481 Loop quits when menu returns proper parameters.
1483 while(kill == false)
1485 // Cursor can be non-visible when coming from the game
1486 device->getCursorControl()->setVisible(true);
1487 // Some stuff are left to scene manager when coming from the game
1490 // Reset or hide the debug gui texts
1491 /*guitext->setText(L"Minetest-c55");
1492 guitext2->setVisible(false);
1493 guitext_info->setVisible(false);
1494 guitext_chat->setVisible(false);*/
1496 // Initialize menu data
1497 MainMenuData menudata;
1498 menudata.address = narrow_to_wide(address);
1499 menudata.name = narrow_to_wide(playername);
1500 menudata.port = narrow_to_wide(itos(port));
1501 menudata.fancy_trees = g_settings->getBool("new_style_leaves");
1502 menudata.smooth_lighting = g_settings->getBool("smooth_lighting");
1503 menudata.clouds_3d = g_settings->getBool("enable_3d_clouds");
1504 menudata.opaque_water = g_settings->getBool("opaque_water");
1505 menudata.creative_mode = g_settings->getBool("creative_mode");
1506 menudata.enable_damage = g_settings->getBool("enable_damage");
1509 new GUIMainMenu(guienv, guiroot, -1,
1510 &g_menumgr, &menudata, g_gamecallback);
1511 menu->allowFocusRemoval(true);
1513 if(error_message != L"")
1515 errorstream<<"error_message = "
1516 <<wide_to_narrow(error_message)<<std::endl;
1518 GUIMessageMenu *menu2 =
1519 new GUIMessageMenu(guienv, guiroot, -1,
1520 &g_menumgr, error_message.c_str());
1522 error_message = L"";
1525 video::IVideoDriver* driver = device->getVideoDriver();
1527 infostream<<"Created main menu"<<std::endl;
1529 while(device->run() && kill == false)
1531 if(menu->getStatus() == true)
1534 //driver->beginScene(true, true, video::SColor(255,0,0,0));
1535 driver->beginScene(true, true, video::SColor(255,128,128,128));
1537 drawMenuBackground(driver);
1543 // On some computers framerate doesn't seem to be
1544 // automatically limited
1548 // Break out of menu-game loop to shut down cleanly
1549 if(device->run() == false || kill == true)
1552 infostream<<"Dropping main menu"<<std::endl;
1556 // Delete map if requested
1557 if(menudata.delete_map)
1559 bool r = fs::RecursiveDeleteContent(map_dir);
1561 error_message = L"Delete failed";
1565 playername = wide_to_narrow(menudata.name);
1567 password = translatePassword(playername, menudata.password);
1569 //infostream<<"Main: password hash: '"<<password<<"'"<<std::endl;
1571 address = wide_to_narrow(menudata.address);
1572 int newport = stoi(wide_to_narrow(menudata.port));
1575 g_settings->set("new_style_leaves", itos(menudata.fancy_trees));
1576 g_settings->set("smooth_lighting", itos(menudata.smooth_lighting));
1577 g_settings->set("enable_3d_clouds", itos(menudata.clouds_3d));
1578 g_settings->set("opaque_water", itos(menudata.opaque_water));
1579 g_settings->set("creative_mode", itos(menudata.creative_mode));
1580 g_settings->set("enable_damage", itos(menudata.enable_damage));
1582 // NOTE: These are now checked server side; no need to do it
1583 // here, so let's not do it here.
1584 /*// Check for valid parameters, restart menu if invalid.
1585 if(playername == "")
1587 error_message = L"Name required.";
1590 // Check that name has only valid chars
1591 if(string_allowed(playername, PLAYERNAME_ALLOWED_CHARS)==false)
1593 error_message = L"Characters allowed: "
1594 +narrow_to_wide(PLAYERNAME_ALLOWED_CHARS);
1599 g_settings->set("name", playername);
1600 g_settings->set("address", address);
1601 g_settings->set("port", itos(port));
1602 // Update configuration file
1603 if(configpath != "")
1604 g_settings->updateConfigFile(configpath.c_str());
1610 // Break out of menu-game loop to shut down cleanly
1611 if(device->run() == false || kill == true)
1633 catch(con::PeerNotFoundException &e)
1635 errorstream<<"Connection error (timed out?)"<<std::endl;
1636 error_message = L"Connection error (timed out?)";
1638 catch(SocketException &e)
1640 errorstream<<"Socket error (port already in use?)"<<std::endl;
1641 error_message = L"Socket error (port already in use?)";
1645 errorstream<<e.what()<<std::endl;
1646 error_message = narrow_to_wide(e.what()) + L"\nCheck debug.txt for details.";
1649 catch(std::exception &e)
1651 std::string narrow_message = "Some exception, what()=\"";
1652 narrow_message += e.what();
1653 narrow_message += "\"";
1654 errorstream<<narrow_message<<std::endl;
1655 error_message = narrow_to_wide(narrow_message);
1664 In the end, delete the Irrlicht device.
1668 END_DEBUG_EXCEPTION_HANDLER(errorstream)
1670 debugstreams_deinit();