Initial directory structure rework
[oweals/minetest.git] / src / servermain.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 2010 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
23
24 */
25
26 #ifndef SERVER
27         #ifdef _WIN32
28                 #pragma error ("For a server build, SERVER must be defined globally")
29         #else
30                 #error "For a server build, SERVER must be defined globally"
31         #endif
32 #endif
33
34 #ifdef NDEBUG
35         #ifdef _WIN32
36                 #pragma message ("Disabling unit tests")
37         #else
38                 #warning "Disabling unit tests"
39         #endif
40         // Disable unit tests
41         #define ENABLE_TESTS 0
42 #else
43         // Enable unit tests
44         #define ENABLE_TESTS 1
45 #endif
46
47 #ifdef _MSC_VER
48 #pragma comment(lib, "jthread.lib")
49 #pragma comment(lib, "zlibwapi.lib")
50 #endif
51
52 #include <iostream>
53 #include <fstream>
54 #include <time.h>
55 #include <jmutexautolock.h>
56 #include <locale.h>
57 #include "common_irrlicht.h"
58 #include "debug.h"
59 #include "map.h"
60 #include "player.h"
61 #include "main.h"
62 #include "test.h"
63 #include "environment.h"
64 #include "server.h"
65 #include "serialization.h"
66 #include "constants.h"
67 #include "strfnd.h"
68 #include "porting.h"
69 #include "config.h"
70 #include "filesys.h"
71 #include "defaultsettings.h"
72 #include "settings.h"
73 #include "profiler.h"
74 #include "log.h"
75 #include "nodedef.h" // For init_contentfeatures
76 #include "content_mapnode.h" // For content_mapnode_init
77 #include "mods.h"
78
79 /*
80         Settings.
81         These are loaded from the config file.
82 */
83 Settings main_settings;
84 Settings *g_settings = &main_settings;
85
86 // Global profiler
87 Profiler main_profiler;
88 Profiler *g_profiler = &main_profiler;
89
90 /*
91         Debug streams
92 */
93
94 // Connection
95 std::ostream *dout_con_ptr = &dummyout;
96 std::ostream *derr_con_ptr = &verbosestream;
97
98 // Server
99 std::ostream *dout_server_ptr = &infostream;
100 std::ostream *derr_server_ptr = &errorstream;
101
102 // Client
103 std::ostream *dout_client_ptr = &infostream;
104 std::ostream *derr_client_ptr = &errorstream;
105
106 /*
107         gettime.h implementation
108 */
109
110 u32 getTimeMs()
111 {
112         /*
113                 Use imprecise system calls directly (from porting.h)
114         */
115         return porting::getTimeMs();
116 }
117
118 class StderrLogOutput: public ILogOutput
119 {
120 public:
121         /* line: Full line with timestamp, level and thread */
122         void printLog(const std::string &line)
123         {
124                 std::cerr<<line<<std::endl;
125         }
126 } main_stderr_log_out;
127
128 class DstreamNoStderrLogOutput: public ILogOutput
129 {
130 public:
131         /* line: Full line with timestamp, level and thread */
132         void printLog(const std::string &line)
133         {
134                 dstream_no_stderr<<line<<std::endl;
135         }
136 } main_dstream_no_stderr_log_out;
137
138 int main(int argc, char *argv[])
139 {
140         /*
141                 Initialization
142         */
143
144         log_add_output_maxlev(&main_stderr_log_out, LMT_ACTION);
145         log_add_output_all_levs(&main_dstream_no_stderr_log_out);
146
147         log_register_thread("main");
148
149         // Set locale. This is for forcing '.' as the decimal point.
150         std::locale::global(std::locale("C"));
151         // This enables printing all characters in bitmap font
152         setlocale(LC_CTYPE, "en_US");
153
154         /*
155                 Low-level initialization
156         */
157
158         bool disable_stderr = false;
159 #ifdef _WIN32
160         disable_stderr = true;
161 #endif
162
163         porting::signal_handler_init();
164         bool &kill = *porting::signal_handler_killstatus();
165         
166         porting::initializePaths();
167
168         // Create user data directory
169         fs::CreateDir(porting::path_user);
170         
171         // Initialize debug streams
172 #ifdef RUN_IN_PLACE
173         std::string debugfile = DEBUGFILE;
174 #else
175         std::string debugfile = porting::path_user+DIR_DELIM+DEBUGFILE;
176 #endif
177         debugstreams_init(disable_stderr, debugfile.c_str());
178         // Initialize debug stacks
179         debug_stacks_init();
180
181         DSTACK(__FUNCTION_NAME);
182
183         // Init material properties table
184         //initializeMaterialProperties();
185
186         // Debug handler
187         BEGIN_DEBUG_EXCEPTION_HANDLER
188
189         // Print startup message
190         actionstream<<PROJECT_NAME<<
191                         " with SER_FMT_VER_HIGHEST="<<(int)SER_FMT_VER_HIGHEST
192                         <<", "<<BUILD_INFO
193                         <<std::endl;
194         
195         try
196         {
197         
198         /*
199                 Parse command line
200         */
201         
202         // List all allowed options
203         core::map<std::string, ValueSpec> allowed_options;
204         allowed_options.insert("help", ValueSpec(VALUETYPE_FLAG,
205                         "Show allowed options"));
206         allowed_options.insert("config", ValueSpec(VALUETYPE_STRING,
207                         "Load configuration from specified file"));
208         allowed_options.insert("port", ValueSpec(VALUETYPE_STRING,
209                         "Set network port (UDP) to use"));
210         allowed_options.insert("disable-unittests", ValueSpec(VALUETYPE_FLAG,
211                         "Disable unit tests"));
212         allowed_options.insert("enable-unittests", ValueSpec(VALUETYPE_FLAG,
213                         "Enable unit tests"));
214         allowed_options.insert("map-dir", ValueSpec(VALUETYPE_STRING,
215                         "Map directory (where everything in the world is stored)"));
216         allowed_options.insert("info-on-stderr", ValueSpec(VALUETYPE_FLAG,
217                         "Print debug information to console"));
218
219         Settings cmd_args;
220         
221         bool ret = cmd_args.parseCommandLine(argc, argv, allowed_options);
222
223         if(ret == false || cmd_args.getFlag("help"))
224         {
225                 dstream<<"Allowed options:"<<std::endl;
226                 for(core::map<std::string, ValueSpec>::Iterator
227                                 i = allowed_options.getIterator();
228                                 i.atEnd() == false; i++)
229                 {
230                         dstream<<"  --"<<i.getNode()->getKey();
231                         if(i.getNode()->getValue().type == VALUETYPE_FLAG)
232                         {
233                         }
234                         else
235                         {
236                                 dstream<<" <value>";
237                         }
238                         dstream<<std::endl;
239
240                         if(i.getNode()->getValue().help != NULL)
241                         {
242                                 dstream<<"      "<<i.getNode()->getValue().help
243                                                 <<std::endl;
244                         }
245                 }
246
247                 return cmd_args.getFlag("help") ? 0 : 1;
248         }
249
250         if(cmd_args.getFlag("info-on-stderr"))
251                 log_add_output(&main_stderr_log_out, LMT_INFO);
252
253         /*
254                 Basic initialization
255         */
256
257         // Initialize default settings
258         set_default_settings(g_settings);
259         
260         // Initialize sockets
261         sockets_init();
262         atexit(sockets_cleanup);
263         
264         /*
265                 Read config file
266         */
267         
268         // Path of configuration file in use
269         std::string configpath = "";
270         
271         if(cmd_args.exists("config"))
272         {
273                 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
274                 if(r == false)
275                 {
276                         errorstream<<"Could not read configuration from \""
277                                         <<cmd_args.get("config")<<"\""<<std::endl;
278                         return 1;
279                 }
280                 configpath = cmd_args.get("config");
281         }
282         else
283         {
284                 core::array<std::string> filenames;
285                 filenames.push_back(porting::path_user +
286                                 DIR_DELIM + "minetest.conf");
287 #ifdef RUN_IN_PLACE
288                 // Try also from a lower level (to aid having the same configuration
289                 // for many RUN_IN_PLACE installs)
290                 filenames.push_back(porting::path_user +
291                                 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
292 #endif
293
294                 for(u32 i=0; i<filenames.size(); i++)
295                 {
296                         bool r = g_settings->readConfigFile(filenames[i].c_str());
297                         if(r)
298                         {
299                                 configpath = filenames[i];
300                                 break;
301                         }
302                 }
303         }
304
305         // Initialize random seed
306         srand(time(0));
307         mysrand(time(0));
308
309         /*
310                 Run unit tests
311         */
312         if((ENABLE_TESTS && cmd_args.getFlag("disable-unittests") == false)
313                         || cmd_args.getFlag("enable-unittests") == true)
314         {
315                 run_tests();
316         }
317
318         /*
319                 Check parameters
320         */
321
322         std::cout<<std::endl<<std::endl;
323         
324         std::cout
325         <<"        .__               __                   __   "<<std::endl
326         <<"  _____ |__| ____   _____/  |_  ____   _______/  |_ "<<std::endl
327         <<" /     \\|  |/    \\_/ __ \\   __\\/ __ \\ /  ___/\\   __\\"<<std::endl
328         <<"|  Y Y  \\  |   |  \\  ___/|  | \\  ___/ \\___ \\  |  |  "<<std::endl
329         <<"|__|_|  /__|___|  /\\___  >__|  \\___  >____  > |__|  "<<std::endl
330         <<"      \\/        \\/     \\/          \\/     \\/        "<<std::endl
331         <<std::endl;
332
333         std::cout<<std::endl;
334         
335         // Port?
336         u16 port = 30000;
337         if(cmd_args.exists("port") && cmd_args.getU16("port") != 0)
338                 port = cmd_args.getU16("port");
339         else if(g_settings->exists("port") && g_settings->getU16("port") != 0)
340                 port = g_settings->getU16("port");
341         
342         // Map directory
343         std::string map_dir = porting::path_user + DIR_DELIM + "server" + DIR_DELIM + "worlds" + DIR_DELIM + "world";
344         if(cmd_args.exists("map-dir"))
345                 map_dir = cmd_args.get("map-dir");
346         else if(g_settings->exists("map-dir"))
347                 map_dir = g_settings->get("map-dir");
348         else{
349                 // No map-dir option was specified.
350                 // Check if the world is found from the default directory, and if
351                 // not, see if the legacy world directory exists.
352                 std::string legacy_map_dir = porting::path_user+DIR_DELIM+".."+DIR_DELIM+"world";
353                 if(!fs::PathExists(map_dir) && fs::PathExists(legacy_map_dir)){
354                         errorstream<<"Warning: Using legacy world directory \""
355                                         <<legacy_map_dir<<"\""<<std::endl;
356                         map_dir = legacy_map_dir;
357                 }
358         }
359         
360         
361         // Create server
362         Server server(map_dir, configpath, "mesetint");
363         server.start(port);
364
365         // Run server
366         dedicated_server_loop(server, kill);
367         
368         } //try
369         catch(con::PeerNotFoundException &e)
370         {
371                 errorstream<<"Connection timed out."<<std::endl;
372         }
373         catch(ModError &e)
374         {
375                 errorstream<<e.what()<<std::endl;
376         }
377
378         END_DEBUG_EXCEPTION_HANDLER(errorstream)
379
380         debugstreams_deinit();
381         
382         return 0;
383 }
384
385 //END