converted main.cpp dos linefeeds to unix linefeeds.
[oweals/minetest.git] / src / main.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 2010-2011 celeron55, Perttu Ahola <celeron55@gmail.com>
4
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.
9
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.
14
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.
18 */
19
20 /*
21 =============================== NOTES ==============================
22 NOTE: Things starting with TODO are sometimes only suggestions.
23
24 NOTE: iostream.imbue(std::locale("C")) is very slow
25 NOTE: Global locale is now set at initialization
26
27 NOTE: If VBO (EHM_STATIC) is used, remember to explicitly free the
28       hardware buffer (it is not freed automatically)
29
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
36                 + Handle objects
37                 - Grow grass, delete leaves without a tree
38                 - Spawn some mobs based on some rules
39                 - Transform cobble to mossy cobble near water
40                 - Run a custom script
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
55                   nearest ones.
56
57 Vim conversion regexpes for moving to extended content type storage:
58 %s/\(\.\|->\)d \([!=]=\)/\1getContent() \2/g
59 %s/content_features(\([^.]*\)\.d)/content_features(\1)/g
60 %s/\(\.\|->\)d = \([^;]*\);/\1setContent(\2);/g
61 %s/\(getNodeNoExNoEmerge([^)]*)\)\.d/\1.getContent()/g
62 %s/\(getNodeNoExNoEmerge(.*)\)\.d/\1.getContent()/g
63 %s/\.d;/.getContent();/g
64 %s/\(content_liquid\|content_flowing_liquid\|make_liquid_flowing\|content_pointable\)(\([^.]*\).d)/\1(\2.getContent())/g
65 Other things to note:
66 - node.d = node.param0 (only in raw serialization; use getContent() otherwise)
67 - node.param = node.param1
68 - node.dir = node.param2
69 - content_walkable(node.d) etc should be changed to
70   content_features(node).walkable etc
71 - Also check for lines that store the result of getContent to a 8-bit
72   variable and fix them (result of getContent() must be stored in
73   content_t, which is 16-bit)
74
75 Old, wild and random suggestions that probably won't be done:
76 -------------------------------------------------------------
77
78 SUGG: If player is on ground, mainly fetch ground-level blocks
79
80 SUGG: Expose Connection's seqnums and ACKs to server and client.
81       - This enables saving many packets and making a faster connection
82           - This also enables server to check if client has received the
83             most recent block sent, for example.
84 SUGG: Add a sane bandwidth throttling system to Connection
85
86 SUGG: More fine-grained control of client's dumping of blocks from
87       memory
88           - ...What does this mean in the first place?
89
90 SUGG: A map editing mode (similar to dedicated server mode)
91
92 SUGG: Transfer more blocks in a single packet
93 SUGG: A blockdata combiner class, to which blocks are added and at
94       destruction it sends all the stuff in as few packets as possible.
95 SUGG: Make a PACKET_COMBINED which contains many subpackets. Utilize
96       it by sending more stuff in a single packet.
97           - Add a packet queue to RemoteClient, from which packets will be
98             combined with object data packets
99                 - This is not exactly trivial: the object data packets are
100                   sometimes very big by themselves
101           - This might not give much network performance gain though.
102
103 SUGG: Precalculate lighting translation table at runtime (at startup)
104       - This is not doable because it is currently hand-made and not
105             based on some mathematical function.
106                 - Note: This has been changing lately
107
108 SUGG: A version number to blocks, which increments when the block is
109       modified (node add/remove, water update, lighting update)
110           - This can then be used to make sure the most recent version of
111             a block has been sent to client, for example
112
113 SUGG: Make the amount of blocks sending to client and the total
114           amount of blocks dynamically limited. Transferring blocks is the
115           main network eater of this system, so it is the one that has
116           to be throttled so that RTTs stay low.
117
118 SUGG: Meshes of blocks could be split into 6 meshes facing into
119       different directions and then only those drawn that need to be
120
121 SUGG: Background music based on cellular automata?
122       http://www.earslap.com/projectslab/otomata
123
124 SUGG: Simple light color information to air
125
126 SUGG: Server-side objects could be moved based on nodes to enable very
127       lightweight operation and simple AI
128         - Not practical; client would still need to show smooth movement.
129
130 SUGG: Make a system for pregenerating quick information for mapblocks, so
131           that the client can show them as cubes before they are actually sent
132           or even generated.
133
134 SUGG: Erosion simulation at map generation time
135     - This might be plausible if larger areas of map were pregenerated
136           without lighting (which is slow)
137         - Simulate water flows, which would carve out dirt fast and
138           then turn stone into gravel and sand and relocate it.
139         - How about relocating minerals, too? Coal and gold in
140           downstream sand and gravel would be kind of cool
141           - This would need a better way of handling minerals, mainly
142                 to have mineral content as a separate field. the first
143                 parameter field is free for this.
144         - Simulate rock falling from cliffs when water has removed
145           enough solid rock from the bottom
146
147 SUGG: For non-mapgen FarMesh: Add a per-sector database to store surface
148       stuff as simple flags/values
149       - Light?
150           - A building?
151           And at some point make the server send this data to the client too,
152           instead of referring to the noise functions
153           - Ground height
154           - Surface ground type
155           - Trees?
156
157 Gaming ideas:
158 -------------
159
160 - Aim for something like controlling a single dwarf in Dwarf Fortress
161 - The player could go faster by a crafting a boat, or riding an animal
162 - Random NPC traders. what else?
163
164 Game content:
165 -------------
166
167 - When furnace is destroyed, move items to player's inventory
168 - Add lots of stuff
169 - Glass blocks
170 - Growing grass, decaying leaves
171         - This can be done in the active blocks I guess.
172         - Lots of stuff can be done in the active blocks.
173         - Uh, is there an active block list somewhere? I think not. Add it.
174 - Breaking weak structures
175         - This can probably be accomplished in the same way as grass
176 - Player health points
177         - When player dies, throw items on map (needs better item-on-map
178           implementation)
179 - Cobble to get mossy if near water
180 - More slots in furnace source list, so that multiple ingredients
181   are possible.
182 - Keys to chests?
183
184 - The Treasure Guard; a big monster with a hammer
185         - The hammer does great damage, shakes the ground and removes a block
186         - You can drop on top of it, and have some time to attack there
187           before he shakes you off
188
189 - Maybe the difficulty could come from monsters getting tougher in
190   far-away places, and the player starting to need something from
191   there when time goes by.
192   - The player would have some of that stuff at the beginning, and
193     would need new supplies of it when it runs out
194
195 - A bomb
196 - A spread-items-on-map routine for the bomb, and for dying players
197
198 - Fighting:
199   - Proper sword swing simulation
200   - Player should get damage from colliding to a wall at high speed
201
202 Documentation:
203 --------------
204
205 Build system / running:
206 -----------------------
207
208 Networking and serialization:
209 -----------------------------
210
211 SUGG: Fix address to be ipv6 compatible
212
213 User Interface:
214 ---------------
215
216 Graphics:
217 ---------
218
219 SUGG: Combine MapBlock's face caches to so big pieces that VBO
220       can be used
221       - That is >500 vertices
222           - This is not easy; all the MapBlocks close to the player would
223             still need to be drawn separately and combining the blocks
224                 would have to happen in a background thread
225
226 SUGG: Make fetching sector's blocks more efficient when rendering
227       sectors that have very large amounts of blocks (on client)
228           - Is this necessary at all?
229
230 SUGG: Draw cubes in inventory directly with 3D drawing commands, so that
231       animating them is easier.
232
233 SUGG: Option for enabling proper alpha channel for textures
234
235 TODO: Flowing water animation
236
237 TODO: A setting for enabling bilinear filtering for textures
238
239 TODO: Better control of draw_control.wanted_max_blocks
240
241 TODO: Further investigate the use of GPU lighting in addition to the
242       current one
243
244 TODO: Artificial (night) light could be more yellow colored than sunlight.
245       - This is technically doable.
246           - Also the actual colors of the textures could be made less colorful
247             in the dark but it's a bit more difficult.
248
249 SUGG: Somehow make the night less colorful
250
251 TODO: Occlusion culling
252       - At the same time, move some of the renderMap() block choosing code
253         to the same place as where the new culling happens.
254       - Shoot some rays per frame and when ready, make a new list of
255             blocks for usage of renderMap and give it a new pointer to it.
256
257 Configuration:
258 --------------
259
260 Client:
261 -------
262
263 TODO: Untie client network operations from framerate
264       - Needs some input queues or something
265           - This won't give much performance boost because calculating block
266             meshes takes so long
267
268 SUGG: Make morning and evening transition more smooth and maybe shorter
269
270 TODO: Don't update all meshes always on single node changes, but
271       check which ones should be updated
272           - implement Map::updateNodeMeshes() and the usage of it
273           - It will give almost always a 4x boost in mesh update performance.
274
275 - A weapon engine
276
277 - Tool/weapon visualization
278
279 FIXME: When disconnected to the menu, memory is not freed properly
280
281 TODO: Investigate how much the mesh generator thread gets used when
282       transferring map data
283
284 Server:
285 -------
286
287 SUGG: Make an option to the server to disable building and digging near
288       the starting position
289
290 FIXME: Server sometimes goes into some infinite PeerNotFoundException loop
291
292 * Fix the problem with the server constantly saving one or a few
293   blocks? List the first saved block, maybe it explains.
294   - It is probably caused by oscillating water
295   - TODO: Investigate if this still happens (this is a very old one)
296 * Make a small history check to transformLiquids to detect and log
297   continuous oscillations, in such detail that they can be fixed.
298
299 FIXME: The new optimized map sending doesn't sometimes send enough blocks
300        from big caves and such
301 FIXME: Block send distance configuration does not take effect for some reason
302
303 Environment:
304 ------------
305
306 TODO: Add proper hooks to when adding and removing active blocks
307
308 TODO: Finish the ActiveBlockModifier stuff and use it for something
309
310 Objects:
311 --------
312
313 TODO: Get rid of MapBlockObjects and use only ActiveObjects
314         - Skipping the MapBlockObject data is nasty - there is no "total
315           length" stored; have to make a SkipMBOs function which contains
316           enough of the current code to skip them properly.
317
318 SUGG: MovingObject::move and Player::move are basically the same.
319       combine them.
320         - NOTE: This is a bit tricky because player has the sneaking ability
321         - NOTE: Player::move is more up-to-date.
322         - NOTE: There is a simple move implementation now in collision.{h,cpp}
323         - NOTE: MovingObject will be deleted (MapBlockObject)
324
325 TODO: Add a long step function to objects that is called with the time
326       difference when block activates
327
328 Map:
329 ----
330
331 TODO: Mineral and ground material properties
332       - This way mineral ground toughness can be calculated with just
333             some formula, as well as tool strengths. Sounds too.
334           - There are TODOs in appropriate files: material.h, content_mapnode.h
335
336 TODO: Flowing water to actually contain flow direction information
337       - There is a space for this - it just has to be implemented.
338
339 TODO: Consider smoothening cave floors after generating them
340
341 TODO: Fix make_tree, make_* to use seed-position-consistent pseudorandom
342           - delta also
343
344 Misc. stuff:
345 ------------
346 TODO: Make sure server handles removing grass when a block is placed (etc)
347       - The client should not do it by itself
348           - NOTE: I think nobody does it currently...
349 TODO: Block cube placement around player's head
350 TODO: Protocol version field
351 TODO: Think about using same bits for material for fences and doors, for
352           example
353 TODO: Move mineral to param2, increment map serialization version, add
354       conversion
355
356 SUGG: Restart irrlicht completely when coming back to main menu from game.
357         - This gets rid of everything that is stored in irrlicht's caches.
358         - This might be needed for texture pack selection in menu
359
360 TODO: Merge bahamada's audio stuff (clean patch available)
361
362 TODO: Move content_features to mapnode_content_features.{h,cpp} or so
363
364 Making it more portable:
365 ------------------------
366  
367 Stuff to do before release:
368 ---------------------------
369
370 Fixes to the current release:
371 -----------------------------
372
373 Stuff to do after release:
374 ---------------------------
375
376 Doing currently:
377 ----------------
378
379 ======================================================================
380
381 */
382
383 #ifdef NDEBUG
384         #ifdef _WIN32
385                 #pragma message ("Disabling unit tests")
386         #else
387                 #warning "Disabling unit tests"
388         #endif
389         // Disable unit tests
390         #define ENABLE_TESTS 0
391 #else
392         // Enable unit tests
393         #define ENABLE_TESTS 1
394 #endif
395
396 #ifdef _MSC_VER
397         #pragma comment(lib, "Irrlicht.lib")
398         //#pragma comment(lib, "jthread.lib")
399         #pragma comment(lib, "zlibwapi.lib")
400         #pragma comment(lib, "Shell32.lib")
401         // This would get rid of the console window
402         //#pragma comment(linker, "/subsystem:windows /ENTRY:mainCRTStartup")
403 #endif
404
405 #include <iostream>
406 #include <fstream>
407 #include <locale.h>
408 #include "main.h"
409 #include "common_irrlicht.h"
410 #include "debug.h"
411 #include "test.h"
412 #include "server.h"
413 #include "constants.h"
414 #include "porting.h"
415 #include "gettime.h"
416 #include "guiMessageMenu.h"
417 #include "filesys.h"
418 #include "config.h"
419 #include "guiMainMenu.h"
420 #include "mineral.h"
421 #include "materials.h"
422 #include "game.h"
423 #include "keycode.h"
424 #include "tile.h"
425
426 #include "gettext.h"
427
428 // This makes textures
429 ITextureSource *g_texturesource = NULL;
430
431 /*
432         Settings.
433         These are loaded from the config file.
434 */
435
436 Settings g_settings;
437 // This is located in defaultsettings.cpp
438 extern void set_default_settings();
439
440 // Global profiler
441 Profiler g_profiler;
442
443 /*
444         Random stuff
445 */
446
447 /*
448         GUI Stuff
449 */
450
451 gui::IGUIEnvironment* guienv = NULL;
452 gui::IGUIStaticText *guiroot = NULL;
453
454 MainMenuManager g_menumgr;
455
456 bool noMenuActive()
457 {
458         return (g_menumgr.menuCount() == 0);
459 }
460
461 // Passed to menus to allow disconnecting and exiting
462
463 MainGameCallback *g_gamecallback = NULL;
464
465 /*
466         Debug streams
467 */
468
469 // Connection
470 std::ostream *dout_con_ptr = &dummyout;
471 std::ostream *derr_con_ptr = &dstream_no_stderr;
472 //std::ostream *dout_con_ptr = &dstream_no_stderr;
473 //std::ostream *derr_con_ptr = &dstream_no_stderr;
474 //std::ostream *dout_con_ptr = &dstream;
475 //std::ostream *derr_con_ptr = &dstream;
476
477 // Server
478 std::ostream *dout_server_ptr = &dstream;
479 std::ostream *derr_server_ptr = &dstream;
480
481 // Client
482 std::ostream *dout_client_ptr = &dstream;
483 std::ostream *derr_client_ptr = &dstream;
484
485 /*
486         gettime.h implementation
487 */
488
489 // A small helper class
490 class TimeGetter
491 {
492 public:
493         virtual u32 getTime() = 0;
494 };
495
496 // A precise irrlicht one
497 class IrrlichtTimeGetter: public TimeGetter
498 {
499 public:
500         IrrlichtTimeGetter(IrrlichtDevice *device):
501                 m_device(device)
502         {}
503         u32 getTime()
504         {
505                 if(m_device == NULL)
506                         return 0;
507                 return m_device->getTimer()->getRealTime();
508         }
509 private:
510         IrrlichtDevice *m_device;
511 };
512 // Not so precise one which works without irrlicht
513 class SimpleTimeGetter: public TimeGetter
514 {
515 public:
516         u32 getTime()
517         {
518                 return porting::getTimeMs();
519         }
520 };
521
522 // A pointer to a global instance of the time getter
523 // TODO: why?
524 TimeGetter *g_timegetter = NULL;
525
526 u32 getTimeMs()
527 {
528         if(g_timegetter == NULL)
529                 return 0;
530         return g_timegetter->getTime();
531 }
532
533 /*
534         Event handler for Irrlicht
535
536         NOTE: Everything possible should be moved out from here,
537               probably to InputHandler and the_game
538 */
539
540 class MyEventReceiver : public IEventReceiver
541 {
542 public:
543         // This is the one method that we have to implement
544         virtual bool OnEvent(const SEvent& event)
545         {
546                 /*
547                         React to nothing here if a menu is active
548                 */
549                 if(noMenuActive() == false)
550                 {
551                         return false;
552                 }
553
554                 // Remember whether each key is down or up
555                 if(event.EventType == irr::EET_KEY_INPUT_EVENT)
556                 {
557                         keyIsDown[event.KeyInput.Key] = event.KeyInput.PressedDown;
558
559                         if(event.KeyInput.PressedDown)
560                                 keyWasDown[event.KeyInput.Key] = true;
561                 }
562
563                 if(event.EventType == irr::EET_MOUSE_INPUT_EVENT)
564                 {
565                         if(noMenuActive() == false)
566                         {
567                                 left_active = false;
568                                 middle_active = false;
569                                 right_active = false;
570                         }
571                         else
572                         {
573                                 //dstream<<"MyEventReceiver: mouse input"<<std::endl;
574                                 left_active = event.MouseInput.isLeftPressed();
575                                 middle_active = event.MouseInput.isMiddlePressed();
576                                 right_active = event.MouseInput.isRightPressed();
577
578                                 if(event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)
579                                 {
580                                         leftclicked = true;
581                                 }
582                                 if(event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN)
583                                 {
584                                         rightclicked = true;
585                                 }
586                                 if(event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP)
587                                 {
588                                         leftreleased = true;
589                                 }
590                                 if(event.MouseInput.Event == EMIE_RMOUSE_LEFT_UP)
591                                 {
592                                         rightreleased = true;
593                                 }
594                                 if(event.MouseInput.Event == EMIE_MOUSE_WHEEL)
595                                 {
596                                         mouse_wheel += event.MouseInput.Wheel;
597                                 }
598                         }
599                 }
600
601                 return false;
602         }
603
604         bool IsKeyDown(EKEY_CODE keyCode) const
605         {
606                 return keyIsDown[keyCode];
607         }
608         
609         // Checks whether a key was down and resets the state
610         bool WasKeyDown(EKEY_CODE keyCode)
611         {
612                 bool b = keyWasDown[keyCode];
613                 keyWasDown[keyCode] = false;
614                 return b;
615         }
616
617         s32 getMouseWheel()
618         {
619                 s32 a = mouse_wheel;
620                 mouse_wheel = 0;
621                 return a;
622         }
623
624         void clearInput()
625         {
626                 for(u32 i=0; i<KEY_KEY_CODES_COUNT; i++)
627                 {
628                         keyIsDown[i] = false;
629                         keyWasDown[i] = false;
630                 }
631                 
632                 leftclicked = false;
633                 rightclicked = false;
634                 leftreleased = false;
635                 rightreleased = false;
636
637                 left_active = false;
638                 middle_active = false;
639                 right_active = false;
640
641                 mouse_wheel = 0;
642         }
643
644         MyEventReceiver()
645         {
646                 clearInput();
647         }
648
649         bool leftclicked;
650         bool rightclicked;
651         bool leftreleased;
652         bool rightreleased;
653
654         bool left_active;
655         bool middle_active;
656         bool right_active;
657
658         s32 mouse_wheel;
659
660 private:
661         IrrlichtDevice *m_device;
662         
663         // The current state of keys
664         bool keyIsDown[KEY_KEY_CODES_COUNT];
665         // Whether a key has been pressed or not
666         bool keyWasDown[KEY_KEY_CODES_COUNT];
667 };
668
669 /*
670         Separated input handler
671 */
672
673 class RealInputHandler : public InputHandler
674 {
675 public:
676         RealInputHandler(IrrlichtDevice *device, MyEventReceiver *receiver):
677                 m_device(device),
678                 m_receiver(receiver)
679         {
680         }
681         virtual bool isKeyDown(EKEY_CODE keyCode)
682         {
683                 return m_receiver->IsKeyDown(keyCode);
684         }
685         virtual bool wasKeyDown(EKEY_CODE keyCode)
686         {
687                 return m_receiver->WasKeyDown(keyCode);
688         }
689         virtual v2s32 getMousePos()
690         {
691                 return m_device->getCursorControl()->getPosition();
692         }
693         virtual void setMousePos(s32 x, s32 y)
694         {
695                 m_device->getCursorControl()->setPosition(x, y);
696         }
697
698         virtual bool getLeftState()
699         {
700                 return m_receiver->left_active;
701         }
702         virtual bool getRightState()
703         {
704                 return m_receiver->right_active;
705         }
706         
707         virtual bool getLeftClicked()
708         {
709                 return m_receiver->leftclicked;
710         }
711         virtual bool getRightClicked()
712         {
713                 return m_receiver->rightclicked;
714         }
715         virtual void resetLeftClicked()
716         {
717                 m_receiver->leftclicked = false;
718         }
719         virtual void resetRightClicked()
720         {
721                 m_receiver->rightclicked = false;
722         }
723
724         virtual bool getLeftReleased()
725         {
726                 return m_receiver->leftreleased;
727         }
728         virtual bool getRightReleased()
729         {
730                 return m_receiver->rightreleased;
731         }
732         virtual void resetLeftReleased()
733         {
734                 m_receiver->leftreleased = false;
735         }
736         virtual void resetRightReleased()
737         {
738                 m_receiver->rightreleased = false;
739         }
740
741         virtual s32 getMouseWheel()
742         {
743                 return m_receiver->getMouseWheel();
744         }
745
746         void clear()
747         {
748                 m_receiver->clearInput();
749         }
750 private:
751         IrrlichtDevice *m_device;
752         MyEventReceiver *m_receiver;
753 };
754
755 class RandomInputHandler : public InputHandler
756 {
757 public:
758         RandomInputHandler()
759         {
760                 leftdown = false;
761                 rightdown = false;
762                 leftclicked = false;
763                 rightclicked = false;
764                 leftreleased = false;
765                 rightreleased = false;
766                 for(u32 i=0; i<KEY_KEY_CODES_COUNT; ++i)
767                         keydown[i] = false;
768         }
769         virtual bool isKeyDown(EKEY_CODE keyCode)
770         {
771                 return keydown[keyCode];
772         }
773         virtual bool wasKeyDown(EKEY_CODE keyCode)
774         {
775                 return false;
776         }
777         virtual v2s32 getMousePos()
778         {
779                 return mousepos;
780         }
781         virtual void setMousePos(s32 x, s32 y)
782         {
783                 mousepos = v2s32(x,y);
784         }
785
786         virtual bool getLeftState()
787         {
788                 return leftdown;
789         }
790         virtual bool getRightState()
791         {
792                 return rightdown;
793         }
794
795         virtual bool getLeftClicked()
796         {
797                 return leftclicked;
798         }
799         virtual bool getRightClicked()
800         {
801                 return rightclicked;
802         }
803         virtual void resetLeftClicked()
804         {
805                 leftclicked = false;
806         }
807         virtual void resetRightClicked()
808         {
809                 rightclicked = false;
810         }
811
812         virtual bool getLeftReleased()
813         {
814                 return leftreleased;
815         }
816         virtual bool getRightReleased()
817         {
818                 return rightreleased;
819         }
820         virtual void resetLeftReleased()
821         {
822                 leftreleased = false;
823         }
824         virtual void resetRightReleased()
825         {
826                 rightreleased = false;
827         }
828
829         virtual s32 getMouseWheel()
830         {
831                 return 0;
832         }
833
834         virtual void step(float dtime)
835         {
836                 {
837                         static float counter1 = 0;
838                         counter1 -= dtime;
839                         if(counter1 < 0.0)
840                         {
841                                 counter1 = 0.1*Rand(1, 40);
842                                 keydown[getKeySetting("keymap_jump")] =
843                                                 !keydown[getKeySetting("keymap_jump")];
844                         }
845                 }
846                 {
847                         static float counter1 = 0;
848                         counter1 -= dtime;
849                         if(counter1 < 0.0)
850                         {
851                                 counter1 = 0.1*Rand(1, 40);
852                                 keydown[getKeySetting("keymap_special1")] =
853                                                 !keydown[getKeySetting("keymap_special1")];
854                         }
855                 }
856                 {
857                         static float counter1 = 0;
858                         counter1 -= dtime;
859                         if(counter1 < 0.0)
860                         {
861                                 counter1 = 0.1*Rand(1, 40);
862                                 keydown[getKeySetting("keymap_forward")] =
863                                                 !keydown[getKeySetting("keymap_forward")];
864                         }
865                 }
866                 {
867                         static float counter1 = 0;
868                         counter1 -= dtime;
869                         if(counter1 < 0.0)
870                         {
871                                 counter1 = 0.1*Rand(1, 40);
872                                 keydown[getKeySetting("keymap_left")] =
873                                                 !keydown[getKeySetting("keymap_left")];
874                         }
875                 }
876                 {
877                         static float counter1 = 0;
878                         counter1 -= dtime;
879                         if(counter1 < 0.0)
880                         {
881                                 counter1 = 0.1*Rand(1, 20);
882                                 mousespeed = v2s32(Rand(-20,20), Rand(-15,20));
883                         }
884                 }
885                 {
886                         static float counter1 = 0;
887                         counter1 -= dtime;
888                         if(counter1 < 0.0)
889                         {
890                                 counter1 = 0.1*Rand(1, 30);
891                                 leftdown = !leftdown;
892                                 if(leftdown)
893                                         leftclicked = true;
894                                 if(!leftdown)
895                                         leftreleased = true;
896                         }
897                 }
898                 {
899                         static float counter1 = 0;
900                         counter1 -= dtime;
901                         if(counter1 < 0.0)
902                         {
903                                 counter1 = 0.1*Rand(1, 15);
904                                 rightdown = !rightdown;
905                                 if(rightdown)
906                                         rightclicked = true;
907                                 if(!rightdown)
908                                         rightreleased = true;
909                         }
910                 }
911                 mousepos += mousespeed;
912         }
913
914         s32 Rand(s32 min, s32 max)
915         {
916                 return (myrand()%(max-min+1))+min;
917         }
918 private:
919         bool keydown[KEY_KEY_CODES_COUNT];
920         v2s32 mousepos;
921         v2s32 mousespeed;
922         bool leftdown;
923         bool rightdown;
924         bool leftclicked;
925         bool rightclicked;
926         bool leftreleased;
927         bool rightreleased;
928 };
929
930 // These are defined global so that they're not optimized too much.
931 // Can't change them to volatile.
932 s16 temp16;
933 f32 tempf;
934 v3f tempv3f1;
935 v3f tempv3f2;
936 std::string tempstring;
937 std::string tempstring2;
938
939 void SpeedTests()
940 {
941         {
942                 dstream<<"The following test should take around 20ms."<<std::endl;
943                 TimeTaker timer("Testing std::string speed");
944                 const u32 jj = 10000;
945                 for(u32 j=0; j<jj; j++)
946                 {
947                         tempstring = "";
948                         tempstring2 = "";
949                         const u32 ii = 10;
950                         for(u32 i=0; i<ii; i++){
951                                 tempstring2 += "asd";
952                         }
953                         for(u32 i=0; i<ii+1; i++){
954                                 tempstring += "asd";
955                                 if(tempstring == tempstring2)
956                                         break;
957                         }
958                 }
959         }
960         
961         dstream<<"All of the following tests should take around 100ms each."
962                         <<std::endl;
963
964         {
965                 TimeTaker timer("Testing floating-point conversion speed");
966                 tempf = 0.001;
967                 for(u32 i=0; i<4000000; i++){
968                         temp16 += tempf;
969                         tempf += 0.001;
970                 }
971         }
972         
973         {
974                 TimeTaker timer("Testing floating-point vector speed");
975
976                 tempv3f1 = v3f(1,2,3);
977                 tempv3f2 = v3f(4,5,6);
978                 for(u32 i=0; i<10000000; i++){
979                         tempf += tempv3f1.dotProduct(tempv3f2);
980                         tempv3f2 += v3f(7,8,9);
981                 }
982         }
983
984         {
985                 TimeTaker timer("Testing core::map speed");
986                 
987                 core::map<v2s16, f32> map1;
988                 tempf = -324;
989                 const s16 ii=300;
990                 for(s16 y=0; y<ii; y++){
991                         for(s16 x=0; x<ii; x++){
992                                 map1.insert(v2s16(x,y), tempf);
993                                 tempf += 1;
994                         }
995                 }
996                 for(s16 y=ii-1; y>=0; y--){
997                         for(s16 x=0; x<ii; x++){
998                                 tempf = map1[v2s16(x,y)];
999                         }
1000                 }
1001         }
1002
1003         {
1004                 dstream<<"Around 5000/ms should do well here."<<std::endl;
1005                 TimeTaker timer("Testing mutex speed");
1006                 
1007                 JMutex m;
1008                 m.Init();
1009                 u32 n = 0;
1010                 u32 i = 0;
1011                 do{
1012                         n += 10000;
1013                         for(; i<n; i++){
1014                                 m.Lock();
1015                                 m.Unlock();
1016                         }
1017                 }
1018                 // Do at least 10ms
1019                 while(timer.getTime() < 10);
1020
1021                 u32 dtime = timer.stop();
1022                 u32 per_ms = n / dtime;
1023                 std::cout<<"Done. "<<dtime<<"ms, "
1024                                 <<per_ms<<"/ms"<<std::endl;
1025         }
1026 }
1027
1028 void drawMenuBackground(video::IVideoDriver* driver)
1029 {
1030         core::dimension2d<u32> screensize = driver->getScreenSize();
1031                 
1032         video::ITexture *bgtexture =
1033                         driver->getTexture(getTexturePath("mud.png").c_str());
1034         if(bgtexture)
1035         {
1036                 s32 texturesize = 128;
1037                 s32 tiled_y = screensize.Height / texturesize + 1;
1038                 s32 tiled_x = screensize.Width / texturesize + 1;
1039                 
1040                 for(s32 y=0; y<tiled_y; y++)
1041                 for(s32 x=0; x<tiled_x; x++)
1042                 {
1043                         core::rect<s32> rect(0,0,texturesize,texturesize);
1044                         rect += v2s32(x*texturesize, y*texturesize);
1045                         driver->draw2DImage(bgtexture, rect,
1046                                 core::rect<s32>(core::position2d<s32>(0,0),
1047                                 core::dimension2di(bgtexture->getSize())),
1048                                 NULL, NULL, true);
1049                 }
1050         }
1051         
1052         video::ITexture *logotexture =
1053                         driver->getTexture(getTexturePath("menulogo.png").c_str());
1054         if(logotexture)
1055         {
1056                 v2s32 logosize(logotexture->getOriginalSize().Width,
1057                                 logotexture->getOriginalSize().Height);
1058                 logosize *= 4;
1059
1060                 video::SColor bgcolor(255,50,50,50);
1061                 core::rect<s32> bgrect(0, screensize.Height-logosize.Y-20,
1062                                 screensize.Width, screensize.Height);
1063                 driver->draw2DRectangle(bgcolor, bgrect, NULL);
1064
1065                 core::rect<s32> rect(0,0,logosize.X,logosize.Y);
1066                 rect += v2s32(screensize.Width/2,screensize.Height-10-logosize.Y);
1067                 rect -= v2s32(logosize.X/2, 0);
1068                 driver->draw2DImage(logotexture, rect,
1069                         core::rect<s32>(core::position2d<s32>(0,0),
1070                         core::dimension2di(logotexture->getSize())),
1071                         NULL, NULL, true);
1072         }
1073 }
1074
1075 int main(int argc, char *argv[])
1076 {
1077         /*
1078                 Initialization
1079         */
1080
1081         // Set locale. This is for forcing '.' as the decimal point.
1082         std::locale::global(std::locale("C"));
1083         // This enables printing all characters in bitmap font
1084         setlocale(LC_CTYPE, "en_US");
1085
1086         /*
1087                 Parse command line
1088         */
1089         
1090         // List all allowed options
1091         core::map<std::string, ValueSpec> allowed_options;
1092         allowed_options.insert("help", ValueSpec(VALUETYPE_FLAG));
1093         allowed_options.insert("server", ValueSpec(VALUETYPE_FLAG,
1094                         "Run server directly"));
1095         allowed_options.insert("config", ValueSpec(VALUETYPE_STRING,
1096                         "Load configuration from specified file"));
1097         allowed_options.insert("port", ValueSpec(VALUETYPE_STRING));
1098         allowed_options.insert("address", ValueSpec(VALUETYPE_STRING));
1099         allowed_options.insert("random-input", ValueSpec(VALUETYPE_FLAG));
1100         allowed_options.insert("disable-unittests", ValueSpec(VALUETYPE_FLAG));
1101         allowed_options.insert("enable-unittests", ValueSpec(VALUETYPE_FLAG));
1102         allowed_options.insert("map-dir", ValueSpec(VALUETYPE_STRING));
1103 #ifdef _WIN32
1104         allowed_options.insert("dstream-on-stderr", ValueSpec(VALUETYPE_FLAG));
1105 #endif
1106         allowed_options.insert("speedtests", ValueSpec(VALUETYPE_FLAG));
1107
1108         Settings cmd_args;
1109         
1110         bool ret = cmd_args.parseCommandLine(argc, argv, allowed_options);
1111
1112         if(ret == false || cmd_args.getFlag("help"))
1113         {
1114                 dstream<<"Allowed options:"<<std::endl;
1115                 for(core::map<std::string, ValueSpec>::Iterator
1116                                 i = allowed_options.getIterator();
1117                                 i.atEnd() == false; i++)
1118                 {
1119                         dstream<<"  --"<<i.getNode()->getKey();
1120                         if(i.getNode()->getValue().type == VALUETYPE_FLAG)
1121                         {
1122                         }
1123                         else
1124                         {
1125                                 dstream<<" <value>";
1126                         }
1127                         dstream<<std::endl;
1128
1129                         if(i.getNode()->getValue().help != NULL)
1130                         {
1131                                 dstream<<"      "<<i.getNode()->getValue().help
1132                                                 <<std::endl;
1133                         }
1134                 }
1135
1136                 return cmd_args.getFlag("help") ? 0 : 1;
1137         }
1138         
1139         /*
1140                 Low-level initialization
1141         */
1142
1143         bool disable_stderr = false;
1144 #ifdef _WIN32
1145         if(cmd_args.getFlag("dstream-on-stderr") == false)
1146                 disable_stderr = true;
1147 #endif
1148
1149         porting::signal_handler_init();
1150         bool &kill = *porting::signal_handler_killstatus();
1151         
1152         // Initialize porting::path_data and porting::path_userdata
1153         porting::initializePaths();
1154
1155         // Create user data directory
1156         fs::CreateDir(porting::path_userdata);
1157
1158         setlocale(LC_MESSAGES, "");
1159         bindtextdomain("minetest", (porting::path_userdata+"/locale").c_str());
1160         textdomain("minetest");
1161         
1162         // Initialize debug streams
1163 #ifdef RUN_IN_PLACE
1164         std::string debugfile = DEBUGFILE;
1165 #else
1166         std::string debugfile = porting::path_userdata+"/"+DEBUGFILE;
1167 #endif
1168         debugstreams_init(disable_stderr, debugfile.c_str());
1169         // Initialize debug stacks
1170         debug_stacks_init();
1171
1172         DSTACK(__FUNCTION_NAME);
1173
1174         // Init material properties table
1175         //initializeMaterialProperties();
1176
1177         // Debug handler
1178         BEGIN_DEBUG_EXCEPTION_HANDLER
1179
1180         // Print startup message
1181         dstream<<DTIME<<"minetest-c55"
1182                         " with SER_FMT_VER_HIGHEST="<<(int)SER_FMT_VER_HIGHEST
1183                         <<", "<<BUILD_INFO
1184                         <<std::endl;
1185         
1186         /*
1187                 Basic initialization
1188         */
1189
1190         // Initialize default settings
1191         set_default_settings();
1192         
1193         // Initialize sockets
1194         sockets_init();
1195         atexit(sockets_cleanup);
1196         
1197         /*
1198                 Read config file
1199         */
1200         
1201         // Path of configuration file in use
1202         std::string configpath = "";
1203         
1204         if(cmd_args.exists("config"))
1205         {
1206                 bool r = g_settings.readConfigFile(cmd_args.get("config").c_str());
1207                 if(r == false)
1208                 {
1209                         dstream<<"Could not read configuration from \""
1210                                         <<cmd_args.get("config")<<"\""<<std::endl;
1211                         return 1;
1212                 }
1213                 configpath = cmd_args.get("config");
1214         }
1215         else
1216         {
1217                 core::array<std::string> filenames;
1218                 filenames.push_back(porting::path_userdata + "/minetest.conf");
1219 #ifdef RUN_IN_PLACE
1220                 filenames.push_back(porting::path_userdata + "/../minetest.conf");
1221 #endif
1222
1223                 for(u32 i=0; i<filenames.size(); i++)
1224                 {
1225                         bool r = g_settings.readConfigFile(filenames[i].c_str());
1226                         if(r)
1227                         {
1228                                 configpath = filenames[i];
1229                                 break;
1230                         }
1231                 }
1232                 
1233                 // If no path found, use the first one (menu creates the file)
1234                 if(configpath == "")
1235                         configpath = filenames[0];
1236         }
1237
1238         // Initialize random seed
1239         srand(time(0));
1240         mysrand(time(0));
1241
1242         /*
1243                 Pre-initialize some stuff with a dummy irrlicht wrapper.
1244
1245                 These are needed for unit tests at least.
1246         */
1247         
1248         // Initial call with g_texturesource not set.
1249         init_mapnode();
1250
1251         /*
1252                 Run unit tests
1253         */
1254
1255         if((ENABLE_TESTS && cmd_args.getFlag("disable-unittests") == false)
1256                         || cmd_args.getFlag("enable-unittests") == true)
1257         {
1258                 run_tests();
1259         }
1260         
1261         /*for(s16 y=-100; y<100; y++)
1262         for(s16 x=-100; x<100; x++)
1263         {
1264                 std::cout<<noise2d_gradient((double)x/10,(double)y/10, 32415)<<std::endl;
1265         }
1266         return 0;*/
1267         
1268         /*
1269                 Game parameters
1270         */
1271
1272         // Port
1273         u16 port = 30000;
1274         if(cmd_args.exists("port"))
1275                 port = cmd_args.getU16("port");
1276         else if(g_settings.exists("port"))
1277                 port = g_settings.getU16("port");
1278         if(port == 0)
1279                 port = 30000;
1280         
1281         // Map directory
1282         std::string map_dir = porting::path_userdata+"/world";
1283         if(cmd_args.exists("map-dir"))
1284                 map_dir = cmd_args.get("map-dir");
1285         else if(g_settings.exists("map-dir"))
1286                 map_dir = g_settings.get("map-dir");
1287         
1288         // Run dedicated server if asked to
1289         if(cmd_args.getFlag("server"))
1290         {
1291                 DSTACK("Dedicated server branch");
1292
1293                 // Create time getter
1294                 g_timegetter = new SimpleTimeGetter();
1295                 
1296                 // Create server
1297                 Server server(map_dir.c_str());
1298                 server.start(port);
1299                 
1300                 // Run server
1301                 dedicated_server_loop(server, kill);
1302
1303                 return 0;
1304         }
1305
1306
1307         /*
1308                 More parameters
1309         */
1310         
1311         // Address to connect to
1312         std::string address = "";
1313         
1314         if(cmd_args.exists("address"))
1315         {
1316                 address = cmd_args.get("address");
1317         }
1318         else
1319         {
1320                 address = g_settings.get("address");
1321         }
1322         
1323         std::string playername = g_settings.get("name");
1324
1325         /*
1326                 Device initialization
1327         */
1328
1329         // Resolution selection
1330         
1331         bool fullscreen = false;
1332         u16 screenW = g_settings.getU16("screenW");
1333         u16 screenH = g_settings.getU16("screenH");
1334
1335         // Determine driver
1336
1337         video::E_DRIVER_TYPE driverType;
1338         
1339         std::string driverstring = g_settings.get("video_driver");
1340
1341         if(driverstring == "null")
1342                 driverType = video::EDT_NULL;
1343         else if(driverstring == "software")
1344                 driverType = video::EDT_SOFTWARE;
1345         else if(driverstring == "burningsvideo")
1346                 driverType = video::EDT_BURNINGSVIDEO;
1347         else if(driverstring == "direct3d8")
1348                 driverType = video::EDT_DIRECT3D8;
1349         else if(driverstring == "direct3d9")
1350                 driverType = video::EDT_DIRECT3D9;
1351         else if(driverstring == "opengl")
1352                 driverType = video::EDT_OPENGL;
1353         else
1354         {
1355                 dstream<<"WARNING: Invalid video_driver specified; defaulting "
1356                                 "to opengl"<<std::endl;
1357                 driverType = video::EDT_OPENGL;
1358         }
1359
1360         /*
1361                 Create device and exit if creation failed
1362         */
1363
1364         MyEventReceiver receiver;
1365
1366         IrrlichtDevice *device;
1367         device = createDevice(driverType,
1368                         core::dimension2d<u32>(screenW, screenH),
1369                         16, fullscreen, false, false, &receiver);
1370
1371         if (device == 0)
1372                 return 1; // could not create selected driver.
1373         
1374         // Set device in game parameters
1375         device = device;
1376
1377         // Set the window caption
1378         device->setWindowCaption(L"Minetest [Main Menu]");
1379         
1380         // Create time getter
1381         g_timegetter = new IrrlichtTimeGetter(device);
1382         
1383         // Create game callback for menus
1384         g_gamecallback = new MainGameCallback(device);
1385         
1386         // Create texture source
1387         g_texturesource = new TextureSource(device);
1388
1389         /*
1390                 Speed tests (done after irrlicht is loaded to get timer)
1391         */
1392         if(cmd_args.getFlag("speedtests"))
1393         {
1394                 dstream<<"Running speed tests"<<std::endl;
1395                 SpeedTests();
1396                 return 0;
1397         }
1398         
1399         device->setResizable(true);
1400
1401         bool random_input = g_settings.getBool("random_input")
1402                         || cmd_args.getFlag("random-input");
1403         InputHandler *input = NULL;
1404         if(random_input)
1405                 input = new RandomInputHandler();
1406         else
1407                 input = new RealInputHandler(device, &receiver);
1408         
1409         /*
1410                 Continue initialization
1411         */
1412
1413         //video::IVideoDriver* driver = device->getVideoDriver();
1414
1415         /*
1416                 This changes the minimum allowed number of vertices in a VBO.
1417                 Default is 500.
1418         */
1419         //driver->setMinHardwareBufferVertexCount(50);
1420
1421         scene::ISceneManager* smgr = device->getSceneManager();
1422
1423         guienv = device->getGUIEnvironment();
1424         gui::IGUISkin* skin = guienv->getSkin();
1425         gui::IGUIFont* font = guienv->getFont(getTexturePath("fontlucida.png").c_str());
1426         if(font)
1427                 skin->setFont(font);
1428         else
1429                 dstream<<"WARNING: Font file was not found."
1430                                 " Using default font."<<std::endl;
1431         // If font was not found, this will get us one
1432         font = skin->getFont();
1433         assert(font);
1434         
1435         u32 text_height = font->getDimension(L"Hello, world!").Height;
1436         dstream<<"text_height="<<text_height<<std::endl;
1437
1438         //skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,0,0,0));
1439         skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,255,255,255));
1440         //skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(0,0,0,0));
1441         //skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(0,0,0,0));
1442         skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255,0,0,0));
1443         skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255,0,0,0));
1444         
1445         /*
1446                 Preload some textures and stuff
1447         */
1448
1449         init_mapnode(); // Second call with g_texturesource set
1450         init_mineral();
1451
1452         /*
1453                 GUI stuff
1454         */
1455
1456         /*
1457                 If an error occurs, this is set to something and the
1458                 menu-game loop is restarted. It is then displayed before
1459                 the menu.
1460         */
1461         std::wstring error_message = L"";
1462
1463         // The password entered during the menu screen,
1464         std::string password;
1465
1466         /*
1467                 Menu-game loop
1468         */
1469         while(device->run() && kill == false)
1470         {
1471
1472                 // This is used for catching disconnects
1473                 try
1474                 {
1475
1476                         /*
1477                                 Clear everything from the GUIEnvironment
1478                         */
1479                         guienv->clear();
1480                         
1481                         /*
1482                                 We need some kind of a root node to be able to add
1483                                 custom gui elements directly on the screen.
1484                                 Otherwise they won't be automatically drawn.
1485                         */
1486                         guiroot = guienv->addStaticText(L"",
1487                                         core::rect<s32>(0, 0, 10000, 10000));
1488                         
1489                         /*
1490                                 Out-of-game menu loop.
1491
1492                                 Loop quits when menu returns proper parameters.
1493                         */
1494                         while(kill == false)
1495                         {
1496                                 // Cursor can be non-visible when coming from the game
1497                                 device->getCursorControl()->setVisible(true);
1498                                 // Some stuff are left to scene manager when coming from the game
1499                                 // (map at least?)
1500                                 smgr->clear();
1501                                 // Reset or hide the debug gui texts
1502                                 /*guitext->setText(L"Minetest-c55");
1503                                 guitext2->setVisible(false);
1504                                 guitext_info->setVisible(false);
1505                                 guitext_chat->setVisible(false);*/
1506                                 
1507                                 // Initialize menu data
1508                                 MainMenuData menudata;
1509                                 menudata.address = narrow_to_wide(address);
1510                                 menudata.name = narrow_to_wide(playername);
1511                                 menudata.port = narrow_to_wide(itos(port));
1512                                 menudata.fancy_trees = g_settings.getBool("new_style_leaves");
1513                                 menudata.smooth_lighting = g_settings.getBool("smooth_lighting");
1514                                 menudata.creative_mode = g_settings.getBool("creative_mode");
1515                                 menudata.enable_damage = g_settings.getBool("enable_damage");
1516
1517                                 GUIMainMenu *menu =
1518                                                 new GUIMainMenu(guienv, guiroot, -1, 
1519                                                         &g_menumgr, &menudata, g_gamecallback);
1520                                 menu->allowFocusRemoval(true);
1521
1522                                 if(error_message != L"")
1523                                 {
1524                                         dstream<<"WARNING: error_message = "
1525                                                         <<wide_to_narrow(error_message)<<std::endl;
1526
1527                                         GUIMessageMenu *menu2 =
1528                                                         new GUIMessageMenu(guienv, guiroot, -1, 
1529                                                                 &g_menumgr, error_message.c_str());
1530                                         menu2->drop();
1531                                         error_message = L"";
1532                                 }
1533
1534                                 video::IVideoDriver* driver = device->getVideoDriver();
1535                                 
1536                                 dstream<<"Created main menu"<<std::endl;
1537
1538                                 while(device->run() && kill == false)
1539                                 {
1540                                         if(menu->getStatus() == true)
1541                                                 break;
1542
1543                                         //driver->beginScene(true, true, video::SColor(255,0,0,0));
1544                                         driver->beginScene(true, true, video::SColor(255,128,128,128));
1545
1546                                         drawMenuBackground(driver);
1547
1548                                         guienv->drawAll();
1549                                         
1550                                         driver->endScene();
1551                                         
1552                                         // On some computers framerate doesn't seem to be
1553                                         // automatically limited
1554                                         sleep_ms(25);
1555                                 }
1556                                 
1557                                 // Break out of menu-game loop to shut down cleanly
1558                                 if(device->run() == false || kill == true)
1559                                         break;
1560                                 
1561                                 dstream<<"Dropping main menu"<<std::endl;
1562
1563                                 menu->drop();
1564                                 
1565                                 // Delete map if requested
1566                                 if(menudata.delete_map)
1567                                 {
1568                                         bool r = fs::RecursiveDeleteContent(map_dir);
1569                                         if(r == false)
1570                                                 error_message = L"Delete failed";
1571                                         continue;
1572                                 }
1573
1574                                 playername = wide_to_narrow(menudata.name);
1575
1576                                 password = translatePassword(playername, menudata.password);
1577
1578                                 address = wide_to_narrow(menudata.address);
1579                                 int newport = stoi(wide_to_narrow(menudata.port));
1580                                 if(newport != 0)
1581                                         port = newport;
1582                                 g_settings.set("new_style_leaves", itos(menudata.fancy_trees));
1583                                 g_settings.set("smooth_lighting", itos(menudata.smooth_lighting));
1584                                 g_settings.set("creative_mode", itos(menudata.creative_mode));
1585                                 g_settings.set("enable_damage", itos(menudata.enable_damage));
1586                                 
1587                                 // NOTE: These are now checked server side; no need to do it
1588                                 //       here, so let's not do it here.
1589                                 /*// Check for valid parameters, restart menu if invalid.
1590                                 if(playername == "")
1591                                 {
1592                                         error_message = L"Name required.";
1593                                         continue;
1594                                 }
1595                                 // Check that name has only valid chars
1596                                 if(string_allowed(playername, PLAYERNAME_ALLOWED_CHARS)==false)
1597                                 {
1598                                         error_message = L"Characters allowed: "
1599                                                         +narrow_to_wide(PLAYERNAME_ALLOWED_CHARS);
1600                                         continue;
1601                                 }*/
1602
1603                                 // Save settings
1604                                 g_settings.set("name", playername);
1605                                 g_settings.set("address", address);
1606                                 g_settings.set("port", itos(port));
1607                                 // Update configuration file
1608                                 if(configpath != "")
1609                                         g_settings.updateConfigFile(configpath.c_str());
1610                         
1611                                 // Continue to game
1612                                 break;
1613                         }
1614                         
1615                         // Break out of menu-game loop to shut down cleanly
1616                         if(device->run() == false)
1617                                 break;
1618                         
1619                         // Initialize mapnode again to enable changed graphics settings
1620                         init_mapnode();
1621
1622                         /*
1623                                 Run game
1624                         */
1625                         the_game(
1626                                 kill,
1627                                 random_input,
1628                                 input,
1629                                 device,
1630                                 font,
1631                                 map_dir,
1632                                 playername,
1633                                 password,
1634                                 address,
1635                                 port,
1636                                 error_message
1637                         );
1638
1639                 } //try
1640                 catch(con::PeerNotFoundException &e)
1641                 {
1642                         dstream<<DTIME<<"Connection error (timed out?)"<<std::endl;
1643                         error_message = L"Connection error (timed out?)";
1644                 }
1645                 catch(SocketException &e)
1646                 {
1647                         dstream<<DTIME<<"Socket error (port already in use?)"<<std::endl;
1648                         error_message = L"Socket error (port already in use?)";
1649                 }
1650 #ifdef NDEBUG
1651                 catch(std::exception &e)
1652                 {
1653                         std::string narrow_message = "Some exception, what()=\"";
1654                         narrow_message += e.what();
1655                         narrow_message += "\"";
1656                         dstream<<DTIME<<narrow_message<<std::endl;
1657                         error_message = narrow_to_wide(narrow_message);
1658                 }
1659 #endif
1660
1661         } // Menu-game loop
1662         
1663         delete input;
1664
1665         /*
1666                 In the end, delete the Irrlicht device.
1667         */
1668         device->drop();
1669         
1670         END_DEBUG_EXCEPTION_HANDLER
1671         
1672         debugstreams_deinit();
1673         
1674         return 0;
1675 }
1676
1677 //END
1678