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