3 Copyright (C) 2010-2011 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 =============================== NOTES ==============================
22 NOTE: Things starting with TODO are sometimes only suggestions.
24 NOTE: iostream.imbue(std::locale("C")) is very slow
25 NOTE: Global locale is now set at initialization
27 NOTE: If VBO (EHM_STATIC) is used, remember to explicitly free the
28 hardware buffer (it is not freed automatically)
30 NOTE: A random to-do list saved here as documentation:
31 A list of "active blocks" in which stuff happens. (+=done)
32 + Add a never-resetted game timer to the server
33 + Add a timestamp value to blocks
34 + The simple rule: All blocks near some player are "active"
35 - Do stuff in real time in active blocks
37 - Grow grass, delete leaves without a tree
38 - Spawn some mobs based on some rules
39 - Transform cobble to mossy cobble near water
41 - ...And all kinds of other dynamic stuff
42 + Keep track of when a block becomes active and becomes inactive
43 + When a block goes inactive:
44 + Store objects statically to block
45 + Store timer value as the timestamp
46 + When a block goes active:
47 + Create active objects out of static objects
48 - Simulate the results of what would have happened if it would have
49 been active for all the time
50 - Grow a lot of grass and so on
51 + Initially it is fine to send information about every active object
52 to every player. Eventually it should be modified to only send info
53 about the nearest ones.
54 + This was left to be done by the old system and it sends only the
57 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
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)
75 NOTE: Seeds in 1260:6c77e7dbfd29:
77 Spawns you on a small sand island with a surface dungeon
79 Enormous jungle + a surface dungeon at ~(250,0,0)
81 Old, wild and random suggestions that probably won't be done:
82 -------------------------------------------------------------
84 SUGG: If player is on ground, mainly fetch ground-level blocks
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
92 SUGG: More fine-grained control of client's dumping of blocks from
94 - ...What does this mean in the first place?
96 SUGG: A map editing mode (similar to dedicated server mode)
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.
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
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
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.
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
127 SUGG: Background music based on cellular automata?
128 http://www.earslap.com/projectslab/otomata
130 SUGG: Simple light color information to air
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.
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
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
153 SUGG: For non-mapgen FarMesh: Add a per-sector database to store surface
154 stuff as simple flags/values
157 And at some point make the server send this data to the client too,
158 instead of referring to the noise functions
160 - Surface ground type
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?
173 - When furnace is destroyed, move items to player's inventory
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
185 - Cobble to get mossy if near water
186 - More slots in furnace source list, so that multiple ingredients
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
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
202 - A spread-items-on-map routine for the bomb, and for dying players
205 - Proper sword swing simulation
206 - Player should get damage from colliding to a wall at high speed
211 Build system / running:
212 -----------------------
214 Networking and serialization:
215 -----------------------------
217 SUGG: Fix address to be ipv6 compatible
225 SUGG: Combine MapBlock's face caches to so big pieces that VBO
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
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?
236 SUGG: Draw cubes in inventory directly with 3D drawing commands, so that
237 animating them is easier.
239 SUGG: Option for enabling proper alpha channel for textures
241 TODO: Flowing water animation
243 TODO: A setting for enabling bilinear filtering for textures
245 TODO: Better control of draw_control.wanted_max_blocks
247 TODO: Further investigate the use of GPU lighting in addition to the
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.
255 SUGG: Somehow make the night less colorful
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.
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
274 SUGG: Make morning and evening transition more smooth and maybe shorter
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.
283 - Tool/weapon visualization
285 FIXME: When disconnected to the menu, memory is not freed properly
287 TODO: Investigate how much the mesh generator thread gets used when
288 transferring map data
293 SUGG: Make an option to the server to disable building and digging near
294 the starting position
296 FIXME: Server sometimes goes into some infinite PeerNotFoundException loop
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.
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
312 TODO: Add proper hooks to when adding and removing active blocks
314 TODO: Finish the ActiveBlockModifier stuff and use it for something
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.
324 SUGG: MovingObject::move and Player::move are basically the same.
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)
331 TODO: Add a long step function to objects that is called with the time
332 difference when block activates
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
342 TODO: Flowing water to actually contain flow direction information
343 - There is a space for this - it just has to be implemented.
345 TODO: Consider smoothening cave floors after generating them
347 TODO: Fix make_tree, make_* to use seed-position-consistent pseudorandom
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
359 TODO: Move mineral to param2, increment map serialization version, add
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
366 TODO: Merge bahamada's audio stuff (clean patch available)
368 TODO: Move content_features to mapnode_content_features.{h,cpp} or so
370 TODO: Fix item use() stuff; dropping a stack of cooked rats and eating
371 it gives 3 hearts and consumes all the rats.
373 Making it more portable:
374 ------------------------
376 Stuff to do before release:
377 ---------------------------
379 Fixes to the current release:
380 -----------------------------
382 Stuff to do after release:
383 ---------------------------
388 ======================================================================
394 #pragma message ("Disabling unit tests")
396 #warning "Disabling unit tests"
398 // Disable unit tests
399 #define ENABLE_TESTS 0
402 #define ENABLE_TESTS 1
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")
414 #include "irrlicht.h" // createDevice
417 #include "mainmenumanager.h"
421 #include "common_irrlicht.h"
425 #include "constants.h"
428 #include "guiMessageMenu.h"
431 #include "guiMainMenu.h"
433 #include "materials.h"
437 #include "defaultsettings.h"
439 #include "settings.h"
440 #include "profiler.h"
443 // This makes textures
444 ITextureSource *g_texturesource = NULL;
448 These are loaded from the config file.
450 Settings main_settings;
451 Settings *g_settings = &main_settings;
454 Profiler main_profiler;
455 Profiler *g_profiler = &main_profiler;
465 gui::IGUIEnvironment* guienv = NULL;
466 gui::IGUIStaticText *guiroot = NULL;
467 MainMenuManager g_menumgr;
471 return (g_menumgr.menuCount() == 0);
474 // Passed to menus to allow disconnecting and exiting
475 MainGameCallback *g_gamecallback = NULL;
482 std::ostream *dout_con_ptr = &dummyout;
483 std::ostream *derr_con_ptr = &verbosestream;
484 //std::ostream *dout_con_ptr = &infostream;
485 //std::ostream *derr_con_ptr = &errorstream;
488 std::ostream *dout_server_ptr = &infostream;
489 std::ostream *derr_server_ptr = &errorstream;
492 std::ostream *dout_client_ptr = &infostream;
493 std::ostream *derr_client_ptr = &errorstream;
496 gettime.h implementation
499 // A small helper class
503 virtual u32 getTime() = 0;
506 // A precise irrlicht one
507 class IrrlichtTimeGetter: public TimeGetter
510 IrrlichtTimeGetter(IrrlichtDevice *device):
517 return m_device->getTimer()->getRealTime();
520 IrrlichtDevice *m_device;
522 // Not so precise one which works without irrlicht
523 class SimpleTimeGetter: public TimeGetter
528 return porting::getTimeMs();
532 // A pointer to a global instance of the time getter
534 TimeGetter *g_timegetter = NULL;
538 if(g_timegetter == NULL)
540 return g_timegetter->getTime();
544 Event handler for Irrlicht
546 NOTE: Everything possible should be moved out from here,
547 probably to InputHandler and the_game
550 class MyEventReceiver : public IEventReceiver
553 // This is the one method that we have to implement
554 virtual bool OnEvent(const SEvent& event)
557 React to nothing here if a menu is active
559 if(noMenuActive() == false)
564 // Remember whether each key is down or up
565 if(event.EventType == irr::EET_KEY_INPUT_EVENT)
567 if(event.KeyInput.PressedDown) {
568 keyIsDown.set(event.KeyInput);
569 keyWasDown.set(event.KeyInput);
571 keyIsDown.unset(event.KeyInput);
575 if(event.EventType == irr::EET_MOUSE_INPUT_EVENT)
577 if(noMenuActive() == false)
580 middle_active = false;
581 right_active = false;
585 left_active = event.MouseInput.isLeftPressed();
586 middle_active = event.MouseInput.isMiddlePressed();
587 right_active = event.MouseInput.isRightPressed();
589 if(event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)
593 if(event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN)
597 if(event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP)
601 if(event.MouseInput.Event == EMIE_RMOUSE_LEFT_UP)
603 rightreleased = true;
605 if(event.MouseInput.Event == EMIE_MOUSE_WHEEL)
607 mouse_wheel += event.MouseInput.Wheel;
615 bool IsKeyDown(const KeyPress &keyCode) const
617 return keyIsDown[keyCode];
620 // Checks whether a key was down and resets the state
621 bool WasKeyDown(const KeyPress &keyCode)
623 bool b = keyWasDown[keyCode];
625 keyWasDown.unset(keyCode);
642 rightclicked = false;
643 leftreleased = false;
644 rightreleased = false;
647 middle_active = false;
648 right_active = false;
670 IrrlichtDevice *m_device;
672 // The current state of keys
674 // Whether a key has been pressed or not
679 Separated input handler
682 class RealInputHandler : public InputHandler
685 RealInputHandler(IrrlichtDevice *device, MyEventReceiver *receiver):
690 virtual bool isKeyDown(const KeyPress &keyCode)
692 return m_receiver->IsKeyDown(keyCode);
694 virtual bool wasKeyDown(const KeyPress &keyCode)
696 return m_receiver->WasKeyDown(keyCode);
698 virtual v2s32 getMousePos()
700 return m_device->getCursorControl()->getPosition();
702 virtual void setMousePos(s32 x, s32 y)
704 m_device->getCursorControl()->setPosition(x, y);
707 virtual bool getLeftState()
709 return m_receiver->left_active;
711 virtual bool getRightState()
713 return m_receiver->right_active;
716 virtual bool getLeftClicked()
718 return m_receiver->leftclicked;
720 virtual bool getRightClicked()
722 return m_receiver->rightclicked;
724 virtual void resetLeftClicked()
726 m_receiver->leftclicked = false;
728 virtual void resetRightClicked()
730 m_receiver->rightclicked = false;
733 virtual bool getLeftReleased()
735 return m_receiver->leftreleased;
737 virtual bool getRightReleased()
739 return m_receiver->rightreleased;
741 virtual void resetLeftReleased()
743 m_receiver->leftreleased = false;
745 virtual void resetRightReleased()
747 m_receiver->rightreleased = false;
750 virtual s32 getMouseWheel()
752 return m_receiver->getMouseWheel();
757 m_receiver->clearInput();
760 IrrlichtDevice *m_device;
761 MyEventReceiver *m_receiver;
764 class RandomInputHandler : public InputHandler
772 rightclicked = false;
773 leftreleased = false;
774 rightreleased = false;
777 virtual bool isKeyDown(const KeyPress &keyCode)
779 return keydown[keyCode];
781 virtual bool wasKeyDown(const KeyPress &keyCode)
785 virtual v2s32 getMousePos()
789 virtual void setMousePos(s32 x, s32 y)
791 mousepos = v2s32(x,y);
794 virtual bool getLeftState()
798 virtual bool getRightState()
803 virtual bool getLeftClicked()
807 virtual bool getRightClicked()
811 virtual void resetLeftClicked()
815 virtual void resetRightClicked()
817 rightclicked = false;
820 virtual bool getLeftReleased()
824 virtual bool getRightReleased()
826 return rightreleased;
828 virtual void resetLeftReleased()
830 leftreleased = false;
832 virtual void resetRightReleased()
834 rightreleased = false;
837 virtual s32 getMouseWheel()
842 virtual void step(float dtime)
845 static float counter1 = 0;
849 counter1 = 0.1*Rand(1, 40);
850 keydown.toggle(getKeySetting("keymap_jump"));
854 static float counter1 = 0;
858 counter1 = 0.1*Rand(1, 40);
859 keydown.toggle(getKeySetting("keymap_special1"));
863 static float counter1 = 0;
867 counter1 = 0.1*Rand(1, 40);
868 keydown.toggle(getKeySetting("keymap_forward"));
872 static float counter1 = 0;
876 counter1 = 0.1*Rand(1, 40);
877 keydown.toggle(getKeySetting("keymap_left"));
881 static float counter1 = 0;
885 counter1 = 0.1*Rand(1, 20);
886 mousespeed = v2s32(Rand(-20,20), Rand(-15,20));
890 static float counter1 = 0;
894 counter1 = 0.1*Rand(1, 30);
895 leftdown = !leftdown;
903 static float counter1 = 0;
907 counter1 = 0.1*Rand(1, 15);
908 rightdown = !rightdown;
912 rightreleased = true;
915 mousepos += mousespeed;
918 s32 Rand(s32 min, s32 max)
920 return (myrand()%(max-min+1))+min;
934 // These are defined global so that they're not optimized too much.
935 // Can't change them to volatile.
940 std::string tempstring;
941 std::string tempstring2;
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++)
954 for(u32 i=0; i<ii; i++){
955 tempstring2 += "asd";
957 for(u32 i=0; i<ii+1; i++){
959 if(tempstring == tempstring2)
965 dstream<<"All of the following tests should take around 100ms each."
969 TimeTaker timer("Testing floating-point conversion speed");
971 for(u32 i=0; i<4000000; i++){
978 TimeTaker timer("Testing floating-point vector speed");
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);
989 TimeTaker timer("Testing core::map speed");
991 core::map<v2s16, f32> map1;
994 for(s16 y=0; y<ii; y++){
995 for(s16 x=0; x<ii; x++){
996 map1.insert(v2s16(x,y), tempf);
1000 for(s16 y=ii-1; y>=0; y--){
1001 for(s16 x=0; x<ii; x++){
1002 tempf = map1[v2s16(x,y)];
1008 dstream<<"Around 5000/ms should do well here."<<std::endl;
1009 TimeTaker timer("Testing mutex speed");
1023 while(timer.getTime() < 10);
1025 u32 dtime = timer.stop();
1026 u32 per_ms = n / dtime;
1027 dstream<<"Done. "<<dtime<<"ms, "
1028 <<per_ms<<"/ms"<<std::endl;
1032 void drawMenuBackground(video::IVideoDriver* driver)
1034 core::dimension2d<u32> screensize = driver->getScreenSize();
1036 video::ITexture *bgtexture =
1037 driver->getTexture(getTexturePath("mud.png").c_str());
1040 s32 texturesize = 128;
1041 s32 tiled_y = screensize.Height / texturesize + 1;
1042 s32 tiled_x = screensize.Width / texturesize + 1;
1044 for(s32 y=0; y<tiled_y; y++)
1045 for(s32 x=0; x<tiled_x; x++)
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())),
1056 video::ITexture *logotexture =
1057 driver->getTexture(getTexturePath("menulogo.png").c_str());
1060 v2s32 logosize(logotexture->getOriginalSize().Width,
1061 logotexture->getOriginalSize().Height);
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);
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())),
1079 class StderrLogOutput: public ILogOutput
1082 /* line: Full line with timestamp, level and thread */
1083 void printLog(const std::string &line)
1085 std::cerr<<line<<std::endl;
1087 } main_stderr_log_out;
1089 class DstreamNoStderrLogOutput: public ILogOutput
1092 /* line: Full line with timestamp, level and thread */
1093 void printLog(const std::string &line)
1095 dstream_no_stderr<<line<<std::endl;
1097 } main_dstream_no_stderr_log_out;
1099 int main(int argc, char *argv[])
1105 log_add_output_maxlev(&main_stderr_log_out, LMT_ACTION);
1106 log_add_output_all_levs(&main_dstream_no_stderr_log_out);
1108 log_register_thread("main");
1110 // Set locale. This is for forcing '.' as the decimal point.
1111 std::locale::global(std::locale("C"));
1112 // This enables printing all characters in bitmap font
1113 setlocale(LC_CTYPE, "en_US");
1119 // List all allowed options
1120 core::map<std::string, ValueSpec> allowed_options;
1121 allowed_options.insert("help", ValueSpec(VALUETYPE_FLAG));
1122 allowed_options.insert("server", ValueSpec(VALUETYPE_FLAG,
1123 "Run server directly"));
1124 allowed_options.insert("config", ValueSpec(VALUETYPE_STRING,
1125 "Load configuration from specified file"));
1126 allowed_options.insert("port", ValueSpec(VALUETYPE_STRING));
1127 allowed_options.insert("address", ValueSpec(VALUETYPE_STRING));
1128 allowed_options.insert("random-input", ValueSpec(VALUETYPE_FLAG));
1129 allowed_options.insert("disable-unittests", ValueSpec(VALUETYPE_FLAG));
1130 allowed_options.insert("enable-unittests", ValueSpec(VALUETYPE_FLAG));
1131 allowed_options.insert("map-dir", ValueSpec(VALUETYPE_STRING));
1133 allowed_options.insert("dstream-on-stderr", ValueSpec(VALUETYPE_FLAG));
1135 allowed_options.insert("speedtests", ValueSpec(VALUETYPE_FLAG));
1136 allowed_options.insert("info-on-stderr", ValueSpec(VALUETYPE_FLAG));
1140 bool ret = cmd_args.parseCommandLine(argc, argv, allowed_options);
1142 if(ret == false || cmd_args.getFlag("help"))
1144 dstream<<"Allowed options:"<<std::endl;
1145 for(core::map<std::string, ValueSpec>::Iterator
1146 i = allowed_options.getIterator();
1147 i.atEnd() == false; i++)
1149 dstream<<" --"<<i.getNode()->getKey();
1150 if(i.getNode()->getValue().type == VALUETYPE_FLAG)
1155 dstream<<" <value>";
1159 if(i.getNode()->getValue().help != NULL)
1161 dstream<<" "<<i.getNode()->getValue().help
1166 return cmd_args.getFlag("help") ? 0 : 1;
1170 Low-level initialization
1173 bool disable_stderr = false;
1175 if(cmd_args.getFlag("dstream-on-stderr") == false)
1176 disable_stderr = true;
1179 if(cmd_args.getFlag("info-on-stderr"))
1180 log_add_output(&main_stderr_log_out, LMT_INFO);
1182 porting::signal_handler_init();
1183 bool &kill = *porting::signal_handler_killstatus();
1185 // Initialize porting::path_data and porting::path_userdata
1186 porting::initializePaths();
1188 // Create user data directory
1189 fs::CreateDir(porting::path_userdata);
1191 init_gettext((porting::path_data+DIR_DELIM+".."+DIR_DELIM+"locale").c_str());
1193 // Initialize debug streams
1195 std::string debugfile = DEBUGFILE;
1197 std::string debugfile = porting::path_userdata+DIR_DELIM+DEBUGFILE;
1199 debugstreams_init(disable_stderr, debugfile.c_str());
1200 // Initialize debug stacks
1201 debug_stacks_init();
1203 DSTACK(__FUNCTION_NAME);
1205 // Init material properties table
1206 //initializeMaterialProperties();
1209 BEGIN_DEBUG_EXCEPTION_HANDLER
1211 // Print startup message
1212 actionstream<<PROJECT_NAME<<
1213 " with SER_FMT_VER_HIGHEST="<<(int)SER_FMT_VER_HIGHEST
1218 Basic initialization
1221 // Initialize default settings
1222 set_default_settings(g_settings);
1224 // Initialize sockets
1226 atexit(sockets_cleanup);
1232 // Path of configuration file in use
1233 std::string configpath = "";
1235 if(cmd_args.exists("config"))
1237 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
1240 errorstream<<"Could not read configuration from \""
1241 <<cmd_args.get("config")<<"\""<<std::endl;
1244 configpath = cmd_args.get("config");
1248 core::array<std::string> filenames;
1249 filenames.push_back(porting::path_userdata +
1250 DIR_DELIM + "minetest.conf");
1252 filenames.push_back(porting::path_userdata +
1253 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
1256 for(u32 i=0; i<filenames.size(); i++)
1258 bool r = g_settings->readConfigFile(filenames[i].c_str());
1261 configpath = filenames[i];
1266 // If no path found, use the first one (menu creates the file)
1267 if(configpath == "")
1268 configpath = filenames[0];
1271 // Initialize random seed
1276 Pre-initialize some stuff with a dummy irrlicht wrapper.
1278 These are needed for unit tests at least.
1281 // Initial call with g_texturesource not set.
1283 // Must be called before g_texturesource is created
1284 // (for texture atlas making)
1291 if((ENABLE_TESTS && cmd_args.getFlag("disable-unittests") == false)
1292 || cmd_args.getFlag("enable-unittests") == true)
1297 /*for(s16 y=-100; y<100; y++)
1298 for(s16 x=-100; x<100; x++)
1300 std::cout<<noise2d_gradient((double)x/10,(double)y/10, 32415)<<std::endl;
1310 if(cmd_args.exists("port"))
1311 port = cmd_args.getU16("port");
1312 else if(g_settings->exists("port"))
1313 port = g_settings->getU16("port");
1318 std::string map_dir = porting::path_userdata+DIR_DELIM+"world";
1319 if(cmd_args.exists("map-dir"))
1320 map_dir = cmd_args.get("map-dir");
1321 else if(g_settings->exists("map-dir"))
1322 map_dir = g_settings->get("map-dir");
1324 // Run dedicated server if asked to
1325 if(cmd_args.getFlag("server"))
1327 DSTACK("Dedicated server branch");
1329 // Create time getter
1330 g_timegetter = new SimpleTimeGetter();
1333 Server server(map_dir.c_str(), configpath);
1337 dedicated_server_loop(server, kill);
1347 // Address to connect to
1348 std::string address = "";
1350 if(cmd_args.exists("address"))
1352 address = cmd_args.get("address");
1356 address = g_settings->get("address");
1359 std::string playername = g_settings->get("name");
1362 Device initialization
1365 // Resolution selection
1367 bool fullscreen = false;
1368 u16 screenW = g_settings->getU16("screenW");
1369 u16 screenH = g_settings->getU16("screenH");
1373 video::E_DRIVER_TYPE driverType;
1375 std::string driverstring = g_settings->get("video_driver");
1377 if(driverstring == "null")
1378 driverType = video::EDT_NULL;
1379 else if(driverstring == "software")
1380 driverType = video::EDT_SOFTWARE;
1381 else if(driverstring == "burningsvideo")
1382 driverType = video::EDT_BURNINGSVIDEO;
1383 else if(driverstring == "direct3d8")
1384 driverType = video::EDT_DIRECT3D8;
1385 else if(driverstring == "direct3d9")
1386 driverType = video::EDT_DIRECT3D9;
1387 else if(driverstring == "opengl")
1388 driverType = video::EDT_OPENGL;
1391 errorstream<<"WARNING: Invalid video_driver specified; defaulting "
1392 "to opengl"<<std::endl;
1393 driverType = video::EDT_OPENGL;
1397 Create device and exit if creation failed
1400 MyEventReceiver receiver;
1402 IrrlichtDevice *device;
1403 device = createDevice(driverType,
1404 core::dimension2d<u32>(screenW, screenH),
1405 16, fullscreen, false, false, &receiver);
1408 return 1; // could not create selected driver.
1410 // Set the window caption
1411 device->setWindowCaption(L"Minetest [Main Menu]");
1413 // Create time getter
1414 g_timegetter = new IrrlichtTimeGetter(device);
1416 // Create game callback for menus
1417 g_gamecallback = new MainGameCallback(device);
1419 // Create texture source
1420 g_texturesource = new TextureSource(device);
1423 Speed tests (done after irrlicht is loaded to get timer)
1425 if(cmd_args.getFlag("speedtests"))
1427 dstream<<"Running speed tests"<<std::endl;
1432 device->setResizable(true);
1434 bool random_input = g_settings->getBool("random_input")
1435 || cmd_args.getFlag("random-input");
1436 InputHandler *input = NULL;
1438 input = new RandomInputHandler();
1440 input = new RealInputHandler(device, &receiver);
1443 Continue initialization
1446 //video::IVideoDriver* driver = device->getVideoDriver();
1449 This changes the minimum allowed number of vertices in a VBO.
1452 //driver->setMinHardwareBufferVertexCount(50);
1454 scene::ISceneManager* smgr = device->getSceneManager();
1456 guienv = device->getGUIEnvironment();
1457 gui::IGUISkin* skin = guienv->getSkin();
1458 gui::IGUIFont* font = guienv->getFont(getTexturePath("fontlucida.png").c_str());
1460 skin->setFont(font);
1462 errorstream<<"WARNING: Font file was not found."
1463 " Using default font."<<std::endl;
1464 // If font was not found, this will get us one
1465 font = skin->getFont();
1468 u32 text_height = font->getDimension(L"Hello, world!").Height;
1469 infostream<<"text_height="<<text_height<<std::endl;
1471 //skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,0,0,0));
1472 skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,255,255,255));
1473 //skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(0,0,0,0));
1474 //skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(0,0,0,0));
1475 skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255,0,0,0));
1476 skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255,0,0,0));
1479 Preload some textures and stuff
1482 init_mapnode(); // Second call with g_texturesource set
1489 If an error occurs, this is set to something and the
1490 menu-game loop is restarted. It is then displayed before
1493 std::wstring error_message = L"";
1495 // The password entered during the menu screen,
1496 std::string password;
1501 while(device->run() && kill == false)
1504 // This is used for catching disconnects
1509 Clear everything from the GUIEnvironment
1514 We need some kind of a root node to be able to add
1515 custom gui elements directly on the screen.
1516 Otherwise they won't be automatically drawn.
1518 guiroot = guienv->addStaticText(L"",
1519 core::rect<s32>(0, 0, 10000, 10000));
1522 Out-of-game menu loop.
1524 Loop quits when menu returns proper parameters.
1526 while(kill == false)
1528 // Cursor can be non-visible when coming from the game
1529 device->getCursorControl()->setVisible(true);
1530 // Some stuff are left to scene manager when coming from the game
1533 // Reset or hide the debug gui texts
1534 /*guitext->setText(L"Minetest-c55");
1535 guitext2->setVisible(false);
1536 guitext_info->setVisible(false);
1537 guitext_chat->setVisible(false);*/
1539 // Initialize menu data
1540 MainMenuData menudata;
1541 menudata.address = narrow_to_wide(address);
1542 menudata.name = narrow_to_wide(playername);
1543 menudata.port = narrow_to_wide(itos(port));
1544 menudata.fancy_trees = g_settings->getBool("new_style_leaves");
1545 menudata.smooth_lighting = g_settings->getBool("smooth_lighting");
1546 menudata.creative_mode = g_settings->getBool("creative_mode");
1547 menudata.enable_damage = g_settings->getBool("enable_damage");
1550 new GUIMainMenu(guienv, guiroot, -1,
1551 &g_menumgr, &menudata, g_gamecallback);
1552 menu->allowFocusRemoval(true);
1554 if(error_message != L"")
1556 errorstream<<"error_message = "
1557 <<wide_to_narrow(error_message)<<std::endl;
1559 GUIMessageMenu *menu2 =
1560 new GUIMessageMenu(guienv, guiroot, -1,
1561 &g_menumgr, error_message.c_str());
1563 error_message = L"";
1566 video::IVideoDriver* driver = device->getVideoDriver();
1568 infostream<<"Created main menu"<<std::endl;
1570 while(device->run() && kill == false)
1572 if(menu->getStatus() == true)
1575 //driver->beginScene(true, true, video::SColor(255,0,0,0));
1576 driver->beginScene(true, true, video::SColor(255,128,128,128));
1578 drawMenuBackground(driver);
1584 // On some computers framerate doesn't seem to be
1585 // automatically limited
1589 // Break out of menu-game loop to shut down cleanly
1590 if(device->run() == false || kill == true)
1593 infostream<<"Dropping main menu"<<std::endl;
1597 // Delete map if requested
1598 if(menudata.delete_map)
1600 bool r = fs::RecursiveDeleteContent(map_dir);
1602 error_message = L"Delete failed";
1606 playername = wide_to_narrow(menudata.name);
1608 password = translatePassword(playername, menudata.password);
1610 //infostream<<"Main: password hash: '"<<password<<"'"<<std::endl;
1612 address = wide_to_narrow(menudata.address);
1613 int newport = stoi(wide_to_narrow(menudata.port));
1616 g_settings->set("new_style_leaves", itos(menudata.fancy_trees));
1617 g_settings->set("smooth_lighting", itos(menudata.smooth_lighting));
1618 g_settings->set("creative_mode", itos(menudata.creative_mode));
1619 g_settings->set("enable_damage", itos(menudata.enable_damage));
1621 // NOTE: These are now checked server side; no need to do it
1622 // here, so let's not do it here.
1623 /*// Check for valid parameters, restart menu if invalid.
1624 if(playername == "")
1626 error_message = L"Name required.";
1629 // Check that name has only valid chars
1630 if(string_allowed(playername, PLAYERNAME_ALLOWED_CHARS)==false)
1632 error_message = L"Characters allowed: "
1633 +narrow_to_wide(PLAYERNAME_ALLOWED_CHARS);
1638 g_settings->set("name", playername);
1639 g_settings->set("address", address);
1640 g_settings->set("port", itos(port));
1641 // Update configuration file
1642 if(configpath != "")
1643 g_settings->updateConfigFile(configpath.c_str());
1649 // Break out of menu-game loop to shut down cleanly
1650 if(device->run() == false)
1653 // Initialize mapnode again to enable changed graphics settings
1675 catch(con::PeerNotFoundException &e)
1677 errorstream<<"Connection error (timed out?)"<<std::endl;
1678 error_message = L"Connection error (timed out?)";
1680 catch(SocketException &e)
1682 errorstream<<"Socket error (port already in use?)"<<std::endl;
1683 error_message = L"Socket error (port already in use?)";
1686 catch(std::exception &e)
1688 std::string narrow_message = "Some exception, what()=\"";
1689 narrow_message += e.what();
1690 narrow_message += "\"";
1691 errorstream<<narrow_message<<std::endl;
1692 error_message = narrow_to_wide(narrow_message);
1701 In the end, delete the Irrlicht device.
1705 END_DEBUG_EXCEPTION_HANDLER(errorstream)
1707 debugstreams_deinit();