10e01be2ad006a6d0fd2f92263839d4adc8a91d7
[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 NOTE: Seeds in 1260:6c77e7dbfd29:
58 5721858502589302589:
59         Spawns you on a small sand island with a surface dungeon
60 2983455799928051958:
61         Enormous jungle + a surface dungeon at ~(250,0,0)
62
63 Old, wild and random suggestions that probably won't be done:
64 -------------------------------------------------------------
65
66 SUGG: If player is on ground, mainly fetch ground-level blocks
67
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
73
74 SUGG: More fine-grained control of client's dumping of blocks from
75       memory
76           - ...What does this mean in the first place?
77
78 SUGG: A map editing mode (similar to dedicated server mode)
79
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.
90
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
95
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
100
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.
105
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
108
109 SUGG: Background music based on cellular automata?
110       http://www.earslap.com/projectslab/otomata
111
112 SUGG: Simple light color information to air
113
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.
117
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
120           or even generated.
121
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
134
135 SUGG: For non-mapgen FarMesh: Add a per-sector database to store surface
136       stuff as simple flags/values
137       - Light?
138           - A building?
139           And at some point make the server send this data to the client too,
140           instead of referring to the noise functions
141           - Ground height
142           - Surface ground type
143           - Trees?
144
145 Gaming ideas:
146 -------------
147
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?
151
152 Game content:
153 -------------
154
155 - When furnace is destroyed, move items to player's inventory
156 - Add lots of stuff
157 - Glass blocks
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
166           implementation)
167 - Cobble to get mossy if near water
168 - More slots in furnace source list, so that multiple ingredients
169   are possible.
170 - Keys to chests?
171
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
176
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
182
183 - A bomb
184 - A spread-items-on-map routine for the bomb, and for dying players
185
186 - Fighting:
187   - Proper sword swing simulation
188   - Player should get damage from colliding to a wall at high speed
189
190 Documentation:
191 --------------
192
193 Build system / running:
194 -----------------------
195
196 Networking and serialization:
197 -----------------------------
198
199 SUGG: Fix address to be ipv6 compatible
200
201 User Interface:
202 ---------------
203
204 Graphics:
205 ---------
206
207 SUGG: Combine MapBlock's face caches to so big pieces that VBO
208       can be used
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
213
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?
217
218 SUGG: Draw cubes in inventory directly with 3D drawing commands, so that
219       animating them is easier.
220
221 SUGG: Option for enabling proper alpha channel for textures
222
223 TODO: Flowing water animation
224
225 TODO: A setting for enabling bilinear filtering for textures
226
227 TODO: Better control of draw_control.wanted_max_blocks
228
229 TODO: Further investigate the use of GPU lighting in addition to the
230       current one
231
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.
236
237 SUGG: Somehow make the night less colorful
238
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.
244
245 Configuration:
246 --------------
247
248 Client:
249 -------
250
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
254             meshes takes so long
255
256 SUGG: Make morning and evening transition more smooth and maybe shorter
257
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.
262
263 - A weapon engine
264
265 - Tool/weapon visualization
266
267 FIXME: When disconnected to the menu, memory is not freed properly
268
269 TODO: Investigate how much the mesh generator thread gets used when
270       transferring map data
271
272 Server:
273 -------
274
275 SUGG: Make an option to the server to disable building and digging near
276       the starting position
277
278 FIXME: Server sometimes goes into some infinite PeerNotFoundException loop
279
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.
286
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
290
291 Environment:
292 ------------
293
294 TODO: Add proper hooks to when adding and removing active blocks
295
296 TODO: Finish the ActiveBlockModifier stuff and use it for something
297
298 Objects:
299 --------
300
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.
305
306 SUGG: MovingObject::move and Player::move are basically the same.
307       combine them.
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)
312
313 TODO: Add a long step function to objects that is called with the time
314       difference when block activates
315
316 Map:
317 ----
318
319 TODO: Flowing water to actually contain flow direction information
320       - There is a space for this - it just has to be implemented.
321
322 TODO: Consider smoothening cave floors after generating them
323
324 TODO: Fix make_tree, make_* to use seed-position-consistent pseudorandom
325           - delta also
326
327 Misc. stuff:
328 ------------
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
335           example
336
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
340
341 TODO: Merge bahamada's audio stuff (clean patch available)
342
343 Making it more portable:
344 ------------------------
345  
346 Stuff to do before release:
347 ---------------------------
348
349 Fixes to the current release:
350 -----------------------------
351
352 Stuff to do after release:
353 ---------------------------
354
355 Doing currently:
356 ----------------
357
358 ======================================================================
359
360 */
361
362 #ifdef NDEBUG
363         /*#ifdef _WIN32
364                 #pragma message ("Disabling unit tests")
365         #else
366                 #warning "Disabling unit tests"
367         #endif*/
368         // Disable unit tests
369         #define ENABLE_TESTS 0
370 #else
371         // Enable unit tests
372         #define ENABLE_TESTS 1
373 #endif
374
375 #ifdef _MSC_VER
376 #ifndef SERVER // Dedicated server isn't linked with Irrlicht
377         #pragma comment(lib, "Irrlicht.lib")
378         // This would get rid of the console window
379         //#pragma comment(linker, "/subsystem:windows /ENTRY:mainCRTStartup")
380 #endif
381         #pragma comment(lib, "zlibwapi.lib")
382         #pragma comment(lib, "Shell32.lib")
383 #endif
384
385 #include "irrlicht.h" // createDevice
386
387 #include "main.h"
388 #include "mainmenumanager.h"
389 #include <iostream>
390 #include <fstream>
391 #include <locale.h>
392 #include "common_irrlicht.h"
393 #include "debug.h"
394 #include "test.h"
395 #include "server.h"
396 #include "constants.h"
397 #include "porting.h"
398 #include "gettime.h"
399 #include "guiMessageMenu.h"
400 #include "filesys.h"
401 #include "config.h"
402 #include "guiMainMenu.h"
403 #include "game.h"
404 #include "keycode.h"
405 #include "tile.h"
406 #include "chat.h"
407 #include "defaultsettings.h"
408 #include "gettext.h"
409 #include "settings.h"
410 #include "profiler.h"
411 #include "log.h"
412 #include "mods.h"
413
414 /*
415         Settings.
416         These are loaded from the config file.
417 */
418 Settings main_settings;
419 Settings *g_settings = &main_settings;
420
421 // Global profiler
422 Profiler main_profiler;
423 Profiler *g_profiler = &main_profiler;
424
425 /*
426         Debug streams
427 */
428
429 // Connection
430 std::ostream *dout_con_ptr = &dummyout;
431 std::ostream *derr_con_ptr = &verbosestream;
432 //std::ostream *dout_con_ptr = &infostream;
433 //std::ostream *derr_con_ptr = &errorstream;
434
435 // Server
436 std::ostream *dout_server_ptr = &infostream;
437 std::ostream *derr_server_ptr = &errorstream;
438
439 // Client
440 std::ostream *dout_client_ptr = &infostream;
441 std::ostream *derr_client_ptr = &errorstream;
442
443 #ifndef SERVER
444 /*
445         Random stuff
446 */
447
448 /* mainmenumanager.h */
449
450 gui::IGUIEnvironment* guienv = NULL;
451 gui::IGUIStaticText *guiroot = NULL;
452 MainMenuManager g_menumgr;
453
454 bool noMenuActive()
455 {
456         return (g_menumgr.menuCount() == 0);
457 }
458
459 // Passed to menus to allow disconnecting and exiting
460 MainGameCallback *g_gamecallback = NULL;
461 #endif
462
463 /*
464         gettime.h implementation
465 */
466
467 #ifdef SERVER
468
469 u32 getTimeMs()
470 {
471         /* Use imprecise system calls directly (from porting.h) */
472         return porting::getTimeMs();
473 }
474
475 #else
476
477 // A small helper class
478 class TimeGetter
479 {
480 public:
481         virtual u32 getTime() = 0;
482 };
483
484 // A precise irrlicht one
485 class IrrlichtTimeGetter: public TimeGetter
486 {
487 public:
488         IrrlichtTimeGetter(IrrlichtDevice *device):
489                 m_device(device)
490         {}
491         u32 getTime()
492         {
493                 if(m_device == NULL)
494                         return 0;
495                 return m_device->getTimer()->getRealTime();
496         }
497 private:
498         IrrlichtDevice *m_device;
499 };
500 // Not so precise one which works without irrlicht
501 class SimpleTimeGetter: public TimeGetter
502 {
503 public:
504         u32 getTime()
505         {
506                 return porting::getTimeMs();
507         }
508 };
509
510 // A pointer to a global instance of the time getter
511 // TODO: why?
512 TimeGetter *g_timegetter = NULL;
513
514 u32 getTimeMs()
515 {
516         if(g_timegetter == NULL)
517                 return 0;
518         return g_timegetter->getTime();
519 }
520
521 #endif
522
523 class StderrLogOutput: public ILogOutput
524 {
525 public:
526         /* line: Full line with timestamp, level and thread */
527         void printLog(const std::string &line)
528         {
529                 std::cerr<<line<<std::endl;
530         }
531 } main_stderr_log_out;
532
533 class DstreamNoStderrLogOutput: public ILogOutput
534 {
535 public:
536         /* line: Full line with timestamp, level and thread */
537         void printLog(const std::string &line)
538         {
539                 dstream_no_stderr<<line<<std::endl;
540         }
541 } main_dstream_no_stderr_log_out;
542
543 #ifndef SERVER
544
545 /*
546         Event handler for Irrlicht
547
548         NOTE: Everything possible should be moved out from here,
549               probably to InputHandler and the_game
550 */
551
552 class MyEventReceiver : public IEventReceiver
553 {
554 public:
555         // This is the one method that we have to implement
556         virtual bool OnEvent(const SEvent& event)
557         {
558                 /*
559                         React to nothing here if a menu is active
560                 */
561                 if(noMenuActive() == false)
562                 {
563                         return false;
564                 }
565
566                 // Remember whether each key is down or up
567                 if(event.EventType == irr::EET_KEY_INPUT_EVENT)
568                 {
569                         if(event.KeyInput.PressedDown) {
570                                 keyIsDown.set(event.KeyInput);
571                                 keyWasDown.set(event.KeyInput);
572                         } else {
573                                 keyIsDown.unset(event.KeyInput);
574                         }
575                 }
576
577                 if(event.EventType == irr::EET_MOUSE_INPUT_EVENT)
578                 {
579                         if(noMenuActive() == false)
580                         {
581                                 left_active = false;
582                                 middle_active = false;
583                                 right_active = false;
584                         }
585                         else
586                         {
587                                 left_active = event.MouseInput.isLeftPressed();
588                                 middle_active = event.MouseInput.isMiddlePressed();
589                                 right_active = event.MouseInput.isRightPressed();
590
591                                 if(event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)
592                                 {
593                                         leftclicked = true;
594                                 }
595                                 if(event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN)
596                                 {
597                                         rightclicked = true;
598                                 }
599                                 if(event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP)
600                                 {
601                                         leftreleased = true;
602                                 }
603                                 if(event.MouseInput.Event == EMIE_RMOUSE_LEFT_UP)
604                                 {
605                                         rightreleased = true;
606                                 }
607                                 if(event.MouseInput.Event == EMIE_MOUSE_WHEEL)
608                                 {
609                                         mouse_wheel += event.MouseInput.Wheel;
610                                 }
611                         }
612                 }
613
614                 return false;
615         }
616
617         bool IsKeyDown(const KeyPress &keyCode) const
618         {
619                 return keyIsDown[keyCode];
620         }
621         
622         // Checks whether a key was down and resets the state
623         bool WasKeyDown(const KeyPress &keyCode)
624         {
625                 bool b = keyWasDown[keyCode];
626                 if (b)
627                         keyWasDown.unset(keyCode);
628                 return b;
629         }
630
631         s32 getMouseWheel()
632         {
633                 s32 a = mouse_wheel;
634                 mouse_wheel = 0;
635                 return a;
636         }
637
638         void clearInput()
639         {
640                 keyIsDown.clear();
641                 keyWasDown.clear();
642
643                 leftclicked = false;
644                 rightclicked = false;
645                 leftreleased = false;
646                 rightreleased = false;
647
648                 left_active = false;
649                 middle_active = false;
650                 right_active = false;
651
652                 mouse_wheel = 0;
653         }
654
655         MyEventReceiver()
656         {
657                 clearInput();
658         }
659
660         bool leftclicked;
661         bool rightclicked;
662         bool leftreleased;
663         bool rightreleased;
664
665         bool left_active;
666         bool middle_active;
667         bool right_active;
668
669         s32 mouse_wheel;
670
671 private:
672         IrrlichtDevice *m_device;
673         
674         // The current state of keys
675         KeyList keyIsDown;
676         // Whether a key has been pressed or not
677         KeyList keyWasDown;
678 };
679
680 /*
681         Separated input handler
682 */
683
684 class RealInputHandler : public InputHandler
685 {
686 public:
687         RealInputHandler(IrrlichtDevice *device, MyEventReceiver *receiver):
688                 m_device(device),
689                 m_receiver(receiver)
690         {
691         }
692         virtual bool isKeyDown(const KeyPress &keyCode)
693         {
694                 return m_receiver->IsKeyDown(keyCode);
695         }
696         virtual bool wasKeyDown(const KeyPress &keyCode)
697         {
698                 return m_receiver->WasKeyDown(keyCode);
699         }
700         virtual v2s32 getMousePos()
701         {
702                 return m_device->getCursorControl()->getPosition();
703         }
704         virtual void setMousePos(s32 x, s32 y)
705         {
706                 m_device->getCursorControl()->setPosition(x, y);
707         }
708
709         virtual bool getLeftState()
710         {
711                 return m_receiver->left_active;
712         }
713         virtual bool getRightState()
714         {
715                 return m_receiver->right_active;
716         }
717         
718         virtual bool getLeftClicked()
719         {
720                 return m_receiver->leftclicked;
721         }
722         virtual bool getRightClicked()
723         {
724                 return m_receiver->rightclicked;
725         }
726         virtual void resetLeftClicked()
727         {
728                 m_receiver->leftclicked = false;
729         }
730         virtual void resetRightClicked()
731         {
732                 m_receiver->rightclicked = false;
733         }
734
735         virtual bool getLeftReleased()
736         {
737                 return m_receiver->leftreleased;
738         }
739         virtual bool getRightReleased()
740         {
741                 return m_receiver->rightreleased;
742         }
743         virtual void resetLeftReleased()
744         {
745                 m_receiver->leftreleased = false;
746         }
747         virtual void resetRightReleased()
748         {
749                 m_receiver->rightreleased = false;
750         }
751
752         virtual s32 getMouseWheel()
753         {
754                 return m_receiver->getMouseWheel();
755         }
756
757         void clear()
758         {
759                 m_receiver->clearInput();
760         }
761 private:
762         IrrlichtDevice *m_device;
763         MyEventReceiver *m_receiver;
764 };
765
766 class RandomInputHandler : public InputHandler
767 {
768 public:
769         RandomInputHandler()
770         {
771                 leftdown = false;
772                 rightdown = false;
773                 leftclicked = false;
774                 rightclicked = false;
775                 leftreleased = false;
776                 rightreleased = false;
777                 keydown.clear();
778         }
779         virtual bool isKeyDown(const KeyPress &keyCode)
780         {
781                 return keydown[keyCode];
782         }
783         virtual bool wasKeyDown(const KeyPress &keyCode)
784         {
785                 return false;
786         }
787         virtual v2s32 getMousePos()
788         {
789                 return mousepos;
790         }
791         virtual void setMousePos(s32 x, s32 y)
792         {
793                 mousepos = v2s32(x,y);
794         }
795
796         virtual bool getLeftState()
797         {
798                 return leftdown;
799         }
800         virtual bool getRightState()
801         {
802                 return rightdown;
803         }
804
805         virtual bool getLeftClicked()
806         {
807                 return leftclicked;
808         }
809         virtual bool getRightClicked()
810         {
811                 return rightclicked;
812         }
813         virtual void resetLeftClicked()
814         {
815                 leftclicked = false;
816         }
817         virtual void resetRightClicked()
818         {
819                 rightclicked = false;
820         }
821
822         virtual bool getLeftReleased()
823         {
824                 return leftreleased;
825         }
826         virtual bool getRightReleased()
827         {
828                 return rightreleased;
829         }
830         virtual void resetLeftReleased()
831         {
832                 leftreleased = false;
833         }
834         virtual void resetRightReleased()
835         {
836                 rightreleased = false;
837         }
838
839         virtual s32 getMouseWheel()
840         {
841                 return 0;
842         }
843
844         virtual void step(float dtime)
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.toggle(getKeySetting("keymap_jump"));
853                         }
854                 }
855                 {
856                         static float counter1 = 0;
857                         counter1 -= dtime;
858                         if(counter1 < 0.0)
859                         {
860                                 counter1 = 0.1*Rand(1, 40);
861                                 keydown.toggle(getKeySetting("keymap_special1"));
862                         }
863                 }
864                 {
865                         static float counter1 = 0;
866                         counter1 -= dtime;
867                         if(counter1 < 0.0)
868                         {
869                                 counter1 = 0.1*Rand(1, 40);
870                                 keydown.toggle(getKeySetting("keymap_forward"));
871                         }
872                 }
873                 {
874                         static float counter1 = 0;
875                         counter1 -= dtime;
876                         if(counter1 < 0.0)
877                         {
878                                 counter1 = 0.1*Rand(1, 40);
879                                 keydown.toggle(getKeySetting("keymap_left"));
880                         }
881                 }
882                 {
883                         static float counter1 = 0;
884                         counter1 -= dtime;
885                         if(counter1 < 0.0)
886                         {
887                                 counter1 = 0.1*Rand(1, 20);
888                                 mousespeed = v2s32(Rand(-20,20), Rand(-15,20));
889                         }
890                 }
891                 {
892                         static float counter1 = 0;
893                         counter1 -= dtime;
894                         if(counter1 < 0.0)
895                         {
896                                 counter1 = 0.1*Rand(1, 30);
897                                 leftdown = !leftdown;
898                                 if(leftdown)
899                                         leftclicked = true;
900                                 if(!leftdown)
901                                         leftreleased = true;
902                         }
903                 }
904                 {
905                         static float counter1 = 0;
906                         counter1 -= dtime;
907                         if(counter1 < 0.0)
908                         {
909                                 counter1 = 0.1*Rand(1, 15);
910                                 rightdown = !rightdown;
911                                 if(rightdown)
912                                         rightclicked = true;
913                                 if(!rightdown)
914                                         rightreleased = true;
915                         }
916                 }
917                 mousepos += mousespeed;
918         }
919
920         s32 Rand(s32 min, s32 max)
921         {
922                 return (myrand()%(max-min+1))+min;
923         }
924 private:
925         KeyList keydown;
926         v2s32 mousepos;
927         v2s32 mousespeed;
928         bool leftdown;
929         bool rightdown;
930         bool leftclicked;
931         bool rightclicked;
932         bool leftreleased;
933         bool rightreleased;
934 };
935
936 void drawMenuBackground(video::IVideoDriver* driver)
937 {
938         core::dimension2d<u32> screensize = driver->getScreenSize();
939                 
940         video::ITexture *bgtexture =
941                         driver->getTexture(getTexturePath("menubg.png").c_str());
942         if(bgtexture)
943         {
944                 s32 scaledsize = 128;
945                 
946                 // The important difference between destsize and screensize is
947                 // that destsize is rounded to whole scaled pixels.
948                 // These formulas use component-wise multiplication and division of v2u32.
949                 v2u32 texturesize = bgtexture->getSize();
950                 v2u32 sourcesize = texturesize * screensize / scaledsize + v2u32(1,1);
951                 v2u32 destsize = scaledsize * sourcesize / texturesize;
952                 
953                 // Default texture wrapping mode in Irrlicht is ETC_REPEAT.
954                 driver->draw2DImage(bgtexture,
955                         core::rect<s32>(0, 0, destsize.X, destsize.Y),
956                         core::rect<s32>(0, 0, sourcesize.X, sourcesize.Y),
957                         NULL, NULL, true);
958         }
959         
960         video::ITexture *logotexture =
961                         driver->getTexture(getTexturePath("menulogo.png").c_str());
962         if(logotexture)
963         {
964                 v2s32 logosize(logotexture->getOriginalSize().Width,
965                                 logotexture->getOriginalSize().Height);
966                 logosize *= 4;
967
968                 video::SColor bgcolor(255,50,50,50);
969                 core::rect<s32> bgrect(0, screensize.Height-logosize.Y-20,
970                                 screensize.Width, screensize.Height);
971                 driver->draw2DRectangle(bgcolor, bgrect, NULL);
972
973                 core::rect<s32> rect(0,0,logosize.X,logosize.Y);
974                 rect += v2s32(screensize.Width/2,screensize.Height-10-logosize.Y);
975                 rect -= v2s32(logosize.X/2, 0);
976                 driver->draw2DImage(logotexture, rect,
977                         core::rect<s32>(core::position2d<s32>(0,0),
978                         core::dimension2di(logotexture->getSize())),
979                         NULL, NULL, true);
980         }
981 }
982
983 #endif
984
985 // These are defined global so that they're not optimized too much.
986 // Can't change them to volatile.
987 s16 temp16;
988 f32 tempf;
989 v3f tempv3f1;
990 v3f tempv3f2;
991 std::string tempstring;
992 std::string tempstring2;
993
994 void SpeedTests()
995 {
996         {
997                 infostream<<"The following test should take around 20ms."<<std::endl;
998                 TimeTaker timer("Testing std::string speed");
999                 const u32 jj = 10000;
1000                 for(u32 j=0; j<jj; j++)
1001                 {
1002                         tempstring = "";
1003                         tempstring2 = "";
1004                         const u32 ii = 10;
1005                         for(u32 i=0; i<ii; i++){
1006                                 tempstring2 += "asd";
1007                         }
1008                         for(u32 i=0; i<ii+1; i++){
1009                                 tempstring += "asd";
1010                                 if(tempstring == tempstring2)
1011                                         break;
1012                         }
1013                 }
1014         }
1015         
1016         infostream<<"All of the following tests should take around 100ms each."
1017                         <<std::endl;
1018
1019         {
1020                 TimeTaker timer("Testing floating-point conversion speed");
1021                 tempf = 0.001;
1022                 for(u32 i=0; i<4000000; i++){
1023                         temp16 += tempf;
1024                         tempf += 0.001;
1025                 }
1026         }
1027         
1028         {
1029                 TimeTaker timer("Testing floating-point vector speed");
1030
1031                 tempv3f1 = v3f(1,2,3);
1032                 tempv3f2 = v3f(4,5,6);
1033                 for(u32 i=0; i<10000000; i++){
1034                         tempf += tempv3f1.dotProduct(tempv3f2);
1035                         tempv3f2 += v3f(7,8,9);
1036                 }
1037         }
1038
1039         {
1040                 TimeTaker timer("Testing core::map speed");
1041                 
1042                 core::map<v2s16, f32> map1;
1043                 tempf = -324;
1044                 const s16 ii=300;
1045                 for(s16 y=0; y<ii; y++){
1046                         for(s16 x=0; x<ii; x++){
1047                                 map1.insert(v2s16(x,y), tempf);
1048                                 tempf += 1;
1049                         }
1050                 }
1051                 for(s16 y=ii-1; y>=0; y--){
1052                         for(s16 x=0; x<ii; x++){
1053                                 tempf = map1[v2s16(x,y)];
1054                         }
1055                 }
1056         }
1057
1058         {
1059                 infostream<<"Around 5000/ms should do well here."<<std::endl;
1060                 TimeTaker timer("Testing mutex speed");
1061                 
1062                 JMutex m;
1063                 m.Init();
1064                 u32 n = 0;
1065                 u32 i = 0;
1066                 do{
1067                         n += 10000;
1068                         for(; i<n; i++){
1069                                 m.Lock();
1070                                 m.Unlock();
1071                         }
1072                 }
1073                 // Do at least 10ms
1074                 while(timer.getTime() < 10);
1075
1076                 u32 dtime = timer.stop();
1077                 u32 per_ms = n / dtime;
1078                 infostream<<"Done. "<<dtime<<"ms, "
1079                                 <<per_ms<<"/ms"<<std::endl;
1080         }
1081 }
1082
1083 int main(int argc, char *argv[])
1084 {
1085         /*
1086                 Initialization
1087         */
1088
1089         log_add_output_maxlev(&main_stderr_log_out, LMT_ACTION);
1090         log_add_output_all_levs(&main_dstream_no_stderr_log_out);
1091
1092         log_register_thread("main");
1093
1094         // Set locale. This is for forcing '.' as the decimal point.
1095         std::locale::global(std::locale("C"));
1096         // This enables printing all characters in bitmap font
1097         setlocale(LC_CTYPE, "en_US");
1098
1099         /*
1100                 Parse command line
1101         */
1102         
1103         // List all allowed options
1104         core::map<std::string, ValueSpec> allowed_options;
1105         allowed_options.insert("help", ValueSpec(VALUETYPE_FLAG,
1106                         "Show allowed options"));
1107         allowed_options.insert("config", ValueSpec(VALUETYPE_STRING,
1108                         "Load configuration from specified file"));
1109         allowed_options.insert("port", ValueSpec(VALUETYPE_STRING,
1110                         "Set network port (UDP) to use"));
1111         allowed_options.insert("disable-unittests", ValueSpec(VALUETYPE_FLAG,
1112                         "Disable unit tests"));
1113         allowed_options.insert("enable-unittests", ValueSpec(VALUETYPE_FLAG,
1114                         "Enable unit tests"));
1115         allowed_options.insert("map-dir", ValueSpec(VALUETYPE_STRING,
1116                         "Map directory (where everything in the world is stored)"));
1117         allowed_options.insert("info-on-stderr", ValueSpec(VALUETYPE_FLAG,
1118                         "Print debug information to console"));
1119 #ifndef SERVER
1120         allowed_options.insert("speedtests", ValueSpec(VALUETYPE_FLAG,
1121                         "Run speed tests"));
1122         allowed_options.insert("address", ValueSpec(VALUETYPE_STRING,
1123                         "Address to connect to"));
1124         allowed_options.insert("random-input", ValueSpec(VALUETYPE_FLAG,
1125                         "Enable random user input, for testing"));
1126         allowed_options.insert("server", ValueSpec(VALUETYPE_FLAG,
1127                         "Run server directly"));
1128 #endif
1129
1130         Settings cmd_args;
1131         
1132         bool ret = cmd_args.parseCommandLine(argc, argv, allowed_options);
1133
1134         if(ret == false || cmd_args.getFlag("help"))
1135         {
1136                 dstream<<"Allowed options:"<<std::endl;
1137                 for(core::map<std::string, ValueSpec>::Iterator
1138                                 i = allowed_options.getIterator();
1139                                 i.atEnd() == false; i++)
1140                 {
1141                         dstream<<"  --"<<i.getNode()->getKey();
1142                         if(i.getNode()->getValue().type == VALUETYPE_FLAG)
1143                         {
1144                         }
1145                         else
1146                         {
1147                                 dstream<<" <value>";
1148                         }
1149                         dstream<<std::endl;
1150
1151                         if(i.getNode()->getValue().help != NULL)
1152                         {
1153                                 dstream<<"      "<<i.getNode()->getValue().help
1154                                                 <<std::endl;
1155                         }
1156                 }
1157
1158                 return cmd_args.getFlag("help") ? 0 : 1;
1159         }
1160         
1161         /*
1162                 Low-level initialization
1163         */
1164
1165         if(cmd_args.getFlag("info-on-stderr") || cmd_args.getFlag("speedtests"))
1166                 log_add_output(&main_stderr_log_out, LMT_INFO);
1167
1168         porting::signal_handler_init();
1169         bool &kill = *porting::signal_handler_killstatus();
1170         
1171         porting::initializePaths();
1172
1173         // Create user data directory
1174         fs::CreateDir(porting::path_user);
1175
1176         init_gettext((porting::path_share+DIR_DELIM+".."+DIR_DELIM+"locale").c_str());
1177         
1178         // Initialize debug streams
1179 #ifdef RUN_IN_PLACE
1180         std::string debugfile = DEBUGFILE;
1181 #else
1182         std::string debugfile = porting::path_user+DIR_DELIM+DEBUGFILE;
1183 #endif
1184         bool disable_stderr = false;
1185         debugstreams_init(disable_stderr, debugfile.c_str());
1186         // Initialize debug stacks
1187         debug_stacks_init();
1188
1189         DSTACK(__FUNCTION_NAME);
1190
1191         // Init material properties table
1192         //initializeMaterialProperties();
1193
1194         // Debug handler
1195         BEGIN_DEBUG_EXCEPTION_HANDLER
1196
1197         // Print startup message
1198         actionstream<<PROJECT_NAME<<
1199                         " with SER_FMT_VER_HIGHEST="<<(int)SER_FMT_VER_HIGHEST
1200                         <<", "<<BUILD_INFO
1201                         <<std::endl;
1202         
1203         /*
1204                 Basic initialization
1205         */
1206
1207         // Initialize default settings
1208         set_default_settings(g_settings);
1209         
1210         // Initialize sockets
1211         sockets_init();
1212         atexit(sockets_cleanup);
1213         
1214         /*
1215                 Read config file
1216         */
1217         
1218         // Path of configuration file in use
1219         std::string configpath = "";
1220         
1221         if(cmd_args.exists("config"))
1222         {
1223                 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
1224                 if(r == false)
1225                 {
1226                         errorstream<<"Could not read configuration from \""
1227                                         <<cmd_args.get("config")<<"\""<<std::endl;
1228                         return 1;
1229                 }
1230                 configpath = cmd_args.get("config");
1231         }
1232         else
1233         {
1234                 core::array<std::string> filenames;
1235                 filenames.push_back(porting::path_user +
1236                                 DIR_DELIM + "minetest.conf");
1237                 // Legacy configuration file location
1238                 filenames.push_back(porting::path_user +
1239                                 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
1240 #ifdef RUN_IN_PLACE
1241                 // Try also from a lower level (to aid having the same configuration
1242                 // for many RUN_IN_PLACE installs)
1243                 filenames.push_back(porting::path_user +
1244                                 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
1245 #endif
1246
1247                 for(u32 i=0; i<filenames.size(); i++)
1248                 {
1249                         bool r = g_settings->readConfigFile(filenames[i].c_str());
1250                         if(r)
1251                         {
1252                                 configpath = filenames[i];
1253                                 break;
1254                         }
1255                 }
1256                 
1257                 // If no path found, use the first one (menu creates the file)
1258                 if(configpath == "")
1259                         configpath = filenames[0];
1260         }
1261
1262         // Initialize random seed
1263         srand(time(0));
1264         mysrand(time(0));
1265
1266         /*
1267                 Run unit tests
1268         */
1269
1270         if((ENABLE_TESTS && cmd_args.getFlag("disable-unittests") == false)
1271                         || cmd_args.getFlag("enable-unittests") == true)
1272         {
1273                 run_tests();
1274         }
1275         
1276         /*
1277                 Game parameters
1278         */
1279
1280         // Port
1281         u16 port = 30000;
1282         if(cmd_args.exists("port"))
1283                 port = cmd_args.getU16("port");
1284         else if(g_settings->exists("port"))
1285                 port = g_settings->getU16("port");
1286         if(port == 0)
1287                 port = 30000;
1288         
1289         // Map directory
1290         std::string map_dir = porting::path_user + DIR_DELIM + "server" + DIR_DELIM + "worlds" + DIR_DELIM + "world";
1291         if(cmd_args.exists("map-dir"))
1292                 map_dir = cmd_args.get("map-dir");
1293         else if(g_settings->exists("map-dir"))
1294                 map_dir = g_settings->get("map-dir");
1295         else{
1296                 // No map-dir option was specified.
1297                 // Check if the world is found from the default directory, and if
1298                 // not, see if the legacy world directory exists.
1299                 std::string legacy_map_dir = porting::path_user+DIR_DELIM+".."+DIR_DELIM+"world";
1300                 if(!fs::PathExists(map_dir) && fs::PathExists(legacy_map_dir)){
1301                         errorstream<<"Warning: Using legacy world directory \""
1302                                         <<legacy_map_dir<<"\""<<std::endl;
1303                         map_dir = legacy_map_dir;
1304                 }
1305         }
1306
1307         // Run dedicated server if asked to or no other option
1308 #ifdef SERVER
1309         bool run_dedicated_server = true;
1310 #else
1311         bool run_dedicated_server = cmd_args.getFlag("server");
1312 #endif
1313         if(run_dedicated_server)
1314         {
1315                 DSTACK("Dedicated server branch");
1316
1317                 // Create time getter if built with Irrlicht
1318 #ifndef SERVER
1319                 g_timegetter = new SimpleTimeGetter();
1320 #endif
1321                 
1322                 // Create server
1323                 Server server(map_dir, configpath, "mesetint");
1324                 server.start(port);
1325                 
1326                 // ASCII art for the win!
1327                 actionstream
1328                 <<"        .__               __                   __   "<<std::endl
1329                 <<"  _____ |__| ____   _____/  |_  ____   _______/  |_ "<<std::endl
1330                 <<" /     \\|  |/    \\_/ __ \\   __\\/ __ \\ /  ___/\\   __\\"<<std::endl
1331                 <<"|  Y Y  \\  |   |  \\  ___/|  | \\  ___/ \\___ \\  |  |  "<<std::endl
1332                 <<"|__|_|  /__|___|  /\\___  >__|  \\___  >____  > |__|  "<<std::endl
1333                 <<"      \\/        \\/     \\/          \\/     \\/        "<<std::endl;
1334                 actionstream<<"Listening at port "<<port<<"."<<std::endl;
1335         
1336                 // Run server
1337                 dedicated_server_loop(server, kill);
1338
1339                 return 0;
1340         }
1341
1342 #ifndef SERVER // Exclude from dedicated server build
1343
1344         /*
1345                 More parameters
1346         */
1347         
1348         // Address to connect to
1349         std::string address = "";
1350         
1351         if(cmd_args.exists("address"))
1352         {
1353                 address = cmd_args.get("address");
1354         }
1355         else
1356         {
1357                 address = g_settings->get("address");
1358         }
1359         
1360         std::string playername = g_settings->get("name");
1361
1362         /*
1363                 Device initialization
1364         */
1365
1366         // Resolution selection
1367         
1368         bool fullscreen = false;
1369         u16 screenW = g_settings->getU16("screenW");
1370         u16 screenH = g_settings->getU16("screenH");
1371
1372         // Determine driver
1373
1374         video::E_DRIVER_TYPE driverType;
1375         
1376         std::string driverstring = g_settings->get("video_driver");
1377
1378         if(driverstring == "null")
1379                 driverType = video::EDT_NULL;
1380         else if(driverstring == "software")
1381                 driverType = video::EDT_SOFTWARE;
1382         else if(driverstring == "burningsvideo")
1383                 driverType = video::EDT_BURNINGSVIDEO;
1384         else if(driverstring == "direct3d8")
1385                 driverType = video::EDT_DIRECT3D8;
1386         else if(driverstring == "direct3d9")
1387                 driverType = video::EDT_DIRECT3D9;
1388         else if(driverstring == "opengl")
1389                 driverType = video::EDT_OPENGL;
1390         else
1391         {
1392                 errorstream<<"WARNING: Invalid video_driver specified; defaulting "
1393                                 "to opengl"<<std::endl;
1394                 driverType = video::EDT_OPENGL;
1395         }
1396
1397         /*
1398                 Create device and exit if creation failed
1399         */
1400
1401         MyEventReceiver receiver;
1402
1403         IrrlichtDevice *device;
1404         device = createDevice(driverType,
1405                         core::dimension2d<u32>(screenW, screenH),
1406                         16, fullscreen, false, false, &receiver);
1407
1408         if (device == 0)
1409                 return 1; // could not create selected driver.
1410         
1411         /*
1412                 Continue initialization
1413         */
1414
1415         video::IVideoDriver* driver = device->getVideoDriver();
1416
1417         // Disable mipmaps (because some of them look ugly)
1418         driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, false);
1419
1420         /*
1421                 This changes the minimum allowed number of vertices in a VBO.
1422                 Default is 500.
1423         */
1424         //driver->setMinHardwareBufferVertexCount(50);
1425
1426         // Set the window caption
1427         device->setWindowCaption(L"Minetest [Main Menu]");
1428         
1429         // Create time getter
1430         g_timegetter = new IrrlichtTimeGetter(device);
1431         
1432         // Create game callback for menus
1433         g_gamecallback = new MainGameCallback(device);
1434         
1435         /*
1436                 Speed tests (done after irrlicht is loaded to get timer)
1437         */
1438         if(cmd_args.getFlag("speedtests"))
1439         {
1440                 dstream<<"Running speed tests"<<std::endl;
1441                 SpeedTests();
1442                 return 0;
1443         }
1444         
1445         device->setResizable(true);
1446
1447         bool random_input = g_settings->getBool("random_input")
1448                         || cmd_args.getFlag("random-input");
1449         InputHandler *input = NULL;
1450         if(random_input)
1451                 input = new RandomInputHandler();
1452         else
1453                 input = new RealInputHandler(device, &receiver);
1454         
1455         scene::ISceneManager* smgr = device->getSceneManager();
1456
1457         guienv = device->getGUIEnvironment();
1458         gui::IGUISkin* skin = guienv->getSkin();
1459         gui::IGUIFont* font = guienv->getFont(getTexturePath("fontlucida.png").c_str());
1460         if(font)
1461                 skin->setFont(font);
1462         else
1463                 errorstream<<"WARNING: Font file was not found."
1464                                 " Using default font."<<std::endl;
1465         // If font was not found, this will get us one
1466         font = skin->getFont();
1467         assert(font);
1468         
1469         u32 text_height = font->getDimension(L"Hello, world!").Height;
1470         infostream<<"text_height="<<text_height<<std::endl;
1471
1472         //skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,0,0,0));
1473         skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,255,255,255));
1474         //skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(0,0,0,0));
1475         //skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(0,0,0,0));
1476         skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255,0,0,0));
1477         skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255,0,0,0));
1478         
1479         /*
1480                 GUI stuff
1481         */
1482
1483         ChatBackend chat_backend;
1484
1485         /*
1486                 If an error occurs, this is set to something and the
1487                 menu-game loop is restarted. It is then displayed before
1488                 the menu.
1489         */
1490         std::wstring error_message = L"";
1491
1492         // The password entered during the menu screen,
1493         std::string password;
1494
1495         /*
1496                 Menu-game loop
1497         */
1498         while(device->run() && kill == false)
1499         {
1500
1501                 // This is used for catching disconnects
1502                 try
1503                 {
1504
1505                         /*
1506                                 Clear everything from the GUIEnvironment
1507                         */
1508                         guienv->clear();
1509                         
1510                         /*
1511                                 We need some kind of a root node to be able to add
1512                                 custom gui elements directly on the screen.
1513                                 Otherwise they won't be automatically drawn.
1514                         */
1515                         guiroot = guienv->addStaticText(L"",
1516                                         core::rect<s32>(0, 0, 10000, 10000));
1517                         
1518                         /*
1519                                 Out-of-game menu loop.
1520
1521                                 Loop quits when menu returns proper parameters.
1522                         */
1523                         while(kill == false)
1524                         {
1525                                 // Cursor can be non-visible when coming from the game
1526                                 device->getCursorControl()->setVisible(true);
1527                                 // Some stuff are left to scene manager when coming from the game
1528                                 // (map at least?)
1529                                 smgr->clear();
1530                                 // Reset or hide the debug gui texts
1531                                 /*guitext->setText(L"Minetest-c55");
1532                                 guitext2->setVisible(false);
1533                                 guitext_info->setVisible(false);
1534                                 guitext_chat->setVisible(false);*/
1535                                 
1536                                 // Initialize menu data
1537                                 MainMenuData menudata;
1538                                 menudata.address = narrow_to_wide(address);
1539                                 menudata.name = narrow_to_wide(playername);
1540                                 menudata.port = narrow_to_wide(itos(port));
1541                                 menudata.fancy_trees = g_settings->getBool("new_style_leaves");
1542                                 menudata.smooth_lighting = g_settings->getBool("smooth_lighting");
1543                                 menudata.clouds_3d = g_settings->getBool("enable_3d_clouds");
1544                                 menudata.opaque_water = g_settings->getBool("opaque_water");
1545                                 menudata.creative_mode = g_settings->getBool("creative_mode");
1546                                 menudata.enable_damage = g_settings->getBool("enable_damage");
1547
1548                                 GUIMainMenu *menu =
1549                                                 new GUIMainMenu(guienv, guiroot, -1, 
1550                                                         &g_menumgr, &menudata, g_gamecallback);
1551                                 menu->allowFocusRemoval(true);
1552
1553                                 if(error_message != L"")
1554                                 {
1555                                         errorstream<<"error_message = "
1556                                                         <<wide_to_narrow(error_message)<<std::endl;
1557
1558                                         GUIMessageMenu *menu2 =
1559                                                         new GUIMessageMenu(guienv, guiroot, -1, 
1560                                                                 &g_menumgr, error_message.c_str());
1561                                         menu2->drop();
1562                                         error_message = L"";
1563                                 }
1564
1565                                 video::IVideoDriver* driver = device->getVideoDriver();
1566                                 
1567                                 infostream<<"Created main menu"<<std::endl;
1568
1569                                 while(device->run() && kill == false)
1570                                 {
1571                                         if(menu->getStatus() == true)
1572                                                 break;
1573
1574                                         //driver->beginScene(true, true, video::SColor(255,0,0,0));
1575                                         driver->beginScene(true, true, video::SColor(255,128,128,128));
1576
1577                                         drawMenuBackground(driver);
1578
1579                                         guienv->drawAll();
1580                                         
1581                                         driver->endScene();
1582                                         
1583                                         // On some computers framerate doesn't seem to be
1584                                         // automatically limited
1585                                         sleep_ms(25);
1586                                 }
1587                                 
1588                                 // Break out of menu-game loop to shut down cleanly
1589                                 if(device->run() == false || kill == true)
1590                                         break;
1591                                 
1592                                 infostream<<"Dropping main menu"<<std::endl;
1593
1594                                 menu->drop();
1595                                 
1596                                 // Delete map if requested
1597                                 if(menudata.delete_map)
1598                                 {
1599                                         bool r = fs::RecursiveDeleteContent(map_dir);
1600                                         if(r == false)
1601                                                 error_message = L"Delete failed";
1602                                         continue;
1603                                 }
1604
1605                                 playername = wide_to_narrow(menudata.name);
1606
1607                                 password = translatePassword(playername, menudata.password);
1608
1609                                 //infostream<<"Main: password hash: '"<<password<<"'"<<std::endl;
1610
1611                                 address = wide_to_narrow(menudata.address);
1612                                 int newport = stoi(wide_to_narrow(menudata.port));
1613                                 if(newport != 0)
1614                                         port = newport;
1615                                 g_settings->set("new_style_leaves", itos(menudata.fancy_trees));
1616                                 g_settings->set("smooth_lighting", itos(menudata.smooth_lighting));
1617                                 g_settings->set("enable_3d_clouds", itos(menudata.clouds_3d));
1618                                 g_settings->set("opaque_water", itos(menudata.opaque_water));
1619                                 g_settings->set("creative_mode", itos(menudata.creative_mode));
1620                                 g_settings->set("enable_damage", itos(menudata.enable_damage));
1621                                 
1622                                 // NOTE: These are now checked server side; no need to do it
1623                                 //       here, so let's not do it here.
1624                                 /*// Check for valid parameters, restart menu if invalid.
1625                                 if(playername == "")
1626                                 {
1627                                         error_message = L"Name required.";
1628                                         continue;
1629                                 }
1630                                 // Check that name has only valid chars
1631                                 if(string_allowed(playername, PLAYERNAME_ALLOWED_CHARS)==false)
1632                                 {
1633                                         error_message = L"Characters allowed: "
1634                                                         +narrow_to_wide(PLAYERNAME_ALLOWED_CHARS);
1635                                         continue;
1636                                 }*/
1637
1638                                 // Save settings
1639                                 g_settings->set("name", playername);
1640                                 g_settings->set("address", address);
1641                                 g_settings->set("port", itos(port));
1642                                 // Update configuration file
1643                                 if(configpath != "")
1644                                         g_settings->updateConfigFile(configpath.c_str());
1645                         
1646                                 // Continue to game
1647                                 break;
1648                         }
1649                         
1650                         // Break out of menu-game loop to shut down cleanly
1651                         if(device->run() == false || kill == true)
1652                                 break;
1653                         
1654                         /*
1655                                 Run game
1656                         */
1657                         the_game(
1658                                 kill,
1659                                 random_input,
1660                                 input,
1661                                 device,
1662                                 font,
1663                                 map_dir,
1664                                 playername,
1665                                 password,
1666                                 address,
1667                                 port,
1668                                 error_message,
1669                                 configpath,
1670                                 chat_backend
1671                         );
1672
1673                 } //try
1674                 catch(con::PeerNotFoundException &e)
1675                 {
1676                         errorstream<<"Connection error (timed out?)"<<std::endl;
1677                         error_message = L"Connection error (timed out?)";
1678                 }
1679                 catch(SocketException &e)
1680                 {
1681                         errorstream<<"Socket error (port already in use?)"<<std::endl;
1682                         error_message = L"Socket error (port already in use?)";
1683                 }
1684                 catch(ModError &e)
1685                 {
1686                         errorstream<<e.what()<<std::endl;
1687                         error_message = narrow_to_wide(e.what()) + L"\nCheck debug.txt for details.";
1688                 }
1689 #ifdef NDEBUG
1690                 catch(std::exception &e)
1691                 {
1692                         std::string narrow_message = "Some exception, what()=\"";
1693                         narrow_message += e.what();
1694                         narrow_message += "\"";
1695                         errorstream<<narrow_message<<std::endl;
1696                         error_message = narrow_to_wide(narrow_message);
1697                 }
1698 #endif
1699
1700         } // Menu-game loop
1701         
1702         delete input;
1703
1704         /*
1705                 In the end, delete the Irrlicht device.
1706         */
1707         device->drop();
1708
1709 #endif // !SERVER
1710         
1711         END_DEBUG_EXCEPTION_HANDLER(errorstream)
1712         
1713         debugstreams_deinit();
1714         
1715         return 0;
1716 }
1717
1718 //END
1719