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