]> git.lizzy.rs Git - dragonfireclient.git/blob - src/porting.cpp
42ee2ffe2994c0b04060cff7a41d54bfea5ef945
[dragonfireclient.git] / src / porting.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 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 Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser 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         Random portability stuff
22
23         See comments in porting.h
24 */
25
26 #include "porting.h"
27
28 #if defined(__FreeBSD__)
29         #include <sys/types.h>
30         #include <sys/sysctl.h>
31 #elif defined(_WIN32)
32         #include <algorithm>
33 #endif
34 #if !defined(_WIN32)
35         #include <unistd.h>
36         #include <sys/utsname.h>
37 #endif
38
39 #include "config.h"
40 #include "debug.h"
41 #include "filesys.h"
42 #include "log.h"
43 #include "util/string.h"
44 #include "main.h"
45 #include "settings.h"
46 #include <list>
47
48 namespace porting
49 {
50
51 /*
52         Signal handler (grabs Ctrl-C on POSIX systems)
53 */
54
55 bool g_killed = false;
56
57 bool * signal_handler_killstatus(void)
58 {
59         return &g_killed;
60 }
61
62 #if !defined(_WIN32) // POSIX
63         #include <signal.h>
64
65 void sigint_handler(int sig)
66 {
67         if(g_killed == false)
68         {
69                 dstream<<DTIME<<"INFO: sigint_handler(): "
70                                 <<"Ctrl-C pressed, shutting down."<<std::endl;
71
72                 // Comment out for less clutter when testing scripts
73                 /*dstream<<DTIME<<"INFO: sigint_handler(): "
74                                 <<"Printing debug stacks"<<std::endl;
75                 debug_stacks_print();*/
76
77                 g_killed = true;
78         }
79         else
80         {
81                 (void)signal(SIGINT, SIG_DFL);
82         }
83 }
84
85 void signal_handler_init(void)
86 {
87         (void)signal(SIGINT, sigint_handler);
88 }
89
90 #else // _WIN32
91         #include <signal.h>
92
93         BOOL WINAPI event_handler(DWORD sig)
94         {
95                 switch(sig)
96                 {
97                 case CTRL_C_EVENT:
98                 case CTRL_CLOSE_EVENT:
99                 case CTRL_LOGOFF_EVENT:
100                 case CTRL_SHUTDOWN_EVENT:
101
102                         if(g_killed == false)
103                         {
104                                 dstream<<DTIME<<"INFO: event_handler(): "
105                                                 <<"Ctrl+C, Close Event, Logoff Event or Shutdown Event, shutting down."<<std::endl;
106                                 // Comment out for less clutter when testing scripts
107                                 /*dstream<<DTIME<<"INFO: event_handler(): "
108                                                 <<"Printing debug stacks"<<std::endl;
109                                 debug_stacks_print();*/
110
111                                 g_killed = true;
112                         }
113                         else
114                         {
115                                 (void)signal(SIGINT, SIG_DFL);
116                         }
117
118                         break;
119                 case CTRL_BREAK_EVENT:
120                         break;
121                 }
122
123                 return TRUE;
124         }
125
126 void signal_handler_init(void)
127 {
128         SetConsoleCtrlHandler( (PHANDLER_ROUTINE)event_handler,TRUE);
129 }
130
131 #endif
132
133
134 /*
135         Multithreading support
136 */
137 int getNumberOfProcessors() {
138 #if defined(_SC_NPROCESSORS_ONLN)
139
140         return sysconf(_SC_NPROCESSORS_ONLN);
141
142 #elif defined(__FreeBSD__) || defined(__APPLE__)
143
144         unsigned int len, count;
145         len = sizeof(count);
146         return sysctlbyname("hw.ncpu", &count, &len, NULL, 0);
147
148 #elif defined(_GNU_SOURCE)
149
150         return get_nprocs();
151
152 #elif defined(_WIN32)
153
154         SYSTEM_INFO sysinfo;
155         GetSystemInfo(&sysinfo);
156         return sysinfo.dwNumberOfProcessors;
157
158 #elif defined(PTW32_VERSION) || defined(__hpux)
159
160         return pthread_num_processors_np();
161
162 #else
163
164         return 1;
165
166 #endif
167 }
168
169
170 #ifndef __ANDROID__
171 bool threadBindToProcessor(threadid_t tid, int pnumber) {
172 #if defined(_WIN32)
173
174         HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, 0, tid);
175         if (!hThread)
176                 return false;
177
178         bool success = SetThreadAffinityMask(hThread, 1 << pnumber) != 0;
179
180         CloseHandle(hThread);
181         return success;
182
183 #elif (defined(__FreeBSD__) && (__FreeBSD_version >= 702106)) \
184         || defined(__linux) || defined(linux)
185
186         cpu_set_t cpuset;
187
188         CPU_ZERO(&cpuset);
189         CPU_SET(pnumber, &cpuset);
190         return pthread_setaffinity_np(tid, sizeof(cpuset), &cpuset) == 0;
191
192 #elif defined(__sun) || defined(sun)
193
194         return processor_bind(P_LWPID, MAKE_LWPID_PTHREAD(tid),
195                                                 pnumber, NULL) == 0;
196
197 #elif defined(_AIX)
198
199         return bindprocessor(BINDTHREAD, (tid_t)tid, pnumber) == 0;
200
201 #elif defined(__hpux) || defined(hpux)
202
203         pthread_spu_t answer;
204
205         return pthread_processor_bind_np(PTHREAD_BIND_ADVISORY_NP,
206                                                                         &answer, pnumber, tid) == 0;
207
208 #elif defined(__APPLE__)
209
210         struct thread_affinity_policy tapol;
211
212         thread_port_t threadport = pthread_mach_thread_np(tid);
213         tapol.affinity_tag = pnumber + 1;
214         return thread_policy_set(threadport, THREAD_AFFINITY_POLICY,
215                         (thread_policy_t)&tapol, THREAD_AFFINITY_POLICY_COUNT) == KERN_SUCCESS;
216
217 #else
218
219         return false;
220
221 #endif
222 }
223 #endif
224
225 bool threadSetPriority(threadid_t tid, int prio) {
226 #if defined(_WIN32)
227
228         HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, 0, tid);
229         if (!hThread)
230                 return false;
231
232         bool success = SetThreadPriority(hThread, prio) != 0;
233
234         CloseHandle(hThread);
235         return success;
236
237 #else
238
239         struct sched_param sparam;
240         int policy;
241
242         if (pthread_getschedparam(tid, &policy, &sparam) != 0)
243                 return false;
244
245         int min = sched_get_priority_min(policy);
246         int max = sched_get_priority_max(policy);
247
248         sparam.sched_priority = min + prio * (max - min) / THREAD_PRIORITY_HIGHEST;
249         return pthread_setschedparam(tid, policy, &sparam) == 0;
250
251 #endif
252 }
253
254
255 /*
256         Path mangler
257 */
258
259 // Default to RUN_IN_PLACE style relative paths
260 std::string path_share = "..";
261 std::string path_user = "..";
262
263 std::string getDataPath(const char *subpath)
264 {
265         return path_share + DIR_DELIM + subpath;
266 }
267
268 void pathRemoveFile(char *path, char delim)
269 {
270         // Remove filename and path delimiter
271         int i;
272         for(i = strlen(path)-1; i>=0; i--)
273         {
274                 if(path[i] == delim)
275                         break;
276         }
277         path[i] = 0;
278 }
279
280 bool detectMSVCBuildDir(char *c_path)
281 {
282         std::string path(c_path);
283         const char *ends[] = {"bin\\Release", "bin\\Build", NULL};
284         return (removeStringEnd(path, ends) != "");
285 }
286
287 std::string get_sysinfo()
288 {
289 #ifdef _WIN32
290         OSVERSIONINFO osvi;
291         std::ostringstream oss;
292         std::string tmp;
293         ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
294         osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
295         GetVersionEx(&osvi);
296         tmp = osvi.szCSDVersion;
297         std::replace(tmp.begin(), tmp.end(), ' ', '_');
298
299         oss << "Windows/" << osvi.dwMajorVersion << "."
300                 << osvi.dwMinorVersion;
301         if(osvi.szCSDVersion[0])
302                 oss << "-" << tmp;
303         oss << " ";
304         #ifdef _WIN64
305         oss << "x86_64";
306         #else
307         BOOL is64 = FALSE;
308         if(IsWow64Process(GetCurrentProcess(), &is64) && is64)
309                 oss << "x86_64"; // 32-bit app on 64-bit OS
310         else
311                 oss << "x86";
312         #endif
313
314         return oss.str();
315 #else
316         struct utsname osinfo;
317         uname(&osinfo);
318         return std::string(osinfo.sysname) + "/"
319                 + osinfo.release + " " + osinfo.machine;
320 #endif
321 }
322
323 void initializePaths()
324 {
325 #if RUN_IN_PLACE
326         /*
327                 Use relative paths if RUN_IN_PLACE
328         */
329
330         infostream<<"Using relative paths (RUN_IN_PLACE)"<<std::endl;
331
332         /*
333                 Windows
334         */
335         #if defined(_WIN32)
336
337         const DWORD buflen = 1000;
338         char buf[buflen];
339         DWORD len;
340
341         // Find path of executable and set path_share relative to it
342         len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen);
343         assert(len < buflen);
344         pathRemoveFile(buf, '\\');
345
346         if(detectMSVCBuildDir(buf)){
347                 infostream<<"MSVC build directory detected"<<std::endl;
348                 path_share = std::string(buf) + "\\..\\..";
349                 path_user = std::string(buf) + "\\..\\..";
350         }
351         else{
352                 path_share = std::string(buf) + "\\..";
353                 path_user = std::string(buf) + "\\..";
354         }
355
356         /*
357                 Linux
358         */
359         #elif defined(linux)
360
361         char buf[BUFSIZ];
362         memset(buf, 0, BUFSIZ);
363         // Get path to executable
364         assert(readlink("/proc/self/exe", buf, BUFSIZ-1) != -1);
365
366         pathRemoveFile(buf, '/');
367
368         path_share = std::string(buf) + "/..";
369         path_user = std::string(buf) + "/..";
370
371         /*
372                 OS X
373         */
374         #elif defined(__APPLE__)
375
376         //https://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/dyld.3.html
377         //TODO: Test this code
378         char buf[BUFSIZ];
379         uint32_t len = sizeof(buf);
380         assert(_NSGetExecutablePath(buf, &len) != -1);
381
382         pathRemoveFile(buf, '/');
383
384         path_share = std::string(buf) + "/..";
385         path_user = std::string(buf) + "/..";
386
387         /*
388                 FreeBSD
389         */
390         #elif defined(__FreeBSD__)
391
392         int mib[4];
393         char buf[BUFSIZ];
394         size_t len = sizeof(buf);
395
396         mib[0] = CTL_KERN;
397         mib[1] = KERN_PROC;
398         mib[2] = KERN_PROC_PATHNAME;
399         mib[3] = -1;
400         assert(sysctl(mib, 4, buf, &len, NULL, 0) != -1);
401
402         pathRemoveFile(buf, '/');
403
404         path_share = std::string(buf) + "/..";
405         path_user = std::string(buf) + "/..";
406
407         #else
408
409         //TODO: Get path of executable. This assumes working directory is bin/
410         dstream<<"WARNING: Relative path not properly supported on this platform"
411                         <<std::endl;
412
413         /* scriptapi no longer allows paths that start with "..", so assuming that
414            the current working directory is bin/, strip off the last component. */
415         char *cwd = getcwd(NULL, 0);
416         pathRemoveFile(cwd, '/');
417         path_share = std::string(cwd);
418         path_user = std::string(cwd);
419
420         #endif
421
422 #else // RUN_IN_PLACE
423
424         /*
425                 Use platform-specific paths otherwise
426         */
427
428         infostream<<"Using system-wide paths (NOT RUN_IN_PLACE)"<<std::endl;
429
430         /*
431                 Windows
432         */
433         #if defined(_WIN32)
434
435         const DWORD buflen = 1000;
436         char buf[buflen];
437         DWORD len;
438
439         // Find path of executable and set path_share relative to it
440         len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen);
441         assert(len < buflen);
442         pathRemoveFile(buf, '\\');
443
444         // Use ".\bin\.."
445         path_share = std::string(buf) + "\\..";
446
447         // Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
448         len = GetEnvironmentVariable("APPDATA", buf, buflen);
449         assert(len < buflen);
450         path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME;
451
452         /*
453                 Linux
454         */
455         #elif defined(linux)
456
457         // Get path to executable
458         std::string bindir = "";
459         {
460                 char buf[BUFSIZ];
461                 memset(buf, 0, BUFSIZ);
462                 if (readlink("/proc/self/exe", buf, BUFSIZ-1) == -1) {
463                         errorstream << "Unable to read bindir "<< std::endl;
464 #ifndef __ANDROID__
465                         assert("Unable to read bindir" == 0);
466 #endif
467                 } else {
468                         pathRemoveFile(buf, '/');
469                         bindir = buf;
470                 }
471         }
472
473         // Find share directory from these.
474         // It is identified by containing the subdirectory "builtin".
475         std::list<std::string> trylist;
476         std::string static_sharedir = STATIC_SHAREDIR;
477         if(static_sharedir != "" && static_sharedir != ".")
478                 trylist.push_back(static_sharedir);
479         trylist.push_back(
480                         bindir + DIR_DELIM + ".." + DIR_DELIM + "share" + DIR_DELIM + PROJECT_NAME);
481         trylist.push_back(bindir + DIR_DELIM + "..");
482 #ifdef __ANDROID__
483         trylist.push_back(path_user);
484 #endif
485
486         for(std::list<std::string>::const_iterator i = trylist.begin();
487                         i != trylist.end(); i++)
488         {
489                 const std::string &trypath = *i;
490                 if(!fs::PathExists(trypath) || !fs::PathExists(trypath + DIR_DELIM + "builtin")){
491                         dstream<<"WARNING: system-wide share not found at \""
492                                         <<trypath<<"\""<<std::endl;
493                         continue;
494                 }
495                 // Warn if was not the first alternative
496                 if(i != trylist.begin()){
497                         dstream<<"WARNING: system-wide share found at \""
498                                         <<trypath<<"\""<<std::endl;
499                 }
500                 path_share = trypath;
501                 break;
502         }
503 #ifndef __ANDROID__
504         path_user = std::string(getenv("HOME")) + DIR_DELIM + "." + PROJECT_NAME;
505 #endif
506
507         /*
508                 OS X
509         */
510         #elif defined(__APPLE__)
511
512         // Code based on
513         // http://stackoverflow.com/questions/516200/relative-paths-not-working-in-xcode-c
514         CFBundleRef main_bundle = CFBundleGetMainBundle();
515         CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
516         char path[PATH_MAX];
517         if(CFURLGetFileSystemRepresentation(resources_url, TRUE, (UInt8 *)path, PATH_MAX))
518         {
519                 dstream<<"Bundle resource path: "<<path<<std::endl;
520                 //chdir(path);
521                 path_share = std::string(path) + DIR_DELIM + "share";
522         }
523         else
524         {
525                 // error!
526                 dstream<<"WARNING: Could not determine bundle resource path"<<std::endl;
527         }
528         CFRelease(resources_url);
529
530         path_user = std::string(getenv("HOME")) + "/Library/Application Support/" + PROJECT_NAME;
531
532         #else // FreeBSD, and probably many other POSIX-like systems.
533
534         path_share = STATIC_SHAREDIR;
535         path_user = std::string(getenv("HOME")) + DIR_DELIM + "." + PROJECT_NAME;
536
537         #endif
538
539 #endif // RUN_IN_PLACE
540 }
541
542 static irr::IrrlichtDevice* device;
543
544 void initIrrlicht(irr::IrrlichtDevice * _device) {
545         device = _device;
546 }
547
548 #ifndef SERVER
549 v2u32 getWindowSize() {
550         return device->getVideoDriver()->getScreenSize();
551 }
552
553 #ifndef __ANDROID__
554
555 float getDisplayDensity() {
556         return g_settings->getFloat("screen_dpi")/96.0;
557 }
558
559 v2u32 getDisplaySize() {
560         IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
561
562         core::dimension2d<u32> deskres = nulldevice->getVideoModeList()->getDesktopResolution();
563         nulldevice -> drop();
564
565         return deskres;
566 }
567 #endif
568 #endif
569
570 } //namespace porting
571